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
/* * 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 describes UBIFS on-flash format and contains definitions of all the * relevant data structures and constants. * * All UBIFS on-flash objects are stored in the form of nodes. All nodes start * with the UBIFS node magic number and have the same common header. Nodes * always sit at 8-byte aligned positions on the media and node header sizes are * also 8-byte aligned (except for the indexing node and the padding node). */ #ifndef __UBIFS_MEDIA_H__ #define __UBIFS_MEDIA_H__ /* UBIFS node magic number (must not have the padding byte first or last) */ #define UBIFS_NODE_MAGIC 0x06101831 /* * UBIFS on-flash format version. This version is increased when the on-flash * format is changing. If this happens, UBIFS is will support older versions as * well. But older UBIFS code will not support newer formats. Format changes * will be rare and only when absolutely necessary, e.g. to fix a bug or to add * a new feature. * * UBIFS went into mainline kernel with format version 4. The older formats * were development formats. */ #define UBIFS_FORMAT_VERSION 4 /* * Read-only compatibility version. If the UBIFS format is changed, older UBIFS * implementations will not be able to mount newer formats in read-write mode. * However, depending on the change, it may be possible to mount newer formats * in R/O mode. This is indicated by the R/O compatibility version which is * stored in the super-block. * * This is needed to support boot-loaders which only need R/O mounting. With * this flag it is possible to do UBIFS format changes without a need to update * boot-loaders. */ #define UBIFS_RO_COMPAT_VERSION 0 /* Minimum logical eraseblock size in bytes */ #define UBIFS_MIN_LEB_SZ (15*1024) /* Initial CRC32 value used when calculating CRC checksums */ #define UBIFS_CRC32_INIT 0xFFFFFFFFU /* * UBIFS does not try to compress data if its length is less than the below * constant. */ #define UBIFS_MIN_COMPR_LEN 128 /* * If compressed data length is less than %UBIFS_MIN_COMPRESS_DIFF bytes * shorter than uncompressed data length, UBIFS prefers to leave this data * node uncompress, because it'll be read faster. */ #define UBIFS_MIN_COMPRESS_DIFF 64 /* Root inode number */ #define UBIFS_ROOT_INO 1 /* Lowest inode number used for regular inodes (not UBIFS-only internal ones) */ #define UBIFS_FIRST_INO 64 /* * Maximum file name and extended attribute length (must be a multiple of 8, * minus 1). */ #define UBIFS_MAX_NLEN 255 /* Maximum number of data journal heads */ #define UBIFS_MAX_JHEADS 1 /* * Size of UBIFS data block. Note, UBIFS is not a block oriented file-system, * which means that it does not treat the underlying media as consisting of * blocks like in case of hard drives. Do not be confused. UBIFS block is just * the maximum amount of data which one data node can have or which can be * attached to an inode node. */ #define UBIFS_BLOCK_SIZE 4096 #define UBIFS_BLOCK_SHIFT 12 /* UBIFS padding byte pattern (must not be first or last byte of node magic) */ #define UBIFS_PADDING_BYTE 0xCE /* Maximum possible key length */ #define UBIFS_MAX_KEY_LEN 16 /* Key length ("simple" format) */ #define UBIFS_SK_LEN 8 /* Minimum index tree fanout */ #define UBIFS_MIN_FANOUT 3 /* Maximum number of levels in UBIFS indexing B-tree */ #define UBIFS_MAX_LEVELS 512 /* Maximum amount of data attached to an inode in bytes */ #define UBIFS_MAX_INO_DATA UBIFS_BLOCK_SIZE /* LEB Properties Tree fanout (must be power of 2) and fanout shift */ #define UBIFS_LPT_FANOUT 4 #define UBIFS_LPT_FANOUT_SHIFT 2 /* LEB Properties Tree bit field sizes */ #define UBIFS_LPT_CRC_BITS 16 #define UBIFS_LPT_CRC_BYTES 2 #define UBIFS_LPT_TYPE_BITS 4 /* The key is always at the same position in all keyed nodes */ #define UBIFS_KEY_OFFSET offsetof(struct ubifs_ino_node, key) /* * LEB Properties Tree node types. * * UBIFS_LPT_PNODE: LPT leaf node (contains LEB properties) * UBIFS_LPT_NNODE: LPT internal node * UBIFS_LPT_LTAB: LPT's own lprops table * UBIFS_LPT_LSAVE: LPT's save table (big model only) * UBIFS_LPT_NODE_CNT: count of LPT node types * UBIFS_LPT_NOT_A_NODE: all ones (15 for 4 bits) is never a valid node type */ enum { UBIFS_LPT_PNODE, UBIFS_LPT_NNODE, UBIFS_LPT_LTAB, UBIFS_LPT_LSAVE, UBIFS_LPT_NODE_CNT, UBIFS_LPT_NOT_A_NODE = (1 << UBIFS_LPT_TYPE_BITS) - 1, }; /* * UBIFS inode types. * * UBIFS_ITYPE_REG: regular file * UBIFS_ITYPE_DIR: directory * UBIFS_ITYPE_LNK: soft link * UBIFS_ITYPE_BLK: block device node * UBIFS_ITYPE_CHR: character device node * UBIFS_ITYPE_FIFO: fifo * UBIFS_ITYPE_SOCK: socket * UBIFS_ITYPES_CNT: count of supported file types */ enum { UBIFS_ITYPE_REG, UBIFS_ITYPE_DIR, UBIFS_ITYPE_LNK, UBIFS_ITYPE_BLK, UBIFS_ITYPE_CHR, UBIFS_ITYPE_FIFO, UBIFS_ITYPE_SOCK, UBIFS_ITYPES_CNT, }; /* * Supported key hash functions. * * UBIFS_KEY_HASH_R5: R5 hash * UBIFS_KEY_HASH_TEST: test hash which just returns first 4 bytes of the name */ enum { UBIFS_KEY_HASH_R5, UBIFS_KEY_HASH_TEST, }; /* * Supported key formats. * * UBIFS_SIMPLE_KEY_FMT: simple key format */ enum { UBIFS_SIMPLE_KEY_FMT, }; /* * The simple key format uses 29 bits for storing UBIFS block number and hash * value. */ #define UBIFS_S_KEY_BLOCK_BITS 29 #define UBIFS_S_KEY_BLOCK_MASK 0x1FFFFFFF #define UBIFS_S_KEY_HASH_BITS UBIFS_S_KEY_BLOCK_BITS #define UBIFS_S_KEY_HASH_MASK UBIFS_S_KEY_BLOCK_MASK /* * Key types. * * UBIFS_INO_KEY: inode node key * UBIFS_DATA_KEY: data node key * UBIFS_DENT_KEY: directory entry node key * UBIFS_XENT_KEY: extended attribute entry key * UBIFS_KEY_TYPES_CNT: number of supported key types */ enum { UBIFS_INO_KEY, UBIFS_DATA_KEY, UBIFS_DENT_KEY, UBIFS_XENT_KEY, UBIFS_KEY_TYPES_CNT, }; /* Count of LEBs reserved for the superblock area */ #define UBIFS_SB_LEBS 1 /* Count of LEBs reserved for the master area */ #define UBIFS_MST_LEBS 2 /* First LEB of the superblock area */ #define UBIFS_SB_LNUM 0 /* First LEB of the master area */ #define UBIFS_MST_LNUM (UBIFS_SB_LNUM + UBIFS_SB_LEBS) /* First LEB of the log area */ #define UBIFS_LOG_LNUM (UBIFS_MST_LNUM + UBIFS_MST_LEBS) /* * The below constants define the absolute minimum values for various UBIFS * media areas. Many of them actually depend of flash geometry and the FS * configuration (number of journal heads, orphan LEBs, etc). This means that * the smallest volume size which can be used for UBIFS cannot be pre-defined * by these constants. The file-system that meets the below limitation will not * necessarily mount. UBIFS does run-time calculations and validates the FS * size. */ /* Minimum number of logical eraseblocks in the log */ #define UBIFS_MIN_LOG_LEBS 2 /* Minimum number of bud logical eraseblocks (one for each head) */ #define UBIFS_MIN_BUD_LEBS 3 /* Minimum number of journal logical eraseblocks */ #define UBIFS_MIN_JNL_LEBS (UBIFS_MIN_LOG_LEBS + UBIFS_MIN_BUD_LEBS) /* Minimum number of LPT area logical eraseblocks */ #define UBIFS_MIN_LPT_LEBS 2 /* Minimum number of orphan area logical eraseblocks */ #define UBIFS_MIN_ORPH_LEBS 1 /* * Minimum number of main area logical eraseblocks (buds, 3 for the index, 1 * for GC, 1 for deletions, and at least 1 for committed data). */ #define UBIFS_MIN_MAIN_LEBS (UBIFS_MIN_BUD_LEBS + 6) /* Minimum number of logical eraseblocks */ #define UBIFS_MIN_LEB_CNT (UBIFS_SB_LEBS + UBIFS_MST_LEBS + \ UBIFS_MIN_LOG_LEBS + UBIFS_MIN_LPT_LEBS + \ UBIFS_MIN_ORPH_LEBS + UBIFS_MIN_MAIN_LEBS) /* Node sizes (N.B. these are guaranteed to be multiples of 8) */ #define UBIFS_CH_SZ sizeof(struct ubifs_ch) #define UBIFS_INO_NODE_SZ sizeof(struct ubifs_ino_node) #define UBIFS_DATA_NODE_SZ sizeof(struct ubifs_data_node) #define UBIFS_DENT_NODE_SZ sizeof(struct ubifs_dent_node) #define UBIFS_TRUN_NODE_SZ sizeof(struct ubifs_trun_node) #define UBIFS_PAD_NODE_SZ sizeof(struct ubifs_pad_node) #define UBIFS_SB_NODE_SZ sizeof(struct ubifs_sb_node) #define UBIFS_MST_NODE_SZ sizeof(struct ubifs_mst_node) #define UBIFS_REF_NODE_SZ sizeof(struct ubifs_ref_node) #define UBIFS_IDX_NODE_SZ sizeof(struct ubifs_idx_node) #define UBIFS_CS_NODE_SZ sizeof(struct ubifs_cs_node) #define UBIFS_ORPH_NODE_SZ sizeof(struct ubifs_orph_node) /* Extended attribute entry nodes are identical to directory entry nodes */ #define UBIFS_XENT_NODE_SZ UBIFS_DENT_NODE_SZ /* Only this does not have to be multiple of 8 bytes */ #define UBIFS_BRANCH_SZ sizeof(struct ubifs_branch) /* Maximum node sizes (N.B. these are guaranteed to be multiples of 8) */ #define UBIFS_MAX_DATA_NODE_SZ (UBIFS_DATA_NODE_SZ + UBIFS_BLOCK_SIZE) #define UBIFS_MAX_INO_NODE_SZ (UBIFS_INO_NODE_SZ + UBIFS_MAX_INO_DATA) #define UBIFS_MAX_DENT_NODE_SZ (UBIFS_DENT_NODE_SZ + UBIFS_MAX_NLEN + 1) #define UBIFS_MAX_XENT_NODE_SZ UBIFS_MAX_DENT_NODE_SZ /* The largest UBIFS node */ #define UBIFS_MAX_NODE_SZ UBIFS_MAX_INO_NODE_SZ /* * On-flash inode flags. * * UBIFS_COMPR_FL: use compression for this inode * UBIFS_SYNC_FL: I/O on this inode has to be synchronous * UBIFS_IMMUTABLE_FL: inode is immutable * UBIFS_APPEND_FL: writes to the inode may only append data * UBIFS_DIRSYNC_FL: I/O on this directory inode has to be synchronous * UBIFS_XATTR_FL: this inode is the inode for an extended attribute value * * Note, these are on-flash flags which correspond to ioctl flags * (@FS_COMPR_FL, etc). They have the same values now, but generally, do not * have to be the same. */ enum { UBIFS_COMPR_FL = 0x01, UBIFS_SYNC_FL = 0x02, UBIFS_IMMUTABLE_FL = 0x04, UBIFS_APPEND_FL = 0x08, UBIFS_DIRSYNC_FL = 0x10, UBIFS_XATTR_FL = 0x20, }; /* Inode flag bits used by UBIFS */ #define UBIFS_FL_MASK 0x0000001F /* * UBIFS compression algorithms. * * UBIFS_COMPR_NONE: no compression * UBIFS_COMPR_LZO: LZO compression * UBIFS_COMPR_ZLIB: ZLIB compression * UBIFS_COMPR_TYPES_CNT: count of supported compression types */ enum { UBIFS_COMPR_NONE, UBIFS_COMPR_LZO, UBIFS_COMPR_ZLIB, UBIFS_COMPR_TYPES_CNT, }; /* * UBIFS node types. * * UBIFS_INO_NODE: inode node * UBIFS_DATA_NODE: data node * UBIFS_DENT_NODE: directory entry node * UBIFS_XENT_NODE: extended attribute node * UBIFS_TRUN_NODE: truncation node * UBIFS_PAD_NODE: padding node * UBIFS_SB_NODE: superblock node * UBIFS_MST_NODE: master node * UBIFS_REF_NODE: LEB reference node * UBIFS_IDX_NODE: index node * UBIFS_CS_NODE: commit start node * UBIFS_ORPH_NODE: orphan node * UBIFS_NODE_TYPES_CNT: count of supported node types * * Note, we index arrays by these numbers, so keep them low and contiguous. * Node type constants for inodes, direntries and so on have to be the same as * corresponding key type constants. */ enum { UBIFS_INO_NODE, UBIFS_DATA_NODE, UBIFS_DENT_NODE, UBIFS_XENT_NODE, UBIFS_TRUN_NODE, UBIFS_PAD_NODE, UBIFS_SB_NODE, UBIFS_MST_NODE, UBIFS_REF_NODE, UBIFS_IDX_NODE, UBIFS_CS_NODE, UBIFS_ORPH_NODE, UBIFS_NODE_TYPES_CNT, }; /* * Master node flags. * * UBIFS_MST_DIRTY: rebooted uncleanly - master node is dirty * UBIFS_MST_NO_ORPHS: no orphan inodes present * UBIFS_MST_RCVRY: written by recovery */ enum { UBIFS_MST_DIRTY = 1, UBIFS_MST_NO_ORPHS = 2, UBIFS_MST_RCVRY = 4, }; /* * Node group type (used by recovery to recover whole group or none). * * UBIFS_NO_NODE_GROUP: this node is not part of a group * UBIFS_IN_NODE_GROUP: this node is a part of a group * UBIFS_LAST_OF_NODE_GROUP: this node is the last in a group */ enum { UBIFS_NO_NODE_GROUP = 0, UBIFS_IN_NODE_GROUP, UBIFS_LAST_OF_NODE_GROUP, }; /* * Superblock flags. * * UBIFS_FLG_BIGLPT: if "big" LPT model is used if set */ enum { UBIFS_FLG_BIGLPT = 0x02, }; /** * struct ubifs_ch - common header node. * @magic: UBIFS node magic number (%UBIFS_NODE_MAGIC) * @crc: CRC-32 checksum of the node header * @sqnum: sequence number * @len: full node length * @node_type: node type * @group_type: node group type * @padding: reserved for future, zeroes * * Every UBIFS node starts with this common part. If the node has a key, the * key always goes next. */ struct ubifs_ch { __le32 magic; __le32 crc; __le64 sqnum; __le32 len; __u8 node_type; __u8 group_type; __u8 padding[2]; } __attribute__ ((packed)); /** * union ubifs_dev_desc - device node descriptor. * @new: new type device descriptor * @huge: huge type device descriptor * * This data structure describes major/minor numbers of a device node. In an * inode is a device node then its data contains an object of this type. UBIFS * uses standard Linux "new" and "huge" device node encodings. */ union ubifs_dev_desc { __le32 new; __le64 huge; } __attribute__ ((packed)); /** * struct ubifs_ino_node - inode node. * @ch: common header * @key: node key * @creat_sqnum: sequence number at time of creation * @size: inode size in bytes (amount of uncompressed data) * @atime_sec: access time seconds * @ctime_sec: creation time seconds * @mtime_sec: modification time seconds * @atime_nsec: access time nanoseconds * @ctime_nsec: creation time nanoseconds * @mtime_nsec: modification time nanoseconds * @nlink: number of hard links * @uid: owner ID * @gid: group ID * @mode: access flags * @flags: per-inode flags (%UBIFS_COMPR_FL, %UBIFS_SYNC_FL, etc) * @data_len: inode data length * @xattr_cnt: count of extended attributes this inode has * @xattr_size: summarized size of all extended attributes in bytes * @padding1: reserved for future, zeroes * @xattr_names: sum of lengths of all extended attribute names belonging to * this inode * @compr_type: compression type used for this inode * @padding2: reserved for future, zeroes * @data: data attached to the inode * * Note, even though inode compression type is defined by @compr_type, some * nodes of this inode may be compressed with different compressor - this * happens if compression type is changed while the inode already has data * nodes. But @compr_type will be use for further writes to the inode. * * Note, do not forget to amend 'zero_ino_node_unused()' function when changing * the padding fields. */ struct ubifs_ino_node { struct ubifs_ch ch; __u8 key[UBIFS_MAX_KEY_LEN]; __le64 creat_sqnum; __le64 size; __le64 atime_sec; __le64 ctime_sec; __le64 mtime_sec; __le32 atime_nsec; __le32 ctime_nsec; __le32 mtime_nsec; __le32 nlink; __le32 uid; __le32 gid; __le32 mode; __le32 flags; __le32 data_len; __le32 xattr_cnt; __le32 xattr_size; __u8 padding1[4]; /* Watch 'zero_ino_node_unused()' if changing! */ __le32 xattr_names; __le16 compr_type; __u8 padding2[26]; /* Watch 'zero_ino_node_unused()' if changing! */ __u8 data[]; } __attribute__ ((packed)); /** * struct ubifs_dent_node - directory entry node. * @ch: common header * @key: node key * @inum: target inode number * @padding1: reserved for future, zeroes * @type: type of the target inode (%UBIFS_ITYPE_REG, %UBIFS_ITYPE_DIR, etc) * @nlen: name length * @padding2: reserved for future, zeroes * @name: zero-terminated name * * Note, do not forget to amend 'zero_dent_node_unused()' function when * changing the padding fields. */ struct ubifs_dent_node { struct ubifs_ch ch; __u8 key[UBIFS_MAX_KEY_LEN]; __le64 inum; __u8 padding1; __u8 type; __le16 nlen; __u8 padding2[4]; /* Watch 'zero_dent_node_unused()' if changing! */ __u8 name[]; } __attribute__ ((packed)); /** * struct ubifs_data_node - data node. * @ch: common header * @key: node key * @size: uncompressed data size in bytes * @compr_type: compression type (%UBIFS_COMPR_NONE, %UBIFS_COMPR_LZO, etc) * @padding: reserved for future, zeroes * @data: data * * Note, do not forget to amend 'zero_data_node_unused()' function when * changing the padding fields. */ struct ubifs_data_node { struct ubifs_ch ch; __u8 key[UBIFS_MAX_KEY_LEN]; __le32 size; __le16 compr_type; __u8 padding[2]; /* Watch 'zero_data_node_unused()' if changing! */ __u8 data[]; } __attribute__ ((packed)); /** * struct ubifs_trun_node - truncation node. * @ch: common header * @inum: truncated inode number * @padding: reserved for future, zeroes * @old_size: size before truncation * @new_size: size after truncation * * This node exists only in the journal and never goes to the main area. Note, * do not forget to amend 'zero_trun_node_unused()' function when changing the * padding fields. */ struct ubifs_trun_node { struct ubifs_ch ch; __le32 inum; __u8 padding[12]; /* Watch 'zero_trun_node_unused()' if changing! */ __le64 old_size; __le64 new_size; } __attribute__ ((packed)); /** * struct ubifs_pad_node - padding node. * @ch: common header * @pad_len: how many bytes after this node are unused (because padded) * @padding: reserved for future, zeroes */ struct ubifs_pad_node { struct ubifs_ch ch; __le32 pad_len; } __attribute__ ((packed)); /** * struct ubifs_sb_node - superblock node. * @ch: common header * @padding: reserved for future, zeroes * @key_hash: type of hash function used in keys * @key_fmt: format of the key * @flags: file-system flags (%UBIFS_FLG_BIGLPT, etc) * @min_io_size: minimal input/output unit size * @leb_size: logical eraseblock size in bytes * @leb_cnt: count of LEBs used by file-system * @max_leb_cnt: maximum count of LEBs used by file-system * @max_bud_bytes: maximum amount of data stored in buds * @log_lebs: log size in logical eraseblocks * @lpt_lebs: number of LEBs used for lprops table * @orph_lebs: number of LEBs used for recording orphans * @jhead_cnt: count of journal heads * @fanout: tree fanout (max. number of links per indexing node) * @lsave_cnt: number of LEB numbers in LPT's save table * @fmt_version: UBIFS on-flash format version * @default_compr: default compression algorithm (%UBIFS_COMPR_LZO, etc) * @padding1: reserved for future, zeroes * @rp_uid: reserve pool UID * @rp_gid: reserve pool GID * @rp_size: size of the reserved pool in bytes * @padding2: reserved for future, zeroes * @time_gran: time granularity in nanoseconds * @uuid: UUID generated when the file system image was created * @ro_compat_version: UBIFS R/O compatibility version */ struct ubifs_sb_node { struct ubifs_ch ch; __u8 padding[2]; __u8 key_hash; __u8 key_fmt; __le32 flags; __le32 min_io_size; __le32 leb_size; __le32 leb_cnt; __le32 max_leb_cnt; __le64 max_bud_bytes; __le32 log_lebs; __le32 lpt_lebs; __le32 orph_lebs; __le32 jhead_cnt; __le32 fanout; __le32 lsave_cnt; __le32 fmt_version; __le16 default_compr; __u8 padding1[2]; __le32 rp_uid; __le32 rp_gid; __le64 rp_size; __le32 time_gran; __u8 uuid[16]; __le32 ro_compat_version; __u8 padding2[3968]; } __attribute__ ((packed)); /** * struct ubifs_mst_node - master node. * @ch: common header * @highest_inum: highest inode number in the committed index * @cmt_no: commit number * @flags: various flags (%UBIFS_MST_DIRTY, etc) * @log_lnum: start of the log * @root_lnum: LEB number of the root indexing node * @root_offs: offset within @root_lnum * @root_len: root indexing node length * @gc_lnum: LEB reserved for garbage collection (%-1 value means the LEB was * not reserved and should be reserved on mount) * @ihead_lnum: LEB number of index head * @ihead_offs: offset of index head * @index_size: size of index on flash * @total_free: total free space in bytes * @total_dirty: total dirty space in bytes * @total_used: total used space in bytes (includes only data LEBs) * @total_dead: total dead space in bytes (includes only data LEBs) * @total_dark: total dark space in bytes (includes only data LEBs) * @lpt_lnum: LEB number of LPT root nnode * @lpt_offs: offset of LPT root nnode * @nhead_lnum: LEB number of LPT head * @nhead_offs: offset of LPT head * @ltab_lnum: LEB number of LPT's own lprops table * @ltab_offs: offset of LPT's own lprops table * @lsave_lnum: LEB number of LPT's save table (big model only) * @lsave_offs: offset of LPT's save table (big model only) * @lscan_lnum: LEB number of last LPT scan * @empty_lebs: number of empty logical eraseblocks * @idx_lebs: number of indexing logical eraseblocks * @leb_cnt: count of LEBs used by file-system * @padding: reserved for future, zeroes */ struct ubifs_mst_node { struct ubifs_ch ch; __le64 highest_inum; __le64 cmt_no; __le32 flags; __le32 log_lnum; __le32 root_lnum; __le32 root_offs; __le32 root_len; __le32 gc_lnum; __le32 ihead_lnum; __le32 ihead_offs; __le64 index_size; __le64 total_free; __le64 total_dirty; __le64 total_used; __le64 total_dead; __le64 total_dark; __le32 lpt_lnum; __le32 lpt_offs; __le32 nhead_lnum; __le32 nhead_offs; __le32 ltab_lnum; __le32 ltab_offs; __le32 lsave_lnum; __le32 lsave_offs; __le32 lscan_lnum; __le32 empty_lebs; __le32 idx_lebs; __le32 leb_cnt; __u8 padding[344]; } __attribute__ ((packed)); /** * struct ubifs_ref_node - logical eraseblock reference node. * @ch: common header * @lnum: the referred logical eraseblock number * @offs: start offset in the referred LEB * @jhead: journal head number * @padding: reserved for future, zeroes */ struct ubifs_ref_node { struct ubifs_ch ch; __le32 lnum; __le32 offs; __le32 jhead; __u8 padding[28]; } __attribute__ ((packed)); /** * struct ubifs_branch - key/reference/length branch * @lnum: LEB number of the target node * @offs: offset within @lnum * @len: target node length * @key: key */ struct ubifs_branch { __le32 lnum; __le32 offs; __le32 len; __u8 key[]; } __attribute__ ((packed)); /** * struct ubifs_idx_node - indexing node. * @ch: common header * @child_cnt: number of child index nodes * @level: tree level * @branches: LEB number / offset / length / key branches */ struct ubifs_idx_node { struct ubifs_ch ch; __le16 child_cnt; __le16 level; __u8 branches[]; } __attribute__ ((packed)); /** * struct ubifs_cs_node - commit start node. * @ch: common header * @cmt_no: commit number */ struct ubifs_cs_node { struct ubifs_ch ch; __le64 cmt_no; } __attribute__ ((packed)); /** * struct ubifs_orph_node - orphan node. * @ch: common header * @cmt_no: commit number (also top bit is set on the last node of the commit) * @inos: inode numbers of orphans */ struct ubifs_orph_node { struct ubifs_ch ch; __le64 cmt_no; __le64 inos[]; } __attribute__ ((packed)); #endif /* __UBIFS_MEDIA_H__ */
1001-study-uboot
fs/ubifs/ubifs-media.h
C
gpl3
23,195
/* * 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 LEB properties tree (LPT) area. The LPT area * contains the LEB properties tree, a table of LPT area eraseblocks (ltab), and * (for the "big" model) a table of saved LEB numbers (lsave). The LPT area sits * between the log and the orphan area. * * The LPT area is like a miniature self-contained file system. It is required * that it never runs out of space, is fast to access and update, and scales * logarithmically. The LEB properties tree is implemented as a wandering tree * much like the TNC, and the LPT area has its own garbage collection. * * The LPT has two slightly different forms called the "small model" and the * "big model". The small model is used when the entire LEB properties table * can be written into a single eraseblock. In that case, garbage collection * consists of just writing the whole table, which therefore makes all other * eraseblocks reusable. In the case of the big model, dirty eraseblocks are * selected for garbage collection, which consists of marking the clean nodes in * that LEB as dirty, and then only the dirty nodes are written out. Also, in * the case of the big model, a table of LEB numbers is saved so that the entire * LPT does not to be scanned looking for empty eraseblocks when UBIFS is first * mounted. */ #include "ubifs.h" #include "crc16.h" #include <linux/math64.h> /** * do_calc_lpt_geom - calculate sizes for the LPT area. * @c: the UBIFS file-system description object * * Calculate the sizes of LPT bit fields, nodes, and tree, based on the * properties of the flash and whether LPT is "big" (c->big_lpt). */ static void do_calc_lpt_geom(struct ubifs_info *c) { int i, n, bits, per_leb_wastage, max_pnode_cnt; long long sz, tot_wastage; n = c->main_lebs + c->max_leb_cnt - c->leb_cnt; max_pnode_cnt = DIV_ROUND_UP(n, UBIFS_LPT_FANOUT); c->lpt_hght = 1; n = UBIFS_LPT_FANOUT; while (n < max_pnode_cnt) { c->lpt_hght += 1; n <<= UBIFS_LPT_FANOUT_SHIFT; } c->pnode_cnt = DIV_ROUND_UP(c->main_lebs, UBIFS_LPT_FANOUT); n = DIV_ROUND_UP(c->pnode_cnt, UBIFS_LPT_FANOUT); c->nnode_cnt = n; for (i = 1; i < c->lpt_hght; i++) { n = DIV_ROUND_UP(n, UBIFS_LPT_FANOUT); c->nnode_cnt += n; } c->space_bits = fls(c->leb_size) - 3; c->lpt_lnum_bits = fls(c->lpt_lebs); c->lpt_offs_bits = fls(c->leb_size - 1); c->lpt_spc_bits = fls(c->leb_size); n = DIV_ROUND_UP(c->max_leb_cnt, UBIFS_LPT_FANOUT); c->pcnt_bits = fls(n - 1); c->lnum_bits = fls(c->max_leb_cnt - 1); bits = UBIFS_LPT_CRC_BITS + UBIFS_LPT_TYPE_BITS + (c->big_lpt ? c->pcnt_bits : 0) + (c->space_bits * 2 + 1) * UBIFS_LPT_FANOUT; c->pnode_sz = (bits + 7) / 8; bits = UBIFS_LPT_CRC_BITS + UBIFS_LPT_TYPE_BITS + (c->big_lpt ? c->pcnt_bits : 0) + (c->lpt_lnum_bits + c->lpt_offs_bits) * UBIFS_LPT_FANOUT; c->nnode_sz = (bits + 7) / 8; bits = UBIFS_LPT_CRC_BITS + UBIFS_LPT_TYPE_BITS + c->lpt_lebs * c->lpt_spc_bits * 2; c->ltab_sz = (bits + 7) / 8; bits = UBIFS_LPT_CRC_BITS + UBIFS_LPT_TYPE_BITS + c->lnum_bits * c->lsave_cnt; c->lsave_sz = (bits + 7) / 8; /* Calculate the minimum LPT size */ c->lpt_sz = (long long)c->pnode_cnt * c->pnode_sz; c->lpt_sz += (long long)c->nnode_cnt * c->nnode_sz; c->lpt_sz += c->ltab_sz; if (c->big_lpt) c->lpt_sz += c->lsave_sz; /* Add wastage */ sz = c->lpt_sz; per_leb_wastage = max_t(int, c->pnode_sz, c->nnode_sz); sz += per_leb_wastage; tot_wastage = per_leb_wastage; while (sz > c->leb_size) { sz += per_leb_wastage; sz -= c->leb_size; tot_wastage += per_leb_wastage; } tot_wastage += ALIGN(sz, c->min_io_size) - sz; c->lpt_sz += tot_wastage; } /** * ubifs_calc_lpt_geom - calculate and check sizes for the LPT area. * @c: the UBIFS file-system description object * * This function returns %0 on success and a negative error code on failure. */ int ubifs_calc_lpt_geom(struct ubifs_info *c) { int lebs_needed; long long sz; do_calc_lpt_geom(c); /* Verify that lpt_lebs is big enough */ sz = c->lpt_sz * 2; /* Must have at least 2 times the size */ lebs_needed = div_u64(sz + c->leb_size - 1, c->leb_size); if (lebs_needed > c->lpt_lebs) { ubifs_err("too few LPT LEBs"); return -EINVAL; } /* Verify that ltab fits in a single LEB (since ltab is a single node */ if (c->ltab_sz > c->leb_size) { ubifs_err("LPT ltab too big"); return -EINVAL; } c->check_lpt_free = c->big_lpt; return 0; } /** * ubifs_unpack_bits - unpack bit fields. * @addr: address at which to unpack (passed and next address returned) * @pos: bit position at which to unpack (passed and next position returned) * @nrbits: number of bits of value to unpack (1-32) * * This functions returns the value unpacked. */ uint32_t ubifs_unpack_bits(uint8_t **addr, int *pos, int nrbits) { const int k = 32 - nrbits; uint8_t *p = *addr; int b = *pos; uint32_t uninitialized_var(val); const int bytes = (nrbits + b + 7) >> 3; ubifs_assert(nrbits > 0); ubifs_assert(nrbits <= 32); ubifs_assert(*pos >= 0); ubifs_assert(*pos < 8); if (b) { switch (bytes) { case 2: val = p[1]; break; case 3: val = p[1] | ((uint32_t)p[2] << 8); break; case 4: val = p[1] | ((uint32_t)p[2] << 8) | ((uint32_t)p[3] << 16); break; case 5: val = p[1] | ((uint32_t)p[2] << 8) | ((uint32_t)p[3] << 16) | ((uint32_t)p[4] << 24); } val <<= (8 - b); val |= *p >> b; nrbits += b; } else { switch (bytes) { case 1: val = p[0]; break; case 2: val = p[0] | ((uint32_t)p[1] << 8); break; case 3: val = p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16); break; case 4: val = p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); break; } } val <<= k; val >>= k; b = nrbits & 7; p += nrbits >> 3; *addr = p; *pos = b; ubifs_assert((val >> nrbits) == 0 || nrbits - b == 32); return val; } /** * ubifs_add_lpt_dirt - add dirty space to LPT LEB properties. * @c: UBIFS file-system description object * @lnum: LEB number to which to add dirty space * @dirty: amount of dirty space to add */ void ubifs_add_lpt_dirt(struct ubifs_info *c, int lnum, int dirty) { if (!dirty || !lnum) return; dbg_lp("LEB %d add %d to %d", lnum, dirty, c->ltab[lnum - c->lpt_first].dirty); ubifs_assert(lnum >= c->lpt_first && lnum <= c->lpt_last); c->ltab[lnum - c->lpt_first].dirty += dirty; } /** * ubifs_add_nnode_dirt - add dirty space to LPT LEB properties. * @c: UBIFS file-system description object * @nnode: nnode for which to add dirt */ void ubifs_add_nnode_dirt(struct ubifs_info *c, struct ubifs_nnode *nnode) { struct ubifs_nnode *np = nnode->parent; if (np) ubifs_add_lpt_dirt(c, np->nbranch[nnode->iip].lnum, c->nnode_sz); else { ubifs_add_lpt_dirt(c, c->lpt_lnum, c->nnode_sz); if (!(c->lpt_drty_flgs & LTAB_DIRTY)) { c->lpt_drty_flgs |= LTAB_DIRTY; ubifs_add_lpt_dirt(c, c->ltab_lnum, c->ltab_sz); } } } /** * add_pnode_dirt - add dirty space to LPT LEB properties. * @c: UBIFS file-system description object * @pnode: pnode for which to add dirt */ static void add_pnode_dirt(struct ubifs_info *c, struct ubifs_pnode *pnode) { ubifs_add_lpt_dirt(c, pnode->parent->nbranch[pnode->iip].lnum, c->pnode_sz); } /** * calc_nnode_num_from_parent - calculate nnode number. * @c: UBIFS file-system description object * @parent: parent nnode * @iip: index in parent * * The nnode number is a number that uniquely identifies a nnode and can be used * easily to traverse the tree from the root to that nnode. * * This function calculates and returns the nnode number based on the parent's * nnode number and the index in parent. */ static int calc_nnode_num_from_parent(const struct ubifs_info *c, struct ubifs_nnode *parent, int iip) { int num, shft; if (!parent) return 1; shft = (c->lpt_hght - parent->level) * UBIFS_LPT_FANOUT_SHIFT; num = parent->num ^ (1 << shft); num |= (UBIFS_LPT_FANOUT + iip) << shft; return num; } /** * calc_pnode_num_from_parent - calculate pnode number. * @c: UBIFS file-system description object * @parent: parent nnode * @iip: index in parent * * The pnode number is a number that uniquely identifies a pnode and can be used * easily to traverse the tree from the root to that pnode. * * This function calculates and returns the pnode number based on the parent's * nnode number and the index in parent. */ static int calc_pnode_num_from_parent(const struct ubifs_info *c, struct ubifs_nnode *parent, int iip) { int i, n = c->lpt_hght - 1, pnum = parent->num, num = 0; for (i = 0; i < n; i++) { num <<= UBIFS_LPT_FANOUT_SHIFT; num |= pnum & (UBIFS_LPT_FANOUT - 1); pnum >>= UBIFS_LPT_FANOUT_SHIFT; } num <<= UBIFS_LPT_FANOUT_SHIFT; num |= iip; return num; } /** * update_cats - add LEB properties of a pnode to LEB category lists and heaps. * @c: UBIFS file-system description object * @pnode: pnode * * When a pnode is loaded into memory, the LEB properties it contains are added, * by this function, to the LEB category lists and heaps. */ static void update_cats(struct ubifs_info *c, struct ubifs_pnode *pnode) { int i; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { int cat = pnode->lprops[i].flags & LPROPS_CAT_MASK; int lnum = pnode->lprops[i].lnum; if (!lnum) return; ubifs_add_to_cat(c, &pnode->lprops[i], cat); } } /** * replace_cats - add LEB properties of a pnode to LEB category lists and heaps. * @c: UBIFS file-system description object * @old_pnode: pnode copied * @new_pnode: pnode copy * * During commit it is sometimes necessary to copy a pnode * (see dirty_cow_pnode). When that happens, references in * category lists and heaps must be replaced. This function does that. */ static void replace_cats(struct ubifs_info *c, struct ubifs_pnode *old_pnode, struct ubifs_pnode *new_pnode) { int i; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { if (!new_pnode->lprops[i].lnum) return; ubifs_replace_cat(c, &old_pnode->lprops[i], &new_pnode->lprops[i]); } } /** * check_lpt_crc - check LPT node crc is correct. * @c: UBIFS file-system description object * @buf: buffer containing node * @len: length of node * * This function returns %0 on success and a negative error code on failure. */ static int check_lpt_crc(void *buf, int len) { int pos = 0; uint8_t *addr = buf; uint16_t crc, calc_crc; crc = ubifs_unpack_bits(&addr, &pos, UBIFS_LPT_CRC_BITS); calc_crc = crc16(-1, buf + UBIFS_LPT_CRC_BYTES, len - UBIFS_LPT_CRC_BYTES); if (crc != calc_crc) { ubifs_err("invalid crc in LPT node: crc %hx calc %hx", crc, calc_crc); dbg_dump_stack(); return -EINVAL; } return 0; } /** * check_lpt_type - check LPT node type is correct. * @c: UBIFS file-system description object * @addr: address of type bit field is passed and returned updated here * @pos: position of type bit field is passed and returned updated here * @type: expected type * * This function returns %0 on success and a negative error code on failure. */ static int check_lpt_type(uint8_t **addr, int *pos, int type) { int node_type; node_type = ubifs_unpack_bits(addr, pos, UBIFS_LPT_TYPE_BITS); if (node_type != type) { ubifs_err("invalid type (%d) in LPT node type %d", node_type, type); dbg_dump_stack(); return -EINVAL; } return 0; } /** * unpack_pnode - unpack a pnode. * @c: UBIFS file-system description object * @buf: buffer containing packed pnode to unpack * @pnode: pnode structure to fill * * This function returns %0 on success and a negative error code on failure. */ static int unpack_pnode(const struct ubifs_info *c, void *buf, struct ubifs_pnode *pnode) { uint8_t *addr = buf + UBIFS_LPT_CRC_BYTES; int i, pos = 0, err; err = check_lpt_type(&addr, &pos, UBIFS_LPT_PNODE); if (err) return err; if (c->big_lpt) pnode->num = ubifs_unpack_bits(&addr, &pos, c->pcnt_bits); for (i = 0; i < UBIFS_LPT_FANOUT; i++) { struct ubifs_lprops * const lprops = &pnode->lprops[i]; lprops->free = ubifs_unpack_bits(&addr, &pos, c->space_bits); lprops->free <<= 3; lprops->dirty = ubifs_unpack_bits(&addr, &pos, c->space_bits); lprops->dirty <<= 3; if (ubifs_unpack_bits(&addr, &pos, 1)) lprops->flags = LPROPS_INDEX; else lprops->flags = 0; lprops->flags |= ubifs_categorize_lprops(c, lprops); } err = check_lpt_crc(buf, c->pnode_sz); return err; } /** * ubifs_unpack_nnode - unpack a nnode. * @c: UBIFS file-system description object * @buf: buffer containing packed nnode to unpack * @nnode: nnode structure to fill * * This function returns %0 on success and a negative error code on failure. */ int ubifs_unpack_nnode(const struct ubifs_info *c, void *buf, struct ubifs_nnode *nnode) { uint8_t *addr = buf + UBIFS_LPT_CRC_BYTES; int i, pos = 0, err; err = check_lpt_type(&addr, &pos, UBIFS_LPT_NNODE); if (err) return err; if (c->big_lpt) nnode->num = ubifs_unpack_bits(&addr, &pos, c->pcnt_bits); for (i = 0; i < UBIFS_LPT_FANOUT; i++) { int lnum; lnum = ubifs_unpack_bits(&addr, &pos, c->lpt_lnum_bits) + c->lpt_first; if (lnum == c->lpt_last + 1) lnum = 0; nnode->nbranch[i].lnum = lnum; nnode->nbranch[i].offs = ubifs_unpack_bits(&addr, &pos, c->lpt_offs_bits); } err = check_lpt_crc(buf, c->nnode_sz); return err; } /** * unpack_ltab - unpack the LPT's own lprops table. * @c: UBIFS file-system description object * @buf: buffer from which to unpack * * This function returns %0 on success and a negative error code on failure. */ static int unpack_ltab(const struct ubifs_info *c, void *buf) { uint8_t *addr = buf + UBIFS_LPT_CRC_BYTES; int i, pos = 0, err; err = check_lpt_type(&addr, &pos, UBIFS_LPT_LTAB); if (err) return err; for (i = 0; i < c->lpt_lebs; i++) { int free = ubifs_unpack_bits(&addr, &pos, c->lpt_spc_bits); int dirty = ubifs_unpack_bits(&addr, &pos, c->lpt_spc_bits); if (free < 0 || free > c->leb_size || dirty < 0 || dirty > c->leb_size || free + dirty > c->leb_size) return -EINVAL; c->ltab[i].free = free; c->ltab[i].dirty = dirty; c->ltab[i].tgc = 0; c->ltab[i].cmt = 0; } err = check_lpt_crc(buf, c->ltab_sz); return err; } /** * validate_nnode - validate a nnode. * @c: UBIFS file-system description object * @nnode: nnode to validate * @parent: parent nnode (or NULL for the root nnode) * @iip: index in parent * * This function returns %0 on success and a negative error code on failure. */ static int validate_nnode(const struct ubifs_info *c, struct ubifs_nnode *nnode, struct ubifs_nnode *parent, int iip) { int i, lvl, max_offs; if (c->big_lpt) { int num = calc_nnode_num_from_parent(c, parent, iip); if (nnode->num != num) return -EINVAL; } lvl = parent ? parent->level - 1 : c->lpt_hght; if (lvl < 1) return -EINVAL; if (lvl == 1) max_offs = c->leb_size - c->pnode_sz; else max_offs = c->leb_size - c->nnode_sz; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { int lnum = nnode->nbranch[i].lnum; int offs = nnode->nbranch[i].offs; if (lnum == 0) { if (offs != 0) return -EINVAL; continue; } if (lnum < c->lpt_first || lnum > c->lpt_last) return -EINVAL; if (offs < 0 || offs > max_offs) return -EINVAL; } return 0; } /** * validate_pnode - validate a pnode. * @c: UBIFS file-system description object * @pnode: pnode to validate * @parent: parent nnode * @iip: index in parent * * This function returns %0 on success and a negative error code on failure. */ static int validate_pnode(const struct ubifs_info *c, struct ubifs_pnode *pnode, struct ubifs_nnode *parent, int iip) { int i; if (c->big_lpt) { int num = calc_pnode_num_from_parent(c, parent, iip); if (pnode->num != num) return -EINVAL; } for (i = 0; i < UBIFS_LPT_FANOUT; i++) { int free = pnode->lprops[i].free; int dirty = pnode->lprops[i].dirty; if (free < 0 || free > c->leb_size || free % c->min_io_size || (free & 7)) return -EINVAL; if (dirty < 0 || dirty > c->leb_size || (dirty & 7)) return -EINVAL; if (dirty + free > c->leb_size) return -EINVAL; } return 0; } /** * set_pnode_lnum - set LEB numbers on a pnode. * @c: UBIFS file-system description object * @pnode: pnode to update * * This function calculates the LEB numbers for the LEB properties it contains * based on the pnode number. */ static void set_pnode_lnum(const struct ubifs_info *c, struct ubifs_pnode *pnode) { int i, lnum; lnum = (pnode->num << UBIFS_LPT_FANOUT_SHIFT) + c->main_first; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { if (lnum >= c->leb_cnt) return; pnode->lprops[i].lnum = lnum++; } } /** * ubifs_read_nnode - read a nnode from flash and link it to the tree in memory. * @c: UBIFS file-system description object * @parent: parent nnode (or NULL for the root) * @iip: index in parent * * This function returns %0 on success and a negative error code on failure. */ int ubifs_read_nnode(struct ubifs_info *c, struct ubifs_nnode *parent, int iip) { struct ubifs_nbranch *branch = NULL; struct ubifs_nnode *nnode = NULL; void *buf = c->lpt_nod_buf; int err, lnum, offs; if (parent) { branch = &parent->nbranch[iip]; lnum = branch->lnum; offs = branch->offs; } else { lnum = c->lpt_lnum; offs = c->lpt_offs; } nnode = kzalloc(sizeof(struct ubifs_nnode), GFP_NOFS); if (!nnode) { err = -ENOMEM; goto out; } if (lnum == 0) { /* * This nnode was not written which just means that the LEB * properties in the subtree below it describe empty LEBs. We * make the nnode as though we had read it, which in fact means * doing almost nothing. */ if (c->big_lpt) nnode->num = calc_nnode_num_from_parent(c, parent, iip); } else { err = ubi_read(c->ubi, lnum, buf, offs, c->nnode_sz); if (err) goto out; err = ubifs_unpack_nnode(c, buf, nnode); if (err) goto out; } err = validate_nnode(c, nnode, parent, iip); if (err) goto out; if (!c->big_lpt) nnode->num = calc_nnode_num_from_parent(c, parent, iip); if (parent) { branch->nnode = nnode; nnode->level = parent->level - 1; } else { c->nroot = nnode; nnode->level = c->lpt_hght; } nnode->parent = parent; nnode->iip = iip; return 0; out: ubifs_err("error %d reading nnode at %d:%d", err, lnum, offs); kfree(nnode); return err; } /** * read_pnode - read a pnode from flash and link it to the tree in memory. * @c: UBIFS file-system description object * @parent: parent nnode * @iip: index in parent * * This function returns %0 on success and a negative error code on failure. */ static int read_pnode(struct ubifs_info *c, struct ubifs_nnode *parent, int iip) { struct ubifs_nbranch *branch; struct ubifs_pnode *pnode = NULL; void *buf = c->lpt_nod_buf; int err, lnum, offs; branch = &parent->nbranch[iip]; lnum = branch->lnum; offs = branch->offs; pnode = kzalloc(sizeof(struct ubifs_pnode), GFP_NOFS); if (!pnode) { err = -ENOMEM; goto out; } if (lnum == 0) { /* * This pnode was not written which just means that the LEB * properties in it describe empty LEBs. We make the pnode as * though we had read it. */ int i; if (c->big_lpt) pnode->num = calc_pnode_num_from_parent(c, parent, iip); for (i = 0; i < UBIFS_LPT_FANOUT; i++) { struct ubifs_lprops * const lprops = &pnode->lprops[i]; lprops->free = c->leb_size; lprops->flags = ubifs_categorize_lprops(c, lprops); } } else { err = ubi_read(c->ubi, lnum, buf, offs, c->pnode_sz); if (err) goto out; err = unpack_pnode(c, buf, pnode); if (err) goto out; } err = validate_pnode(c, pnode, parent, iip); if (err) goto out; if (!c->big_lpt) pnode->num = calc_pnode_num_from_parent(c, parent, iip); branch->pnode = pnode; pnode->parent = parent; pnode->iip = iip; set_pnode_lnum(c, pnode); c->pnodes_have += 1; return 0; out: ubifs_err("error %d reading pnode at %d:%d", err, lnum, offs); dbg_dump_pnode(c, pnode, parent, iip); dbg_msg("calc num: %d", calc_pnode_num_from_parent(c, parent, iip)); kfree(pnode); return err; } /** * read_ltab - read LPT's own lprops table. * @c: UBIFS file-system description object * * This function returns %0 on success and a negative error code on failure. */ static int read_ltab(struct ubifs_info *c) { int err; void *buf; buf = vmalloc(c->ltab_sz); if (!buf) return -ENOMEM; err = ubi_read(c->ubi, c->ltab_lnum, buf, c->ltab_offs, c->ltab_sz); if (err) goto out; err = unpack_ltab(c, buf); out: vfree(buf); return err; } /** * ubifs_get_nnode - get a nnode. * @c: UBIFS file-system description object * @parent: parent nnode (or NULL for the root) * @iip: index in parent * * This function returns a pointer to the nnode on success or a negative error * code on failure. */ struct ubifs_nnode *ubifs_get_nnode(struct ubifs_info *c, struct ubifs_nnode *parent, int iip) { struct ubifs_nbranch *branch; struct ubifs_nnode *nnode; int err; branch = &parent->nbranch[iip]; nnode = branch->nnode; if (nnode) return nnode; err = ubifs_read_nnode(c, parent, iip); if (err) return ERR_PTR(err); return branch->nnode; } /** * ubifs_get_pnode - get a pnode. * @c: UBIFS file-system description object * @parent: parent nnode * @iip: index in parent * * This function returns a pointer to the pnode on success or a negative error * code on failure. */ struct ubifs_pnode *ubifs_get_pnode(struct ubifs_info *c, struct ubifs_nnode *parent, int iip) { struct ubifs_nbranch *branch; struct ubifs_pnode *pnode; int err; branch = &parent->nbranch[iip]; pnode = branch->pnode; if (pnode) return pnode; err = read_pnode(c, parent, iip); if (err) return ERR_PTR(err); update_cats(c, branch->pnode); return branch->pnode; } /** * ubifs_lpt_lookup - lookup LEB properties in the LPT. * @c: UBIFS file-system description object * @lnum: LEB number to lookup * * This function returns a pointer to the LEB properties on success or a * negative error code on failure. */ struct ubifs_lprops *ubifs_lpt_lookup(struct ubifs_info *c, int lnum) { int err, i, h, iip, shft; struct ubifs_nnode *nnode; struct ubifs_pnode *pnode; if (!c->nroot) { err = ubifs_read_nnode(c, NULL, 0); if (err) return ERR_PTR(err); } nnode = c->nroot; i = lnum - c->main_first; shft = c->lpt_hght * UBIFS_LPT_FANOUT_SHIFT; for (h = 1; h < c->lpt_hght; h++) { iip = ((i >> shft) & (UBIFS_LPT_FANOUT - 1)); shft -= UBIFS_LPT_FANOUT_SHIFT; nnode = ubifs_get_nnode(c, nnode, iip); if (IS_ERR(nnode)) return ERR_PTR(PTR_ERR(nnode)); } iip = ((i >> shft) & (UBIFS_LPT_FANOUT - 1)); shft -= UBIFS_LPT_FANOUT_SHIFT; pnode = ubifs_get_pnode(c, nnode, iip); if (IS_ERR(pnode)) return ERR_PTR(PTR_ERR(pnode)); iip = (i & (UBIFS_LPT_FANOUT - 1)); dbg_lp("LEB %d, free %d, dirty %d, flags %d", lnum, pnode->lprops[iip].free, pnode->lprops[iip].dirty, pnode->lprops[iip].flags); return &pnode->lprops[iip]; } /** * dirty_cow_nnode - ensure a nnode is not being committed. * @c: UBIFS file-system description object * @nnode: nnode to check * * Returns dirtied nnode on success or negative error code on failure. */ static struct ubifs_nnode *dirty_cow_nnode(struct ubifs_info *c, struct ubifs_nnode *nnode) { struct ubifs_nnode *n; int i; if (!test_bit(COW_CNODE, &nnode->flags)) { /* nnode is not being committed */ if (!test_and_set_bit(DIRTY_CNODE, &nnode->flags)) { c->dirty_nn_cnt += 1; ubifs_add_nnode_dirt(c, nnode); } return nnode; } /* nnode is being committed, so copy it */ n = kmalloc(sizeof(struct ubifs_nnode), GFP_NOFS); if (unlikely(!n)) return ERR_PTR(-ENOMEM); memcpy(n, nnode, sizeof(struct ubifs_nnode)); n->cnext = NULL; __set_bit(DIRTY_CNODE, &n->flags); __clear_bit(COW_CNODE, &n->flags); /* The children now have new parent */ for (i = 0; i < UBIFS_LPT_FANOUT; i++) { struct ubifs_nbranch *branch = &n->nbranch[i]; if (branch->cnode) branch->cnode->parent = n; } ubifs_assert(!test_bit(OBSOLETE_CNODE, &nnode->flags)); __set_bit(OBSOLETE_CNODE, &nnode->flags); c->dirty_nn_cnt += 1; ubifs_add_nnode_dirt(c, nnode); if (nnode->parent) nnode->parent->nbranch[n->iip].nnode = n; else c->nroot = n; return n; } /** * dirty_cow_pnode - ensure a pnode is not being committed. * @c: UBIFS file-system description object * @pnode: pnode to check * * Returns dirtied pnode on success or negative error code on failure. */ static struct ubifs_pnode *dirty_cow_pnode(struct ubifs_info *c, struct ubifs_pnode *pnode) { struct ubifs_pnode *p; if (!test_bit(COW_CNODE, &pnode->flags)) { /* pnode is not being committed */ if (!test_and_set_bit(DIRTY_CNODE, &pnode->flags)) { c->dirty_pn_cnt += 1; add_pnode_dirt(c, pnode); } return pnode; } /* pnode is being committed, so copy it */ p = kmalloc(sizeof(struct ubifs_pnode), GFP_NOFS); if (unlikely(!p)) return ERR_PTR(-ENOMEM); memcpy(p, pnode, sizeof(struct ubifs_pnode)); p->cnext = NULL; __set_bit(DIRTY_CNODE, &p->flags); __clear_bit(COW_CNODE, &p->flags); replace_cats(c, pnode, p); ubifs_assert(!test_bit(OBSOLETE_CNODE, &pnode->flags)); __set_bit(OBSOLETE_CNODE, &pnode->flags); c->dirty_pn_cnt += 1; add_pnode_dirt(c, pnode); pnode->parent->nbranch[p->iip].pnode = p; return p; } /** * ubifs_lpt_lookup_dirty - lookup LEB properties in the LPT. * @c: UBIFS file-system description object * @lnum: LEB number to lookup * * This function returns a pointer to the LEB properties on success or a * negative error code on failure. */ struct ubifs_lprops *ubifs_lpt_lookup_dirty(struct ubifs_info *c, int lnum) { int err, i, h, iip, shft; struct ubifs_nnode *nnode; struct ubifs_pnode *pnode; if (!c->nroot) { err = ubifs_read_nnode(c, NULL, 0); if (err) return ERR_PTR(err); } nnode = c->nroot; nnode = dirty_cow_nnode(c, nnode); if (IS_ERR(nnode)) return ERR_PTR(PTR_ERR(nnode)); i = lnum - c->main_first; shft = c->lpt_hght * UBIFS_LPT_FANOUT_SHIFT; for (h = 1; h < c->lpt_hght; h++) { iip = ((i >> shft) & (UBIFS_LPT_FANOUT - 1)); shft -= UBIFS_LPT_FANOUT_SHIFT; nnode = ubifs_get_nnode(c, nnode, iip); if (IS_ERR(nnode)) return ERR_PTR(PTR_ERR(nnode)); nnode = dirty_cow_nnode(c, nnode); if (IS_ERR(nnode)) return ERR_PTR(PTR_ERR(nnode)); } iip = ((i >> shft) & (UBIFS_LPT_FANOUT - 1)); shft -= UBIFS_LPT_FANOUT_SHIFT; pnode = ubifs_get_pnode(c, nnode, iip); if (IS_ERR(pnode)) return ERR_PTR(PTR_ERR(pnode)); pnode = dirty_cow_pnode(c, pnode); if (IS_ERR(pnode)) return ERR_PTR(PTR_ERR(pnode)); iip = (i & (UBIFS_LPT_FANOUT - 1)); dbg_lp("LEB %d, free %d, dirty %d, flags %d", lnum, pnode->lprops[iip].free, pnode->lprops[iip].dirty, pnode->lprops[iip].flags); ubifs_assert(test_bit(DIRTY_CNODE, &pnode->flags)); return &pnode->lprops[iip]; } /** * lpt_init_rd - initialize the LPT for reading. * @c: UBIFS file-system description object * * This function returns %0 on success and a negative error code on failure. */ static int lpt_init_rd(struct ubifs_info *c) { int err, i; c->ltab = vmalloc(sizeof(struct ubifs_lpt_lprops) * c->lpt_lebs); if (!c->ltab) return -ENOMEM; i = max_t(int, c->nnode_sz, c->pnode_sz); c->lpt_nod_buf = kmalloc(i, GFP_KERNEL); if (!c->lpt_nod_buf) return -ENOMEM; for (i = 0; i < LPROPS_HEAP_CNT; i++) { c->lpt_heap[i].arr = kmalloc(sizeof(void *) * LPT_HEAP_SZ, GFP_KERNEL); if (!c->lpt_heap[i].arr) return -ENOMEM; c->lpt_heap[i].cnt = 0; c->lpt_heap[i].max_cnt = LPT_HEAP_SZ; } c->dirty_idx.arr = kmalloc(sizeof(void *) * LPT_HEAP_SZ, GFP_KERNEL); if (!c->dirty_idx.arr) return -ENOMEM; c->dirty_idx.cnt = 0; c->dirty_idx.max_cnt = LPT_HEAP_SZ; err = read_ltab(c); if (err) return err; dbg_lp("space_bits %d", c->space_bits); dbg_lp("lpt_lnum_bits %d", c->lpt_lnum_bits); dbg_lp("lpt_offs_bits %d", c->lpt_offs_bits); dbg_lp("lpt_spc_bits %d", c->lpt_spc_bits); dbg_lp("pcnt_bits %d", c->pcnt_bits); dbg_lp("lnum_bits %d", c->lnum_bits); dbg_lp("pnode_sz %d", c->pnode_sz); dbg_lp("nnode_sz %d", c->nnode_sz); dbg_lp("ltab_sz %d", c->ltab_sz); dbg_lp("lsave_sz %d", c->lsave_sz); dbg_lp("lsave_cnt %d", c->lsave_cnt); dbg_lp("lpt_hght %d", c->lpt_hght); dbg_lp("big_lpt %d", c->big_lpt); dbg_lp("LPT root is at %d:%d", c->lpt_lnum, c->lpt_offs); dbg_lp("LPT head is at %d:%d", c->nhead_lnum, c->nhead_offs); dbg_lp("LPT ltab is at %d:%d", c->ltab_lnum, c->ltab_offs); if (c->big_lpt) dbg_lp("LPT lsave is at %d:%d", c->lsave_lnum, c->lsave_offs); return 0; } /** * ubifs_lpt_init - initialize the LPT. * @c: UBIFS file-system description object * @rd: whether to initialize lpt for reading * @wr: whether to initialize lpt for writing * * For mounting 'rw', @rd and @wr are both true. For mounting 'ro', @rd is true * and @wr is false. For mounting from 'ro' to 'rw', @rd is false and @wr is * true. * * This function returns %0 on success and a negative error code on failure. */ int ubifs_lpt_init(struct ubifs_info *c, int rd, int wr) { int err; if (rd) { err = lpt_init_rd(c); if (err) return err; } return 0; }
1001-study-uboot
fs/ubifs/lpt.c
C
gpl3
30,115
/* * 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 contains journal replay code. It runs when the file-system is being * mounted and requires no locking. * * The larger is the journal, the longer it takes to scan it, so the longer it * takes to mount UBIFS. This is why the journal has limited size which may be * changed depending on the system requirements. But a larger journal gives * faster I/O speed because it writes the index less frequently. So this is a * trade-off. Also, the journal is indexed by the in-memory index (TNC), so the * larger is the journal, the more memory its index may consume. */ #include "ubifs.h" /* * Replay flags. * * REPLAY_DELETION: node was deleted * REPLAY_REF: node is a reference node */ enum { REPLAY_DELETION = 1, REPLAY_REF = 2, }; /** * struct replay_entry - replay tree entry. * @lnum: logical eraseblock number of the node * @offs: node offset * @len: node length * @sqnum: node sequence number * @flags: replay flags * @rb: links the replay tree * @key: node key * @nm: directory entry name * @old_size: truncation old size * @new_size: truncation new size * @free: amount of free space in a bud * @dirty: amount of dirty space in a bud from padding and deletion nodes * * UBIFS journal replay must compare node sequence numbers, which means it must * build a tree of node information to insert into the TNC. */ struct replay_entry { int lnum; int offs; int len; unsigned long long sqnum; int flags; struct rb_node rb; union ubifs_key key; union { struct qstr nm; struct { loff_t old_size; loff_t new_size; }; struct { int free; int dirty; }; }; }; /** * struct bud_entry - entry in the list of buds to replay. * @list: next bud in the list * @bud: bud description object * @free: free bytes in the bud * @sqnum: reference node sequence number */ struct bud_entry { struct list_head list; struct ubifs_bud *bud; int free; unsigned long long sqnum; }; /** * set_bud_lprops - set free and dirty space used by a bud. * @c: UBIFS file-system description object * @r: replay entry of bud */ static int set_bud_lprops(struct ubifs_info *c, struct replay_entry *r) { const struct ubifs_lprops *lp; int err = 0, dirty; ubifs_get_lprops(c); lp = ubifs_lpt_lookup_dirty(c, r->lnum); if (IS_ERR(lp)) { err = PTR_ERR(lp); goto out; } dirty = lp->dirty; if (r->offs == 0 && (lp->free != c->leb_size || lp->dirty != 0)) { /* * The LEB was added to the journal with a starting offset of * zero which means the LEB must have been empty. The LEB * property values should be lp->free == c->leb_size and * lp->dirty == 0, but that is not the case. The reason is that * the LEB was garbage collected. The garbage collector resets * the free and dirty space without recording it anywhere except * lprops, so if there is not a commit then lprops does not have * that information next time the file system is mounted. * * We do not need to adjust free space because the scan has told * us the exact value which is recorded in the replay entry as * r->free. * * However we do need to subtract from the dirty space the * amount of space that the garbage collector reclaimed, which * is the whole LEB minus the amount of space that was free. */ dbg_mnt("bud LEB %d was GC'd (%d free, %d dirty)", r->lnum, lp->free, lp->dirty); dbg_gc("bud LEB %d was GC'd (%d free, %d dirty)", r->lnum, lp->free, lp->dirty); dirty -= c->leb_size - lp->free; /* * If the replay order was perfect the dirty space would now be * zero. The order is not perfect because the the journal heads * race with each other. This is not a problem but is does mean * that the dirty space may temporarily exceed c->leb_size * during the replay. */ if (dirty != 0) dbg_msg("LEB %d lp: %d free %d dirty " "replay: %d free %d dirty", r->lnum, lp->free, lp->dirty, r->free, r->dirty); } lp = ubifs_change_lp(c, lp, r->free, dirty + r->dirty, lp->flags | LPROPS_TAKEN, 0); if (IS_ERR(lp)) { err = PTR_ERR(lp); goto out; } out: ubifs_release_lprops(c); return err; } /** * trun_remove_range - apply a replay entry for a truncation to the TNC. * @c: UBIFS file-system description object * @r: replay entry of truncation */ static int trun_remove_range(struct ubifs_info *c, struct replay_entry *r) { unsigned min_blk, max_blk; union ubifs_key min_key, max_key; ino_t ino; min_blk = r->new_size / UBIFS_BLOCK_SIZE; if (r->new_size & (UBIFS_BLOCK_SIZE - 1)) min_blk += 1; max_blk = r->old_size / UBIFS_BLOCK_SIZE; if ((r->old_size & (UBIFS_BLOCK_SIZE - 1)) == 0) max_blk -= 1; ino = key_inum(c, &r->key); data_key_init(c, &min_key, ino, min_blk); data_key_init(c, &max_key, ino, max_blk); return ubifs_tnc_remove_range(c, &min_key, &max_key); } /** * apply_replay_entry - apply a replay entry to the TNC. * @c: UBIFS file-system description object * @r: replay entry to apply * * Apply a replay entry to the TNC. */ static int apply_replay_entry(struct ubifs_info *c, struct replay_entry *r) { int err, deletion = ((r->flags & REPLAY_DELETION) != 0); dbg_mnt("LEB %d:%d len %d flgs %d sqnum %llu %s", r->lnum, r->offs, r->len, r->flags, r->sqnum, DBGKEY(&r->key)); /* Set c->replay_sqnum to help deal with dangling branches. */ c->replay_sqnum = r->sqnum; if (r->flags & REPLAY_REF) err = set_bud_lprops(c, r); else if (is_hash_key(c, &r->key)) { if (deletion) err = ubifs_tnc_remove_nm(c, &r->key, &r->nm); else err = ubifs_tnc_add_nm(c, &r->key, r->lnum, r->offs, r->len, &r->nm); } else { if (deletion) switch (key_type(c, &r->key)) { case UBIFS_INO_KEY: { ino_t inum = key_inum(c, &r->key); err = ubifs_tnc_remove_ino(c, inum); break; } case UBIFS_TRUN_KEY: err = trun_remove_range(c, r); break; default: err = ubifs_tnc_remove(c, &r->key); break; } else err = ubifs_tnc_add(c, &r->key, r->lnum, r->offs, r->len); if (err) return err; if (c->need_recovery) err = ubifs_recover_size_accum(c, &r->key, deletion, r->new_size); } return err; } /** * destroy_replay_tree - destroy the replay. * @c: UBIFS file-system description object * * Destroy the replay tree. */ static void destroy_replay_tree(struct ubifs_info *c) { struct rb_node *this = c->replay_tree.rb_node; struct replay_entry *r; while (this) { if (this->rb_left) { this = this->rb_left; continue; } else if (this->rb_right) { this = this->rb_right; continue; } r = rb_entry(this, struct replay_entry, rb); this = rb_parent(this); if (this) { if (this->rb_left == &r->rb) this->rb_left = NULL; else this->rb_right = NULL; } if (is_hash_key(c, &r->key)) kfree((void *)r->nm.name); kfree(r); } c->replay_tree = RB_ROOT; } /** * apply_replay_tree - apply the replay tree to the TNC. * @c: UBIFS file-system description object * * Apply the replay tree. * Returns zero in case of success and a negative error code in case of * failure. */ static int apply_replay_tree(struct ubifs_info *c) { struct rb_node *this = rb_first(&c->replay_tree); while (this) { struct replay_entry *r; int err; cond_resched(); r = rb_entry(this, struct replay_entry, rb); err = apply_replay_entry(c, r); if (err) return err; this = rb_next(this); } return 0; } /** * insert_node - insert a node to the replay tree. * @c: UBIFS file-system description object * @lnum: node logical eraseblock number * @offs: node offset * @len: node length * @key: node key * @sqnum: sequence number * @deletion: non-zero if this is a deletion * @used: number of bytes in use in a LEB * @old_size: truncation old size * @new_size: truncation new size * * This function inserts a scanned non-direntry node to the replay tree. The * replay tree is an RB-tree containing @struct replay_entry elements which are * indexed by the sequence number. The replay tree is applied at the very end * of the replay process. Since the tree is sorted in sequence number order, * the older modifications are applied first. This function returns zero in * case of success and a negative error code in case of failure. */ static int insert_node(struct ubifs_info *c, int lnum, int offs, int len, union ubifs_key *key, unsigned long long sqnum, int deletion, int *used, loff_t old_size, loff_t new_size) { struct rb_node **p = &c->replay_tree.rb_node, *parent = NULL; struct replay_entry *r; if (key_inum(c, key) >= c->highest_inum) c->highest_inum = key_inum(c, key); dbg_mnt("add LEB %d:%d, key %s", lnum, offs, DBGKEY(key)); while (*p) { parent = *p; r = rb_entry(parent, struct replay_entry, rb); if (sqnum < r->sqnum) { p = &(*p)->rb_left; continue; } else if (sqnum > r->sqnum) { p = &(*p)->rb_right; continue; } ubifs_err("duplicate sqnum in replay"); return -EINVAL; } r = kzalloc(sizeof(struct replay_entry), GFP_KERNEL); if (!r) return -ENOMEM; if (!deletion) *used += ALIGN(len, 8); r->lnum = lnum; r->offs = offs; r->len = len; r->sqnum = sqnum; r->flags = (deletion ? REPLAY_DELETION : 0); r->old_size = old_size; r->new_size = new_size; key_copy(c, key, &r->key); rb_link_node(&r->rb, parent, p); rb_insert_color(&r->rb, &c->replay_tree); return 0; } /** * insert_dent - insert a directory entry node into the replay tree. * @c: UBIFS file-system description object * @lnum: node logical eraseblock number * @offs: node offset * @len: node length * @key: node key * @name: directory entry name * @nlen: directory entry name length * @sqnum: sequence number * @deletion: non-zero if this is a deletion * @used: number of bytes in use in a LEB * * This function inserts a scanned directory entry node to the replay tree. * Returns zero in case of success and a negative error code in case of * failure. * * This function is also used for extended attribute entries because they are * implemented as directory entry nodes. */ static int insert_dent(struct ubifs_info *c, int lnum, int offs, int len, union ubifs_key *key, const char *name, int nlen, unsigned long long sqnum, int deletion, int *used) { struct rb_node **p = &c->replay_tree.rb_node, *parent = NULL; struct replay_entry *r; char *nbuf; if (key_inum(c, key) >= c->highest_inum) c->highest_inum = key_inum(c, key); dbg_mnt("add LEB %d:%d, key %s", lnum, offs, DBGKEY(key)); while (*p) { parent = *p; r = rb_entry(parent, struct replay_entry, rb); if (sqnum < r->sqnum) { p = &(*p)->rb_left; continue; } if (sqnum > r->sqnum) { p = &(*p)->rb_right; continue; } ubifs_err("duplicate sqnum in replay"); return -EINVAL; } r = kzalloc(sizeof(struct replay_entry), GFP_KERNEL); if (!r) return -ENOMEM; nbuf = kmalloc(nlen + 1, GFP_KERNEL); if (!nbuf) { kfree(r); return -ENOMEM; } if (!deletion) *used += ALIGN(len, 8); r->lnum = lnum; r->offs = offs; r->len = len; r->sqnum = sqnum; r->nm.len = nlen; memcpy(nbuf, name, nlen); nbuf[nlen] = '\0'; r->nm.name = nbuf; r->flags = (deletion ? REPLAY_DELETION : 0); key_copy(c, key, &r->key); ubifs_assert(!*p); rb_link_node(&r->rb, parent, p); rb_insert_color(&r->rb, &c->replay_tree); return 0; } /** * ubifs_validate_entry - validate directory or extended attribute entry node. * @c: UBIFS file-system description object * @dent: the node to validate * * This function validates directory or extended attribute entry node @dent. * Returns zero if the node is all right and a %-EINVAL if not. */ int ubifs_validate_entry(struct ubifs_info *c, const struct ubifs_dent_node *dent) { int key_type = key_type_flash(c, dent->key); int nlen = le16_to_cpu(dent->nlen); if (le32_to_cpu(dent->ch.len) != nlen + UBIFS_DENT_NODE_SZ + 1 || dent->type >= UBIFS_ITYPES_CNT || nlen > UBIFS_MAX_NLEN || dent->name[nlen] != 0 || strnlen((char *)dent->name, nlen) != nlen || le64_to_cpu(dent->inum) > MAX_INUM) { ubifs_err("bad %s node", key_type == UBIFS_DENT_KEY ? "directory entry" : "extended attribute entry"); return -EINVAL; } if (key_type != UBIFS_DENT_KEY && key_type != UBIFS_XENT_KEY) { ubifs_err("bad key type %d", key_type); return -EINVAL; } return 0; } /** * replay_bud - replay a bud logical eraseblock. * @c: UBIFS file-system description object * @lnum: bud logical eraseblock number to replay * @offs: bud start offset * @jhead: journal head to which this bud belongs * @free: amount of free space in the bud is returned here * @dirty: amount of dirty space from padding and deletion nodes is returned * here * * This function returns zero in case of success and a negative error code in * case of failure. */ static int replay_bud(struct ubifs_info *c, int lnum, int offs, int jhead, int *free, int *dirty) { int err = 0, used = 0; struct ubifs_scan_leb *sleb; struct ubifs_scan_node *snod; struct ubifs_bud *bud; dbg_mnt("replay bud LEB %d, head %d", lnum, jhead); if (c->need_recovery) sleb = ubifs_recover_leb(c, lnum, offs, c->sbuf, jhead != GCHD); else sleb = ubifs_scan(c, lnum, offs, c->sbuf); if (IS_ERR(sleb)) return PTR_ERR(sleb); /* * The bud does not have to start from offset zero - the beginning of * the 'lnum' LEB may contain previously committed data. One of the * things we have to do in replay is to correctly update lprops with * newer information about this LEB. * * At this point lprops thinks that this LEB has 'c->leb_size - offs' * bytes of free space because it only contain information about * committed data. * * But we know that real amount of free space is 'c->leb_size - * sleb->endpt', and the space in the 'lnum' LEB between 'offs' and * 'sleb->endpt' is used by bud data. We have to correctly calculate * how much of these data are dirty and update lprops with this * information. * * The dirt in that LEB region is comprised of padding nodes, deletion * nodes, truncation nodes and nodes which are obsoleted by subsequent * nodes in this LEB. So instead of calculating clean space, we * calculate used space ('used' variable). */ list_for_each_entry(snod, &sleb->nodes, list) { int deletion = 0; cond_resched(); if (snod->sqnum >= SQNUM_WATERMARK) { ubifs_err("file system's life ended"); goto out_dump; } if (snod->sqnum > c->max_sqnum) c->max_sqnum = snod->sqnum; switch (snod->type) { case UBIFS_INO_NODE: { struct ubifs_ino_node *ino = snod->node; loff_t new_size = le64_to_cpu(ino->size); if (le32_to_cpu(ino->nlink) == 0) deletion = 1; err = insert_node(c, lnum, snod->offs, snod->len, &snod->key, snod->sqnum, deletion, &used, 0, new_size); break; } case UBIFS_DATA_NODE: { struct ubifs_data_node *dn = snod->node; loff_t new_size = le32_to_cpu(dn->size) + key_block(c, &snod->key) * UBIFS_BLOCK_SIZE; err = insert_node(c, lnum, snod->offs, snod->len, &snod->key, snod->sqnum, deletion, &used, 0, new_size); break; } case UBIFS_DENT_NODE: case UBIFS_XENT_NODE: { struct ubifs_dent_node *dent = snod->node; err = ubifs_validate_entry(c, dent); if (err) goto out_dump; err = insert_dent(c, lnum, snod->offs, snod->len, &snod->key, (char *)dent->name, le16_to_cpu(dent->nlen), snod->sqnum, !le64_to_cpu(dent->inum), &used); break; } case UBIFS_TRUN_NODE: { struct ubifs_trun_node *trun = snod->node; loff_t old_size = le64_to_cpu(trun->old_size); loff_t new_size = le64_to_cpu(trun->new_size); union ubifs_key key; /* Validate truncation node */ if (old_size < 0 || old_size > c->max_inode_sz || new_size < 0 || new_size > c->max_inode_sz || old_size <= new_size) { ubifs_err("bad truncation node"); goto out_dump; } /* * Create a fake truncation key just to use the same * functions which expect nodes to have keys. */ trun_key_init(c, &key, le32_to_cpu(trun->inum)); err = insert_node(c, lnum, snod->offs, snod->len, &key, snod->sqnum, 1, &used, old_size, new_size); break; } default: ubifs_err("unexpected node type %d in bud LEB %d:%d", snod->type, lnum, snod->offs); err = -EINVAL; goto out_dump; } if (err) goto out; } bud = ubifs_search_bud(c, lnum); if (!bud) BUG(); ubifs_assert(sleb->endpt - offs >= used); ubifs_assert(sleb->endpt % c->min_io_size == 0); *dirty = sleb->endpt - offs - used; *free = c->leb_size - sleb->endpt; out: ubifs_scan_destroy(sleb); return err; out_dump: ubifs_err("bad node is at LEB %d:%d", lnum, snod->offs); dbg_dump_node(c, snod->node); ubifs_scan_destroy(sleb); return -EINVAL; } /** * insert_ref_node - insert a reference node to the replay tree. * @c: UBIFS file-system description object * @lnum: node logical eraseblock number * @offs: node offset * @sqnum: sequence number * @free: amount of free space in bud * @dirty: amount of dirty space from padding and deletion nodes * * This function inserts a reference node to the replay tree and returns zero * in case of success or a negative error code in case of failure. */ static int insert_ref_node(struct ubifs_info *c, int lnum, int offs, unsigned long long sqnum, int free, int dirty) { struct rb_node **p = &c->replay_tree.rb_node, *parent = NULL; struct replay_entry *r; dbg_mnt("add ref LEB %d:%d", lnum, offs); while (*p) { parent = *p; r = rb_entry(parent, struct replay_entry, rb); if (sqnum < r->sqnum) { p = &(*p)->rb_left; continue; } else if (sqnum > r->sqnum) { p = &(*p)->rb_right; continue; } ubifs_err("duplicate sqnum in replay tree"); return -EINVAL; } r = kzalloc(sizeof(struct replay_entry), GFP_KERNEL); if (!r) return -ENOMEM; r->lnum = lnum; r->offs = offs; r->sqnum = sqnum; r->flags = REPLAY_REF; r->free = free; r->dirty = dirty; rb_link_node(&r->rb, parent, p); rb_insert_color(&r->rb, &c->replay_tree); return 0; } /** * replay_buds - replay all buds. * @c: UBIFS file-system description object * * This function returns zero in case of success and a negative error code in * case of failure. */ static int replay_buds(struct ubifs_info *c) { struct bud_entry *b; int err, uninitialized_var(free), uninitialized_var(dirty); list_for_each_entry(b, &c->replay_buds, list) { err = replay_bud(c, b->bud->lnum, b->bud->start, b->bud->jhead, &free, &dirty); if (err) return err; err = insert_ref_node(c, b->bud->lnum, b->bud->start, b->sqnum, free, dirty); if (err) return err; } return 0; } /** * destroy_bud_list - destroy the list of buds to replay. * @c: UBIFS file-system description object */ static void destroy_bud_list(struct ubifs_info *c) { struct bud_entry *b; while (!list_empty(&c->replay_buds)) { b = list_entry(c->replay_buds.next, struct bud_entry, list); list_del(&b->list); kfree(b); } } /** * add_replay_bud - add a bud to the list of buds to replay. * @c: UBIFS file-system description object * @lnum: bud logical eraseblock number to replay * @offs: bud start offset * @jhead: journal head to which this bud belongs * @sqnum: reference node sequence number * * This function returns zero in case of success and a negative error code in * case of failure. */ static int add_replay_bud(struct ubifs_info *c, int lnum, int offs, int jhead, unsigned long long sqnum) { struct ubifs_bud *bud; struct bud_entry *b; dbg_mnt("add replay bud LEB %d:%d, head %d", lnum, offs, jhead); bud = kmalloc(sizeof(struct ubifs_bud), GFP_KERNEL); if (!bud) return -ENOMEM; b = kmalloc(sizeof(struct bud_entry), GFP_KERNEL); if (!b) { kfree(bud); return -ENOMEM; } bud->lnum = lnum; bud->start = offs; bud->jhead = jhead; ubifs_add_bud(c, bud); b->bud = bud; b->sqnum = sqnum; list_add_tail(&b->list, &c->replay_buds); return 0; } /** * validate_ref - validate a reference node. * @c: UBIFS file-system description object * @ref: the reference node to validate * @ref_lnum: LEB number of the reference node * @ref_offs: reference node offset * * This function returns %1 if a bud reference already exists for the LEB. %0 is * returned if the reference node is new, otherwise %-EINVAL is returned if * validation failed. */ static int validate_ref(struct ubifs_info *c, const struct ubifs_ref_node *ref) { struct ubifs_bud *bud; int lnum = le32_to_cpu(ref->lnum); unsigned int offs = le32_to_cpu(ref->offs); unsigned int jhead = le32_to_cpu(ref->jhead); /* * ref->offs may point to the end of LEB when the journal head points * to the end of LEB and we write reference node for it during commit. * So this is why we require 'offs > c->leb_size'. */ if (jhead >= c->jhead_cnt || lnum >= c->leb_cnt || lnum < c->main_first || offs > c->leb_size || offs & (c->min_io_size - 1)) return -EINVAL; /* Make sure we have not already looked at this bud */ bud = ubifs_search_bud(c, lnum); if (bud) { if (bud->jhead == jhead && bud->start <= offs) return 1; ubifs_err("bud at LEB %d:%d was already referred", lnum, offs); return -EINVAL; } return 0; } /** * replay_log_leb - replay a log logical eraseblock. * @c: UBIFS file-system description object * @lnum: log logical eraseblock to replay * @offs: offset to start replaying from * @sbuf: scan buffer * * This function replays a log LEB and returns zero in case of success, %1 if * this is the last LEB in the log, and a negative error code in case of * failure. */ static int replay_log_leb(struct ubifs_info *c, int lnum, int offs, void *sbuf) { int err; struct ubifs_scan_leb *sleb; struct ubifs_scan_node *snod; const struct ubifs_cs_node *node; dbg_mnt("replay log LEB %d:%d", lnum, offs); sleb = ubifs_scan(c, lnum, offs, sbuf); if (IS_ERR(sleb)) { if (c->need_recovery) sleb = ubifs_recover_log_leb(c, lnum, offs, sbuf); if (IS_ERR(sleb)) return PTR_ERR(sleb); } if (sleb->nodes_cnt == 0) { err = 1; goto out; } node = sleb->buf; snod = list_entry(sleb->nodes.next, struct ubifs_scan_node, list); if (c->cs_sqnum == 0) { /* * This is the first log LEB we are looking at, make sure that * the first node is a commit start node. Also record its * sequence number so that UBIFS can determine where the log * ends, because all nodes which were have higher sequence * numbers. */ if (snod->type != UBIFS_CS_NODE) { dbg_err("first log node at LEB %d:%d is not CS node", lnum, offs); goto out_dump; } if (le64_to_cpu(node->cmt_no) != c->cmt_no) { dbg_err("first CS node at LEB %d:%d has wrong " "commit number %llu expected %llu", lnum, offs, (unsigned long long)le64_to_cpu(node->cmt_no), c->cmt_no); goto out_dump; } c->cs_sqnum = le64_to_cpu(node->ch.sqnum); dbg_mnt("commit start sqnum %llu", c->cs_sqnum); } if (snod->sqnum < c->cs_sqnum) { /* * This means that we reached end of log and now * look to the older log data, which was already * committed but the eraseblock was not erased (UBIFS * only un-maps it). So this basically means we have to * exit with "end of log" code. */ err = 1; goto out; } /* Make sure the first node sits at offset zero of the LEB */ if (snod->offs != 0) { dbg_err("first node is not at zero offset"); goto out_dump; } list_for_each_entry(snod, &sleb->nodes, list) { cond_resched(); if (snod->sqnum >= SQNUM_WATERMARK) { ubifs_err("file system's life ended"); goto out_dump; } if (snod->sqnum < c->cs_sqnum) { dbg_err("bad sqnum %llu, commit sqnum %llu", snod->sqnum, c->cs_sqnum); goto out_dump; } if (snod->sqnum > c->max_sqnum) c->max_sqnum = snod->sqnum; switch (snod->type) { case UBIFS_REF_NODE: { const struct ubifs_ref_node *ref = snod->node; err = validate_ref(c, ref); if (err == 1) break; /* Already have this bud */ if (err) goto out_dump; err = add_replay_bud(c, le32_to_cpu(ref->lnum), le32_to_cpu(ref->offs), le32_to_cpu(ref->jhead), snod->sqnum); if (err) goto out; break; } case UBIFS_CS_NODE: /* Make sure it sits at the beginning of LEB */ if (snod->offs != 0) { ubifs_err("unexpected node in log"); goto out_dump; } break; default: ubifs_err("unexpected node in log"); goto out_dump; } } if (sleb->endpt || c->lhead_offs >= c->leb_size) { c->lhead_lnum = lnum; c->lhead_offs = sleb->endpt; } err = !sleb->endpt; out: ubifs_scan_destroy(sleb); return err; out_dump: ubifs_err("log error detected while replying the log at LEB %d:%d", lnum, offs + snod->offs); dbg_dump_node(c, snod->node); ubifs_scan_destroy(sleb); return -EINVAL; } /** * take_ihead - update the status of the index head in lprops to 'taken'. * @c: UBIFS file-system description object * * This function returns the amount of free space in the index head LEB or a * negative error code. */ static int take_ihead(struct ubifs_info *c) { const struct ubifs_lprops *lp; int err, free; ubifs_get_lprops(c); lp = ubifs_lpt_lookup_dirty(c, c->ihead_lnum); if (IS_ERR(lp)) { err = PTR_ERR(lp); goto out; } free = lp->free; lp = ubifs_change_lp(c, lp, LPROPS_NC, LPROPS_NC, lp->flags | LPROPS_TAKEN, 0); if (IS_ERR(lp)) { err = PTR_ERR(lp); goto out; } err = free; out: ubifs_release_lprops(c); return err; } /** * ubifs_replay_journal - replay journal. * @c: UBIFS file-system description object * * This function scans the journal, replays and cleans it up. It makes sure all * memory data structures related to uncommitted journal are built (dirty TNC * tree, tree of buds, modified lprops, etc). */ int ubifs_replay_journal(struct ubifs_info *c) { int err, i, lnum, offs, _free; void *sbuf = NULL; BUILD_BUG_ON(UBIFS_TRUN_KEY > 5); /* Update the status of the index head in lprops to 'taken' */ _free = take_ihead(c); if (_free < 0) return _free; /* Error code */ if (c->ihead_offs != c->leb_size - _free) { ubifs_err("bad index head LEB %d:%d", c->ihead_lnum, c->ihead_offs); return -EINVAL; } sbuf = vmalloc(c->leb_size); if (!sbuf) return -ENOMEM; dbg_mnt("start replaying the journal"); c->replaying = 1; lnum = c->ltail_lnum = c->lhead_lnum; offs = c->lhead_offs; for (i = 0; i < c->log_lebs; i++, lnum++) { if (lnum >= UBIFS_LOG_LNUM + c->log_lebs) { /* * The log is logically circular, we reached the last * LEB, switch to the first one. */ lnum = UBIFS_LOG_LNUM; offs = 0; } err = replay_log_leb(c, lnum, offs, sbuf); if (err == 1) /* We hit the end of the log */ break; if (err) goto out; offs = 0; } err = replay_buds(c); if (err) goto out; err = apply_replay_tree(c); if (err) goto out; ubifs_assert(c->bud_bytes <= c->max_bud_bytes || c->need_recovery); dbg_mnt("finished, log head LEB %d:%d, max_sqnum %llu, " "highest_inum %lu", c->lhead_lnum, c->lhead_offs, c->max_sqnum, (unsigned long)c->highest_inum); out: destroy_replay_tree(c); destroy_bud_list(c); vfree(sbuf); c->replaying = 0; return err; }
1001-study-uboot
fs/ubifs/replay.c
C
gpl3
28,107
/* * 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 functions needed to recover from unclean un-mounts. * When UBIFS is mounted, it checks a flag on the master node to determine if * an un-mount was completed sucessfully. If not, the process of mounting * incorparates additional checking and fixing of on-flash data structures. * UBIFS always cleans away all remnants of an unclean un-mount, so that * errors do not accumulate. However UBIFS defers recovery if it is mounted * read-only, and the flash is not modified in that case. */ #include "ubifs.h" /** * is_empty - determine whether a buffer is empty (contains all 0xff). * @buf: buffer to clean * @len: length of buffer * * This function returns %1 if the buffer is empty (contains all 0xff) otherwise * %0 is returned. */ static int is_empty(void *buf, int len) { uint8_t *p = buf; int i; for (i = 0; i < len; i++) if (*p++ != 0xff) return 0; return 1; } /** * get_master_node - get the last valid master node allowing for corruption. * @c: UBIFS file-system description object * @lnum: LEB number * @pbuf: buffer containing the LEB read, is returned here * @mst: master node, if found, is returned here * @cor: corruption, if found, is returned here * * This function allocates a buffer, reads the LEB into it, and finds and * returns the last valid master node allowing for one area of corruption. * The corrupt area, if there is one, must be consistent with the assumption * that it is the result of an unclean unmount while the master node was being * written. Under those circumstances, it is valid to use the previously written * master node. * * This function returns %0 on success and a negative error code on failure. */ static int get_master_node(const struct ubifs_info *c, int lnum, void **pbuf, struct ubifs_mst_node **mst, void **cor) { const int sz = c->mst_node_alsz; int err, offs, len; void *sbuf, *buf; sbuf = vmalloc(c->leb_size); if (!sbuf) return -ENOMEM; err = ubi_read(c->ubi, lnum, sbuf, 0, c->leb_size); if (err && err != -EBADMSG) goto out_free; /* Find the first position that is definitely not a node */ offs = 0; buf = sbuf; len = c->leb_size; while (offs + UBIFS_MST_NODE_SZ <= c->leb_size) { struct ubifs_ch *ch = buf; if (le32_to_cpu(ch->magic) != UBIFS_NODE_MAGIC) break; offs += sz; buf += sz; len -= sz; } /* See if there was a valid master node before that */ if (offs) { int ret; offs -= sz; buf -= sz; len += sz; ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1); if (ret != SCANNED_A_NODE && offs) { /* Could have been corruption so check one place back */ offs -= sz; buf -= sz; len += sz; ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1); if (ret != SCANNED_A_NODE) /* * We accept only one area of corruption because * we are assuming that it was caused while * trying to write a master node. */ goto out_err; } if (ret == SCANNED_A_NODE) { struct ubifs_ch *ch = buf; if (ch->node_type != UBIFS_MST_NODE) goto out_err; dbg_rcvry("found a master node at %d:%d", lnum, offs); *mst = buf; offs += sz; buf += sz; len -= sz; } } /* Check for corruption */ if (offs < c->leb_size) { if (!is_empty(buf, min_t(int, len, sz))) { *cor = buf; dbg_rcvry("found corruption at %d:%d", lnum, offs); } offs += sz; buf += sz; len -= sz; } /* Check remaining empty space */ if (offs < c->leb_size) if (!is_empty(buf, len)) goto out_err; *pbuf = sbuf; return 0; out_err: err = -EINVAL; out_free: vfree(sbuf); *mst = NULL; *cor = NULL; return err; } /** * write_rcvrd_mst_node - write recovered master node. * @c: UBIFS file-system description object * @mst: master node * * This function returns %0 on success and a negative error code on failure. */ static int write_rcvrd_mst_node(struct ubifs_info *c, struct ubifs_mst_node *mst) { int err = 0, lnum = UBIFS_MST_LNUM, sz = c->mst_node_alsz; __le32 save_flags; dbg_rcvry("recovery"); save_flags = mst->flags; mst->flags |= cpu_to_le32(UBIFS_MST_RCVRY); ubifs_prepare_node(c, mst, UBIFS_MST_NODE_SZ, 1); err = ubi_leb_change(c->ubi, lnum, mst, sz, UBI_SHORTTERM); if (err) goto out; err = ubi_leb_change(c->ubi, lnum + 1, mst, sz, UBI_SHORTTERM); if (err) goto out; out: mst->flags = save_flags; return err; } /** * ubifs_recover_master_node - recover the master node. * @c: UBIFS file-system description object * * This function recovers the master node from corruption that may occur due to * an unclean unmount. * * This function returns %0 on success and a negative error code on failure. */ int ubifs_recover_master_node(struct ubifs_info *c) { void *buf1 = NULL, *buf2 = NULL, *cor1 = NULL, *cor2 = NULL; struct ubifs_mst_node *mst1 = NULL, *mst2 = NULL, *mst; const int sz = c->mst_node_alsz; int err, offs1, offs2; dbg_rcvry("recovery"); err = get_master_node(c, UBIFS_MST_LNUM, &buf1, &mst1, &cor1); if (err) goto out_free; err = get_master_node(c, UBIFS_MST_LNUM + 1, &buf2, &mst2, &cor2); if (err) goto out_free; if (mst1) { offs1 = (void *)mst1 - buf1; if ((le32_to_cpu(mst1->flags) & UBIFS_MST_RCVRY) && (offs1 == 0 && !cor1)) { /* * mst1 was written by recovery at offset 0 with no * corruption. */ dbg_rcvry("recovery recovery"); mst = mst1; } else if (mst2) { offs2 = (void *)mst2 - buf2; if (offs1 == offs2) { /* Same offset, so must be the same */ if (memcmp((void *)mst1 + UBIFS_CH_SZ, (void *)mst2 + UBIFS_CH_SZ, UBIFS_MST_NODE_SZ - UBIFS_CH_SZ)) goto out_err; mst = mst1; } else if (offs2 + sz == offs1) { /* 1st LEB was written, 2nd was not */ if (cor1) goto out_err; mst = mst1; } else if (offs1 == 0 && offs2 + sz >= c->leb_size) { /* 1st LEB was unmapped and written, 2nd not */ if (cor1) goto out_err; mst = mst1; } else goto out_err; } else { /* * 2nd LEB was unmapped and about to be written, so * there must be only one master node in the first LEB * and no corruption. */ if (offs1 != 0 || cor1) goto out_err; mst = mst1; } } else { if (!mst2) goto out_err; /* * 1st LEB was unmapped and about to be written, so there must * be no room left in 2nd LEB. */ offs2 = (void *)mst2 - buf2; if (offs2 + sz + sz <= c->leb_size) goto out_err; mst = mst2; } dbg_rcvry("recovered master node from LEB %d", (mst == mst1 ? UBIFS_MST_LNUM : UBIFS_MST_LNUM + 1)); memcpy(c->mst_node, mst, UBIFS_MST_NODE_SZ); if ((c->vfs_sb->s_flags & MS_RDONLY)) { /* Read-only mode. Keep a copy for switching to rw mode */ c->rcvrd_mst_node = kmalloc(sz, GFP_KERNEL); if (!c->rcvrd_mst_node) { err = -ENOMEM; goto out_free; } memcpy(c->rcvrd_mst_node, c->mst_node, UBIFS_MST_NODE_SZ); } vfree(buf2); vfree(buf1); return 0; out_err: err = -EINVAL; out_free: ubifs_err("failed to recover master node"); if (mst1) { dbg_err("dumping first master node"); dbg_dump_node(c, mst1); } if (mst2) { dbg_err("dumping second master node"); dbg_dump_node(c, mst2); } vfree(buf2); vfree(buf1); return err; } /** * ubifs_write_rcvrd_mst_node - write the recovered master node. * @c: UBIFS file-system description object * * This function writes the master node that was recovered during mounting in * read-only mode and must now be written because we are remounting rw. * * This function returns %0 on success and a negative error code on failure. */ int ubifs_write_rcvrd_mst_node(struct ubifs_info *c) { int err; if (!c->rcvrd_mst_node) return 0; c->rcvrd_mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY); c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY); err = write_rcvrd_mst_node(c, c->rcvrd_mst_node); if (err) return err; kfree(c->rcvrd_mst_node); c->rcvrd_mst_node = NULL; return 0; } /** * is_last_write - determine if an offset was in the last write to a LEB. * @c: UBIFS file-system description object * @buf: buffer to check * @offs: offset to check * * This function returns %1 if @offs was in the last write to the LEB whose data * is in @buf, otherwise %0 is returned. The determination is made by checking * for subsequent empty space starting from the next min_io_size boundary (or a * bit less than the common header size if min_io_size is one). */ static int is_last_write(const struct ubifs_info *c, void *buf, int offs) { int empty_offs; int check_len; uint8_t *p; if (c->min_io_size == 1) { check_len = c->leb_size - offs; p = buf + check_len; for (; check_len > 0; check_len--) if (*--p != 0xff) break; /* * 'check_len' is the size of the corruption which cannot be * more than the size of 1 node if it was caused by an unclean * unmount. */ if (check_len > UBIFS_MAX_NODE_SZ) return 0; return 1; } /* * Round up to the next c->min_io_size boundary i.e. 'offs' is in the * last wbuf written. After that should be empty space. */ empty_offs = ALIGN(offs + 1, c->min_io_size); check_len = c->leb_size - empty_offs; p = buf + empty_offs - offs; for (; check_len > 0; check_len--) if (*p++ != 0xff) return 0; return 1; } /** * clean_buf - clean the data from an LEB sitting in a buffer. * @c: UBIFS file-system description object * @buf: buffer to clean * @lnum: LEB number to clean * @offs: offset from which to clean * @len: length of buffer * * This function pads up to the next min_io_size boundary (if there is one) and * sets empty space to all 0xff. @buf, @offs and @len are updated to the next * min_io_size boundary (if there is one). */ static void clean_buf(const struct ubifs_info *c, void **buf, int lnum, int *offs, int *len) { int empty_offs, pad_len; lnum = lnum; dbg_rcvry("cleaning corruption at %d:%d", lnum, *offs); if (c->min_io_size == 1) { memset(*buf, 0xff, c->leb_size - *offs); return; } ubifs_assert(!(*offs & 7)); empty_offs = ALIGN(*offs, c->min_io_size); pad_len = empty_offs - *offs; ubifs_pad(c, *buf, pad_len); *offs += pad_len; *buf += pad_len; *len -= pad_len; memset(*buf, 0xff, c->leb_size - empty_offs); } /** * no_more_nodes - determine if there are no more nodes in a buffer. * @c: UBIFS file-system description object * @buf: buffer to check * @len: length of buffer * @lnum: LEB number of the LEB from which @buf was read * @offs: offset from which @buf was read * * This function ensures that the corrupted node at @offs is the last thing * written to a LEB. This function returns %1 if more data is not found and * %0 if more data is found. */ static int no_more_nodes(const struct ubifs_info *c, void *buf, int len, int lnum, int offs) { struct ubifs_ch *ch = buf; int skip, dlen = le32_to_cpu(ch->len); /* Check for empty space after the corrupt node's common header */ skip = ALIGN(offs + UBIFS_CH_SZ, c->min_io_size) - offs; if (is_empty(buf + skip, len - skip)) return 1; /* * The area after the common header size is not empty, so the common * header must be intact. Check it. */ if (ubifs_check_node(c, buf, lnum, offs, 1, 0) != -EUCLEAN) { dbg_rcvry("unexpected bad common header at %d:%d", lnum, offs); return 0; } /* Now we know the corrupt node's length we can skip over it */ skip = ALIGN(offs + dlen, c->min_io_size) - offs; /* After which there should be empty space */ if (is_empty(buf + skip, len - skip)) return 1; dbg_rcvry("unexpected data at %d:%d", lnum, offs + skip); return 0; } /** * fix_unclean_leb - fix an unclean LEB. * @c: UBIFS file-system description object * @sleb: scanned LEB information * @start: offset where scan started */ static int fix_unclean_leb(struct ubifs_info *c, struct ubifs_scan_leb *sleb, int start) { int lnum = sleb->lnum, endpt = start; /* Get the end offset of the last node we are keeping */ if (!list_empty(&sleb->nodes)) { struct ubifs_scan_node *snod; snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node, list); endpt = snod->offs + snod->len; } if ((c->vfs_sb->s_flags & MS_RDONLY) && !c->remounting_rw) { /* Add to recovery list */ struct ubifs_unclean_leb *ucleb; dbg_rcvry("need to fix LEB %d start %d endpt %d", lnum, start, sleb->endpt); ucleb = kzalloc(sizeof(struct ubifs_unclean_leb), GFP_NOFS); if (!ucleb) return -ENOMEM; ucleb->lnum = lnum; ucleb->endpt = endpt; list_add_tail(&ucleb->list, &c->unclean_leb_list); } return 0; } /** * drop_incomplete_group - drop nodes from an incomplete group. * @sleb: scanned LEB information * @offs: offset of dropped nodes is returned here * * This function returns %1 if nodes are dropped and %0 otherwise. */ static int drop_incomplete_group(struct ubifs_scan_leb *sleb, int *offs) { int dropped = 0; while (!list_empty(&sleb->nodes)) { struct ubifs_scan_node *snod; struct ubifs_ch *ch; snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node, list); ch = snod->node; if (ch->group_type != UBIFS_IN_NODE_GROUP) return dropped; dbg_rcvry("dropping node at %d:%d", sleb->lnum, snod->offs); *offs = snod->offs; list_del(&snod->list); kfree(snod); sleb->nodes_cnt -= 1; dropped = 1; } return dropped; } /** * ubifs_recover_leb - scan and recover a LEB. * @c: UBIFS file-system description object * @lnum: LEB number * @offs: offset * @sbuf: LEB-sized buffer to use * @grouped: nodes may be grouped for recovery * * This function does a scan of a LEB, but caters for errors that might have * been caused by the unclean unmount from which we are attempting to recover. * * This function returns %0 on success and a negative error code on failure. */ struct ubifs_scan_leb *ubifs_recover_leb(struct ubifs_info *c, int lnum, int offs, void *sbuf, int grouped) { int err, len = c->leb_size - offs, need_clean = 0, quiet = 1; int empty_chkd = 0, start = offs; struct ubifs_scan_leb *sleb; void *buf = sbuf + offs; dbg_rcvry("%d:%d", lnum, offs); sleb = ubifs_start_scan(c, lnum, offs, sbuf); if (IS_ERR(sleb)) return sleb; if (sleb->ecc) need_clean = 1; while (len >= 8) { int ret; dbg_scan("look at LEB %d:%d (%d bytes left)", lnum, offs, len); cond_resched(); /* * Scan quietly until there is an error from which we cannot * recover */ ret = ubifs_scan_a_node(c, buf, len, lnum, offs, quiet); if (ret == SCANNED_A_NODE) { /* A valid node, and not a padding node */ struct ubifs_ch *ch = buf; int node_len; 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; continue; } if (ret > 0) { /* Padding bytes or a valid padding node */ offs += ret; buf += ret; len -= ret; continue; } if (ret == SCANNED_EMPTY_SPACE) { if (!is_empty(buf, len)) { if (!is_last_write(c, buf, offs)) break; clean_buf(c, &buf, lnum, &offs, &len); need_clean = 1; } empty_chkd = 1; break; } if (ret == SCANNED_GARBAGE || ret == SCANNED_A_BAD_PAD_NODE) if (is_last_write(c, buf, offs)) { clean_buf(c, &buf, lnum, &offs, &len); need_clean = 1; empty_chkd = 1; break; } if (ret == SCANNED_A_CORRUPT_NODE) if (no_more_nodes(c, buf, len, lnum, offs)) { clean_buf(c, &buf, lnum, &offs, &len); need_clean = 1; empty_chkd = 1; break; } if (quiet) { /* Redo the last scan but noisily */ quiet = 0; continue; } switch (ret) { case SCANNED_GARBAGE: dbg_err("garbage"); goto corrupted; case SCANNED_A_CORRUPT_NODE: case SCANNED_A_BAD_PAD_NODE: dbg_err("bad node"); goto corrupted; default: dbg_err("unknown"); goto corrupted; } } if (!empty_chkd && !is_empty(buf, len)) { if (is_last_write(c, buf, offs)) { clean_buf(c, &buf, lnum, &offs, &len); need_clean = 1; } else { ubifs_err("corrupt empty space at LEB %d:%d", lnum, offs); goto corrupted; } } /* Drop nodes from incomplete group */ if (grouped && drop_incomplete_group(sleb, &offs)) { buf = sbuf + offs; len = c->leb_size - offs; clean_buf(c, &buf, lnum, &offs, &len); need_clean = 1; } if (offs % c->min_io_size) { clean_buf(c, &buf, lnum, &offs, &len); need_clean = 1; } ubifs_end_scan(c, sleb, lnum, offs); if (need_clean) { err = fix_unclean_leb(c, sleb, start); if (err) goto error; } 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); } /** * get_cs_sqnum - get commit start sequence number. * @c: UBIFS file-system description object * @lnum: LEB number of commit start node * @offs: offset of commit start node * @cs_sqnum: commit start sequence number is returned here * * This function returns %0 on success and a negative error code on failure. */ static int get_cs_sqnum(struct ubifs_info *c, int lnum, int offs, unsigned long long *cs_sqnum) { struct ubifs_cs_node *cs_node = NULL; int err, ret; dbg_rcvry("at %d:%d", lnum, offs); cs_node = kmalloc(UBIFS_CS_NODE_SZ, GFP_KERNEL); if (!cs_node) return -ENOMEM; if (c->leb_size - offs < UBIFS_CS_NODE_SZ) goto out_err; err = ubi_read(c->ubi, lnum, (void *)cs_node, offs, UBIFS_CS_NODE_SZ); if (err && err != -EBADMSG) goto out_free; ret = ubifs_scan_a_node(c, cs_node, UBIFS_CS_NODE_SZ, lnum, offs, 0); if (ret != SCANNED_A_NODE) { dbg_err("Not a valid node"); goto out_err; } if (cs_node->ch.node_type != UBIFS_CS_NODE) { dbg_err("Node a CS node, type is %d", cs_node->ch.node_type); goto out_err; } if (le64_to_cpu(cs_node->cmt_no) != c->cmt_no) { dbg_err("CS node cmt_no %llu != current cmt_no %llu", (unsigned long long)le64_to_cpu(cs_node->cmt_no), c->cmt_no); goto out_err; } *cs_sqnum = le64_to_cpu(cs_node->ch.sqnum); dbg_rcvry("commit start sqnum %llu", *cs_sqnum); kfree(cs_node); return 0; out_err: err = -EINVAL; out_free: ubifs_err("failed to get CS sqnum"); kfree(cs_node); return err; } /** * ubifs_recover_log_leb - scan and recover a log LEB. * @c: UBIFS file-system description object * @lnum: LEB number * @offs: offset * @sbuf: LEB-sized buffer to use * * This function does a scan of a LEB, but caters for errors that might have * been caused by the unclean unmount from which we are attempting to recover. * * This function returns %0 on success and a negative error code on failure. */ struct ubifs_scan_leb *ubifs_recover_log_leb(struct ubifs_info *c, int lnum, int offs, void *sbuf) { struct ubifs_scan_leb *sleb; int next_lnum; dbg_rcvry("LEB %d", lnum); next_lnum = lnum + 1; if (next_lnum >= UBIFS_LOG_LNUM + c->log_lebs) next_lnum = UBIFS_LOG_LNUM; if (next_lnum != c->ltail_lnum) { /* * We can only recover at the end of the log, so check that the * next log LEB is empty or out of date. */ sleb = ubifs_scan(c, next_lnum, 0, sbuf); if (IS_ERR(sleb)) return sleb; if (sleb->nodes_cnt) { struct ubifs_scan_node *snod; unsigned long long cs_sqnum = c->cs_sqnum; snod = list_entry(sleb->nodes.next, struct ubifs_scan_node, list); if (cs_sqnum == 0) { int err; err = get_cs_sqnum(c, lnum, offs, &cs_sqnum); if (err) { ubifs_scan_destroy(sleb); return ERR_PTR(err); } } if (snod->sqnum > cs_sqnum) { ubifs_err("unrecoverable log corruption " "in LEB %d", lnum); ubifs_scan_destroy(sleb); return ERR_PTR(-EUCLEAN); } } ubifs_scan_destroy(sleb); } return ubifs_recover_leb(c, lnum, offs, sbuf, 0); } /** * recover_head - recover a head. * @c: UBIFS file-system description object * @lnum: LEB number of head to recover * @offs: offset of head to recover * @sbuf: LEB-sized buffer to use * * This function ensures that there is no data on the flash at a head location. * * This function returns %0 on success and a negative error code on failure. */ static int recover_head(const struct ubifs_info *c, int lnum, int offs, void *sbuf) { int len, err, need_clean = 0; if (c->min_io_size > 1) len = c->min_io_size; else len = 512; if (offs + len > c->leb_size) len = c->leb_size - offs; if (!len) return 0; /* Read at the head location and check it is empty flash */ err = ubi_read(c->ubi, lnum, sbuf, offs, len); if (err) need_clean = 1; else { uint8_t *p = sbuf; while (len--) if (*p++ != 0xff) { need_clean = 1; break; } } if (need_clean) { dbg_rcvry("cleaning head at %d:%d", lnum, offs); if (offs == 0) return ubifs_leb_unmap(c, lnum); err = ubi_read(c->ubi, lnum, sbuf, 0, offs); if (err) return err; return ubi_leb_change(c->ubi, lnum, sbuf, offs, UBI_UNKNOWN); } return 0; } /** * ubifs_recover_inl_heads - recover index and LPT heads. * @c: UBIFS file-system description object * @sbuf: LEB-sized buffer to use * * This function ensures that there is no data on the flash at the index and * LPT head locations. * * This deals with the recovery of a half-completed journal commit. UBIFS is * careful never to overwrite the last version of the index or the LPT. Because * the index and LPT are wandering trees, data from a half-completed commit will * not be referenced anywhere in UBIFS. The data will be either in LEBs that are * assumed to be empty and will be unmapped anyway before use, or in the index * and LPT heads. * * This function returns %0 on success and a negative error code on failure. */ int ubifs_recover_inl_heads(const struct ubifs_info *c, void *sbuf) { int err; ubifs_assert(!(c->vfs_sb->s_flags & MS_RDONLY) || c->remounting_rw); dbg_rcvry("checking index head at %d:%d", c->ihead_lnum, c->ihead_offs); err = recover_head(c, c->ihead_lnum, c->ihead_offs, sbuf); if (err) return err; dbg_rcvry("checking LPT head at %d:%d", c->nhead_lnum, c->nhead_offs); err = recover_head(c, c->nhead_lnum, c->nhead_offs, sbuf); if (err) return err; return 0; } /** * clean_an_unclean_leb - read and write a LEB to remove corruption. * @c: UBIFS file-system description object * @ucleb: unclean LEB information * @sbuf: LEB-sized buffer to use * * This function reads a LEB up to a point pre-determined by the mount recovery, * checks the nodes, and writes the result back to the flash, thereby cleaning * off any following corruption, or non-fatal ECC errors. * * This function returns %0 on success and a negative error code on failure. */ static int clean_an_unclean_leb(const struct ubifs_info *c, struct ubifs_unclean_leb *ucleb, void *sbuf) { int err, lnum = ucleb->lnum, offs = 0, len = ucleb->endpt, quiet = 1; void *buf = sbuf; dbg_rcvry("LEB %d len %d", lnum, len); if (len == 0) { /* Nothing to read, just unmap it */ err = ubifs_leb_unmap(c, lnum); if (err) return err; return 0; } err = ubi_read(c->ubi, lnum, buf, offs, len); if (err && err != -EBADMSG) return err; while (len >= 8) { int ret; cond_resched(); /* Scan quietly until there is an error */ ret = ubifs_scan_a_node(c, buf, len, lnum, offs, quiet); if (ret == SCANNED_A_NODE) { /* A valid node, and not a padding node */ struct ubifs_ch *ch = buf; int node_len; node_len = ALIGN(le32_to_cpu(ch->len), 8); offs += node_len; buf += node_len; len -= node_len; continue; } if (ret > 0) { /* Padding bytes or a valid padding node */ offs += ret; buf += ret; len -= ret; continue; } if (ret == SCANNED_EMPTY_SPACE) { ubifs_err("unexpected empty space at %d:%d", lnum, offs); return -EUCLEAN; } if (quiet) { /* Redo the last scan but noisily */ quiet = 0; continue; } ubifs_scanned_corruption(c, lnum, offs, buf); return -EUCLEAN; } /* Pad to min_io_size */ len = ALIGN(ucleb->endpt, c->min_io_size); if (len > ucleb->endpt) { int pad_len = len - ALIGN(ucleb->endpt, 8); if (pad_len > 0) { buf = c->sbuf + len - pad_len; ubifs_pad(c, buf, pad_len); } } /* Write back the LEB atomically */ err = ubi_leb_change(c->ubi, lnum, sbuf, len, UBI_UNKNOWN); if (err) return err; dbg_rcvry("cleaned LEB %d", lnum); return 0; } /** * ubifs_clean_lebs - clean LEBs recovered during read-only mount. * @c: UBIFS file-system description object * @sbuf: LEB-sized buffer to use * * This function cleans a LEB identified during recovery that needs to be * written but was not because UBIFS was mounted read-only. This happens when * remounting to read-write mode. * * This function returns %0 on success and a negative error code on failure. */ int ubifs_clean_lebs(const struct ubifs_info *c, void *sbuf) { dbg_rcvry("recovery"); while (!list_empty(&c->unclean_leb_list)) { struct ubifs_unclean_leb *ucleb; int err; ucleb = list_entry(c->unclean_leb_list.next, struct ubifs_unclean_leb, list); err = clean_an_unclean_leb(c, ucleb, sbuf); if (err) return err; list_del(&ucleb->list); kfree(ucleb); } return 0; } /** * struct size_entry - inode size information for recovery. * @rb: link in the RB-tree of sizes * @inum: inode number * @i_size: size on inode * @d_size: maximum size based on data nodes * @exists: indicates whether the inode exists * @inode: inode if pinned in memory awaiting rw mode to fix it */ struct size_entry { struct rb_node rb; ino_t inum; loff_t i_size; loff_t d_size; int exists; struct inode *inode; }; /** * add_ino - add an entry to the size tree. * @c: UBIFS file-system description object * @inum: inode number * @i_size: size on inode * @d_size: maximum size based on data nodes * @exists: indicates whether the inode exists */ static int add_ino(struct ubifs_info *c, ino_t inum, loff_t i_size, loff_t d_size, int exists) { struct rb_node **p = &c->size_tree.rb_node, *parent = NULL; struct size_entry *e; while (*p) { parent = *p; e = rb_entry(parent, struct size_entry, rb); if (inum < e->inum) p = &(*p)->rb_left; else p = &(*p)->rb_right; } e = kzalloc(sizeof(struct size_entry), GFP_KERNEL); if (!e) return -ENOMEM; e->inum = inum; e->i_size = i_size; e->d_size = d_size; e->exists = exists; rb_link_node(&e->rb, parent, p); rb_insert_color(&e->rb, &c->size_tree); return 0; } /** * find_ino - find an entry on the size tree. * @c: UBIFS file-system description object * @inum: inode number */ static struct size_entry *find_ino(struct ubifs_info *c, ino_t inum) { struct rb_node *p = c->size_tree.rb_node; struct size_entry *e; while (p) { e = rb_entry(p, struct size_entry, rb); if (inum < e->inum) p = p->rb_left; else if (inum > e->inum) p = p->rb_right; else return e; } return NULL; } /** * remove_ino - remove an entry from the size tree. * @c: UBIFS file-system description object * @inum: inode number */ static void remove_ino(struct ubifs_info *c, ino_t inum) { struct size_entry *e = find_ino(c, inum); if (!e) return; rb_erase(&e->rb, &c->size_tree); kfree(e); } /** * ubifs_recover_size_accum - accumulate inode sizes for recovery. * @c: UBIFS file-system description object * @key: node key * @deletion: node is for a deletion * @new_size: inode size * * This function has two purposes: * 1) to ensure there are no data nodes that fall outside the inode size * 2) to ensure there are no data nodes for inodes that do not exist * To accomplish those purposes, a rb-tree is constructed containing an entry * for each inode number in the journal that has not been deleted, and recording * the size from the inode node, the maximum size of any data node (also altered * by truncations) and a flag indicating a inode number for which no inode node * was present in the journal. * * Note that there is still the possibility that there are data nodes that have * been committed that are beyond the inode size, however the only way to find * them would be to scan the entire index. Alternatively, some provision could * be made to record the size of inodes at the start of commit, which would seem * very cumbersome for a scenario that is quite unlikely and the only negative * consequence of which is wasted space. * * This functions returns %0 on success and a negative error code on failure. */ int ubifs_recover_size_accum(struct ubifs_info *c, union ubifs_key *key, int deletion, loff_t new_size) { ino_t inum = key_inum(c, key); struct size_entry *e; int err; switch (key_type(c, key)) { case UBIFS_INO_KEY: if (deletion) remove_ino(c, inum); else { e = find_ino(c, inum); if (e) { e->i_size = new_size; e->exists = 1; } else { err = add_ino(c, inum, new_size, 0, 1); if (err) return err; } } break; case UBIFS_DATA_KEY: e = find_ino(c, inum); if (e) { if (new_size > e->d_size) e->d_size = new_size; } else { err = add_ino(c, inum, 0, new_size, 0); if (err) return err; } break; case UBIFS_TRUN_KEY: e = find_ino(c, inum); if (e) e->d_size = new_size; break; } return 0; } /** * ubifs_recover_size - recover inode size. * @c: UBIFS file-system description object * * This function attempts to fix inode size discrepancies identified by the * 'ubifs_recover_size_accum()' function. * * This functions returns %0 on success and a negative error code on failure. */ int ubifs_recover_size(struct ubifs_info *c) { struct rb_node *this = rb_first(&c->size_tree); while (this) { struct size_entry *e; int err; e = rb_entry(this, struct size_entry, rb); if (!e->exists) { union ubifs_key key; ino_key_init(c, &key, e->inum); err = ubifs_tnc_lookup(c, &key, c->sbuf); if (err && err != -ENOENT) return err; if (err == -ENOENT) { /* Remove data nodes that have no inode */ dbg_rcvry("removing ino %lu", (unsigned long)e->inum); err = ubifs_tnc_remove_ino(c, e->inum); if (err) return err; } else { struct ubifs_ino_node *ino = c->sbuf; e->exists = 1; e->i_size = le64_to_cpu(ino->size); } } if (e->exists && e->i_size < e->d_size) { if (!e->inode && (c->vfs_sb->s_flags & MS_RDONLY)) { /* Fix the inode size and pin it in memory */ struct inode *inode; inode = ubifs_iget(c->vfs_sb, e->inum); if (IS_ERR(inode)) return PTR_ERR(inode); if (inode->i_size < e->d_size) { dbg_rcvry("ino %lu size %lld -> %lld", (unsigned long)e->inum, e->d_size, inode->i_size); inode->i_size = e->d_size; ubifs_inode(inode)->ui_size = e->d_size; e->inode = inode; this = rb_next(this); continue; } iput(inode); } } this = rb_next(this); rb_erase(&e->rb, &c->size_tree); kfree(e); } return 0; }
1001-study-uboot
fs/ubifs/recovery.c
C
gpl3
31,658
/* * 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 functions that access LEB properties and their * categories. LEBs are categorized based on the needs of UBIFS, and the * categories are stored as either heaps or lists to provide a fast way of * finding a LEB in a particular category. For example, UBIFS may need to find * an empty LEB for the journal, or a very dirty LEB for garbage collection. */ #include "ubifs.h" /** * get_heap_comp_val - get the LEB properties value for heap comparisons. * @lprops: LEB properties * @cat: LEB category */ static int get_heap_comp_val(struct ubifs_lprops *lprops, int cat) { switch (cat) { case LPROPS_FREE: return lprops->free; case LPROPS_DIRTY_IDX: return lprops->free + lprops->dirty; default: return lprops->dirty; } } /** * move_up_lpt_heap - move a new heap entry up as far as possible. * @c: UBIFS file-system description object * @heap: LEB category heap * @lprops: LEB properties to move * @cat: LEB category * * New entries to a heap are added at the bottom and then moved up until the * parent's value is greater. In the case of LPT's category heaps, the value * is either the amount of free space or the amount of dirty space, depending * on the category. */ static void move_up_lpt_heap(struct ubifs_info *c, struct ubifs_lpt_heap *heap, struct ubifs_lprops *lprops, int cat) { int val1, val2, hpos; hpos = lprops->hpos; if (!hpos) return; /* Already top of the heap */ val1 = get_heap_comp_val(lprops, cat); /* Compare to parent and, if greater, move up the heap */ do { int ppos = (hpos - 1) / 2; val2 = get_heap_comp_val(heap->arr[ppos], cat); if (val2 >= val1) return; /* Greater than parent so move up */ heap->arr[ppos]->hpos = hpos; heap->arr[hpos] = heap->arr[ppos]; heap->arr[ppos] = lprops; lprops->hpos = ppos; hpos = ppos; } while (hpos); } /** * adjust_lpt_heap - move a changed heap entry up or down the heap. * @c: UBIFS file-system description object * @heap: LEB category heap * @lprops: LEB properties to move * @hpos: heap position of @lprops * @cat: LEB category * * Changed entries in a heap are moved up or down until the parent's value is * greater. In the case of LPT's category heaps, the value is either the amount * of free space or the amount of dirty space, depending on the category. */ static void adjust_lpt_heap(struct ubifs_info *c, struct ubifs_lpt_heap *heap, struct ubifs_lprops *lprops, int hpos, int cat) { int val1, val2, val3, cpos; val1 = get_heap_comp_val(lprops, cat); /* Compare to parent and, if greater than parent, move up the heap */ if (hpos) { int ppos = (hpos - 1) / 2; val2 = get_heap_comp_val(heap->arr[ppos], cat); if (val1 > val2) { /* Greater than parent so move up */ while (1) { heap->arr[ppos]->hpos = hpos; heap->arr[hpos] = heap->arr[ppos]; heap->arr[ppos] = lprops; lprops->hpos = ppos; hpos = ppos; if (!hpos) return; ppos = (hpos - 1) / 2; val2 = get_heap_comp_val(heap->arr[ppos], cat); if (val1 <= val2) return; /* Still greater than parent so keep going */ } } } /* Not greater than parent, so compare to children */ while (1) { /* Compare to left child */ cpos = hpos * 2 + 1; if (cpos >= heap->cnt) return; val2 = get_heap_comp_val(heap->arr[cpos], cat); if (val1 < val2) { /* Less than left child, so promote biggest child */ if (cpos + 1 < heap->cnt) { val3 = get_heap_comp_val(heap->arr[cpos + 1], cat); if (val3 > val2) cpos += 1; /* Right child is bigger */ } heap->arr[cpos]->hpos = hpos; heap->arr[hpos] = heap->arr[cpos]; heap->arr[cpos] = lprops; lprops->hpos = cpos; hpos = cpos; continue; } /* Compare to right child */ cpos += 1; if (cpos >= heap->cnt) return; val3 = get_heap_comp_val(heap->arr[cpos], cat); if (val1 < val3) { /* Less than right child, so promote right child */ heap->arr[cpos]->hpos = hpos; heap->arr[hpos] = heap->arr[cpos]; heap->arr[cpos] = lprops; lprops->hpos = cpos; hpos = cpos; continue; } return; } } /** * add_to_lpt_heap - add LEB properties to a LEB category heap. * @c: UBIFS file-system description object * @lprops: LEB properties to add * @cat: LEB category * * This function returns %1 if @lprops is added to the heap for LEB category * @cat, otherwise %0 is returned because the heap is full. */ static int add_to_lpt_heap(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat) { struct ubifs_lpt_heap *heap = &c->lpt_heap[cat - 1]; if (heap->cnt >= heap->max_cnt) { const int b = LPT_HEAP_SZ / 2 - 1; int cpos, val1, val2; /* Compare to some other LEB on the bottom of heap */ /* Pick a position kind of randomly */ cpos = (((size_t)lprops >> 4) & b) + b; ubifs_assert(cpos >= b); ubifs_assert(cpos < LPT_HEAP_SZ); ubifs_assert(cpos < heap->cnt); val1 = get_heap_comp_val(lprops, cat); val2 = get_heap_comp_val(heap->arr[cpos], cat); if (val1 > val2) { struct ubifs_lprops *lp; lp = heap->arr[cpos]; lp->flags &= ~LPROPS_CAT_MASK; lp->flags |= LPROPS_UNCAT; list_add(&lp->list, &c->uncat_list); lprops->hpos = cpos; heap->arr[cpos] = lprops; move_up_lpt_heap(c, heap, lprops, cat); dbg_check_heap(c, heap, cat, lprops->hpos); return 1; /* Added to heap */ } dbg_check_heap(c, heap, cat, -1); return 0; /* Not added to heap */ } else { lprops->hpos = heap->cnt++; heap->arr[lprops->hpos] = lprops; move_up_lpt_heap(c, heap, lprops, cat); dbg_check_heap(c, heap, cat, lprops->hpos); return 1; /* Added to heap */ } } /** * remove_from_lpt_heap - remove LEB properties from a LEB category heap. * @c: UBIFS file-system description object * @lprops: LEB properties to remove * @cat: LEB category */ static void remove_from_lpt_heap(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat) { struct ubifs_lpt_heap *heap; int hpos = lprops->hpos; heap = &c->lpt_heap[cat - 1]; ubifs_assert(hpos >= 0 && hpos < heap->cnt); ubifs_assert(heap->arr[hpos] == lprops); heap->cnt -= 1; if (hpos < heap->cnt) { heap->arr[hpos] = heap->arr[heap->cnt]; heap->arr[hpos]->hpos = hpos; adjust_lpt_heap(c, heap, heap->arr[hpos], hpos, cat); } dbg_check_heap(c, heap, cat, -1); } /** * lpt_heap_replace - replace lprops in a category heap. * @c: UBIFS file-system description object * @old_lprops: LEB properties to replace * @new_lprops: LEB properties with which to replace * @cat: LEB category * * During commit it is sometimes necessary to copy a pnode (see dirty_cow_pnode) * and the lprops that the pnode contains. When that happens, references in * the category heaps to those lprops must be updated to point to the new * lprops. This function does that. */ static void lpt_heap_replace(struct ubifs_info *c, struct ubifs_lprops *old_lprops, struct ubifs_lprops *new_lprops, int cat) { struct ubifs_lpt_heap *heap; int hpos = new_lprops->hpos; heap = &c->lpt_heap[cat - 1]; heap->arr[hpos] = new_lprops; } /** * ubifs_add_to_cat - add LEB properties to a category list or heap. * @c: UBIFS file-system description object * @lprops: LEB properties to add * @cat: LEB category to which to add * * LEB properties are categorized to enable fast find operations. */ void ubifs_add_to_cat(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat) { switch (cat) { case LPROPS_DIRTY: case LPROPS_DIRTY_IDX: case LPROPS_FREE: if (add_to_lpt_heap(c, lprops, cat)) break; /* No more room on heap so make it uncategorized */ cat = LPROPS_UNCAT; /* Fall through */ case LPROPS_UNCAT: list_add(&lprops->list, &c->uncat_list); break; case LPROPS_EMPTY: list_add(&lprops->list, &c->empty_list); break; case LPROPS_FREEABLE: list_add(&lprops->list, &c->freeable_list); c->freeable_cnt += 1; break; case LPROPS_FRDI_IDX: list_add(&lprops->list, &c->frdi_idx_list); break; default: ubifs_assert(0); } lprops->flags &= ~LPROPS_CAT_MASK; lprops->flags |= cat; } /** * ubifs_remove_from_cat - remove LEB properties from a category list or heap. * @c: UBIFS file-system description object * @lprops: LEB properties to remove * @cat: LEB category from which to remove * * LEB properties are categorized to enable fast find operations. */ static void ubifs_remove_from_cat(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat) { switch (cat) { case LPROPS_DIRTY: case LPROPS_DIRTY_IDX: case LPROPS_FREE: remove_from_lpt_heap(c, lprops, cat); break; case LPROPS_FREEABLE: c->freeable_cnt -= 1; ubifs_assert(c->freeable_cnt >= 0); /* Fall through */ case LPROPS_UNCAT: case LPROPS_EMPTY: case LPROPS_FRDI_IDX: ubifs_assert(!list_empty(&lprops->list)); list_del(&lprops->list); break; default: ubifs_assert(0); } } /** * ubifs_replace_cat - replace lprops in a category list or heap. * @c: UBIFS file-system description object * @old_lprops: LEB properties to replace * @new_lprops: LEB properties with which to replace * * During commit it is sometimes necessary to copy a pnode (see dirty_cow_pnode) * and the lprops that the pnode contains. When that happens, references in * category lists and heaps must be replaced. This function does that. */ void ubifs_replace_cat(struct ubifs_info *c, struct ubifs_lprops *old_lprops, struct ubifs_lprops *new_lprops) { int cat; cat = new_lprops->flags & LPROPS_CAT_MASK; switch (cat) { case LPROPS_DIRTY: case LPROPS_DIRTY_IDX: case LPROPS_FREE: lpt_heap_replace(c, old_lprops, new_lprops, cat); break; case LPROPS_UNCAT: case LPROPS_EMPTY: case LPROPS_FREEABLE: case LPROPS_FRDI_IDX: list_replace(&old_lprops->list, &new_lprops->list); break; default: ubifs_assert(0); } } /** * ubifs_ensure_cat - ensure LEB properties are categorized. * @c: UBIFS file-system description object * @lprops: LEB properties * * A LEB may have fallen off of the bottom of a heap, and ended up as * uncategorized even though it has enough space for us now. If that is the case * this function will put the LEB back onto a heap. */ void ubifs_ensure_cat(struct ubifs_info *c, struct ubifs_lprops *lprops) { int cat = lprops->flags & LPROPS_CAT_MASK; if (cat != LPROPS_UNCAT) return; cat = ubifs_categorize_lprops(c, lprops); if (cat == LPROPS_UNCAT) return; ubifs_remove_from_cat(c, lprops, LPROPS_UNCAT); ubifs_add_to_cat(c, lprops, cat); } /** * ubifs_categorize_lprops - categorize LEB properties. * @c: UBIFS file-system description object * @lprops: LEB properties to categorize * * LEB properties are categorized to enable fast find operations. This function * returns the LEB category to which the LEB properties belong. Note however * that if the LEB category is stored as a heap and the heap is full, the * LEB properties may have their category changed to %LPROPS_UNCAT. */ int ubifs_categorize_lprops(const struct ubifs_info *c, const struct ubifs_lprops *lprops) { if (lprops->flags & LPROPS_TAKEN) return LPROPS_UNCAT; if (lprops->free == c->leb_size) { ubifs_assert(!(lprops->flags & LPROPS_INDEX)); return LPROPS_EMPTY; } if (lprops->free + lprops->dirty == c->leb_size) { if (lprops->flags & LPROPS_INDEX) return LPROPS_FRDI_IDX; else return LPROPS_FREEABLE; } if (lprops->flags & LPROPS_INDEX) { if (lprops->dirty + lprops->free >= c->min_idx_node_sz) return LPROPS_DIRTY_IDX; } else { if (lprops->dirty >= c->dead_wm && lprops->dirty > lprops->free) return LPROPS_DIRTY; if (lprops->free > 0) return LPROPS_FREE; } return LPROPS_UNCAT; } /** * change_category - change LEB properties category. * @c: UBIFS file-system description object * @lprops: LEB properties to recategorize * * LEB properties are categorized to enable fast find operations. When the LEB * properties change they must be recategorized. */ static void change_category(struct ubifs_info *c, struct ubifs_lprops *lprops) { int old_cat = lprops->flags & LPROPS_CAT_MASK; int new_cat = ubifs_categorize_lprops(c, lprops); if (old_cat == new_cat) { struct ubifs_lpt_heap *heap = &c->lpt_heap[new_cat - 1]; /* lprops on a heap now must be moved up or down */ if (new_cat < 1 || new_cat > LPROPS_HEAP_CNT) return; /* Not on a heap */ heap = &c->lpt_heap[new_cat - 1]; adjust_lpt_heap(c, heap, lprops, lprops->hpos, new_cat); } else { ubifs_remove_from_cat(c, lprops, old_cat); ubifs_add_to_cat(c, lprops, new_cat); } } /** * calc_dark - calculate LEB dark space size. * @c: the UBIFS file-system description object * @spc: amount of free and dirty space in the LEB * * This function calculates amount of dark space in an LEB which has @spc bytes * of free and dirty space. Returns the calculations result. * * Dark space is the space which is not always usable - it depends on which * nodes are written in which order. E.g., if an LEB has only 512 free bytes, * it is dark space, because it cannot fit a large data node. So UBIFS cannot * count on this LEB and treat these 512 bytes as usable because it is not true * if, for example, only big chunks of uncompressible data will be written to * the FS. */ static int calc_dark(struct ubifs_info *c, int spc) { ubifs_assert(!(spc & 7)); if (spc < c->dark_wm) return spc; /* * If we have slightly more space then the dark space watermark, we can * anyway safely assume it we'll be able to write a node of the * smallest size there. */ if (spc - c->dark_wm < MIN_WRITE_SZ) return spc - MIN_WRITE_SZ; return c->dark_wm; } /** * is_lprops_dirty - determine if LEB properties are dirty. * @c: the UBIFS file-system description object * @lprops: LEB properties to test */ static int is_lprops_dirty(struct ubifs_info *c, struct ubifs_lprops *lprops) { struct ubifs_pnode *pnode; int pos; pos = (lprops->lnum - c->main_first) & (UBIFS_LPT_FANOUT - 1); pnode = (struct ubifs_pnode *)container_of(lprops - pos, struct ubifs_pnode, lprops[0]); return !test_bit(COW_ZNODE, &pnode->flags) && test_bit(DIRTY_CNODE, &pnode->flags); } /** * ubifs_change_lp - change LEB properties. * @c: the UBIFS file-system description object * @lp: LEB properties to change * @free: new free space amount * @dirty: new dirty space amount * @flags: new flags * @idx_gc_cnt: change to the count of idx_gc list * * This function changes LEB properties (@free, @dirty or @flag). However, the * property which has the %LPROPS_NC value is not changed. Returns a pointer to * the updated LEB properties on success and a negative error code on failure. * * Note, the LEB properties may have had to be copied (due to COW) and * consequently the pointer returned may not be the same as the pointer * passed. */ const struct ubifs_lprops *ubifs_change_lp(struct ubifs_info *c, const struct ubifs_lprops *lp, int free, int dirty, int flags, int idx_gc_cnt) { /* * This is the only function that is allowed to change lprops, so we * discard the const qualifier. */ struct ubifs_lprops *lprops = (struct ubifs_lprops *)lp; dbg_lp("LEB %d, free %d, dirty %d, flags %d", lprops->lnum, free, dirty, flags); ubifs_assert(mutex_is_locked(&c->lp_mutex)); ubifs_assert(c->lst.empty_lebs >= 0 && c->lst.empty_lebs <= c->main_lebs); ubifs_assert(c->freeable_cnt >= 0); ubifs_assert(c->freeable_cnt <= c->main_lebs); ubifs_assert(c->lst.taken_empty_lebs >= 0); ubifs_assert(c->lst.taken_empty_lebs <= c->lst.empty_lebs); ubifs_assert(!(c->lst.total_free & 7) && !(c->lst.total_dirty & 7)); ubifs_assert(!(c->lst.total_dead & 7) && !(c->lst.total_dark & 7)); ubifs_assert(!(c->lst.total_used & 7)); ubifs_assert(free == LPROPS_NC || free >= 0); ubifs_assert(dirty == LPROPS_NC || dirty >= 0); if (!is_lprops_dirty(c, lprops)) { lprops = ubifs_lpt_lookup_dirty(c, lprops->lnum); if (IS_ERR(lprops)) return lprops; } else ubifs_assert(lprops == ubifs_lpt_lookup_dirty(c, lprops->lnum)); ubifs_assert(!(lprops->free & 7) && !(lprops->dirty & 7)); spin_lock(&c->space_lock); if ((lprops->flags & LPROPS_TAKEN) && lprops->free == c->leb_size) c->lst.taken_empty_lebs -= 1; if (!(lprops->flags & LPROPS_INDEX)) { int old_spc; old_spc = lprops->free + lprops->dirty; if (old_spc < c->dead_wm) c->lst.total_dead -= old_spc; else c->lst.total_dark -= calc_dark(c, old_spc); c->lst.total_used -= c->leb_size - old_spc; } if (free != LPROPS_NC) { free = ALIGN(free, 8); c->lst.total_free += free - lprops->free; /* Increase or decrease empty LEBs counter if needed */ if (free == c->leb_size) { if (lprops->free != c->leb_size) c->lst.empty_lebs += 1; } else if (lprops->free == c->leb_size) c->lst.empty_lebs -= 1; lprops->free = free; } if (dirty != LPROPS_NC) { dirty = ALIGN(dirty, 8); c->lst.total_dirty += dirty - lprops->dirty; lprops->dirty = dirty; } if (flags != LPROPS_NC) { /* Take care about indexing LEBs counter if needed */ if ((lprops->flags & LPROPS_INDEX)) { if (!(flags & LPROPS_INDEX)) c->lst.idx_lebs -= 1; } else if (flags & LPROPS_INDEX) c->lst.idx_lebs += 1; lprops->flags = flags; } if (!(lprops->flags & LPROPS_INDEX)) { int new_spc; new_spc = lprops->free + lprops->dirty; if (new_spc < c->dead_wm) c->lst.total_dead += new_spc; else c->lst.total_dark += calc_dark(c, new_spc); c->lst.total_used += c->leb_size - new_spc; } if ((lprops->flags & LPROPS_TAKEN) && lprops->free == c->leb_size) c->lst.taken_empty_lebs += 1; change_category(c, lprops); c->idx_gc_cnt += idx_gc_cnt; spin_unlock(&c->space_lock); return lprops; } /** * ubifs_get_lp_stats - get lprops statistics. * @c: UBIFS file-system description object * @st: return statistics */ void ubifs_get_lp_stats(struct ubifs_info *c, struct ubifs_lp_stats *lst) { spin_lock(&c->space_lock); memcpy(lst, &c->lst, sizeof(struct ubifs_lp_stats)); spin_unlock(&c->space_lock); } /** * ubifs_change_one_lp - change LEB properties. * @c: the UBIFS file-system description object * @lnum: LEB to change properties for * @free: amount of free space * @dirty: amount of dirty space * @flags_set: flags to set * @flags_clean: flags to clean * @idx_gc_cnt: change to the count of idx_gc list * * This function changes properties of LEB @lnum. It is a helper wrapper over * 'ubifs_change_lp()' which hides lprops get/release. The arguments are the * same as in case of 'ubifs_change_lp()'. Returns zero in case of success and * a negative error code in case of failure. */ int ubifs_change_one_lp(struct ubifs_info *c, int lnum, int free, int dirty, int flags_set, int flags_clean, int idx_gc_cnt) { int err = 0, flags; const struct ubifs_lprops *lp; ubifs_get_lprops(c); lp = ubifs_lpt_lookup_dirty(c, lnum); if (IS_ERR(lp)) { err = PTR_ERR(lp); goto out; } flags = (lp->flags | flags_set) & ~flags_clean; lp = ubifs_change_lp(c, lp, free, dirty, flags, idx_gc_cnt); if (IS_ERR(lp)) err = PTR_ERR(lp); out: ubifs_release_lprops(c); return err; } /** * ubifs_update_one_lp - update LEB properties. * @c: the UBIFS file-system description object * @lnum: LEB to change properties for * @free: amount of free space * @dirty: amount of dirty space to add * @flags_set: flags to set * @flags_clean: flags to clean * * This function is the same as 'ubifs_change_one_lp()' but @dirty is added to * current dirty space, not substitutes it. */ int ubifs_update_one_lp(struct ubifs_info *c, int lnum, int free, int dirty, int flags_set, int flags_clean) { int err = 0, flags; const struct ubifs_lprops *lp; ubifs_get_lprops(c); lp = ubifs_lpt_lookup_dirty(c, lnum); if (IS_ERR(lp)) { err = PTR_ERR(lp); goto out; } flags = (lp->flags | flags_set) & ~flags_clean; lp = ubifs_change_lp(c, lp, free, lp->dirty + dirty, flags, 0); if (IS_ERR(lp)) err = PTR_ERR(lp); out: ubifs_release_lprops(c); return err; } /** * ubifs_read_one_lp - read LEB properties. * @c: the UBIFS file-system description object * @lnum: LEB to read properties for * @lp: where to store read properties * * This helper function reads properties of a LEB @lnum and stores them in @lp. * Returns zero in case of success and a negative error code in case of * failure. */ int ubifs_read_one_lp(struct ubifs_info *c, int lnum, struct ubifs_lprops *lp) { int err = 0; const struct ubifs_lprops *lpp; ubifs_get_lprops(c); lpp = ubifs_lpt_lookup(c, lnum); if (IS_ERR(lpp)) { err = PTR_ERR(lpp); goto out; } memcpy(lp, lpp, sizeof(struct ubifs_lprops)); out: ubifs_release_lprops(c); return err; } /** * ubifs_fast_find_free - try to find a LEB with free space quickly. * @c: the UBIFS file-system description object * * This function returns LEB properties for a LEB with free space or %NULL if * the function is unable to find a LEB quickly. */ const struct ubifs_lprops *ubifs_fast_find_free(struct ubifs_info *c) { struct ubifs_lprops *lprops; struct ubifs_lpt_heap *heap; ubifs_assert(mutex_is_locked(&c->lp_mutex)); heap = &c->lpt_heap[LPROPS_FREE - 1]; if (heap->cnt == 0) return NULL; lprops = heap->arr[0]; ubifs_assert(!(lprops->flags & LPROPS_TAKEN)); ubifs_assert(!(lprops->flags & LPROPS_INDEX)); return lprops; } /** * ubifs_fast_find_empty - try to find an empty LEB quickly. * @c: the UBIFS file-system description object * * This function returns LEB properties for an empty LEB or %NULL if the * function is unable to find an empty LEB quickly. */ const struct ubifs_lprops *ubifs_fast_find_empty(struct ubifs_info *c) { struct ubifs_lprops *lprops; ubifs_assert(mutex_is_locked(&c->lp_mutex)); if (list_empty(&c->empty_list)) return NULL; lprops = list_entry(c->empty_list.next, struct ubifs_lprops, list); ubifs_assert(!(lprops->flags & LPROPS_TAKEN)); ubifs_assert(!(lprops->flags & LPROPS_INDEX)); ubifs_assert(lprops->free == c->leb_size); return lprops; } /** * ubifs_fast_find_freeable - try to find a freeable LEB quickly. * @c: the UBIFS file-system description object * * This function returns LEB properties for a freeable LEB or %NULL if the * function is unable to find a freeable LEB quickly. */ const struct ubifs_lprops *ubifs_fast_find_freeable(struct ubifs_info *c) { struct ubifs_lprops *lprops; ubifs_assert(mutex_is_locked(&c->lp_mutex)); if (list_empty(&c->freeable_list)) return NULL; lprops = list_entry(c->freeable_list.next, struct ubifs_lprops, list); ubifs_assert(!(lprops->flags & LPROPS_TAKEN)); ubifs_assert(!(lprops->flags & LPROPS_INDEX)); ubifs_assert(lprops->free + lprops->dirty == c->leb_size); ubifs_assert(c->freeable_cnt > 0); return lprops; } /** * ubifs_fast_find_frdi_idx - try to find a freeable index LEB quickly. * @c: the UBIFS file-system description object * * This function returns LEB properties for a freeable index LEB or %NULL if the * function is unable to find a freeable index LEB quickly. */ const struct ubifs_lprops *ubifs_fast_find_frdi_idx(struct ubifs_info *c) { struct ubifs_lprops *lprops; ubifs_assert(mutex_is_locked(&c->lp_mutex)); if (list_empty(&c->frdi_idx_list)) return NULL; lprops = list_entry(c->frdi_idx_list.next, struct ubifs_lprops, list); ubifs_assert(!(lprops->flags & LPROPS_TAKEN)); ubifs_assert((lprops->flags & LPROPS_INDEX)); ubifs_assert(lprops->free + lprops->dirty == c->leb_size); return lprops; }
1001-study-uboot
fs/ubifs/lprops.c
C
gpl3
24,336
/* * crc16.h - CRC-16 routine * * Implements the standard CRC-16: * Width 16 * Poly 0x8005 (x^16 + x^15 + x^2 + 1) * Init 0 * * Copyright (c) 2005 Ben Gardner <bgardner@wabtec.com> * * This source code is licensed under the GNU General Public License, * Version 2. See the file COPYING for more details. */ #ifndef __CRC16_H #define __CRC16_H #include <linux/types.h> extern u16 const crc16_table[256]; extern u16 crc16(u16 crc, const u8 *buffer, size_t len); static inline u16 crc16_byte(u16 crc, const u8 data) { return (crc >> 8) ^ crc16_table[(crc ^ data) & 0xff]; } #endif /* __CRC16_H */
1001-study-uboot
fs/ubifs/crc16.h
C
gpl3
621
/* * 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 header contains various key-related definitions and helper function. * UBIFS allows several key schemes, so we access key fields only via these * helpers. At the moment only one key scheme is supported. * * Simple key scheme * ~~~~~~~~~~~~~~~~~ * * Keys are 64-bits long. First 32-bits are inode number (parent inode number * in case of direntry key). Next 3 bits are node type. The last 29 bits are * 4KiB offset in case of inode node, and direntry hash in case of a direntry * node. We use "r5" hash borrowed from reiserfs. */ #ifndef __UBIFS_KEY_H__ #define __UBIFS_KEY_H__ /** * key_mask_hash - mask a valid hash value. * @val: value to be masked * * We use hash values as offset in directories, so values %0 and %1 are * reserved for "." and "..". %2 is reserved for "end of readdir" marker. This * function makes sure the reserved values are not used. */ static inline uint32_t key_mask_hash(uint32_t hash) { hash &= UBIFS_S_KEY_HASH_MASK; if (unlikely(hash <= 2)) hash += 3; return hash; } /** * key_r5_hash - R5 hash function (borrowed from reiserfs). * @s: direntry name * @len: name length */ static inline uint32_t key_r5_hash(const char *s, int len) { uint32_t a = 0; const signed char *str = (const signed char *)s; while (*str) { a += *str << 4; a += *str >> 4; a *= 11; str++; } return key_mask_hash(a); } /** * key_test_hash - testing hash function. * @str: direntry name * @len: name length */ static inline uint32_t key_test_hash(const char *str, int len) { uint32_t a = 0; len = min_t(uint32_t, len, 4); memcpy(&a, str, len); return key_mask_hash(a); } /** * ino_key_init - initialize inode key. * @c: UBIFS file-system description object * @key: key to initialize * @inum: inode number */ static inline void ino_key_init(const struct ubifs_info *c, union ubifs_key *key, ino_t inum) { key->u32[0] = inum; key->u32[1] = UBIFS_INO_KEY << UBIFS_S_KEY_BLOCK_BITS; } /** * ino_key_init_flash - initialize on-flash inode key. * @c: UBIFS file-system description object * @k: key to initialize * @inum: inode number */ static inline void ino_key_init_flash(const struct ubifs_info *c, void *k, ino_t inum) { union ubifs_key *key = k; key->j32[0] = cpu_to_le32(inum); key->j32[1] = cpu_to_le32(UBIFS_INO_KEY << UBIFS_S_KEY_BLOCK_BITS); memset(k + 8, 0, UBIFS_MAX_KEY_LEN - 8); } /** * lowest_ino_key - get the lowest possible inode key. * @c: UBIFS file-system description object * @key: key to initialize * @inum: inode number */ static inline void lowest_ino_key(const struct ubifs_info *c, union ubifs_key *key, ino_t inum) { key->u32[0] = inum; key->u32[1] = 0; } /** * highest_ino_key - get the highest possible inode key. * @c: UBIFS file-system description object * @key: key to initialize * @inum: inode number */ static inline void highest_ino_key(const struct ubifs_info *c, union ubifs_key *key, ino_t inum) { key->u32[0] = inum; key->u32[1] = 0xffffffff; } /** * dent_key_init - initialize directory entry key. * @c: UBIFS file-system description object * @key: key to initialize * @inum: parent inode number * @nm: direntry name and length */ static inline void dent_key_init(const struct ubifs_info *c, union ubifs_key *key, ino_t inum, const struct qstr *nm) { uint32_t hash = c->key_hash(nm->name, nm->len); ubifs_assert(!(hash & ~UBIFS_S_KEY_HASH_MASK)); key->u32[0] = inum; key->u32[1] = hash | (UBIFS_DENT_KEY << UBIFS_S_KEY_HASH_BITS); } /** * dent_key_init_hash - initialize directory entry key without re-calculating * hash function. * @c: UBIFS file-system description object * @key: key to initialize * @inum: parent inode number * @hash: direntry name hash */ static inline void dent_key_init_hash(const struct ubifs_info *c, union ubifs_key *key, ino_t inum, uint32_t hash) { ubifs_assert(!(hash & ~UBIFS_S_KEY_HASH_MASK)); key->u32[0] = inum; key->u32[1] = hash | (UBIFS_DENT_KEY << UBIFS_S_KEY_HASH_BITS); } /** * dent_key_init_flash - initialize on-flash directory entry key. * @c: UBIFS file-system description object * @k: key to initialize * @inum: parent inode number * @nm: direntry name and length */ static inline void dent_key_init_flash(const struct ubifs_info *c, void *k, ino_t inum, const struct qstr *nm) { union ubifs_key *key = k; uint32_t hash = c->key_hash(nm->name, nm->len); ubifs_assert(!(hash & ~UBIFS_S_KEY_HASH_MASK)); key->j32[0] = cpu_to_le32(inum); key->j32[1] = cpu_to_le32(hash | (UBIFS_DENT_KEY << UBIFS_S_KEY_HASH_BITS)); memset(k + 8, 0, UBIFS_MAX_KEY_LEN - 8); } /** * lowest_dent_key - get the lowest possible directory entry key. * @c: UBIFS file-system description object * @key: where to store the lowest key * @inum: parent inode number */ static inline void lowest_dent_key(const struct ubifs_info *c, union ubifs_key *key, ino_t inum) { key->u32[0] = inum; key->u32[1] = UBIFS_DENT_KEY << UBIFS_S_KEY_HASH_BITS; } /** * xent_key_init - initialize extended attribute entry key. * @c: UBIFS file-system description object * @key: key to initialize * @inum: host inode number * @nm: extended attribute entry name and length */ static inline void xent_key_init(const struct ubifs_info *c, union ubifs_key *key, ino_t inum, const struct qstr *nm) { uint32_t hash = c->key_hash(nm->name, nm->len); ubifs_assert(!(hash & ~UBIFS_S_KEY_HASH_MASK)); key->u32[0] = inum; key->u32[1] = hash | (UBIFS_XENT_KEY << UBIFS_S_KEY_HASH_BITS); } /** * xent_key_init_hash - initialize extended attribute entry key without * re-calculating hash function. * @c: UBIFS file-system description object * @key: key to initialize * @inum: host inode number * @hash: extended attribute entry name hash */ static inline void xent_key_init_hash(const struct ubifs_info *c, union ubifs_key *key, ino_t inum, uint32_t hash) { ubifs_assert(!(hash & ~UBIFS_S_KEY_HASH_MASK)); key->u32[0] = inum; key->u32[1] = hash | (UBIFS_XENT_KEY << UBIFS_S_KEY_HASH_BITS); } /** * xent_key_init_flash - initialize on-flash extended attribute entry key. * @c: UBIFS file-system description object * @k: key to initialize * @inum: host inode number * @nm: extended attribute entry name and length */ static inline void xent_key_init_flash(const struct ubifs_info *c, void *k, ino_t inum, const struct qstr *nm) { union ubifs_key *key = k; uint32_t hash = c->key_hash(nm->name, nm->len); ubifs_assert(!(hash & ~UBIFS_S_KEY_HASH_MASK)); key->j32[0] = cpu_to_le32(inum); key->j32[1] = cpu_to_le32(hash | (UBIFS_XENT_KEY << UBIFS_S_KEY_HASH_BITS)); memset(k + 8, 0, UBIFS_MAX_KEY_LEN - 8); } /** * lowest_xent_key - get the lowest possible extended attribute entry key. * @c: UBIFS file-system description object * @key: where to store the lowest key * @inum: host inode number */ static inline void lowest_xent_key(const struct ubifs_info *c, union ubifs_key *key, ino_t inum) { key->u32[0] = inum; key->u32[1] = UBIFS_XENT_KEY << UBIFS_S_KEY_HASH_BITS; } /** * data_key_init - initialize data key. * @c: UBIFS file-system description object * @key: key to initialize * @inum: inode number * @block: block number */ static inline void data_key_init(const struct ubifs_info *c, union ubifs_key *key, ino_t inum, unsigned int block) { ubifs_assert(!(block & ~UBIFS_S_KEY_BLOCK_MASK)); key->u32[0] = inum; key->u32[1] = block | (UBIFS_DATA_KEY << UBIFS_S_KEY_BLOCK_BITS); } /** * data_key_init_flash - initialize on-flash data key. * @c: UBIFS file-system description object * @k: key to initialize * @inum: inode number * @block: block number */ static inline void data_key_init_flash(const struct ubifs_info *c, void *k, ino_t inum, unsigned int block) { union ubifs_key *key = k; ubifs_assert(!(block & ~UBIFS_S_KEY_BLOCK_MASK)); key->j32[0] = cpu_to_le32(inum); key->j32[1] = cpu_to_le32(block | (UBIFS_DATA_KEY << UBIFS_S_KEY_BLOCK_BITS)); memset(k + 8, 0, UBIFS_MAX_KEY_LEN - 8); } /** * trun_key_init - initialize truncation node key. * @c: UBIFS file-system description object * @key: key to initialize * @inum: inode number * * Note, UBIFS does not have truncation keys on the media and this function is * only used for purposes of replay. */ static inline void trun_key_init(const struct ubifs_info *c, union ubifs_key *key, ino_t inum) { key->u32[0] = inum; key->u32[1] = UBIFS_TRUN_KEY << UBIFS_S_KEY_BLOCK_BITS; } /** * key_type - get key type. * @c: UBIFS file-system description object * @key: key to get type of */ static inline int key_type(const struct ubifs_info *c, const union ubifs_key *key) { return key->u32[1] >> UBIFS_S_KEY_BLOCK_BITS; } /** * key_type_flash - get type of a on-flash formatted key. * @c: UBIFS file-system description object * @k: key to get type of */ static inline int key_type_flash(const struct ubifs_info *c, const void *k) { const union ubifs_key *key = k; return le32_to_cpu(key->j32[1]) >> UBIFS_S_KEY_BLOCK_BITS; } /** * key_inum - fetch inode number from key. * @c: UBIFS file-system description object * @k: key to fetch inode number from */ static inline ino_t key_inum(const struct ubifs_info *c, const void *k) { const union ubifs_key *key = k; return key->u32[0]; } /** * key_inum_flash - fetch inode number from an on-flash formatted key. * @c: UBIFS file-system description object * @k: key to fetch inode number from */ static inline ino_t key_inum_flash(const struct ubifs_info *c, const void *k) { const union ubifs_key *key = k; return le32_to_cpu(key->j32[0]); } /** * key_hash - get directory entry hash. * @c: UBIFS file-system description object * @key: the key to get hash from */ static inline int key_hash(const struct ubifs_info *c, const union ubifs_key *key) { return key->u32[1] & UBIFS_S_KEY_HASH_MASK; } /** * key_hash_flash - get directory entry hash from an on-flash formatted key. * @c: UBIFS file-system description object * @k: the key to get hash from */ static inline int key_hash_flash(const struct ubifs_info *c, const void *k) { const union ubifs_key *key = k; return le32_to_cpu(key->j32[1]) & UBIFS_S_KEY_HASH_MASK; } /** * key_block - get data block number. * @c: UBIFS file-system description object * @key: the key to get the block number from */ static inline unsigned int key_block(const struct ubifs_info *c, const union ubifs_key *key) { return key->u32[1] & UBIFS_S_KEY_BLOCK_MASK; } /** * key_block_flash - get data block number from an on-flash formatted key. * @c: UBIFS file-system description object * @k: the key to get the block number from */ static inline unsigned int key_block_flash(const struct ubifs_info *c, const void *k) { const union ubifs_key *key = k; return le32_to_cpu(key->j32[1]) & UBIFS_S_KEY_BLOCK_MASK; } /** * key_read - transform a key to in-memory format. * @c: UBIFS file-system description object * @from: the key to transform * @to: the key to store the result */ static inline void key_read(const struct ubifs_info *c, const void *from, union ubifs_key *to) { const union ubifs_key *f = from; to->u32[0] = le32_to_cpu(f->j32[0]); to->u32[1] = le32_to_cpu(f->j32[1]); } /** * key_write - transform a key from in-memory format. * @c: UBIFS file-system description object * @from: the key to transform * @to: the key to store the result */ static inline void key_write(const struct ubifs_info *c, const union ubifs_key *from, void *to) { union ubifs_key *t = to; t->j32[0] = cpu_to_le32(from->u32[0]); t->j32[1] = cpu_to_le32(from->u32[1]); memset(to + 8, 0, UBIFS_MAX_KEY_LEN - 8); } /** * key_write_idx - transform a key from in-memory format for the index. * @c: UBIFS file-system description object * @from: the key to transform * @to: the key to store the result */ static inline void key_write_idx(const struct ubifs_info *c, const union ubifs_key *from, void *to) { union ubifs_key *t = to; t->j32[0] = cpu_to_le32(from->u32[0]); t->j32[1] = cpu_to_le32(from->u32[1]); } /** * key_copy - copy a key. * @c: UBIFS file-system description object * @from: the key to copy from * @to: the key to copy to */ static inline void key_copy(const struct ubifs_info *c, const union ubifs_key *from, union ubifs_key *to) { to->u64[0] = from->u64[0]; } /** * keys_cmp - compare keys. * @c: UBIFS file-system description object * @key1: the first key to compare * @key2: the second key to compare * * This function compares 2 keys and returns %-1 if @key1 is less than * @key2, %0 if the keys are equivalent and %1 if @key1 is greater than @key2. */ static inline int keys_cmp(const struct ubifs_info *c, const union ubifs_key *key1, const union ubifs_key *key2) { if (key1->u32[0] < key2->u32[0]) return -1; if (key1->u32[0] > key2->u32[0]) return 1; if (key1->u32[1] < key2->u32[1]) return -1; if (key1->u32[1] > key2->u32[1]) return 1; return 0; } /** * keys_eq - determine if keys are equivalent. * @c: UBIFS file-system description object * @key1: the first key to compare * @key2: the second key to compare * * This function compares 2 keys and returns %1 if @key1 is equal to @key2 and * %0 if not. */ static inline int keys_eq(const struct ubifs_info *c, const union ubifs_key *key1, const union ubifs_key *key2) { if (key1->u32[0] != key2->u32[0]) return 0; if (key1->u32[1] != key2->u32[1]) return 0; return 1; } /** * is_hash_key - is a key vulnerable to hash collisions. * @c: UBIFS file-system description object * @key: key * * This function returns %1 if @key is a hashed key or %0 otherwise. */ static inline int is_hash_key(const struct ubifs_info *c, const union ubifs_key *key) { int type = key_type(c, key); return type == UBIFS_DENT_KEY || type == UBIFS_XENT_KEY; } /** * key_max_inode_size - get maximum file size allowed by current key format. * @c: UBIFS file-system description object */ static inline unsigned long long key_max_inode_size(const struct ubifs_info *c) { switch (c->key_fmt) { case UBIFS_SIMPLE_KEY_FMT: return (1ULL << UBIFS_S_KEY_BLOCK_BITS) * UBIFS_BLOCK_SIZE; default: return 0; } } #endif /* !__UBIFS_KEY_H__ */
1001-study-uboot
fs/ubifs/key.h
C
gpl3
15,199
/* * 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 commit-related functionality of the LEB properties * subsystem. */ #include "crc16.h" #include "ubifs.h" /** * free_obsolete_cnodes - free obsolete cnodes for commit end. * @c: UBIFS file-system description object */ static void free_obsolete_cnodes(struct ubifs_info *c) { struct ubifs_cnode *cnode, *cnext; cnext = c->lpt_cnext; if (!cnext) return; do { cnode = cnext; cnext = cnode->cnext; if (test_bit(OBSOLETE_CNODE, &cnode->flags)) kfree(cnode); else cnode->cnext = NULL; } while (cnext != c->lpt_cnext); c->lpt_cnext = NULL; } /** * first_nnode - find the first nnode in memory. * @c: UBIFS file-system description object * @hght: height of tree where nnode found is returned here * * This function returns a pointer to the nnode found or %NULL if no nnode is * found. This function is a helper to 'ubifs_lpt_free()'. */ static struct ubifs_nnode *first_nnode(struct ubifs_info *c, int *hght) { struct ubifs_nnode *nnode; int h, i, found; nnode = c->nroot; *hght = 0; if (!nnode) return NULL; for (h = 1; h < c->lpt_hght; h++) { found = 0; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { if (nnode->nbranch[i].nnode) { found = 1; nnode = nnode->nbranch[i].nnode; *hght = h; break; } } if (!found) break; } return nnode; } /** * next_nnode - find the next nnode in memory. * @c: UBIFS file-system description object * @nnode: nnode from which to start. * @hght: height of tree where nnode is, is passed and returned here * * This function returns a pointer to the nnode found or %NULL if no nnode is * found. This function is a helper to 'ubifs_lpt_free()'. */ static struct ubifs_nnode *next_nnode(struct ubifs_info *c, struct ubifs_nnode *nnode, int *hght) { struct ubifs_nnode *parent; int iip, h, i, found; parent = nnode->parent; if (!parent) return NULL; if (nnode->iip == UBIFS_LPT_FANOUT - 1) { *hght -= 1; return parent; } for (iip = nnode->iip + 1; iip < UBIFS_LPT_FANOUT; iip++) { nnode = parent->nbranch[iip].nnode; if (nnode) break; } if (!nnode) { *hght -= 1; return parent; } for (h = *hght + 1; h < c->lpt_hght; h++) { found = 0; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { if (nnode->nbranch[i].nnode) { found = 1; nnode = nnode->nbranch[i].nnode; *hght = h; break; } } if (!found) break; } return nnode; } /** * ubifs_lpt_free - free resources owned by the LPT. * @c: UBIFS file-system description object * @wr_only: free only resources used for writing */ void ubifs_lpt_free(struct ubifs_info *c, int wr_only) { struct ubifs_nnode *nnode; int i, hght; /* Free write-only things first */ free_obsolete_cnodes(c); /* Leftover from a failed commit */ vfree(c->ltab_cmt); c->ltab_cmt = NULL; vfree(c->lpt_buf); c->lpt_buf = NULL; kfree(c->lsave); c->lsave = NULL; if (wr_only) return; /* Now free the rest */ nnode = first_nnode(c, &hght); while (nnode) { for (i = 0; i < UBIFS_LPT_FANOUT; i++) kfree(nnode->nbranch[i].nnode); nnode = next_nnode(c, nnode, &hght); } for (i = 0; i < LPROPS_HEAP_CNT; i++) kfree(c->lpt_heap[i].arr); kfree(c->dirty_idx.arr); kfree(c->nroot); vfree(c->ltab); kfree(c->lpt_nod_buf); }
1001-study-uboot
fs/ubifs/lpt_commit.c
C
gpl3
4,086
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation * * (C) Copyright 2008-2009 * Stefan Roese, DENX Software Engineering, sr@denx.de. * * 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_H__ #define __UBIFS_H__ #if 0 /* Enable for debugging output */ #define CONFIG_UBIFS_FS_DEBUG #define CONFIG_UBIFS_FS_DEBUG_MSG_LVL 3 #endif #include <ubi_uboot.h> #include <linux/ctype.h> #include <linux/time.h> #include <linux/math64.h> #include "ubifs-media.h" struct dentry; struct file; struct iattr; struct kstat; struct vfsmount; extern struct super_block *ubifs_sb; extern unsigned int ubifs_msg_flags; extern unsigned int ubifs_chk_flags; extern unsigned int ubifs_tst_flags; #define pgoff_t unsigned long /* * We "simulate" the Linux page struct much simpler here */ struct page { pgoff_t index; void *addr; struct inode *inode; }; void iput(struct inode *inode); /* * The atomic operations are used for budgeting etc which is not * needed for the read-only U-Boot implementation: */ #define atomic_long_inc(a) #define atomic_long_dec(a) #define atomic_long_sub(a, b) /* linux/include/time.h */ struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; /* linux/include/dcache.h */ /* * "quick string" -- eases parameter passing, but more importantly * saves "metadata" about the string (ie length and the hash). * * hash comes first so it snuggles against d_parent in the * dentry. */ struct qstr { unsigned int hash; unsigned int len; const char *name; }; struct inode { struct hlist_node i_hash; struct list_head i_list; struct list_head i_sb_list; struct list_head i_dentry; unsigned long i_ino; unsigned int i_nlink; uid_t i_uid; gid_t i_gid; dev_t i_rdev; u64 i_version; loff_t i_size; #ifdef __NEED_I_SIZE_ORDERED seqcount_t i_size_seqcount; #endif struct timespec i_atime; struct timespec i_mtime; struct timespec i_ctime; unsigned int i_blkbits; unsigned short i_bytes; umode_t i_mode; spinlock_t i_lock; /* i_blocks, i_bytes, maybe i_size */ struct mutex i_mutex; struct rw_semaphore i_alloc_sem; const struct inode_operations *i_op; const struct file_operations *i_fop; /* former ->i_op->default_file_ops */ struct super_block *i_sb; struct file_lock *i_flock; #ifdef CONFIG_QUOTA struct dquot *i_dquot[MAXQUOTAS]; #endif struct list_head i_devices; int i_cindex; __u32 i_generation; #ifdef CONFIG_DNOTIFY unsigned long i_dnotify_mask; /* Directory notify events */ struct dnotify_struct *i_dnotify; /* for directory notifications */ #endif #ifdef CONFIG_INOTIFY struct list_head inotify_watches; /* watches on this inode */ struct mutex inotify_mutex; /* protects the watches list */ #endif unsigned long i_state; unsigned long dirtied_when; /* jiffies of first dirtying */ unsigned int i_flags; #ifdef CONFIG_SECURITY void *i_security; #endif void *i_private; /* fs or device private pointer */ }; struct super_block { struct list_head s_list; /* Keep this first */ dev_t s_dev; /* search index; _not_ kdev_t */ unsigned long s_blocksize; unsigned char s_blocksize_bits; unsigned char s_dirt; unsigned long long s_maxbytes; /* Max file size */ struct file_system_type *s_type; const struct super_operations *s_op; struct dquot_operations *dq_op; struct quotactl_ops *s_qcop; const struct export_operations *s_export_op; unsigned long s_flags; unsigned long s_magic; struct dentry *s_root; struct rw_semaphore s_umount; struct mutex s_lock; int s_count; int s_syncing; int s_need_sync_fs; #ifdef CONFIG_SECURITY void *s_security; #endif struct xattr_handler **s_xattr; struct list_head s_inodes; /* all inodes */ struct list_head s_dirty; /* dirty inodes */ struct list_head s_io; /* parked for writeback */ struct list_head s_more_io; /* parked for more writeback */ struct hlist_head s_anon; /* anonymous dentries for (nfs) exporting */ struct list_head s_files; /* s_dentry_lru and s_nr_dentry_unused are protected by dcache_lock */ struct list_head s_dentry_lru; /* unused dentry lru */ int s_nr_dentry_unused; /* # of dentry on lru */ struct block_device *s_bdev; struct mtd_info *s_mtd; struct list_head s_instances; int s_frozen; wait_queue_head_t s_wait_unfrozen; char s_id[32]; /* Informational name */ void *s_fs_info; /* Filesystem private info */ /* * The next field is for VFS *only*. No filesystems have any business * even looking at it. You had been warned. */ struct mutex s_vfs_rename_mutex; /* Kludge */ /* Granularity of c/m/atime in ns. Cannot be worse than a second */ u32 s_time_gran; /* * Filesystem subtype. If non-empty the filesystem type field * in /proc/mounts will be "type.subtype" */ char *s_subtype; /* * Saved mount options for lazy filesystems using * generic_show_options() */ char *s_options; }; struct file_system_type { const char *name; int fs_flags; int (*get_sb) (struct file_system_type *, int, const char *, void *, struct vfsmount *); void (*kill_sb) (struct super_block *); struct module *owner; struct file_system_type * next; struct list_head fs_supers; }; struct vfsmount { struct list_head mnt_hash; struct vfsmount *mnt_parent; /* fs we are mounted on */ struct dentry *mnt_mountpoint; /* dentry of mountpoint */ struct dentry *mnt_root; /* root of the mounted tree */ struct super_block *mnt_sb; /* pointer to superblock */ struct list_head mnt_mounts; /* list of children, anchored here */ struct list_head mnt_child; /* and going through their mnt_child */ int mnt_flags; /* 4 bytes hole on 64bits arches */ const char *mnt_devname; /* Name of device e.g. /dev/dsk/hda1 */ struct list_head mnt_list; struct list_head mnt_expire; /* link in fs-specific expiry list */ struct list_head mnt_share; /* circular list of shared mounts */ struct list_head mnt_slave_list;/* list of slave mounts */ struct list_head mnt_slave; /* slave list entry */ struct vfsmount *mnt_master; /* slave is on master->mnt_slave_list */ struct mnt_namespace *mnt_ns; /* containing namespace */ int mnt_id; /* mount identifier */ int mnt_group_id; /* peer group identifier */ /* * We put mnt_count & mnt_expiry_mark at the end of struct vfsmount * to let these frequently modified fields in a separate cache line * (so that reads of mnt_flags wont ping-pong on SMP machines) */ int mnt_expiry_mark; /* true if marked for expiry */ int mnt_pinned; int mnt_ghosts; /* * This value is not stable unless all of the mnt_writers[] spinlocks * are held, and all mnt_writer[]s on this mount have 0 as their ->count */ }; struct path { struct vfsmount *mnt; struct dentry *dentry; }; struct file { struct path f_path; #define f_dentry f_path.dentry #define f_vfsmnt f_path.mnt const struct file_operations *f_op; unsigned int f_flags; loff_t f_pos; unsigned int f_uid, f_gid; u64 f_version; #ifdef CONFIG_SECURITY void *f_security; #endif /* needed for tty driver, and maybe others */ void *private_data; #ifdef CONFIG_EPOLL /* Used by fs/eventpoll.c to link all the hooks to this file */ struct list_head f_ep_links; spinlock_t f_ep_lock; #endif /* #ifdef CONFIG_EPOLL */ #ifdef CONFIG_DEBUG_WRITECOUNT unsigned long f_mnt_write_state; #endif }; /* * get_seconds() not really needed in the read-only implmentation */ #define get_seconds() 0 /* 4k page size */ #define PAGE_CACHE_SHIFT 12 #define PAGE_CACHE_SIZE (1 << PAGE_CACHE_SHIFT) /* Page cache limit. The filesystems should put that into their s_maxbytes limits, otherwise bad things can happen in VM. */ #if BITS_PER_LONG==32 #define MAX_LFS_FILESIZE (((u64)PAGE_CACHE_SIZE << (BITS_PER_LONG-1))-1) #elif BITS_PER_LONG==64 #define MAX_LFS_FILESIZE 0x7fffffffffffffffUL #endif #define INT_MAX ((int)(~0U>>1)) #define INT_MIN (-INT_MAX - 1) #define LLONG_MAX ((long long)(~0ULL>>1)) /* * These are the fs-independent mount-flags: up to 32 flags are supported */ #define MS_RDONLY 1 /* Mount read-only */ #define MS_NOSUID 2 /* Ignore suid and sgid bits */ #define MS_NODEV 4 /* Disallow access to device special files */ #define MS_NOEXEC 8 /* Disallow program execution */ #define MS_SYNCHRONOUS 16 /* Writes are synced at once */ #define MS_REMOUNT 32 /* Alter flags of a mounted FS */ #define MS_MANDLOCK 64 /* Allow mandatory locks on an FS */ #define MS_DIRSYNC 128 /* Directory modifications are synchronous */ #define MS_NOATIME 1024 /* Do not update access times. */ #define MS_NODIRATIME 2048 /* Do not update directory access times */ #define MS_BIND 4096 #define MS_MOVE 8192 #define MS_REC 16384 #define MS_VERBOSE 32768 /* War is peace. Verbosity is silence. MS_VERBOSE is deprecated. */ #define MS_SILENT 32768 #define MS_POSIXACL (1<<16) /* VFS does not apply the umask */ #define MS_UNBINDABLE (1<<17) /* change to unbindable */ #define MS_PRIVATE (1<<18) /* change to private */ #define MS_SLAVE (1<<19) /* change to slave */ #define MS_SHARED (1<<20) /* change to shared */ #define MS_RELATIME (1<<21) /* Update atime relative to mtime/ctime. */ #define MS_KERNMOUNT (1<<22) /* this is a kern_mount call */ #define MS_I_VERSION (1<<23) /* Update inode I_version field */ #define MS_ACTIVE (1<<30) #define MS_NOUSER (1<<31) #define I_NEW 8 /* Inode flags - they have nothing to superblock flags now */ #define S_SYNC 1 /* Writes are synced at once */ #define S_NOATIME 2 /* Do not update access times */ #define S_APPEND 4 /* Append-only file */ #define S_IMMUTABLE 8 /* Immutable file */ #define S_DEAD 16 /* removed, but still open directory */ #define S_NOQUOTA 32 /* Inode is not counted to quota */ #define S_DIRSYNC 64 /* Directory modifications are synchronous */ #define S_NOCMTIME 128 /* Do not update file c/mtime */ #define S_SWAPFILE 256 /* Do not truncate: swapon got its bmaps */ #define S_PRIVATE 512 /* Inode is fs-internal */ /* include/linux/stat.h */ #define S_IFMT 00170000 #define S_IFSOCK 0140000 #define S_IFLNK 0120000 #define S_IFREG 0100000 #define S_IFBLK 0060000 #define S_IFDIR 0040000 #define S_IFCHR 0020000 #define S_IFIFO 0010000 #define S_ISUID 0004000 #define S_ISGID 0002000 #define S_ISVTX 0001000 /* include/linux/fs.h */ /* * File types * * NOTE! These match bits 12..15 of stat.st_mode * (ie "(i_mode >> 12) & 15"). */ #define DT_UNKNOWN 0 #define DT_FIFO 1 #define DT_CHR 2 #define DT_DIR 4 #define DT_BLK 6 #define DT_REG 8 #define DT_LNK 10 #define DT_SOCK 12 #define DT_WHT 14 #define I_DIRTY_SYNC 1 #define I_DIRTY_DATASYNC 2 #define I_DIRTY_PAGES 4 #define I_NEW 8 #define I_WILL_FREE 16 #define I_FREEING 32 #define I_CLEAR 64 #define __I_LOCK 7 #define I_LOCK (1 << __I_LOCK) #define __I_SYNC 8 #define I_SYNC (1 << __I_SYNC) #define I_DIRTY (I_DIRTY_SYNC | I_DIRTY_DATASYNC | I_DIRTY_PAGES) /* linux/include/dcache.h */ #define DNAME_INLINE_LEN_MIN 36 struct dentry { unsigned int d_flags; /* protected by d_lock */ spinlock_t d_lock; /* per dentry lock */ struct inode *d_inode; /* Where the name belongs to - NULL is * negative */ /* * The next three fields are touched by __d_lookup. Place them here * so they all fit in a cache line. */ struct hlist_node d_hash; /* lookup hash list */ struct dentry *d_parent; /* parent directory */ struct qstr d_name; struct list_head d_lru; /* LRU list */ /* * d_child and d_rcu can share memory */ struct list_head d_subdirs; /* our children */ struct list_head d_alias; /* inode alias list */ unsigned long d_time; /* used by d_revalidate */ struct super_block *d_sb; /* The root of the dentry tree */ void *d_fsdata; /* fs-specific data */ #ifdef CONFIG_PROFILING struct dcookie_struct *d_cookie; /* cookie, if any */ #endif int d_mounted; unsigned char d_iname[DNAME_INLINE_LEN_MIN]; /* small names */ }; static inline ino_t parent_ino(struct dentry *dentry) { ino_t res; spin_lock(&dentry->d_lock); res = dentry->d_parent->d_inode->i_ino; spin_unlock(&dentry->d_lock); return res; } /* debug.c */ #define DEFINE_SPINLOCK(...) #define module_param_named(...) /* misc.h */ #define mutex_lock_nested(...) #define mutex_unlock_nested(...) #define mutex_is_locked(...) 0 /* Version of this UBIFS implementation */ #define UBIFS_VERSION 1 /* Normal UBIFS messages */ #define ubifs_msg(fmt, ...) \ printk(KERN_NOTICE "UBIFS: " fmt "\n", ##__VA_ARGS__) /* UBIFS error messages */ #define ubifs_err(fmt, ...) \ printk(KERN_ERR "UBIFS error (pid %d): %s: " fmt "\n", 0, \ __func__, ##__VA_ARGS__) /* UBIFS warning messages */ #define ubifs_warn(fmt, ...) \ printk(KERN_WARNING "UBIFS warning (pid %d): %s: " fmt "\n", \ 0, __func__, ##__VA_ARGS__) /* UBIFS file system VFS magic number */ #define UBIFS_SUPER_MAGIC 0x24051905 /* Number of UBIFS blocks per VFS page */ #define UBIFS_BLOCKS_PER_PAGE (PAGE_CACHE_SIZE / UBIFS_BLOCK_SIZE) #define UBIFS_BLOCKS_PER_PAGE_SHIFT (PAGE_CACHE_SHIFT - UBIFS_BLOCK_SHIFT) /* "File system end of life" sequence number watermark */ #define SQNUM_WARN_WATERMARK 0xFFFFFFFF00000000ULL #define SQNUM_WATERMARK 0xFFFFFFFFFF000000ULL /* * Minimum amount of LEBs reserved for the index. At present the index needs at * least 2 LEBs: one for the index head and one for in-the-gaps method (which * currently does not cater for the index head and so excludes it from * consideration). */ #define MIN_INDEX_LEBS 2 /* Minimum amount of data UBIFS writes to the flash */ #define MIN_WRITE_SZ (UBIFS_DATA_NODE_SZ + 8) /* * Currently we do not support inode number overlapping and re-using, so this * watermark defines dangerous inode number level. This should be fixed later, * although it is difficult to exceed current limit. Another option is to use * 64-bit inode numbers, but this means more overhead. */ #define INUM_WARN_WATERMARK 0xFFF00000 #define INUM_WATERMARK 0xFFFFFF00 /* Largest key size supported in this implementation */ #define CUR_MAX_KEY_LEN UBIFS_SK_LEN /* Maximum number of entries in each LPT (LEB category) heap */ #define LPT_HEAP_SZ 256 /* * Background thread name pattern. The numbers are UBI device and volume * numbers. */ #define BGT_NAME_PATTERN "ubifs_bgt%d_%d" /* Default write-buffer synchronization timeout (5 secs) */ #define DEFAULT_WBUF_TIMEOUT (5 * HZ) /* Maximum possible inode number (only 32-bit inodes are supported now) */ #define MAX_INUM 0xFFFFFFFF /* Number of non-data journal heads */ #define NONDATA_JHEADS_CNT 2 /* Garbage collector head */ #define GCHD 0 /* Base journal head number */ #define BASEHD 1 /* First "general purpose" journal head */ #define DATAHD 2 /* 'No change' value for 'ubifs_change_lp()' */ #define LPROPS_NC 0x80000001 /* * There is no notion of truncation key because truncation nodes do not exist * in TNC. However, when replaying, it is handy to introduce fake "truncation" * keys for truncation nodes because the code becomes simpler. So we define * %UBIFS_TRUN_KEY type. */ #define UBIFS_TRUN_KEY UBIFS_KEY_TYPES_CNT /* * How much a directory entry/extended attribute entry adds to the parent/host * inode. */ #define CALC_DENT_SIZE(name_len) ALIGN(UBIFS_DENT_NODE_SZ + (name_len) + 1, 8) /* How much an extended attribute adds to the host inode */ #define CALC_XATTR_BYTES(data_len) ALIGN(UBIFS_INO_NODE_SZ + (data_len) + 1, 8) /* * Znodes which were not touched for 'OLD_ZNODE_AGE' seconds are considered * "old", and znode which were touched last 'YOUNG_ZNODE_AGE' seconds ago are * considered "young". This is used by shrinker when selecting znode to trim * off. */ #define OLD_ZNODE_AGE 20 #define YOUNG_ZNODE_AGE 5 /* * Some compressors, like LZO, may end up with more data then the input buffer. * So UBIFS always allocates larger output buffer, to be sure the compressor * will not corrupt memory in case of worst case compression. */ #define WORST_COMPR_FACTOR 2 /* Maximum expected tree height for use by bottom_up_buf */ #define BOTTOM_UP_HEIGHT 64 /* Maximum number of data nodes to bulk-read */ #define UBIFS_MAX_BULK_READ 32 /* * Lockdep classes for UBIFS inode @ui_mutex. */ enum { WB_MUTEX_1 = 0, WB_MUTEX_2 = 1, WB_MUTEX_3 = 2, }; /* * Znode flags (actually, bit numbers which store the flags). * * DIRTY_ZNODE: znode is dirty * COW_ZNODE: znode is being committed and a new instance of this znode has to * be created before changing this znode * OBSOLETE_ZNODE: znode is obsolete, which means it was deleted, but it is * still in the commit list and the ongoing commit operation * will commit it, and delete this znode after it is done */ enum { DIRTY_ZNODE = 0, COW_ZNODE = 1, OBSOLETE_ZNODE = 2, }; /* * Commit states. * * COMMIT_RESTING: commit is not wanted * COMMIT_BACKGROUND: background commit has been requested * COMMIT_REQUIRED: commit is required * COMMIT_RUNNING_BACKGROUND: background commit is running * COMMIT_RUNNING_REQUIRED: commit is running and it is required * COMMIT_BROKEN: commit failed */ enum { COMMIT_RESTING = 0, COMMIT_BACKGROUND, COMMIT_REQUIRED, COMMIT_RUNNING_BACKGROUND, COMMIT_RUNNING_REQUIRED, COMMIT_BROKEN, }; /* * 'ubifs_scan_a_node()' return values. * * SCANNED_GARBAGE: scanned garbage * SCANNED_EMPTY_SPACE: scanned empty space * SCANNED_A_NODE: scanned a valid node * SCANNED_A_CORRUPT_NODE: scanned a corrupted node * SCANNED_A_BAD_PAD_NODE: scanned a padding node with invalid pad length * * Greater than zero means: 'scanned that number of padding bytes' */ enum { SCANNED_GARBAGE = 0, SCANNED_EMPTY_SPACE = -1, SCANNED_A_NODE = -2, SCANNED_A_CORRUPT_NODE = -3, SCANNED_A_BAD_PAD_NODE = -4, }; /* * LPT cnode flag bits. * * DIRTY_CNODE: cnode is dirty * COW_CNODE: cnode is being committed and must be copied before writing * OBSOLETE_CNODE: cnode is being committed and has been copied (or deleted), * so it can (and must) be freed when the commit is finished */ enum { DIRTY_CNODE = 0, COW_CNODE = 1, OBSOLETE_CNODE = 2, }; /* * Dirty flag bits (lpt_drty_flgs) for LPT special nodes. * * LTAB_DIRTY: ltab node is dirty * LSAVE_DIRTY: lsave node is dirty */ enum { LTAB_DIRTY = 1, LSAVE_DIRTY = 2, }; /* * Return codes used by the garbage collector. * @LEB_FREED: the logical eraseblock was freed and is ready to use * @LEB_FREED_IDX: indexing LEB was freed and can be used only after the commit * @LEB_RETAINED: the logical eraseblock was freed and retained for GC purposes */ enum { LEB_FREED, LEB_FREED_IDX, LEB_RETAINED, }; /** * struct ubifs_old_idx - index node obsoleted since last commit start. * @rb: rb-tree node * @lnum: LEB number of obsoleted index node * @offs: offset of obsoleted index node */ struct ubifs_old_idx { struct rb_node rb; int lnum; int offs; }; /* The below union makes it easier to deal with keys */ union ubifs_key { uint8_t u8[CUR_MAX_KEY_LEN]; uint32_t u32[CUR_MAX_KEY_LEN/4]; uint64_t u64[CUR_MAX_KEY_LEN/8]; __le32 j32[CUR_MAX_KEY_LEN/4]; }; /** * struct ubifs_scan_node - UBIFS scanned node information. * @list: list of scanned nodes * @key: key of node scanned (if it has one) * @sqnum: sequence number * @type: type of node scanned * @offs: offset with LEB of node scanned * @len: length of node scanned * @node: raw node */ struct ubifs_scan_node { struct list_head list; union ubifs_key key; unsigned long long sqnum; int type; int offs; int len; void *node; }; /** * struct ubifs_scan_leb - UBIFS scanned LEB information. * @lnum: logical eraseblock number * @nodes_cnt: number of nodes scanned * @nodes: list of struct ubifs_scan_node * @endpt: end point (and therefore the start of empty space) * @ecc: read returned -EBADMSG * @buf: buffer containing entire LEB scanned */ struct ubifs_scan_leb { int lnum; int nodes_cnt; struct list_head nodes; int endpt; int ecc; void *buf; }; /** * struct ubifs_gced_idx_leb - garbage-collected indexing LEB. * @list: list * @lnum: LEB number * @unmap: OK to unmap this LEB * * This data structure is used to temporary store garbage-collected indexing * LEBs - they are not released immediately, but only after the next commit. * This is needed to guarantee recoverability. */ struct ubifs_gced_idx_leb { struct list_head list; int lnum; int unmap; }; /** * struct ubifs_inode - UBIFS in-memory inode description. * @vfs_inode: VFS inode description object * @creat_sqnum: sequence number at time of creation * @del_cmtno: commit number corresponding to the time the inode was deleted, * protected by @c->commit_sem; * @xattr_size: summarized size of all extended attributes in bytes * @xattr_cnt: count of extended attributes this inode has * @xattr_names: sum of lengths of all extended attribute names belonging to * this inode * @dirty: non-zero if the inode is dirty * @xattr: non-zero if this is an extended attribute inode * @bulk_read: non-zero if bulk-read should be used * @ui_mutex: serializes inode write-back with the rest of VFS operations, * serializes "clean <-> dirty" state changes, serializes bulk-read, * protects @dirty, @bulk_read, @ui_size, and @xattr_size * @ui_lock: protects @synced_i_size * @synced_i_size: synchronized size of inode, i.e. the value of inode size * currently stored on the flash; used only for regular file * inodes * @ui_size: inode size used by UBIFS when writing to flash * @flags: inode flags (@UBIFS_COMPR_FL, etc) * @compr_type: default compression type used for this inode * @last_page_read: page number of last page read (for bulk read) * @read_in_a_row: number of consecutive pages read in a row (for bulk read) * @data_len: length of the data attached to the inode * @data: inode's data * * @ui_mutex exists for two main reasons. At first it prevents inodes from * being written back while UBIFS changing them, being in the middle of an VFS * operation. This way UBIFS makes sure the inode fields are consistent. For * example, in 'ubifs_rename()' we change 3 inodes simultaneously, and * write-back must not write any of them before we have finished. * * The second reason is budgeting - UBIFS has to budget all operations. If an * operation is going to mark an inode dirty, it has to allocate budget for * this. It cannot just mark it dirty because there is no guarantee there will * be enough flash space to write the inode back later. This means UBIFS has * to have full control over inode "clean <-> dirty" transitions (and pages * actually). But unfortunately, VFS marks inodes dirty in many places, and it * does not ask the file-system if it is allowed to do so (there is a notifier, * but it is not enough), i.e., there is no mechanism to synchronize with this. * So UBIFS has its own inode dirty flag and its own mutex to serialize * "clean <-> dirty" transitions. * * The @synced_i_size field is used to make sure we never write pages which are * beyond last synchronized inode size. See 'ubifs_writepage()' for more * information. * * The @ui_size is a "shadow" variable for @inode->i_size and UBIFS uses * @ui_size instead of @inode->i_size. The reason for this is that UBIFS cannot * make sure @inode->i_size is always changed under @ui_mutex, because it * cannot call 'vmtruncate()' with @ui_mutex locked, because it would deadlock * with 'ubifs_writepage()' (see file.c). All the other inode fields are * changed under @ui_mutex, so they do not need "shadow" fields. Note, one * could consider to rework locking and base it on "shadow" fields. */ struct ubifs_inode { struct inode vfs_inode; unsigned long long creat_sqnum; unsigned long long del_cmtno; unsigned int xattr_size; unsigned int xattr_cnt; unsigned int xattr_names; unsigned int dirty:1; unsigned int xattr:1; unsigned int bulk_read:1; unsigned int compr_type:2; struct mutex ui_mutex; spinlock_t ui_lock; loff_t synced_i_size; loff_t ui_size; int flags; pgoff_t last_page_read; pgoff_t read_in_a_row; int data_len; void *data; }; /** * struct ubifs_unclean_leb - records a LEB recovered under read-only mode. * @list: list * @lnum: LEB number of recovered LEB * @endpt: offset where recovery ended * * This structure records a LEB identified during recovery that needs to be * cleaned but was not because UBIFS was mounted read-only. The information * is used to clean the LEB when remounting to read-write mode. */ struct ubifs_unclean_leb { struct list_head list; int lnum; int endpt; }; /* * LEB properties flags. * * LPROPS_UNCAT: not categorized * LPROPS_DIRTY: dirty > free, dirty >= @c->dead_wm, not index * LPROPS_DIRTY_IDX: dirty + free > @c->min_idx_node_sze and index * LPROPS_FREE: free > 0, dirty < @c->dead_wm, not empty, not index * LPROPS_HEAP_CNT: number of heaps used for storing categorized LEBs * LPROPS_EMPTY: LEB is empty, not taken * LPROPS_FREEABLE: free + dirty == leb_size, not index, not taken * LPROPS_FRDI_IDX: free + dirty == leb_size and index, may be taken * LPROPS_CAT_MASK: mask for the LEB categories above * LPROPS_TAKEN: LEB was taken (this flag is not saved on the media) * LPROPS_INDEX: LEB contains indexing nodes (this flag also exists on flash) */ enum { LPROPS_UNCAT = 0, LPROPS_DIRTY = 1, LPROPS_DIRTY_IDX = 2, LPROPS_FREE = 3, LPROPS_HEAP_CNT = 3, LPROPS_EMPTY = 4, LPROPS_FREEABLE = 5, LPROPS_FRDI_IDX = 6, LPROPS_CAT_MASK = 15, LPROPS_TAKEN = 16, LPROPS_INDEX = 32, }; /** * struct ubifs_lprops - logical eraseblock properties. * @free: amount of free space in bytes * @dirty: amount of dirty space in bytes * @flags: LEB properties flags (see above) * @lnum: LEB number * @list: list of same-category lprops (for LPROPS_EMPTY and LPROPS_FREEABLE) * @hpos: heap position in heap of same-category lprops (other categories) */ struct ubifs_lprops { int free; int dirty; int flags; int lnum; union { struct list_head list; int hpos; }; }; /** * struct ubifs_lpt_lprops - LPT logical eraseblock properties. * @free: amount of free space in bytes * @dirty: amount of dirty space in bytes * @tgc: trivial GC flag (1 => unmap after commit end) * @cmt: commit flag (1 => reserved for commit) */ struct ubifs_lpt_lprops { int free; int dirty; unsigned tgc:1; unsigned cmt:1; }; /** * struct ubifs_lp_stats - statistics of eraseblocks in the main area. * @empty_lebs: number of empty LEBs * @taken_empty_lebs: number of taken LEBs * @idx_lebs: number of indexing LEBs * @total_free: total free space in bytes (includes all LEBs) * @total_dirty: total dirty space in bytes (includes all LEBs) * @total_used: total used space in bytes (does not include index LEBs) * @total_dead: total dead space in bytes (does not include index LEBs) * @total_dark: total dark space in bytes (does not include index LEBs) * * The @taken_empty_lebs field counts the LEBs that are in the transient state * of having been "taken" for use but not yet written to. @taken_empty_lebs is * needed to account correctly for @gc_lnum, otherwise @empty_lebs could be * used by itself (in which case 'unused_lebs' would be a better name). In the * case of @gc_lnum, it is "taken" at mount time or whenever a LEB is retained * by GC, but unlike other empty LEBs that are "taken", it may not be written * straight away (i.e. before the next commit start or unmount), so either * @gc_lnum must be specially accounted for, or the current approach followed * i.e. count it under @taken_empty_lebs. * * @empty_lebs includes @taken_empty_lebs. * * @total_used, @total_dead and @total_dark fields do not account indexing * LEBs. */ struct ubifs_lp_stats { int empty_lebs; int taken_empty_lebs; int idx_lebs; long long total_free; long long total_dirty; long long total_used; long long total_dead; long long total_dark; }; struct ubifs_nnode; /** * struct ubifs_cnode - LEB Properties Tree common node. * @parent: parent nnode * @cnext: next cnode to commit * @flags: flags (%DIRTY_LPT_NODE or %OBSOLETE_LPT_NODE) * @iip: index in parent * @level: level in the tree (zero for pnodes, greater than zero for nnodes) * @num: node number */ struct ubifs_cnode { struct ubifs_nnode *parent; struct ubifs_cnode *cnext; unsigned long flags; int iip; int level; int num; }; /** * struct ubifs_pnode - LEB Properties Tree leaf node. * @parent: parent nnode * @cnext: next cnode to commit * @flags: flags (%DIRTY_LPT_NODE or %OBSOLETE_LPT_NODE) * @iip: index in parent * @level: level in the tree (always zero for pnodes) * @num: node number * @lprops: LEB properties array */ struct ubifs_pnode { struct ubifs_nnode *parent; struct ubifs_cnode *cnext; unsigned long flags; int iip; int level; int num; struct ubifs_lprops lprops[UBIFS_LPT_FANOUT]; }; /** * struct ubifs_nbranch - LEB Properties Tree internal node branch. * @lnum: LEB number of child * @offs: offset of child * @nnode: nnode child * @pnode: pnode child * @cnode: cnode child */ struct ubifs_nbranch { int lnum; int offs; union { struct ubifs_nnode *nnode; struct ubifs_pnode *pnode; struct ubifs_cnode *cnode; }; }; /** * struct ubifs_nnode - LEB Properties Tree internal node. * @parent: parent nnode * @cnext: next cnode to commit * @flags: flags (%DIRTY_LPT_NODE or %OBSOLETE_LPT_NODE) * @iip: index in parent * @level: level in the tree (always greater than zero for nnodes) * @num: node number * @nbranch: branches to child nodes */ struct ubifs_nnode { struct ubifs_nnode *parent; struct ubifs_cnode *cnext; unsigned long flags; int iip; int level; int num; struct ubifs_nbranch nbranch[UBIFS_LPT_FANOUT]; }; /** * struct ubifs_lpt_heap - heap of categorized lprops. * @arr: heap array * @cnt: number in heap * @max_cnt: maximum number allowed in heap * * There are %LPROPS_HEAP_CNT heaps. */ struct ubifs_lpt_heap { struct ubifs_lprops **arr; int cnt; int max_cnt; }; /* * Return codes for LPT scan callback function. * * LPT_SCAN_CONTINUE: continue scanning * LPT_SCAN_ADD: add the LEB properties scanned to the tree in memory * LPT_SCAN_STOP: stop scanning */ enum { LPT_SCAN_CONTINUE = 0, LPT_SCAN_ADD = 1, LPT_SCAN_STOP = 2, }; struct ubifs_info; /* Callback used by the 'ubifs_lpt_scan_nolock()' function */ typedef int (*ubifs_lpt_scan_callback)(struct ubifs_info *c, const struct ubifs_lprops *lprops, int in_tree, void *data); /** * struct ubifs_wbuf - UBIFS write-buffer. * @c: UBIFS file-system description object * @buf: write-buffer (of min. flash I/O unit size) * @lnum: logical eraseblock number the write-buffer points to * @offs: write-buffer offset in this logical eraseblock * @avail: number of bytes available in the write-buffer * @used: number of used bytes in the write-buffer * @dtype: type of data stored in this LEB (%UBI_LONGTERM, %UBI_SHORTTERM, * %UBI_UNKNOWN) * @jhead: journal head the mutex belongs to (note, needed only to shut lockdep * up by 'mutex_lock_nested()). * @sync_callback: write-buffer synchronization callback * @io_mutex: serializes write-buffer I/O * @lock: serializes @buf, @lnum, @offs, @avail, @used, @next_ino and @inodes * fields * @timer: write-buffer timer * @timeout: timer expire interval in jiffies * @need_sync: it is set if its timer expired and needs sync * @next_ino: points to the next position of the following inode number * @inodes: stores the inode numbers of the nodes which are in wbuf * * The write-buffer synchronization callback is called when the write-buffer is * synchronized in order to notify how much space was wasted due to * write-buffer padding and how much free space is left in the LEB. * * Note: the fields @buf, @lnum, @offs, @avail and @used can be read under * spin-lock or mutex because they are written under both mutex and spin-lock. * @buf is appended to under mutex but overwritten under both mutex and * spin-lock. Thus the data between @buf and @buf + @used can be read under * spinlock. */ struct ubifs_wbuf { struct ubifs_info *c; void *buf; int lnum; int offs; int avail; int used; int dtype; int jhead; int (*sync_callback)(struct ubifs_info *c, int lnum, int free, int pad); struct mutex io_mutex; spinlock_t lock; int timeout; int need_sync; int next_ino; ino_t *inodes; }; /** * struct ubifs_bud - bud logical eraseblock. * @lnum: logical eraseblock number * @start: where the (uncommitted) bud data starts * @jhead: journal head number this bud belongs to * @list: link in the list buds belonging to the same journal head * @rb: link in the tree of all buds */ struct ubifs_bud { int lnum; int start; int jhead; struct list_head list; struct rb_node rb; }; /** * struct ubifs_jhead - journal head. * @wbuf: head's write-buffer * @buds_list: list of bud LEBs belonging to this journal head * * Note, the @buds list is protected by the @c->buds_lock. */ struct ubifs_jhead { struct ubifs_wbuf wbuf; struct list_head buds_list; }; /** * struct ubifs_zbranch - key/coordinate/length branch stored in znodes. * @key: key * @znode: znode address in memory * @lnum: LEB number of the target node (indexing node or data node) * @offs: target node offset within @lnum * @len: target node length */ struct ubifs_zbranch { union ubifs_key key; union { struct ubifs_znode *znode; void *leaf; }; int lnum; int offs; int len; }; /** * struct ubifs_znode - in-memory representation of an indexing node. * @parent: parent znode or NULL if it is the root * @cnext: next znode to commit * @flags: znode flags (%DIRTY_ZNODE, %COW_ZNODE or %OBSOLETE_ZNODE) * @time: last access time (seconds) * @level: level of the entry in the TNC tree * @child_cnt: count of child znodes * @iip: index in parent's zbranch array * @alt: lower bound of key range has altered i.e. child inserted at slot 0 * @lnum: LEB number of the corresponding indexing node * @offs: offset of the corresponding indexing node * @len: length of the corresponding indexing node * @zbranch: array of znode branches (@c->fanout elements) */ struct ubifs_znode { struct ubifs_znode *parent; struct ubifs_znode *cnext; unsigned long flags; unsigned long time; int level; int child_cnt; int iip; int alt; #ifdef CONFIG_UBIFS_FS_DEBUG int lnum, offs, len; #endif struct ubifs_zbranch zbranch[]; }; /** * struct bu_info - bulk-read information. * @key: first data node key * @zbranch: zbranches of data nodes to bulk read * @buf: buffer to read into * @buf_len: buffer length * @gc_seq: GC sequence number to detect races with GC * @cnt: number of data nodes for bulk read * @blk_cnt: number of data blocks including holes * @oef: end of file reached */ struct bu_info { union ubifs_key key; struct ubifs_zbranch zbranch[UBIFS_MAX_BULK_READ]; void *buf; int buf_len; int gc_seq; int cnt; int blk_cnt; int eof; }; /** * struct ubifs_node_range - node length range description data structure. * @len: fixed node length * @min_len: minimum possible node length * @max_len: maximum possible node length * * If @max_len is %0, the node has fixed length @len. */ struct ubifs_node_range { union { int len; int min_len; }; int max_len; }; /** * struct ubifs_compressor - UBIFS compressor description structure. * @compr_type: compressor type (%UBIFS_COMPR_LZO, etc) * @cc: cryptoapi compressor handle * @comp_mutex: mutex used during compression * @decomp_mutex: mutex used during decompression * @name: compressor name * @capi_name: cryptoapi compressor name */ struct ubifs_compressor { int compr_type; char *name; char *capi_name; int (*decompress)(const unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len); }; /** * struct ubifs_budget_req - budget requirements of an operation. * * @fast: non-zero if the budgeting should try to acquire budget quickly and * should not try to call write-back * @recalculate: non-zero if @idx_growth, @data_growth, and @dd_growth fields * have to be re-calculated * @new_page: non-zero if the operation adds a new page * @dirtied_page: non-zero if the operation makes a page dirty * @new_dent: non-zero if the operation adds a new directory entry * @mod_dent: non-zero if the operation removes or modifies an existing * directory entry * @new_ino: non-zero if the operation adds a new inode * @new_ino_d: now much data newly created inode contains * @dirtied_ino: how many inodes the operation makes dirty * @dirtied_ino_d: now much data dirtied inode contains * @idx_growth: how much the index will supposedly grow * @data_growth: how much new data the operation will supposedly add * @dd_growth: how much data that makes other data dirty the operation will * supposedly add * * @idx_growth, @data_growth and @dd_growth are not used in budget request. The * budgeting subsystem caches index and data growth values there to avoid * re-calculating them when the budget is released. However, if @idx_growth is * %-1, it is calculated by the release function using other fields. * * An inode may contain 4KiB of data at max., thus the widths of @new_ino_d * is 13 bits, and @dirtied_ino_d - 15, because up to 4 inodes may be made * dirty by the re-name operation. * * Note, UBIFS aligns node lengths to 8-bytes boundary, so the requester has to * make sure the amount of inode data which contribute to @new_ino_d and * @dirtied_ino_d fields are aligned. */ struct ubifs_budget_req { unsigned int fast:1; unsigned int recalculate:1; #ifndef UBIFS_DEBUG unsigned int new_page:1; unsigned int dirtied_page:1; unsigned int new_dent:1; unsigned int mod_dent:1; unsigned int new_ino:1; unsigned int new_ino_d:13; unsigned int dirtied_ino:4; unsigned int dirtied_ino_d:15; #else /* Not bit-fields to check for overflows */ unsigned int new_page; unsigned int dirtied_page; unsigned int new_dent; unsigned int mod_dent; unsigned int new_ino; unsigned int new_ino_d; unsigned int dirtied_ino; unsigned int dirtied_ino_d; #endif int idx_growth; int data_growth; int dd_growth; }; /** * struct ubifs_orphan - stores the inode number of an orphan. * @rb: rb-tree node of rb-tree of orphans sorted by inode number * @list: list head of list of orphans in order added * @new_list: list head of list of orphans added since the last commit * @cnext: next orphan to commit * @dnext: next orphan to delete * @inum: inode number * @new: %1 => added since the last commit, otherwise %0 */ struct ubifs_orphan { struct rb_node rb; struct list_head list; struct list_head new_list; struct ubifs_orphan *cnext; struct ubifs_orphan *dnext; ino_t inum; int new; }; /** * struct ubifs_mount_opts - UBIFS-specific mount options information. * @unmount_mode: selected unmount mode (%0 default, %1 normal, %2 fast) * @bulk_read: enable/disable bulk-reads (%0 default, %1 disabe, %2 enable) * @chk_data_crc: enable/disable CRC data checking when reading data nodes * (%0 default, %1 disabe, %2 enable) * @override_compr: override default compressor (%0 - do not override and use * superblock compressor, %1 - override and use compressor * specified in @compr_type) * @compr_type: compressor type to override the superblock compressor with * (%UBIFS_COMPR_NONE, etc) */ struct ubifs_mount_opts { unsigned int unmount_mode:2; unsigned int bulk_read:2; unsigned int chk_data_crc:2; unsigned int override_compr:1; unsigned int compr_type:2; }; struct ubifs_debug_info; /** * struct ubifs_info - UBIFS file-system description data structure * (per-superblock). * @vfs_sb: VFS @struct super_block object * @bdi: backing device info object to make VFS happy and disable read-ahead * * @highest_inum: highest used inode number * @max_sqnum: current global sequence number * @cmt_no: commit number of the last successfully completed commit, protected * by @commit_sem * @cnt_lock: protects @highest_inum and @max_sqnum counters * @fmt_version: UBIFS on-flash format version * @ro_compat_version: R/O compatibility version * @uuid: UUID from super block * * @lhead_lnum: log head logical eraseblock number * @lhead_offs: log head offset * @ltail_lnum: log tail logical eraseblock number (offset is always 0) * @log_mutex: protects the log, @lhead_lnum, @lhead_offs, @ltail_lnum, and * @bud_bytes * @min_log_bytes: minimum required number of bytes in the log * @cmt_bud_bytes: used during commit to temporarily amount of bytes in * committed buds * * @buds: tree of all buds indexed by bud LEB number * @bud_bytes: how many bytes of flash is used by buds * @buds_lock: protects the @buds tree, @bud_bytes, and per-journal head bud * lists * @jhead_cnt: count of journal heads * @jheads: journal heads (head zero is base head) * @max_bud_bytes: maximum number of bytes allowed in buds * @bg_bud_bytes: number of bud bytes when background commit is initiated * @old_buds: buds to be released after commit ends * @max_bud_cnt: maximum number of buds * * @commit_sem: synchronizes committer with other processes * @cmt_state: commit state * @cs_lock: commit state lock * @cmt_wq: wait queue to sleep on if the log is full and a commit is running * * @big_lpt: flag that LPT is too big to write whole during commit * @no_chk_data_crc: do not check CRCs when reading data nodes (except during * recovery) * @bulk_read: enable bulk-reads * @default_compr: default compression algorithm (%UBIFS_COMPR_LZO, etc) * @rw_incompat: the media is not R/W compatible * * @tnc_mutex: protects the Tree Node Cache (TNC), @zroot, @cnext, @enext, and * @calc_idx_sz * @zroot: zbranch which points to the root index node and znode * @cnext: next znode to commit * @enext: next znode to commit to empty space * @gap_lebs: array of LEBs used by the in-gaps commit method * @cbuf: commit buffer * @ileb_buf: buffer for commit in-the-gaps method * @ileb_len: length of data in ileb_buf * @ihead_lnum: LEB number of index head * @ihead_offs: offset of index head * @ilebs: pre-allocated index LEBs * @ileb_cnt: number of pre-allocated index LEBs * @ileb_nxt: next pre-allocated index LEBs * @old_idx: tree of index nodes obsoleted since the last commit start * @bottom_up_buf: a buffer which is used by 'dirty_cow_bottom_up()' in tnc.c * * @mst_node: master node * @mst_offs: offset of valid master node * @mst_mutex: protects the master node area, @mst_node, and @mst_offs * * @max_bu_buf_len: maximum bulk-read buffer length * @bu_mutex: protects the pre-allocated bulk-read buffer and @c->bu * @bu: pre-allocated bulk-read information * * @log_lebs: number of logical eraseblocks in the log * @log_bytes: log size in bytes * @log_last: last LEB of the log * @lpt_lebs: number of LEBs used for lprops table * @lpt_first: first LEB of the lprops table area * @lpt_last: last LEB of the lprops table area * @orph_lebs: number of LEBs used for the orphan area * @orph_first: first LEB of the orphan area * @orph_last: last LEB of the orphan area * @main_lebs: count of LEBs in the main area * @main_first: first LEB of the main area * @main_bytes: main area size in bytes * * @key_hash_type: type of the key hash * @key_hash: direntry key hash function * @key_fmt: key format * @key_len: key length * @fanout: fanout of the index tree (number of links per indexing node) * * @min_io_size: minimal input/output unit size * @min_io_shift: number of bits in @min_io_size minus one * @leb_size: logical eraseblock size in bytes * @half_leb_size: half LEB size * @leb_cnt: count of logical eraseblocks * @max_leb_cnt: maximum count of logical eraseblocks * @old_leb_cnt: count of logical eraseblocks before re-size * @ro_media: the underlying UBI volume is read-only * * @dirty_pg_cnt: number of dirty pages (not used) * @dirty_zn_cnt: number of dirty znodes * @clean_zn_cnt: number of clean znodes * * @budg_idx_growth: amount of bytes budgeted for index growth * @budg_data_growth: amount of bytes budgeted for cached data * @budg_dd_growth: amount of bytes budgeted for cached data that will make * other data dirty * @budg_uncommitted_idx: amount of bytes were budgeted for growth of the index, * but which still have to be taken into account because * the index has not been committed so far * @space_lock: protects @budg_idx_growth, @budg_data_growth, @budg_dd_growth, * @budg_uncommited_idx, @min_idx_lebs, @old_idx_sz, @lst, * @nospace, and @nospace_rp; * @min_idx_lebs: minimum number of LEBs required for the index * @old_idx_sz: size of index on flash * @calc_idx_sz: temporary variable which is used to calculate new index size * (contains accurate new index size at end of TNC commit start) * @lst: lprops statistics * @nospace: non-zero if the file-system does not have flash space (used as * optimization) * @nospace_rp: the same as @nospace, but additionally means that even reserved * pool is full * * @page_budget: budget for a page * @inode_budget: budget for an inode * @dent_budget: budget for a directory entry * * @ref_node_alsz: size of the LEB reference node aligned to the min. flash * I/O unit * @mst_node_alsz: master node aligned size * @min_idx_node_sz: minimum indexing node aligned on 8-bytes boundary * @max_idx_node_sz: maximum indexing node aligned on 8-bytes boundary * @max_inode_sz: maximum possible inode size in bytes * @max_znode_sz: size of znode in bytes * * @leb_overhead: how many bytes are wasted in an LEB when it is filled with * data nodes of maximum size - used in free space reporting * @dead_wm: LEB dead space watermark * @dark_wm: LEB dark space watermark * @block_cnt: count of 4KiB blocks on the FS * * @ranges: UBIFS node length ranges * @ubi: UBI volume descriptor * @di: UBI device information * @vi: UBI volume information * * @orph_tree: rb-tree of orphan inode numbers * @orph_list: list of orphan inode numbers in order added * @orph_new: list of orphan inode numbers added since last commit * @orph_cnext: next orphan to commit * @orph_dnext: next orphan to delete * @orphan_lock: lock for orph_tree and orph_new * @orph_buf: buffer for orphan nodes * @new_orphans: number of orphans since last commit * @cmt_orphans: number of orphans being committed * @tot_orphans: number of orphans in the rb_tree * @max_orphans: maximum number of orphans allowed * @ohead_lnum: orphan head LEB number * @ohead_offs: orphan head offset * @no_orphs: non-zero if there are no orphans * * @bgt: UBIFS background thread * @bgt_name: background thread name * @need_bgt: if background thread should run * @need_wbuf_sync: if write-buffers have to be synchronized * * @gc_lnum: LEB number used for garbage collection * @sbuf: a buffer of LEB size used by GC and replay for scanning * @idx_gc: list of index LEBs that have been garbage collected * @idx_gc_cnt: number of elements on the idx_gc list * @gc_seq: incremented for every non-index LEB garbage collected * @gced_lnum: last non-index LEB that was garbage collected * * @infos_list: links all 'ubifs_info' objects * @umount_mutex: serializes shrinker and un-mount * @shrinker_run_no: shrinker run number * * @space_bits: number of bits needed to record free or dirty space * @lpt_lnum_bits: number of bits needed to record a LEB number in the LPT * @lpt_offs_bits: number of bits needed to record an offset in the LPT * @lpt_spc_bits: number of bits needed to space in the LPT * @pcnt_bits: number of bits needed to record pnode or nnode number * @lnum_bits: number of bits needed to record LEB number * @nnode_sz: size of on-flash nnode * @pnode_sz: size of on-flash pnode * @ltab_sz: size of on-flash LPT lprops table * @lsave_sz: size of on-flash LPT save table * @pnode_cnt: number of pnodes * @nnode_cnt: number of nnodes * @lpt_hght: height of the LPT * @pnodes_have: number of pnodes in memory * * @lp_mutex: protects lprops table and all the other lprops-related fields * @lpt_lnum: LEB number of the root nnode of the LPT * @lpt_offs: offset of the root nnode of the LPT * @nhead_lnum: LEB number of LPT head * @nhead_offs: offset of LPT head * @lpt_drty_flgs: dirty flags for LPT special nodes e.g. ltab * @dirty_nn_cnt: number of dirty nnodes * @dirty_pn_cnt: number of dirty pnodes * @check_lpt_free: flag that indicates LPT GC may be needed * @lpt_sz: LPT size * @lpt_nod_buf: buffer for an on-flash nnode or pnode * @lpt_buf: buffer of LEB size used by LPT * @nroot: address in memory of the root nnode of the LPT * @lpt_cnext: next LPT node to commit * @lpt_heap: array of heaps of categorized lprops * @dirty_idx: a (reverse sorted) copy of the LPROPS_DIRTY_IDX heap as at * previous commit start * @uncat_list: list of un-categorized LEBs * @empty_list: list of empty LEBs * @freeable_list: list of freeable non-index LEBs (free + dirty == leb_size) * @frdi_idx_list: list of freeable index LEBs (free + dirty == leb_size) * @freeable_cnt: number of freeable LEBs in @freeable_list * * @ltab_lnum: LEB number of LPT's own lprops table * @ltab_offs: offset of LPT's own lprops table * @ltab: LPT's own lprops table * @ltab_cmt: LPT's own lprops table (commit copy) * @lsave_cnt: number of LEB numbers in LPT's save table * @lsave_lnum: LEB number of LPT's save table * @lsave_offs: offset of LPT's save table * @lsave: LPT's save table * @lscan_lnum: LEB number of last LPT scan * * @rp_size: size of the reserved pool in bytes * @report_rp_size: size of the reserved pool reported to user-space * @rp_uid: reserved pool user ID * @rp_gid: reserved pool group ID * * @empty: if the UBI device is empty * @replay_tree: temporary tree used during journal replay * @replay_list: temporary list used during journal replay * @replay_buds: list of buds to replay * @cs_sqnum: sequence number of first node in the log (commit start node) * @replay_sqnum: sequence number of node currently being replayed * @need_recovery: file-system needs recovery * @replaying: set to %1 during journal replay * @unclean_leb_list: LEBs to recover when mounting ro to rw * @rcvrd_mst_node: recovered master node to write when mounting ro to rw * @size_tree: inode size information for recovery * @remounting_rw: set while remounting from ro to rw (sb flags have MS_RDONLY) * @always_chk_crc: always check CRCs (while mounting and remounting rw) * @mount_opts: UBIFS-specific mount options * * @dbg: debugging-related information */ struct ubifs_info { struct super_block *vfs_sb; ino_t highest_inum; unsigned long long max_sqnum; unsigned long long cmt_no; spinlock_t cnt_lock; int fmt_version; int ro_compat_version; unsigned char uuid[16]; int lhead_lnum; int lhead_offs; int ltail_lnum; struct mutex log_mutex; int min_log_bytes; long long cmt_bud_bytes; struct rb_root buds; long long bud_bytes; spinlock_t buds_lock; int jhead_cnt; struct ubifs_jhead *jheads; long long max_bud_bytes; long long bg_bud_bytes; struct list_head old_buds; int max_bud_cnt; struct rw_semaphore commit_sem; int cmt_state; spinlock_t cs_lock; wait_queue_head_t cmt_wq; unsigned int big_lpt:1; unsigned int no_chk_data_crc:1; unsigned int bulk_read:1; unsigned int default_compr:2; unsigned int rw_incompat:1; struct mutex tnc_mutex; struct ubifs_zbranch zroot; struct ubifs_znode *cnext; struct ubifs_znode *enext; int *gap_lebs; void *cbuf; void *ileb_buf; int ileb_len; int ihead_lnum; int ihead_offs; int *ilebs; int ileb_cnt; int ileb_nxt; struct rb_root old_idx; int *bottom_up_buf; struct ubifs_mst_node *mst_node; int mst_offs; struct mutex mst_mutex; int max_bu_buf_len; struct mutex bu_mutex; struct bu_info bu; int log_lebs; long long log_bytes; int log_last; int lpt_lebs; int lpt_first; int lpt_last; int orph_lebs; int orph_first; int orph_last; int main_lebs; int main_first; long long main_bytes; uint8_t key_hash_type; uint32_t (*key_hash)(const char *str, int len); int key_fmt; int key_len; int fanout; int min_io_size; int min_io_shift; int leb_size; int half_leb_size; int leb_cnt; int max_leb_cnt; int old_leb_cnt; int ro_media; long long budg_idx_growth; long long budg_data_growth; long long budg_dd_growth; long long budg_uncommitted_idx; spinlock_t space_lock; int min_idx_lebs; unsigned long long old_idx_sz; unsigned long long calc_idx_sz; struct ubifs_lp_stats lst; unsigned int nospace:1; unsigned int nospace_rp:1; int page_budget; int inode_budget; int dent_budget; int ref_node_alsz; int mst_node_alsz; int min_idx_node_sz; int max_idx_node_sz; long long max_inode_sz; int max_znode_sz; int leb_overhead; int dead_wm; int dark_wm; int block_cnt; struct ubifs_node_range ranges[UBIFS_NODE_TYPES_CNT]; struct ubi_volume_desc *ubi; struct ubi_device_info di; struct ubi_volume_info vi; struct rb_root orph_tree; struct list_head orph_list; struct list_head orph_new; struct ubifs_orphan *orph_cnext; struct ubifs_orphan *orph_dnext; spinlock_t orphan_lock; void *orph_buf; int new_orphans; int cmt_orphans; int tot_orphans; int max_orphans; int ohead_lnum; int ohead_offs; int no_orphs; struct task_struct *bgt; char bgt_name[sizeof(BGT_NAME_PATTERN) + 9]; int need_bgt; int need_wbuf_sync; int gc_lnum; void *sbuf; struct list_head idx_gc; int idx_gc_cnt; int gc_seq; int gced_lnum; struct list_head infos_list; struct mutex umount_mutex; unsigned int shrinker_run_no; int space_bits; int lpt_lnum_bits; int lpt_offs_bits; int lpt_spc_bits; int pcnt_bits; int lnum_bits; int nnode_sz; int pnode_sz; int ltab_sz; int lsave_sz; int pnode_cnt; int nnode_cnt; int lpt_hght; int pnodes_have; struct mutex lp_mutex; int lpt_lnum; int lpt_offs; int nhead_lnum; int nhead_offs; int lpt_drty_flgs; int dirty_nn_cnt; int dirty_pn_cnt; int check_lpt_free; long long lpt_sz; void *lpt_nod_buf; void *lpt_buf; struct ubifs_nnode *nroot; struct ubifs_cnode *lpt_cnext; struct ubifs_lpt_heap lpt_heap[LPROPS_HEAP_CNT]; struct ubifs_lpt_heap dirty_idx; struct list_head uncat_list; struct list_head empty_list; struct list_head freeable_list; struct list_head frdi_idx_list; int freeable_cnt; int ltab_lnum; int ltab_offs; struct ubifs_lpt_lprops *ltab; struct ubifs_lpt_lprops *ltab_cmt; int lsave_cnt; int lsave_lnum; int lsave_offs; int *lsave; int lscan_lnum; long long rp_size; long long report_rp_size; uid_t rp_uid; gid_t rp_gid; /* The below fields are used only during mounting and re-mounting */ int empty; struct rb_root replay_tree; struct list_head replay_list; struct list_head replay_buds; unsigned long long cs_sqnum; unsigned long long replay_sqnum; int need_recovery; int replaying; struct list_head unclean_leb_list; struct ubifs_mst_node *rcvrd_mst_node; struct rb_root size_tree; int remounting_rw; int always_chk_crc; struct ubifs_mount_opts mount_opts; #ifdef CONFIG_UBIFS_FS_DEBUG struct ubifs_debug_info *dbg; #endif }; extern spinlock_t ubifs_infos_lock; extern struct kmem_cache *ubifs_inode_slab; extern const struct super_operations ubifs_super_operations; extern const struct address_space_operations ubifs_file_address_operations; extern const struct file_operations ubifs_file_operations; extern const struct inode_operations ubifs_file_inode_operations; extern const struct file_operations ubifs_dir_operations; extern const struct inode_operations ubifs_dir_inode_operations; extern const struct inode_operations ubifs_symlink_inode_operations; extern struct backing_dev_info ubifs_backing_dev_info; extern struct ubifs_compressor *ubifs_compressors[UBIFS_COMPR_TYPES_CNT]; /* io.c */ void ubifs_ro_mode(struct ubifs_info *c, int err); int ubifs_wbuf_write_nolock(struct ubifs_wbuf *wbuf, void *buf, int len); int ubifs_wbuf_seek_nolock(struct ubifs_wbuf *wbuf, int lnum, int offs, int dtype); int ubifs_wbuf_init(struct ubifs_info *c, struct ubifs_wbuf *wbuf); int ubifs_read_node(const struct ubifs_info *c, void *buf, int type, int len, int lnum, int offs); int ubifs_read_node_wbuf(struct ubifs_wbuf *wbuf, void *buf, int type, int len, int lnum, int offs); int ubifs_write_node(struct ubifs_info *c, void *node, int len, int lnum, int offs, int dtype); int ubifs_check_node(const struct ubifs_info *c, const void *buf, int lnum, int offs, int quiet, int must_chk_crc); void ubifs_prepare_node(struct ubifs_info *c, void *buf, int len, int pad); void ubifs_prep_grp_node(struct ubifs_info *c, void *node, int len, int last); int ubifs_io_init(struct ubifs_info *c); void ubifs_pad(const struct ubifs_info *c, void *buf, int pad); int ubifs_wbuf_sync_nolock(struct ubifs_wbuf *wbuf); int ubifs_bg_wbufs_sync(struct ubifs_info *c); void ubifs_wbuf_add_ino_nolock(struct ubifs_wbuf *wbuf, ino_t inum); int ubifs_sync_wbufs_by_inode(struct ubifs_info *c, struct inode *inode); /* scan.c */ struct ubifs_scan_leb *ubifs_scan(const struct ubifs_info *c, int lnum, int offs, void *sbuf); void ubifs_scan_destroy(struct ubifs_scan_leb *sleb); int ubifs_scan_a_node(const struct ubifs_info *c, void *buf, int len, int lnum, int offs, int quiet); struct ubifs_scan_leb *ubifs_start_scan(const struct ubifs_info *c, int lnum, int offs, void *sbuf); void ubifs_end_scan(const struct ubifs_info *c, struct ubifs_scan_leb *sleb, int lnum, int offs); int ubifs_add_snod(const struct ubifs_info *c, struct ubifs_scan_leb *sleb, void *buf, int offs); void ubifs_scanned_corruption(const struct ubifs_info *c, int lnum, int offs, void *buf); /* log.c */ void ubifs_add_bud(struct ubifs_info *c, struct ubifs_bud *bud); void ubifs_create_buds_lists(struct ubifs_info *c); int ubifs_add_bud_to_log(struct ubifs_info *c, int jhead, int lnum, int offs); struct ubifs_bud *ubifs_search_bud(struct ubifs_info *c, int lnum); struct ubifs_wbuf *ubifs_get_wbuf(struct ubifs_info *c, int lnum); int ubifs_log_start_commit(struct ubifs_info *c, int *ltail_lnum); int ubifs_log_end_commit(struct ubifs_info *c, int new_ltail_lnum); int ubifs_log_post_commit(struct ubifs_info *c, int old_ltail_lnum); int ubifs_consolidate_log(struct ubifs_info *c); /* journal.c */ int ubifs_jnl_update(struct ubifs_info *c, const struct inode *dir, const struct qstr *nm, const struct inode *inode, int deletion, int xent); int ubifs_jnl_write_data(struct ubifs_info *c, const struct inode *inode, const union ubifs_key *key, const void *buf, int len); int ubifs_jnl_write_inode(struct ubifs_info *c, const struct inode *inode); int ubifs_jnl_delete_inode(struct ubifs_info *c, const struct inode *inode); int ubifs_jnl_rename(struct ubifs_info *c, const struct inode *old_dir, const struct dentry *old_dentry, const struct inode *new_dir, const struct dentry *new_dentry, int sync); int ubifs_jnl_truncate(struct ubifs_info *c, const struct inode *inode, loff_t old_size, loff_t new_size); int ubifs_jnl_delete_xattr(struct ubifs_info *c, const struct inode *host, const struct inode *inode, const struct qstr *nm); int ubifs_jnl_change_xattr(struct ubifs_info *c, const struct inode *inode1, const struct inode *inode2); /* budget.c */ int ubifs_budget_space(struct ubifs_info *c, struct ubifs_budget_req *req); void ubifs_release_budget(struct ubifs_info *c, struct ubifs_budget_req *req); void ubifs_release_dirty_inode_budget(struct ubifs_info *c, struct ubifs_inode *ui); int ubifs_budget_inode_op(struct ubifs_info *c, struct inode *inode, struct ubifs_budget_req *req); void ubifs_release_ino_dirty(struct ubifs_info *c, struct inode *inode, struct ubifs_budget_req *req); void ubifs_cancel_ino_op(struct ubifs_info *c, struct inode *inode, struct ubifs_budget_req *req); long long ubifs_get_free_space(struct ubifs_info *c); long long ubifs_get_free_space_nolock(struct ubifs_info *c); int ubifs_calc_min_idx_lebs(struct ubifs_info *c); void ubifs_convert_page_budget(struct ubifs_info *c); long long ubifs_reported_space(const struct ubifs_info *c, long long free); long long ubifs_calc_available(const struct ubifs_info *c, int min_idx_lebs); /* find.c */ int ubifs_find_free_space(struct ubifs_info *c, int min_space, int *free, int squeeze); int ubifs_find_free_leb_for_idx(struct ubifs_info *c); int ubifs_find_dirty_leb(struct ubifs_info *c, struct ubifs_lprops *ret_lp, int min_space, int pick_free); int ubifs_find_dirty_idx_leb(struct ubifs_info *c); int ubifs_save_dirty_idx_lnums(struct ubifs_info *c); /* tnc.c */ int ubifs_lookup_level0(struct ubifs_info *c, const union ubifs_key *key, struct ubifs_znode **zn, int *n); int ubifs_tnc_lookup_nm(struct ubifs_info *c, const union ubifs_key *key, void *node, const struct qstr *nm); int ubifs_tnc_locate(struct ubifs_info *c, const union ubifs_key *key, void *node, int *lnum, int *offs); int ubifs_tnc_add(struct ubifs_info *c, const union ubifs_key *key, int lnum, int offs, int len); 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 ubifs_tnc_add_nm(struct ubifs_info *c, const union ubifs_key *key, int lnum, int offs, int len, const struct qstr *nm); int ubifs_tnc_remove(struct ubifs_info *c, const union ubifs_key *key); int ubifs_tnc_remove_nm(struct ubifs_info *c, const union ubifs_key *key, const struct qstr *nm); int ubifs_tnc_remove_range(struct ubifs_info *c, union ubifs_key *from_key, union ubifs_key *to_key); int ubifs_tnc_remove_ino(struct ubifs_info *c, ino_t inum); struct ubifs_dent_node *ubifs_tnc_next_ent(struct ubifs_info *c, union ubifs_key *key, const struct qstr *nm); void ubifs_tnc_close(struct ubifs_info *c); int ubifs_tnc_has_node(struct ubifs_info *c, union ubifs_key *key, int level, int lnum, int offs, int is_idx); int ubifs_dirty_idx_node(struct ubifs_info *c, union ubifs_key *key, int level, int lnum, int offs); /* Shared by tnc.c for tnc_commit.c */ void destroy_old_idx(struct ubifs_info *c); int is_idx_node_in_tnc(struct ubifs_info *c, union ubifs_key *key, int level, int lnum, int offs); int insert_old_idx_znode(struct ubifs_info *c, struct ubifs_znode *znode); int ubifs_tnc_get_bu_keys(struct ubifs_info *c, struct bu_info *bu); int ubifs_tnc_bulk_read(struct ubifs_info *c, struct bu_info *bu); /* tnc_misc.c */ struct ubifs_znode *ubifs_tnc_levelorder_next(struct ubifs_znode *zr, struct ubifs_znode *znode); int ubifs_search_zbranch(const struct ubifs_info *c, const struct ubifs_znode *znode, const union ubifs_key *key, int *n); struct ubifs_znode *ubifs_tnc_postorder_first(struct ubifs_znode *znode); struct ubifs_znode *ubifs_tnc_postorder_next(struct ubifs_znode *znode); long ubifs_destroy_tnc_subtree(struct ubifs_znode *zr); struct ubifs_znode *ubifs_load_znode(struct ubifs_info *c, struct ubifs_zbranch *zbr, struct ubifs_znode *parent, int iip); int ubifs_tnc_read_node(struct ubifs_info *c, struct ubifs_zbranch *zbr, void *node); /* tnc_commit.c */ int ubifs_tnc_start_commit(struct ubifs_info *c, struct ubifs_zbranch *zroot); int ubifs_tnc_end_commit(struct ubifs_info *c); /* shrinker.c */ int ubifs_shrinker(int nr_to_scan, gfp_t gfp_mask); /* commit.c */ int ubifs_bg_thread(void *info); void ubifs_commit_required(struct ubifs_info *c); void ubifs_request_bg_commit(struct ubifs_info *c); int ubifs_run_commit(struct ubifs_info *c); void ubifs_recovery_commit(struct ubifs_info *c); int ubifs_gc_should_commit(struct ubifs_info *c); void ubifs_wait_for_commit(struct ubifs_info *c); /* master.c */ int ubifs_read_master(struct ubifs_info *c); int ubifs_write_master(struct ubifs_info *c); /* sb.c */ int ubifs_read_superblock(struct ubifs_info *c); struct ubifs_sb_node *ubifs_read_sb_node(struct ubifs_info *c); int ubifs_write_sb_node(struct ubifs_info *c, struct ubifs_sb_node *sup); /* replay.c */ int ubifs_validate_entry(struct ubifs_info *c, const struct ubifs_dent_node *dent); int ubifs_replay_journal(struct ubifs_info *c); /* gc.c */ int ubifs_garbage_collect(struct ubifs_info *c, int anyway); int ubifs_gc_start_commit(struct ubifs_info *c); int ubifs_gc_end_commit(struct ubifs_info *c); void ubifs_destroy_idx_gc(struct ubifs_info *c); int ubifs_get_idx_gc_leb(struct ubifs_info *c); int ubifs_garbage_collect_leb(struct ubifs_info *c, struct ubifs_lprops *lp); /* orphan.c */ int ubifs_add_orphan(struct ubifs_info *c, ino_t inum); void ubifs_delete_orphan(struct ubifs_info *c, ino_t inum); int ubifs_orphan_start_commit(struct ubifs_info *c); int ubifs_orphan_end_commit(struct ubifs_info *c); int ubifs_mount_orphans(struct ubifs_info *c, int unclean, int read_only); int ubifs_clear_orphans(struct ubifs_info *c); /* lpt.c */ int ubifs_calc_lpt_geom(struct ubifs_info *c); int ubifs_create_dflt_lpt(struct ubifs_info *c, int *main_lebs, int lpt_first, int *lpt_lebs, int *big_lpt); int ubifs_lpt_init(struct ubifs_info *c, int rd, int wr); struct ubifs_lprops *ubifs_lpt_lookup(struct ubifs_info *c, int lnum); struct ubifs_lprops *ubifs_lpt_lookup_dirty(struct ubifs_info *c, int lnum); int ubifs_lpt_scan_nolock(struct ubifs_info *c, int start_lnum, int end_lnum, ubifs_lpt_scan_callback scan_cb, void *data); /* Shared by lpt.c for lpt_commit.c */ void ubifs_pack_lsave(struct ubifs_info *c, void *buf, int *lsave); void ubifs_pack_ltab(struct ubifs_info *c, void *buf, struct ubifs_lpt_lprops *ltab); void ubifs_pack_pnode(struct ubifs_info *c, void *buf, struct ubifs_pnode *pnode); void ubifs_pack_nnode(struct ubifs_info *c, void *buf, struct ubifs_nnode *nnode); struct ubifs_pnode *ubifs_get_pnode(struct ubifs_info *c, struct ubifs_nnode *parent, int iip); struct ubifs_nnode *ubifs_get_nnode(struct ubifs_info *c, struct ubifs_nnode *parent, int iip); int ubifs_read_nnode(struct ubifs_info *c, struct ubifs_nnode *parent, int iip); void ubifs_add_lpt_dirt(struct ubifs_info *c, int lnum, int dirty); void ubifs_add_nnode_dirt(struct ubifs_info *c, struct ubifs_nnode *nnode); uint32_t ubifs_unpack_bits(uint8_t **addr, int *pos, int nrbits); struct ubifs_nnode *ubifs_first_nnode(struct ubifs_info *c, int *hght); /* Needed only in debugging code in lpt_commit.c */ int ubifs_unpack_nnode(const struct ubifs_info *c, void *buf, struct ubifs_nnode *nnode); /* lpt_commit.c */ int ubifs_lpt_start_commit(struct ubifs_info *c); int ubifs_lpt_end_commit(struct ubifs_info *c); int ubifs_lpt_post_commit(struct ubifs_info *c); void ubifs_lpt_free(struct ubifs_info *c, int wr_only); /* lprops.c */ const struct ubifs_lprops *ubifs_change_lp(struct ubifs_info *c, const struct ubifs_lprops *lp, int free, int dirty, int flags, int idx_gc_cnt); void ubifs_get_lp_stats(struct ubifs_info *c, struct ubifs_lp_stats *lst); void ubifs_add_to_cat(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat); void ubifs_replace_cat(struct ubifs_info *c, struct ubifs_lprops *old_lprops, struct ubifs_lprops *new_lprops); void ubifs_ensure_cat(struct ubifs_info *c, struct ubifs_lprops *lprops); int ubifs_categorize_lprops(const struct ubifs_info *c, const struct ubifs_lprops *lprops); int ubifs_change_one_lp(struct ubifs_info *c, int lnum, int free, int dirty, int flags_set, int flags_clean, int idx_gc_cnt); int ubifs_update_one_lp(struct ubifs_info *c, int lnum, int free, int dirty, int flags_set, int flags_clean); int ubifs_read_one_lp(struct ubifs_info *c, int lnum, struct ubifs_lprops *lp); const struct ubifs_lprops *ubifs_fast_find_free(struct ubifs_info *c); const struct ubifs_lprops *ubifs_fast_find_empty(struct ubifs_info *c); const struct ubifs_lprops *ubifs_fast_find_freeable(struct ubifs_info *c); const struct ubifs_lprops *ubifs_fast_find_frdi_idx(struct ubifs_info *c); /* file.c */ int ubifs_fsync(struct file *file, struct dentry *dentry, int datasync); int ubifs_setattr(struct dentry *dentry, struct iattr *attr); /* dir.c */ struct inode *ubifs_new_inode(struct ubifs_info *c, const struct inode *dir, int mode); int ubifs_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat); /* xattr.c */ int ubifs_setxattr(struct dentry *dentry, const char *name, const void *value, size_t size, int flags); ssize_t ubifs_getxattr(struct dentry *dentry, const char *name, void *buf, size_t size); ssize_t ubifs_listxattr(struct dentry *dentry, char *buffer, size_t size); int ubifs_removexattr(struct dentry *dentry, const char *name); /* super.c */ struct inode *ubifs_iget(struct super_block *sb, unsigned long inum); int ubifs_iput(struct inode *inode); /* recovery.c */ int ubifs_recover_master_node(struct ubifs_info *c); int ubifs_write_rcvrd_mst_node(struct ubifs_info *c); struct ubifs_scan_leb *ubifs_recover_leb(struct ubifs_info *c, int lnum, int offs, void *sbuf, int grouped); struct ubifs_scan_leb *ubifs_recover_log_leb(struct ubifs_info *c, int lnum, int offs, void *sbuf); int ubifs_recover_inl_heads(const struct ubifs_info *c, void *sbuf); int ubifs_clean_lebs(const struct ubifs_info *c, void *sbuf); int ubifs_rcvry_gc_commit(struct ubifs_info *c); int ubifs_recover_size_accum(struct ubifs_info *c, union ubifs_key *key, int deletion, loff_t new_size); int ubifs_recover_size(struct ubifs_info *c); void ubifs_destroy_size_tree(struct ubifs_info *c); /* ioctl.c */ long ubifs_ioctl(struct file *file, unsigned int cmd, unsigned long arg); void ubifs_set_inode_flags(struct inode *inode); #ifdef CONFIG_COMPAT long ubifs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #endif /* compressor.c */ int __init ubifs_compressors_init(void); void __exit ubifs_compressors_exit(void); void ubifs_compress(const void *in_buf, int in_len, void *out_buf, int *out_len, int *compr_type); int ubifs_decompress(const void *buf, int len, void *out, int *out_len, int compr_type); #include "debug.h" #include "misc.h" #include "key.h" /* todo: Move these to a common U-Boot header */ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len); #endif /* !__UBIFS_H__ */
1001-study-uboot
fs/ubifs/ubifs.h
C
gpl3
71,580
/* * 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 budgeting sub-system which is responsible for UBIFS * space management. * * Factors such as compression, wasted space at the ends of LEBs, space in other * journal heads, the effect of updates on the index, and so on, make it * impossible to accurately predict the amount of space needed. Consequently * approximations are used. */ #include "ubifs.h" #include <linux/math64.h> /** * ubifs_calc_min_idx_lebs - calculate amount of eraseblocks for the index. * @c: UBIFS file-system description object * * This function calculates and returns the number of eraseblocks which should * be kept for index usage. */ int ubifs_calc_min_idx_lebs(struct ubifs_info *c) { int idx_lebs, eff_leb_size = c->leb_size - c->max_idx_node_sz; long long idx_size; idx_size = c->old_idx_sz + c->budg_idx_growth + c->budg_uncommitted_idx; /* And make sure we have thrice the index size of space reserved */ idx_size = idx_size + (idx_size << 1); /* * We do not maintain 'old_idx_size' as 'old_idx_lebs'/'old_idx_bytes' * pair, nor similarly the two variables for the new index size, so we * have to do this costly 64-bit division on fast-path. */ idx_size += eff_leb_size - 1; idx_lebs = div_u64(idx_size, eff_leb_size); /* * The index head is not available for the in-the-gaps method, so add an * extra LEB to compensate. */ idx_lebs += 1; if (idx_lebs < MIN_INDEX_LEBS) idx_lebs = MIN_INDEX_LEBS; return idx_lebs; } /** * ubifs_reported_space - calculate reported free space. * @c: the UBIFS file-system description object * @free: amount of free space * * This function calculates amount of free space which will be reported to * user-space. User-space application tend to expect that if the file-system * (e.g., via the 'statfs()' call) reports that it has N bytes available, they * are able to write a file of size N. UBIFS attaches node headers to each data * node and it has to write indexing nodes as well. This introduces additional * overhead, and UBIFS has to report slightly less free space to meet the above * expectations. * * This function assumes free space is made up of uncompressed data nodes and * full index nodes (one per data node, tripled because we always allow enough * space to write the index thrice). * * Note, the calculation is pessimistic, which means that most of the time * UBIFS reports less space than it actually has. */ long long ubifs_reported_space(const struct ubifs_info *c, long long free) { int divisor, factor, f; /* * Reported space size is @free * X, where X is UBIFS block size * divided by UBIFS block size + all overhead one data block * introduces. The overhead is the node header + indexing overhead. * * Indexing overhead calculations are based on the following formula: * I = N/(f - 1) + 1, where I - number of indexing nodes, N - number * of data nodes, f - fanout. Because effective UBIFS fanout is twice * as less than maximum fanout, we assume that each data node * introduces 3 * @c->max_idx_node_sz / (@c->fanout/2 - 1) bytes. * Note, the multiplier 3 is because UBIFS reserves thrice as more space * for the index. */ f = c->fanout > 3 ? c->fanout >> 1 : 2; factor = UBIFS_BLOCK_SIZE; divisor = UBIFS_MAX_DATA_NODE_SZ; divisor += (c->max_idx_node_sz * 3) / (f - 1); free *= factor; return div_u64(free, divisor); }
1001-study-uboot
fs/ubifs/budget.c
C
gpl3
4,210
/* * 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 contains miscellaneous helper functions. */ #ifndef __UBIFS_MISC_H__ #define __UBIFS_MISC_H__ /** * ubifs_zn_dirty - check if znode is dirty. * @znode: znode to check * * This helper function returns %1 if @znode is dirty and %0 otherwise. */ static inline int ubifs_zn_dirty(const struct ubifs_znode *znode) { return !!test_bit(DIRTY_ZNODE, &znode->flags); } /** * ubifs_wake_up_bgt - wake up background thread. * @c: UBIFS file-system description object */ static inline void ubifs_wake_up_bgt(struct ubifs_info *c) { if (c->bgt && !c->need_bgt) { c->need_bgt = 1; wake_up_process(c->bgt); } } /** * ubifs_tnc_find_child - find next child in znode. * @znode: znode to search at * @start: the zbranch index to start at * * This helper function looks for znode child starting at index @start. Returns * the child or %NULL if no children were found. */ static inline struct ubifs_znode * ubifs_tnc_find_child(struct ubifs_znode *znode, int start) { while (start < znode->child_cnt) { if (znode->zbranch[start].znode) return znode->zbranch[start].znode; start += 1; } return NULL; } /** * ubifs_inode - get UBIFS inode information by VFS 'struct inode' object. * @inode: the VFS 'struct inode' pointer */ static inline struct ubifs_inode *ubifs_inode(const struct inode *inode) { return container_of(inode, struct ubifs_inode, vfs_inode); } /** * ubifs_compr_present - check if compressor was compiled in. * @compr_type: compressor type to check * * This function returns %1 of compressor of type @compr_type is present, and * %0 if not. */ static inline int ubifs_compr_present(int compr_type) { ubifs_assert(compr_type >= 0 && compr_type < UBIFS_COMPR_TYPES_CNT); return !!ubifs_compressors[compr_type]->capi_name; } /** * ubifs_compr_name - get compressor name string by its type. * @compr_type: compressor type * * This function returns compressor type string. */ static inline const char *ubifs_compr_name(int compr_type) { ubifs_assert(compr_type >= 0 && compr_type < UBIFS_COMPR_TYPES_CNT); return ubifs_compressors[compr_type]->name; } /** * ubifs_wbuf_sync - synchronize write-buffer. * @wbuf: write-buffer to synchronize * * This is the same as as 'ubifs_wbuf_sync_nolock()' but it does not assume * that the write-buffer is already locked. */ static inline int ubifs_wbuf_sync(struct ubifs_wbuf *wbuf) { int err; mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead); err = ubifs_wbuf_sync_nolock(wbuf); mutex_unlock(&wbuf->io_mutex); return err; } /** * ubifs_leb_unmap - unmap an LEB. * @c: UBIFS file-system description object * @lnum: LEB number to unmap * * This function returns %0 on success and a negative error code on failure. */ static inline int ubifs_leb_unmap(const struct ubifs_info *c, int lnum) { int err; if (c->ro_media) return -EROFS; err = ubi_leb_unmap(c->ubi, lnum); if (err) { ubifs_err("unmap LEB %d failed, error %d", lnum, err); return err; } return 0; } /** * ubifs_leb_write - write to a LEB. * @c: UBIFS file-system description object * @lnum: LEB number to write * @buf: buffer to write from * @offs: offset within LEB to write to * @len: length to write * @dtype: data type * * This function returns %0 on success and a negative error code on failure. */ static inline int ubifs_leb_write(const struct ubifs_info *c, int lnum, const void *buf, int offs, int len, int dtype) { int err; if (c->ro_media) return -EROFS; err = ubi_leb_write(c->ubi, lnum, buf, offs, len, dtype); if (err) { ubifs_err("writing %d bytes at %d:%d, error %d", len, lnum, offs, err); return err; } return 0; } /** * ubifs_leb_change - atomic LEB change. * @c: UBIFS file-system description object * @lnum: LEB number to write * @buf: buffer to write from * @len: length to write * @dtype: data type * * This function returns %0 on success and a negative error code on failure. */ static inline int ubifs_leb_change(const struct ubifs_info *c, int lnum, const void *buf, int len, int dtype) { int err; if (c->ro_media) return -EROFS; err = ubi_leb_change(c->ubi, lnum, buf, len, dtype); if (err) { ubifs_err("changing %d bytes in LEB %d, error %d", len, lnum, err); return err; } return 0; } /** * ubifs_add_dirt - add dirty space to LEB properties. * @c: the UBIFS file-system description object * @lnum: LEB to add dirty space for * @dirty: dirty space to add * * This is a helper function which increased amount of dirty LEB space. Returns * zero in case of success and a negative error code in case of failure. */ static inline int ubifs_add_dirt(struct ubifs_info *c, int lnum, int dirty) { return ubifs_update_one_lp(c, lnum, LPROPS_NC, dirty, 0, 0); } /** * ubifs_return_leb - return LEB to lprops. * @c: the UBIFS file-system description object * @lnum: LEB to return * * This helper function cleans the "taken" flag of a logical eraseblock in the * lprops. Returns zero in case of success and a negative error code in case of * failure. */ static inline int ubifs_return_leb(struct ubifs_info *c, int lnum) { return ubifs_change_one_lp(c, lnum, LPROPS_NC, LPROPS_NC, 0, LPROPS_TAKEN, 0); } /** * ubifs_idx_node_sz - return index node size. * @c: the UBIFS file-system description object * @child_cnt: number of children of this index node */ static inline int ubifs_idx_node_sz(const struct ubifs_info *c, int child_cnt) { return UBIFS_IDX_NODE_SZ + (UBIFS_BRANCH_SZ + c->key_len) * child_cnt; } /** * ubifs_idx_branch - return pointer to an index branch. * @c: the UBIFS file-system description object * @idx: index node * @bnum: branch number */ static inline struct ubifs_branch *ubifs_idx_branch(const struct ubifs_info *c, const struct ubifs_idx_node *idx, int bnum) { return (struct ubifs_branch *)((void *)idx->branches + (UBIFS_BRANCH_SZ + c->key_len) * bnum); } /** * ubifs_idx_key - return pointer to an index key. * @c: the UBIFS file-system description object * @idx: index node */ static inline void *ubifs_idx_key(const struct ubifs_info *c, const struct ubifs_idx_node *idx) { const __u8 *branch = idx->branches; return (void *)((struct ubifs_branch *)branch)->key; } /** * ubifs_tnc_lookup - look up a file-system node. * @c: UBIFS file-system description object * @key: node key to lookup * @node: the node 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. */ static inline int ubifs_tnc_lookup(struct ubifs_info *c, const union ubifs_key *key, void *node) { return ubifs_tnc_locate(c, key, node, NULL, NULL); } /** * ubifs_get_lprops - get reference to LEB properties. * @c: the UBIFS file-system description object * * This function locks lprops. Lprops have to be unlocked by * 'ubifs_release_lprops()'. */ static inline void ubifs_get_lprops(struct ubifs_info *c) { mutex_lock(&c->lp_mutex); } /** * ubifs_release_lprops - release lprops lock. * @c: the UBIFS file-system description object * * This function has to be called after each 'ubifs_get_lprops()' call to * unlock lprops. */ static inline void ubifs_release_lprops(struct ubifs_info *c) { ubifs_assert(mutex_is_locked(&c->lp_mutex)); ubifs_assert(c->lst.empty_lebs >= 0 && c->lst.empty_lebs <= c->main_lebs); mutex_unlock(&c->lp_mutex); } #endif /* __UBIFS_MISC_H__ */
1001-study-uboot
fs/ubifs/misc.h
C
gpl3
8,426
/* * 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 superblock. The superblock is stored at the first * LEB of the volume and is never changed by UBIFS. Only user-space tools may * change it. The superblock node mostly contains geometry information. */ #include "ubifs.h" /* * Default journal size in logical eraseblocks as a percent of total * flash size. */ #define DEFAULT_JNL_PERCENT 5 /* Default maximum journal size in bytes */ #define DEFAULT_MAX_JNL (32*1024*1024) /* Default indexing tree fanout */ #define DEFAULT_FANOUT 8 /* Default number of data journal heads */ #define DEFAULT_JHEADS_CNT 1 /* Default positions of different LEBs in the main area */ #define DEFAULT_IDX_LEB 0 #define DEFAULT_DATA_LEB 1 #define DEFAULT_GC_LEB 2 /* Default number of LEB numbers in LPT's save table */ #define DEFAULT_LSAVE_CNT 256 /* Default reserved pool size as a percent of maximum free space */ #define DEFAULT_RP_PERCENT 5 /* The default maximum size of reserved pool in bytes */ #define DEFAULT_MAX_RP_SIZE (5*1024*1024) /* Default time granularity in nanoseconds */ #define DEFAULT_TIME_GRAN 1000000000 /** * validate_sb - validate superblock node. * @c: UBIFS file-system description object * @sup: superblock node * * This function validates superblock node @sup. Since most of data was read * from the superblock and stored in @c, the function validates fields in @c * instead. Returns zero in case of success and %-EINVAL in case of validation * failure. */ static int validate_sb(struct ubifs_info *c, struct ubifs_sb_node *sup) { long long max_bytes; int err = 1, min_leb_cnt; if (!c->key_hash) { err = 2; goto failed; } if (sup->key_fmt != UBIFS_SIMPLE_KEY_FMT) { err = 3; goto failed; } if (le32_to_cpu(sup->min_io_size) != c->min_io_size) { ubifs_err("min. I/O unit mismatch: %d in superblock, %d real", le32_to_cpu(sup->min_io_size), c->min_io_size); goto failed; } if (le32_to_cpu(sup->leb_size) != c->leb_size) { ubifs_err("LEB size mismatch: %d in superblock, %d real", le32_to_cpu(sup->leb_size), c->leb_size); goto failed; } if (c->log_lebs < UBIFS_MIN_LOG_LEBS || c->lpt_lebs < UBIFS_MIN_LPT_LEBS || c->orph_lebs < UBIFS_MIN_ORPH_LEBS || c->main_lebs < UBIFS_MIN_MAIN_LEBS) { err = 4; goto failed; } /* * Calculate minimum allowed amount of main area LEBs. This is very * similar to %UBIFS_MIN_LEB_CNT, but we take into account real what we * have just read from the superblock. */ min_leb_cnt = UBIFS_SB_LEBS + UBIFS_MST_LEBS + c->log_lebs; min_leb_cnt += c->lpt_lebs + c->orph_lebs + c->jhead_cnt + 6; if (c->leb_cnt < min_leb_cnt || c->leb_cnt > c->vi.size) { ubifs_err("bad LEB count: %d in superblock, %d on UBI volume, " "%d minimum required", c->leb_cnt, c->vi.size, min_leb_cnt); goto failed; } if (c->max_leb_cnt < c->leb_cnt) { ubifs_err("max. LEB count %d less than LEB count %d", c->max_leb_cnt, c->leb_cnt); goto failed; } if (c->main_lebs < UBIFS_MIN_MAIN_LEBS) { err = 7; goto failed; } if (c->max_bud_bytes < (long long)c->leb_size * UBIFS_MIN_BUD_LEBS || c->max_bud_bytes > (long long)c->leb_size * c->main_lebs) { err = 8; goto failed; } if (c->jhead_cnt < NONDATA_JHEADS_CNT + 1 || c->jhead_cnt > NONDATA_JHEADS_CNT + UBIFS_MAX_JHEADS) { err = 9; goto failed; } if (c->fanout < UBIFS_MIN_FANOUT || ubifs_idx_node_sz(c, c->fanout) > c->leb_size) { err = 10; goto failed; } if (c->lsave_cnt < 0 || (c->lsave_cnt > DEFAULT_LSAVE_CNT && c->lsave_cnt > c->max_leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS - c->log_lebs - c->lpt_lebs - c->orph_lebs)) { err = 11; goto failed; } if (UBIFS_SB_LEBS + UBIFS_MST_LEBS + c->log_lebs + c->lpt_lebs + c->orph_lebs + c->main_lebs != c->leb_cnt) { err = 12; goto failed; } if (c->default_compr < 0 || c->default_compr >= UBIFS_COMPR_TYPES_CNT) { err = 13; goto failed; } max_bytes = c->main_lebs * (long long)c->leb_size; if (c->rp_size < 0 || max_bytes < c->rp_size) { err = 14; goto failed; } if (le32_to_cpu(sup->time_gran) > 1000000000 || le32_to_cpu(sup->time_gran) < 1) { err = 15; goto failed; } return 0; failed: ubifs_err("bad superblock, error %d", err); dbg_dump_node(c, sup); return -EINVAL; } /** * ubifs_read_sb_node - read superblock node. * @c: UBIFS file-system description object * * This function returns a pointer to the superblock node or a negative error * code. */ struct ubifs_sb_node *ubifs_read_sb_node(struct ubifs_info *c) { struct ubifs_sb_node *sup; int err; sup = kmalloc(ALIGN(UBIFS_SB_NODE_SZ, c->min_io_size), GFP_NOFS); if (!sup) return ERR_PTR(-ENOMEM); err = ubifs_read_node(c, sup, UBIFS_SB_NODE, UBIFS_SB_NODE_SZ, UBIFS_SB_LNUM, 0); if (err) { kfree(sup); return ERR_PTR(err); } return sup; } /** * ubifs_read_superblock - read superblock. * @c: UBIFS file-system description object * * This function finds, reads and checks the superblock. If an empty UBI volume * is being mounted, this function creates default superblock. Returns zero in * case of success, and a negative error code in case of failure. */ int ubifs_read_superblock(struct ubifs_info *c) { int err, sup_flags; struct ubifs_sb_node *sup; if (c->empty) { printf("No UBIFS filesystem found!\n"); return -1; } sup = ubifs_read_sb_node(c); if (IS_ERR(sup)) return PTR_ERR(sup); c->fmt_version = le32_to_cpu(sup->fmt_version); c->ro_compat_version = le32_to_cpu(sup->ro_compat_version); /* * The software supports all previous versions but not future versions, * due to the unavailability of time-travelling equipment. */ if (c->fmt_version > UBIFS_FORMAT_VERSION) { struct super_block *sb = c->vfs_sb; int mounting_ro = sb->s_flags & MS_RDONLY; ubifs_assert(!c->ro_media || mounting_ro); if (!mounting_ro || c->ro_compat_version > UBIFS_RO_COMPAT_VERSION) { ubifs_err("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); if (c->ro_compat_version <= UBIFS_RO_COMPAT_VERSION) { ubifs_msg("only R/O mounting is possible"); err = -EROFS; } else err = -EINVAL; goto out; } /* * The FS is mounted R/O, and the media format is * R/O-compatible with the UBIFS implementation, so we can * mount. */ c->rw_incompat = 1; } if (c->fmt_version < 3) { ubifs_err("on-flash format version %d is not supported", c->fmt_version); err = -EINVAL; goto out; } switch (sup->key_hash) { case UBIFS_KEY_HASH_R5: c->key_hash = key_r5_hash; c->key_hash_type = UBIFS_KEY_HASH_R5; break; case UBIFS_KEY_HASH_TEST: c->key_hash = key_test_hash; c->key_hash_type = UBIFS_KEY_HASH_TEST; break; }; c->key_fmt = sup->key_fmt; switch (c->key_fmt) { case UBIFS_SIMPLE_KEY_FMT: c->key_len = UBIFS_SK_LEN; break; default: ubifs_err("unsupported key format"); err = -EINVAL; goto out; } c->leb_cnt = le32_to_cpu(sup->leb_cnt); c->max_leb_cnt = le32_to_cpu(sup->max_leb_cnt); c->max_bud_bytes = le64_to_cpu(sup->max_bud_bytes); c->log_lebs = le32_to_cpu(sup->log_lebs); c->lpt_lebs = le32_to_cpu(sup->lpt_lebs); c->orph_lebs = le32_to_cpu(sup->orph_lebs); c->jhead_cnt = le32_to_cpu(sup->jhead_cnt) + NONDATA_JHEADS_CNT; c->fanout = le32_to_cpu(sup->fanout); c->lsave_cnt = le32_to_cpu(sup->lsave_cnt); c->default_compr = le16_to_cpu(sup->default_compr); c->rp_size = le64_to_cpu(sup->rp_size); c->rp_uid = le32_to_cpu(sup->rp_uid); c->rp_gid = le32_to_cpu(sup->rp_gid); sup_flags = le32_to_cpu(sup->flags); c->vfs_sb->s_time_gran = le32_to_cpu(sup->time_gran); memcpy(&c->uuid, &sup->uuid, 16); c->big_lpt = !!(sup_flags & UBIFS_FLG_BIGLPT); /* Automatically increase file system size to the maximum size */ c->old_leb_cnt = c->leb_cnt; if (c->leb_cnt < c->vi.size && c->leb_cnt < c->max_leb_cnt) { c->leb_cnt = min_t(int, c->max_leb_cnt, c->vi.size); dbg_mnt("Auto resizing (ro) from %d LEBs to %d LEBs", c->old_leb_cnt, c->leb_cnt); } c->log_bytes = (long long)c->log_lebs * c->leb_size; c->log_last = UBIFS_LOG_LNUM + c->log_lebs - 1; c->lpt_first = UBIFS_LOG_LNUM + c->log_lebs; c->lpt_last = c->lpt_first + c->lpt_lebs - 1; c->orph_first = c->lpt_last + 1; c->orph_last = c->orph_first + c->orph_lebs - 1; c->main_lebs = c->leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS; c->main_lebs -= c->log_lebs + c->lpt_lebs + c->orph_lebs; c->main_first = c->leb_cnt - c->main_lebs; c->report_rp_size = ubifs_reported_space(c, c->rp_size); err = validate_sb(c, sup); out: kfree(sup); return err; }
1001-study-uboot
fs/ubifs/sb.c
C
gpl3
9,601
/* * 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 contains miscelanious TNC-related functions shared betweend * different files. This file does not form any logically separate TNC * sub-system. The file was created because there is a lot of TNC code and * putting it all in one file would make that file too big and unreadable. */ #include "ubifs.h" /** * ubifs_tnc_levelorder_next - next TNC tree element in levelorder traversal. * @zr: root of the subtree to traverse * @znode: previous znode * * This function implements levelorder TNC traversal. The LNC is ignored. * Returns the next element or %NULL if @znode is already the last one. */ struct ubifs_znode *ubifs_tnc_levelorder_next(struct ubifs_znode *zr, struct ubifs_znode *znode) { int level, iip, level_search = 0; struct ubifs_znode *zn; ubifs_assert(zr); if (unlikely(!znode)) return zr; if (unlikely(znode == zr)) { if (znode->level == 0) return NULL; return ubifs_tnc_find_child(zr, 0); } level = znode->level; iip = znode->iip; while (1) { ubifs_assert(znode->level <= zr->level); /* * First walk up until there is a znode with next branch to * look at. */ while (znode->parent != zr && iip >= znode->parent->child_cnt) { znode = znode->parent; iip = znode->iip; } if (unlikely(znode->parent == zr && iip >= znode->parent->child_cnt)) { /* This level is done, switch to the lower one */ level -= 1; if (level_search || level < 0) /* * We were already looking for znode at lower * level ('level_search'). As we are here * again, it just does not exist. Or all levels * were finished ('level < 0'). */ return NULL; level_search = 1; iip = -1; znode = ubifs_tnc_find_child(zr, 0); ubifs_assert(znode); } /* Switch to the next index */ zn = ubifs_tnc_find_child(znode->parent, iip + 1); if (!zn) { /* No more children to look at, we have walk up */ iip = znode->parent->child_cnt; continue; } /* Walk back down to the level we came from ('level') */ while (zn->level != level) { znode = zn; zn = ubifs_tnc_find_child(zn, 0); if (!zn) { /* * This path is not too deep so it does not * reach 'level'. Try next path. */ iip = znode->iip; break; } } if (zn) { ubifs_assert(zn->level >= 0); return zn; } } } /** * ubifs_search_zbranch - search znode branch. * @c: UBIFS file-system description object * @znode: znode to search in * @key: key to search for * @n: znode branch slot number is returned here * * This is a helper function which search branch with key @key in @znode using * binary search. The result of the search may be: * o exact match, then %1 is returned, and the slot number of the branch is * stored in @n; * o no exact match, then %0 is returned and the slot number of the left * closest branch is returned in @n; the slot if all keys in this znode are * greater than @key, then %-1 is returned in @n. */ int ubifs_search_zbranch(const struct ubifs_info *c, const struct ubifs_znode *znode, const union ubifs_key *key, int *n) { int beg = 0, end = znode->child_cnt, uninitialized_var(mid); int uninitialized_var(cmp); const struct ubifs_zbranch *zbr = &znode->zbranch[0]; ubifs_assert(end > beg); while (end > beg) { mid = (beg + end) >> 1; cmp = keys_cmp(c, key, &zbr[mid].key); if (cmp > 0) beg = mid + 1; else if (cmp < 0) end = mid; else { *n = mid; return 1; } } *n = end - 1; /* The insert point is after *n */ ubifs_assert(*n >= -1 && *n < znode->child_cnt); if (*n == -1) ubifs_assert(keys_cmp(c, key, &zbr[0].key) < 0); else ubifs_assert(keys_cmp(c, key, &zbr[*n].key) > 0); if (*n + 1 < znode->child_cnt) ubifs_assert(keys_cmp(c, key, &zbr[*n + 1].key) < 0); return 0; } /** * ubifs_tnc_postorder_first - find first znode to do postorder tree traversal. * @znode: znode to start at (root of the sub-tree to traverse) * * Find the lowest leftmost znode in a subtree of the TNC tree. The LNC is * ignored. */ struct ubifs_znode *ubifs_tnc_postorder_first(struct ubifs_znode *znode) { if (unlikely(!znode)) return NULL; while (znode->level > 0) { struct ubifs_znode *child; child = ubifs_tnc_find_child(znode, 0); if (!child) return znode; znode = child; } return znode; } /** * ubifs_tnc_postorder_next - next TNC tree element in postorder traversal. * @znode: previous znode * * This function implements postorder TNC traversal. The LNC is ignored. * Returns the next element or %NULL if @znode is already the last one. */ struct ubifs_znode *ubifs_tnc_postorder_next(struct ubifs_znode *znode) { struct ubifs_znode *zn; ubifs_assert(znode); if (unlikely(!znode->parent)) return NULL; /* Switch to the next index in the parent */ zn = ubifs_tnc_find_child(znode->parent, znode->iip + 1); if (!zn) /* This is in fact the last child, return parent */ return znode->parent; /* Go to the first znode in this new subtree */ return ubifs_tnc_postorder_first(zn); } /** * read_znode - read an indexing node from flash and fill znode. * @c: UBIFS file-system description object * @lnum: LEB of the indexing node to read * @offs: node offset * @len: node length * @znode: znode to read to * * This function reads an indexing node from the flash media and fills znode * with the read data. Returns zero in case of success and a negative error * code in case of failure. The read indexing node is validated and if anything * is wrong with it, this function prints complaint messages and returns * %-EINVAL. */ static int read_znode(struct ubifs_info *c, int lnum, int offs, int len, struct ubifs_znode *znode) { int i, err, type, cmp; struct ubifs_idx_node *idx; idx = kmalloc(c->max_idx_node_sz, GFP_NOFS); if (!idx) return -ENOMEM; err = ubifs_read_node(c, idx, UBIFS_IDX_NODE, len, lnum, offs); if (err < 0) { kfree(idx); return err; } znode->child_cnt = le16_to_cpu(idx->child_cnt); znode->level = le16_to_cpu(idx->level); dbg_tnc("LEB %d:%d, level %d, %d branch", lnum, offs, znode->level, znode->child_cnt); if (znode->child_cnt > c->fanout || znode->level > UBIFS_MAX_LEVELS) { dbg_err("current fanout %d, branch count %d", c->fanout, znode->child_cnt); dbg_err("max levels %d, znode level %d", UBIFS_MAX_LEVELS, znode->level); err = 1; goto out_dump; } for (i = 0; i < znode->child_cnt; i++) { const struct ubifs_branch *br = ubifs_idx_branch(c, idx, i); struct ubifs_zbranch *zbr = &znode->zbranch[i]; key_read(c, &br->key, &zbr->key); zbr->lnum = le32_to_cpu(br->lnum); zbr->offs = le32_to_cpu(br->offs); zbr->len = le32_to_cpu(br->len); zbr->znode = NULL; /* Validate branch */ if (zbr->lnum < c->main_first || zbr->lnum >= c->leb_cnt || zbr->offs < 0 || zbr->offs + zbr->len > c->leb_size || zbr->offs & 7) { dbg_err("bad branch %d", i); err = 2; goto out_dump; } switch (key_type(c, &zbr->key)) { case UBIFS_INO_KEY: case UBIFS_DATA_KEY: case UBIFS_DENT_KEY: case UBIFS_XENT_KEY: break; default: dbg_msg("bad key type at slot %d: %s", i, DBGKEY(&zbr->key)); err = 3; goto out_dump; } if (znode->level) continue; type = key_type(c, &zbr->key); if (c->ranges[type].max_len == 0) { if (zbr->len != c->ranges[type].len) { dbg_err("bad target node (type %d) length (%d)", type, zbr->len); dbg_err("have to be %d", c->ranges[type].len); err = 4; goto out_dump; } } else if (zbr->len < c->ranges[type].min_len || zbr->len > c->ranges[type].max_len) { dbg_err("bad target node (type %d) length (%d)", type, zbr->len); dbg_err("have to be in range of %d-%d", c->ranges[type].min_len, c->ranges[type].max_len); err = 5; goto out_dump; } } /* * Ensure that the next key is greater or equivalent to the * previous one. */ for (i = 0; i < znode->child_cnt - 1; i++) { const union ubifs_key *key1, *key2; key1 = &znode->zbranch[i].key; key2 = &znode->zbranch[i + 1].key; cmp = keys_cmp(c, key1, key2); if (cmp > 0) { dbg_err("bad key order (keys %d and %d)", i, i + 1); err = 6; goto out_dump; } else if (cmp == 0 && !is_hash_key(c, key1)) { /* These can only be keys with colliding hash */ dbg_err("keys %d and %d are not hashed but equivalent", i, i + 1); err = 7; goto out_dump; } } kfree(idx); return 0; out_dump: ubifs_err("bad indexing node at LEB %d:%d, error %d", lnum, offs, err); dbg_dump_node(c, idx); kfree(idx); return -EINVAL; } /** * ubifs_load_znode - load znode to TNC cache. * @c: UBIFS file-system description object * @zbr: znode branch * @parent: znode's parent * @iip: index in parent * * This function loads znode pointed to by @zbr into the TNC cache and * returns pointer to it in case of success and a negative error code in case * of failure. */ struct ubifs_znode *ubifs_load_znode(struct ubifs_info *c, struct ubifs_zbranch *zbr, struct ubifs_znode *parent, int iip) { int err; struct ubifs_znode *znode; ubifs_assert(!zbr->znode); /* * A slab cache is not presently used for znodes because the znode size * depends on the fanout which is stored in the superblock. */ znode = kzalloc(c->max_znode_sz, GFP_NOFS); if (!znode) return ERR_PTR(-ENOMEM); err = read_znode(c, zbr->lnum, zbr->offs, zbr->len, znode); if (err) goto out; zbr->znode = znode; znode->parent = parent; znode->time = get_seconds(); znode->iip = iip; return znode; out: kfree(znode); return ERR_PTR(err); } /** * ubifs_tnc_read_node - read a leaf node from the flash media. * @c: UBIFS file-system description object * @zbr: key and position of the node * @node: node is returned here * * This function reads a node defined by @zbr from the flash media. Returns * zero in case of success or a negative negative error code in case of * failure. */ int ubifs_tnc_read_node(struct ubifs_info *c, struct ubifs_zbranch *zbr, void *node) { union ubifs_key key1, *key = &zbr->key; int err, type = key_type(c, key); err = ubifs_read_node(c, node, type, zbr->len, zbr->lnum, zbr->offs); if (err) { dbg_tnc("key %s", DBGKEY(key)); return err; } /* Make sure the key of the read node is correct */ key_read(c, node + UBIFS_KEY_OFFSET, &key1); if (!keys_eq(c, 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(key), DBGKEY1(&key1)); dbg_dump_node(c, node); return -EINVAL; } return 0; }
1001-study-uboot
fs/ubifs/tnc_misc.c
C
gpl3
11,454
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * (C) Copyright 2008-2010 * Stefan Roese, DENX Software Engineering, sr@denx.de. * * 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 */ #include "ubifs.h" #include <u-boot/zlib.h> DECLARE_GLOBAL_DATA_PTR; /* compress.c */ /* * We need a wrapper for zunzip() because the parameters are * incompatible with the lzo decompressor. */ static int gzip_decompress(const unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len) { unsigned long len = in_len; return zunzip(out, *out_len, (unsigned char *)in, &len, 0, 0); } /* Fake description object for the "none" compressor */ static struct ubifs_compressor none_compr = { .compr_type = UBIFS_COMPR_NONE, .name = "no compression", .capi_name = "", .decompress = NULL, }; static struct ubifs_compressor lzo_compr = { .compr_type = UBIFS_COMPR_LZO, .name = "LZO", .capi_name = "lzo", .decompress = lzo1x_decompress_safe, }; static struct ubifs_compressor zlib_compr = { .compr_type = UBIFS_COMPR_ZLIB, .name = "zlib", .capi_name = "deflate", .decompress = gzip_decompress, }; /* All UBIFS compressors */ struct ubifs_compressor *ubifs_compressors[UBIFS_COMPR_TYPES_CNT]; /** * ubifs_decompress - decompress data. * @in_buf: data to decompress * @in_len: length of the data to decompress * @out_buf: output buffer where decompressed data should * @out_len: output length is returned here * @compr_type: type of compression * * This function decompresses data from buffer @in_buf into buffer @out_buf. * The length of the uncompressed data is returned in @out_len. This functions * returns %0 on success or a negative error code on failure. */ int ubifs_decompress(const void *in_buf, int in_len, void *out_buf, int *out_len, int compr_type) { int err; struct ubifs_compressor *compr; if (unlikely(compr_type < 0 || compr_type >= UBIFS_COMPR_TYPES_CNT)) { ubifs_err("invalid compression type %d", compr_type); return -EINVAL; } compr = ubifs_compressors[compr_type]; if (unlikely(!compr->capi_name)) { ubifs_err("%s compression is not compiled in", compr->name); return -EINVAL; } if (compr_type == UBIFS_COMPR_NONE) { memcpy(out_buf, in_buf, in_len); *out_len = in_len; return 0; } err = compr->decompress(in_buf, in_len, out_buf, (size_t *)out_len); if (err) ubifs_err("cannot decompress %d bytes, compressor %s, " "error %d", in_len, compr->name, err); return err; } /** * compr_init - initialize a compressor. * @compr: compressor description object * * This function initializes the requested compressor and returns zero in case * of success or a negative error code in case of failure. */ static int __init compr_init(struct ubifs_compressor *compr) { ubifs_compressors[compr->compr_type] = compr; #ifdef CONFIG_NEEDS_MANUAL_RELOC ubifs_compressors[compr->compr_type]->name += gd->reloc_off; ubifs_compressors[compr->compr_type]->capi_name += gd->reloc_off; ubifs_compressors[compr->compr_type]->decompress += gd->reloc_off; #endif return 0; } /** * ubifs_compressors_init - initialize UBIFS compressors. * * This function initializes the compressor which were compiled in. Returns * zero in case of success and a negative error code in case of failure. */ int __init ubifs_compressors_init(void) { int err; err = compr_init(&lzo_compr); if (err) return err; err = compr_init(&zlib_compr); if (err) return err; err = compr_init(&none_compr); if (err) return err; return 0; } /* * ubifsls... */ static int filldir(struct ubifs_info *c, const char *name, int namlen, u64 ino, unsigned int d_type) { struct inode *inode; char filetime[32]; switch (d_type) { case UBIFS_ITYPE_REG: printf("\t"); break; case UBIFS_ITYPE_DIR: printf("<DIR>\t"); break; case UBIFS_ITYPE_LNK: printf("<LNK>\t"); break; default: printf("other\t"); break; } inode = ubifs_iget(c->vfs_sb, ino); if (IS_ERR(inode)) { printf("%s: Error in ubifs_iget(), ino=%lld ret=%p!\n", __func__, ino, inode); return -1; } ctime_r((time_t *)&inode->i_mtime, filetime); printf("%9lld %24.24s ", inode->i_size, filetime); ubifs_iput(inode); printf("%s\n", name); return 0; } static int ubifs_printdir(struct file *file, void *dirent) { int err, over = 0; struct qstr nm; union ubifs_key key; struct ubifs_dent_node *dent; struct inode *dir = file->f_path.dentry->d_inode; struct ubifs_info *c = dir->i_sb->s_fs_info; dbg_gen("dir ino %lu, f_pos %#llx", dir->i_ino, file->f_pos); if (file->f_pos > UBIFS_S_KEY_HASH_MASK || file->f_pos == 2) /* * The directory was seek'ed to a senseless position or there * are no more entries. */ return 0; if (file->f_pos == 1) { /* Find the first entry in TNC and save it */ lowest_dent_key(c, &key, dir->i_ino); nm.name = NULL; dent = ubifs_tnc_next_ent(c, &key, &nm); if (IS_ERR(dent)) { err = PTR_ERR(dent); goto out; } file->f_pos = key_hash_flash(c, &dent->key); file->private_data = dent; } dent = file->private_data; if (!dent) { /* * The directory was seek'ed to and is now readdir'ed. * Find the entry corresponding to @file->f_pos or the * closest one. */ dent_key_init_hash(c, &key, dir->i_ino, file->f_pos); nm.name = NULL; dent = ubifs_tnc_next_ent(c, &key, &nm); if (IS_ERR(dent)) { err = PTR_ERR(dent); goto out; } file->f_pos = key_hash_flash(c, &dent->key); file->private_data = dent; } while (1) { dbg_gen("feed '%s', ino %llu, new f_pos %#x", dent->name, (unsigned long long)le64_to_cpu(dent->inum), key_hash_flash(c, &dent->key)); ubifs_assert(le64_to_cpu(dent->ch.sqnum) > ubifs_inode(dir)->creat_sqnum); nm.len = le16_to_cpu(dent->nlen); over = filldir(c, (char *)dent->name, nm.len, le64_to_cpu(dent->inum), dent->type); if (over) return 0; /* Switch to the next entry */ key_read(c, &dent->key, &key); nm.name = (char *)dent->name; dent = ubifs_tnc_next_ent(c, &key, &nm); if (IS_ERR(dent)) { err = PTR_ERR(dent); goto out; } kfree(file->private_data); file->f_pos = key_hash_flash(c, &dent->key); file->private_data = dent; cond_resched(); } out: if (err != -ENOENT) { ubifs_err("cannot find next direntry, error %d", err); return err; } kfree(file->private_data); file->private_data = NULL; file->f_pos = 2; return 0; } static int ubifs_finddir(struct super_block *sb, char *dirname, unsigned long root_inum, unsigned long *inum) { int err; struct qstr nm; union ubifs_key key; struct ubifs_dent_node *dent; struct ubifs_info *c; struct file *file; struct dentry *dentry; struct inode *dir; file = kzalloc(sizeof(struct file), 0); dentry = kzalloc(sizeof(struct dentry), 0); dir = kzalloc(sizeof(struct inode), 0); if (!file || !dentry || !dir) { printf("%s: Error, no memory for malloc!\n", __func__); err = -ENOMEM; goto out; } dir->i_sb = sb; file->f_path.dentry = dentry; file->f_path.dentry->d_parent = dentry; file->f_path.dentry->d_inode = dir; file->f_path.dentry->d_inode->i_ino = root_inum; c = sb->s_fs_info; dbg_gen("dir ino %lu, f_pos %#llx", dir->i_ino, file->f_pos); /* Find the first entry in TNC and save it */ lowest_dent_key(c, &key, dir->i_ino); nm.name = NULL; dent = ubifs_tnc_next_ent(c, &key, &nm); if (IS_ERR(dent)) { err = PTR_ERR(dent); goto out; } file->f_pos = key_hash_flash(c, &dent->key); file->private_data = dent; while (1) { dbg_gen("feed '%s', ino %llu, new f_pos %#x", dent->name, (unsigned long long)le64_to_cpu(dent->inum), key_hash_flash(c, &dent->key)); ubifs_assert(le64_to_cpu(dent->ch.sqnum) > ubifs_inode(dir)->creat_sqnum); nm.len = le16_to_cpu(dent->nlen); if ((strncmp(dirname, (char *)dent->name, nm.len) == 0) && (strlen(dirname) == nm.len)) { *inum = le64_to_cpu(dent->inum); return 1; } /* Switch to the next entry */ key_read(c, &dent->key, &key); nm.name = (char *)dent->name; dent = ubifs_tnc_next_ent(c, &key, &nm); if (IS_ERR(dent)) { err = PTR_ERR(dent); goto out; } kfree(file->private_data); file->f_pos = key_hash_flash(c, &dent->key); file->private_data = dent; cond_resched(); } out: if (err != -ENOENT) { ubifs_err("cannot find next direntry, error %d", err); return err; } if (file->private_data) kfree(file->private_data); if (file) free(file); if (dentry) free(dentry); if (dir) free(dir); return 0; } static unsigned long ubifs_findfile(struct super_block *sb, char *filename) { int ret; char *next; char fpath[128]; char symlinkpath[128]; char *name = fpath; unsigned long root_inum = 1; unsigned long inum; int symlink_count = 0; /* Don't allow symlink recursion */ char link_name[64]; strcpy(fpath, filename); /* Remove all leading slashes */ while (*name == '/') name++; /* * Handle root-direcoty ('/') */ inum = root_inum; if (!name || *name == '\0') return inum; for (;;) { struct inode *inode; struct ubifs_inode *ui; /* Extract the actual part from the pathname. */ next = strchr(name, '/'); if (next) { /* Remove all leading slashes. */ while (*next == '/') *(next++) = '\0'; } ret = ubifs_finddir(sb, name, root_inum, &inum); if (!ret) return 0; inode = ubifs_iget(sb, inum); if (!inode) return 0; ui = ubifs_inode(inode); if ((inode->i_mode & S_IFMT) == S_IFLNK) { char buf[128]; /* We have some sort of symlink recursion, bail out */ if (symlink_count++ > 8) { printf("Symlink recursion, aborting\n"); return 0; } memcpy(link_name, ui->data, ui->data_len); link_name[ui->data_len] = '\0'; if (link_name[0] == '/') { /* Absolute path, redo everything without * the leading slash */ next = name = link_name + 1; root_inum = 1; continue; } /* Relative to cur dir */ sprintf(buf, "%s/%s", link_name, next == NULL ? "" : next); memcpy(symlinkpath, buf, sizeof(buf)); next = name = symlinkpath; continue; } /* * Check if directory with this name exists */ /* Found the node! */ if (!next || *next == '\0') return inum; root_inum = inum; name = next; } return 0; } int ubifs_ls(char *filename) { struct ubifs_info *c = ubifs_sb->s_fs_info; struct file *file; struct dentry *dentry; struct inode *dir; void *dirent = NULL; unsigned long inum; int ret = 0; c->ubi = ubi_open_volume(c->vi.ubi_num, c->vi.vol_id, UBI_READONLY); inum = ubifs_findfile(ubifs_sb, filename); if (!inum) { ret = -1; goto out; } file = kzalloc(sizeof(struct file), 0); dentry = kzalloc(sizeof(struct dentry), 0); dir = kzalloc(sizeof(struct inode), 0); if (!file || !dentry || !dir) { printf("%s: Error, no memory for malloc!\n", __func__); ret = -ENOMEM; goto out_mem; } dir->i_sb = ubifs_sb; file->f_path.dentry = dentry; file->f_path.dentry->d_parent = dentry; file->f_path.dentry->d_inode = dir; file->f_path.dentry->d_inode->i_ino = inum; file->f_pos = 1; file->private_data = NULL; ubifs_printdir(file, dirent); out_mem: if (file) free(file); if (dentry) free(dentry); if (dir) free(dir); out: ubi_close_volume(c->ubi); return ret; } /* * ubifsload... */ /* file.c */ static inline void *kmap(struct page *page) { return page->addr; } static int read_block(struct inode *inode, void *addr, unsigned int block, struct ubifs_data_node *dn) { struct ubifs_info *c = inode->i_sb->s_fs_info; int err, len, out_len; union ubifs_key key; unsigned int dlen; data_key_init(c, &key, inode->i_ino, block); err = ubifs_tnc_lookup(c, &key, dn); if (err) { if (err == -ENOENT) /* Not found, so it must be a hole */ memset(addr, 0, UBIFS_BLOCK_SIZE); return err; } ubifs_assert(le64_to_cpu(dn->ch.sqnum) > ubifs_inode(inode)->creat_sqnum); len = le32_to_cpu(dn->size); if (len <= 0 || len > UBIFS_BLOCK_SIZE) goto dump; dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ; out_len = UBIFS_BLOCK_SIZE; err = ubifs_decompress(&dn->data, dlen, addr, &out_len, le16_to_cpu(dn->compr_type)); if (err || len != out_len) goto dump; /* * Data length can be less than a full block, even for blocks that are * not the last in the file (e.g., as a result of making a hole and * appending data). Ensure that the remainder is zeroed out. */ if (len < UBIFS_BLOCK_SIZE) memset(addr + len, 0, UBIFS_BLOCK_SIZE - len); return 0; dump: ubifs_err("bad data node (block %u, inode %lu)", block, inode->i_ino); dbg_dump_node(c, dn); return -EINVAL; } static int do_readpage(struct ubifs_info *c, struct inode *inode, struct page *page, int last_block_size) { void *addr; int err = 0, i; unsigned int block, beyond; struct ubifs_data_node *dn; loff_t i_size = inode->i_size; dbg_gen("ino %lu, pg %lu, i_size %lld", inode->i_ino, page->index, i_size); addr = kmap(page); block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT; beyond = (i_size + UBIFS_BLOCK_SIZE - 1) >> UBIFS_BLOCK_SHIFT; if (block >= beyond) { /* Reading beyond inode */ memset(addr, 0, PAGE_CACHE_SIZE); goto out; } dn = kmalloc(UBIFS_MAX_DATA_NODE_SZ, GFP_NOFS); if (!dn) return -ENOMEM; i = 0; while (1) { int ret; if (block >= beyond) { /* Reading beyond inode */ err = -ENOENT; memset(addr, 0, UBIFS_BLOCK_SIZE); } else { /* * Reading last block? Make sure to not write beyond * the requested size in the destination buffer. */ if (((block + 1) == beyond) || last_block_size) { void *buff; int dlen; /* * We need to buffer the data locally for the * last block. This is to not pad the * destination area to a multiple of * UBIFS_BLOCK_SIZE. */ buff = malloc(UBIFS_BLOCK_SIZE); if (!buff) { printf("%s: Error, malloc fails!\n", __func__); err = -ENOMEM; break; } /* Read block-size into temp buffer */ ret = read_block(inode, buff, block, dn); if (ret) { err = ret; if (err != -ENOENT) { free(buff); break; } } if (last_block_size) dlen = last_block_size; else dlen = le32_to_cpu(dn->size); /* Now copy required size back to dest */ memcpy(addr, buff, dlen); free(buff); } else { ret = read_block(inode, addr, block, dn); if (ret) { err = ret; if (err != -ENOENT) break; } } } if (++i >= UBIFS_BLOCKS_PER_PAGE) break; block += 1; addr += UBIFS_BLOCK_SIZE; } if (err) { if (err == -ENOENT) { /* Not found, so it must be a hole */ dbg_gen("hole"); goto out_free; } ubifs_err("cannot read page %lu of inode %lu, error %d", page->index, inode->i_ino, err); goto error; } out_free: kfree(dn); out: return 0; error: kfree(dn); return err; } int ubifs_load(char *filename, u32 addr, u32 size) { struct ubifs_info *c = ubifs_sb->s_fs_info; unsigned long inum; struct inode *inode; struct page page; int err = 0; int i; int count; int last_block_size = 0; char buf [10]; c->ubi = ubi_open_volume(c->vi.ubi_num, c->vi.vol_id, UBI_READONLY); /* ubifs_findfile will resolve symlinks, so we know that we get * the real file here */ inum = ubifs_findfile(ubifs_sb, filename); if (!inum) { err = -1; goto out; } /* * Read file inode */ inode = ubifs_iget(ubifs_sb, inum); if (IS_ERR(inode)) { printf("%s: Error reading inode %ld!\n", __func__, inum); err = PTR_ERR(inode); goto out; } /* * If no size was specified or if size bigger than filesize * set size to filesize */ if ((size == 0) || (size > inode->i_size)) size = inode->i_size; count = (size + UBIFS_BLOCK_SIZE - 1) >> UBIFS_BLOCK_SHIFT; printf("Loading file '%s' to addr 0x%08x with size %d (0x%08x)...\n", filename, addr, size, size); page.addr = (void *)addr; page.index = 0; page.inode = inode; for (i = 0; i < count; i++) { /* * Make sure to not read beyond the requested size */ if (((i + 1) == count) && (size < inode->i_size)) last_block_size = size - (i * PAGE_SIZE); err = do_readpage(c, inode, &page, last_block_size); if (err) break; page.addr += PAGE_SIZE; page.index++; } if (err) printf("Error reading file '%s'\n", filename); else { sprintf(buf, "%X", size); setenv("filesize", buf); printf("Done\n"); } ubifs_iput(inode); out: ubi_close_volume(c->ubi); return err; }
1001-study-uboot
fs/ubifs/ubifs.c
C
gpl3
17,170
/* * (C) Copyright 2002 * Stäubli Faverges - <www.staubli.com> * Pierre AUBERT p.aubert@staubli.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 <common.h> #include <config.h> #include <malloc.h> #include "dos.h" #include "fdos.h" static int cache_sect; static unsigned char cache [SZ_STD_SECTOR]; #define min(x,y) ((x)<(y)?(x):(y)) static int descend (Slot_t *parent, Fs_t *fs, char *path); /*----------------------------------------------------------------------------- * init_subdir -- *----------------------------------------------------------------------------- */ void init_subdir (void) { cache_sect = -1; } /*----------------------------------------------------------------------------- * basename -- *----------------------------------------------------------------------------- */ char *basename (char *name) { register char *cptr; if (!name || !*name) { return (""); } for (cptr= name; *cptr++; ); while (--cptr >= name) { if (*cptr == '/') { return (cptr + 1); } } return(name); } /*----------------------------------------------------------------------------- * root_map -- *----------------------------------------------------------------------------- */ static int root_map (Fs_t *fs, Slot_t *file, int where, int *len) { *len = min (*len, fs -> dir_len * SZ_STD_SECTOR - where); if (*len < 0 ) { *len = 0; return (-1); } return fs -> dir_start * SZ_STD_SECTOR + where; } /*----------------------------------------------------------------------------- * normal_map -- *----------------------------------------------------------------------------- */ static int normal_map (Fs_t *fs, Slot_t *file, int where, int *len) { int offset; int NrClu; unsigned short RelCluNr; unsigned short CurCluNr; unsigned short NewCluNr; unsigned short AbsCluNr; int clus_size; clus_size = fs -> cluster_size * SZ_STD_SECTOR; offset = where % clus_size; *len = min (*len, file -> FileSize - where); if (*len < 0 ) { *len = 0; return (0); } if (file -> FirstAbsCluNr < 2){ *len = 0; return (0); } RelCluNr = where / clus_size; if (RelCluNr >= file -> PreviousRelCluNr){ CurCluNr = file -> PreviousRelCluNr; AbsCluNr = file -> PreviousAbsCluNr; } else { CurCluNr = 0; AbsCluNr = file -> FirstAbsCluNr; } NrClu = (offset + *len - 1) / clus_size; while (CurCluNr <= RelCluNr + NrClu) { if (CurCluNr == RelCluNr){ /* we have reached the beginning of our zone. Save * coordinates */ file -> PreviousRelCluNr = RelCluNr; file -> PreviousAbsCluNr = AbsCluNr; } NewCluNr = fat_decode (fs, AbsCluNr); if (NewCluNr == 1 || NewCluNr == 0) { PRINTF("Fat problem while decoding %d %x\n", AbsCluNr, NewCluNr); return (-1); } if (CurCluNr == RelCluNr + NrClu) { break; } if (CurCluNr < RelCluNr && NewCluNr == FAT12_END) { *len = 0; return 0; } if (CurCluNr >= RelCluNr && NewCluNr != AbsCluNr + 1) break; CurCluNr++; AbsCluNr = NewCluNr; } *len = min (*len, (1 + CurCluNr - RelCluNr) * clus_size - offset); return (((file -> PreviousAbsCluNr - 2) * fs -> cluster_size + fs -> dir_start + fs -> dir_len) * SZ_STD_SECTOR + offset); } /*----------------------------------------------------------------------------- * open_subdir -- open the subdir containing the file *----------------------------------------------------------------------------- */ int open_subdir (File_t *desc) { char *pathname; char *tmp, *s, *path; char terminator; if ((pathname = (char *)malloc (MAX_PATH)) == NULL) { return (-1); } strcpy (pathname, desc -> name); /* Suppress file name */ tmp = basename (pathname); *tmp = '\0'; /* root directory init */ desc -> subdir.FirstAbsCluNr = 0; desc -> subdir.FileSize = -1; desc -> subdir.map = root_map; desc -> subdir.dir.attr = ATTR_DIRECTORY; tmp = pathname; for (s = tmp; ; ++s) { if (*s == '/' || *s == '\0') { path = tmp; terminator = *s; *s = '\0'; if (s != tmp && strcmp (path,".")) { if (descend (&desc -> subdir, desc -> fs, path) < 0) { free (pathname); return (-1); } } if (terminator == 0) { break; } tmp = s + 1; } } free (pathname); return (0); } /*----------------------------------------------------------------------------- * descend -- *----------------------------------------------------------------------------- */ static int descend (Slot_t *parent, Fs_t *fs, char *path) { int entry; Slot_t SubDir; if(path[0] == '\0' || strcmp (path, ".") == 0) { return (0); } entry = 0; if (vfat_lookup (parent, fs, &(SubDir.dir), &entry, 0, path, ACCEPT_DIR | SINGLE | DO_OPEN, 0, &SubDir) == 0) { *parent = SubDir; return (0); } if (strcmp(path, "..") == 0) { parent -> FileSize = -1; parent -> FirstAbsCluNr = 0; parent -> map = root_map; return (0); } return (-1); } /*----------------------------------------------------------------------------- * open_file -- *----------------------------------------------------------------------------- */ int open_file (Slot_t *file, Directory_t *dir) { int first; unsigned long size; first = __le16_to_cpu (dir -> start); if(first == 0 && (dir -> attr & ATTR_DIRECTORY) != 0) { file -> FirstAbsCluNr = 0; file -> FileSize = -1; file -> map = root_map; return (0); } if ((dir -> attr & ATTR_DIRECTORY) != 0) { size = (1UL << 31) - 1; } else { size = __le32_to_cpu (dir -> size); } file -> map = normal_map; file -> FirstAbsCluNr = first; file -> PreviousRelCluNr = 0xffff; file -> FileSize = size; return (0); } /*----------------------------------------------------------------------------- * read_file -- *----------------------------------------------------------------------------- */ int read_file (Fs_t *fs, Slot_t *file, char *buf, int where, int len) { int pos; int read, nb, sect, offset; pos = file -> map (fs, file, where, &len); if (pos < 0) { return -1; } if (len == 0) { return (0); } /* Compute sector number */ sect = pos / SZ_STD_SECTOR; offset = pos % SZ_STD_SECTOR; read = 0; if (offset) { /* Read doesn't start at the sector beginning. We need to use our */ /* cache */ if (sect != cache_sect) { if (dev_read (cache, sect, 1) < 0) { return (-1); } cache_sect = sect; } nb = min (len, SZ_STD_SECTOR - offset); memcpy (buf, cache + offset, nb); read += nb; len -= nb; sect += 1; } if (len > SZ_STD_SECTOR) { nb = (len - 1) / SZ_STD_SECTOR; if (dev_read (buf + read, sect, nb) < 0) { return ((read) ? read : -1); } /* update sector position */ sect += nb; /* Update byte position */ nb *= SZ_STD_SECTOR; read += nb; len -= nb; } if (len) { if (sect != cache_sect) { if (dev_read (cache, sect, 1) < 0) { return ((read) ? read : -1); cache_sect = -1; } cache_sect = sect; } memcpy (buf + read, cache, len); read += len; } return (read); }
1001-study-uboot
fs/fdos/subdir.c
C
gpl3
8,385
/* * (C) Copyright 2002 * Stäubli Faverges - <www.staubli.com> * Pierre AUBERT p.aubert@staubli.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 <common.h> #include <config.h> #include <malloc.h> #include "dos.h" #include "fdos.h" /*----------------------------------------------------------------------------- * fill_fs -- Read info on file system *----------------------------------------------------------------------------- */ static int fill_fs (BootSector_t *boot, Fs_t *fs) { fs -> fat_start = __le16_to_cpu (boot -> nrsvsect); fs -> fat_len = __le16_to_cpu (boot -> fatlen); fs -> nb_fat = boot -> nfat; fs -> dir_start = fs -> fat_start + fs -> nb_fat * fs -> fat_len; fs -> dir_len = __le16_to_cpu (boot -> dirents) * MDIR_SIZE / SZ_STD_SECTOR; fs -> cluster_size = boot -> clsiz; fs -> num_clus = (fs -> tot_sectors - fs -> dir_start - fs -> dir_len) / fs -> cluster_size; return (0); } /*----------------------------------------------------------------------------- * fs_init -- *----------------------------------------------------------------------------- */ int fs_init (Fs_t *fs) { BootSector_t *boot; /* Initialize physical device */ if (dev_open () < 0) { PRINTF ("Unable to initialize the fdc\n"); return (-1); } init_subdir (); /* Allocate space for read the boot sector */ if ((boot = (BootSector_t *)malloc (sizeof (BootSector_t))) == NULL) { PRINTF ("Unable to allocate space for boot sector\n"); return (-1); } /* read boot sector */ if (dev_read (boot, 0, 1)){ PRINTF ("Error during boot sector read\n"); free (boot); return (-1); } /* we verify it'a a DOS diskette */ if (boot -> jump [0] != JUMP_0_1 && boot -> jump [0] != JUMP_0_2) { PRINTF ("Not a DOS diskette\n"); free (boot); return (-1); } if (boot -> descr < MEDIA_STD) { /* We handle only recent medias (type F0) */ PRINTF ("unrecognized diskette type\n"); free (boot); return (-1); } if (check_dev (boot, fs) < 0) { PRINTF ("Bad diskette\n"); free (boot); return (-1); } if (fill_fs (boot, fs) < 0) { free (boot); return (-1); } /* Read FAT */ if (read_fat (boot, fs) < 0) { free (boot); return (-1); } free (boot); return (0); }
1001-study-uboot
fs/fdos/fs.c
C
gpl3
3,317
/* * (C) Copyright 2002 * Stäubli Faverges - <www.staubli.com> * Pierre AUBERT p.aubert@staubli.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 */ #ifndef _DOS_H_ #define _DOS_H_ /* Definitions for Dos diskettes */ /* General definitions */ #define SZ_STD_SECTOR 512 /* Standard sector size */ #define MDIR_SIZE 32 /* Direntry size */ #define FAT_BITS 12 /* Diskette use 12 bits fat */ #define MAX_PATH 128 /* Max size of the MSDOS PATH */ #define MAX_DIR_SECS 64 /* Taille max d'un repertoire (en */ /* secteurs) */ /* Misc. definitions */ #define DELMARK '\xe5' #define EXTENDED_BOOT (0x29) #define MEDIA_STD (0xf0) #define JUMP_0_1 (0xe9) #define JUMP_0_2 (0xeb) /* Boot size is 256 bytes, but we need to read almost a sector, then assume bootsize is 512 */ #define BOOTSIZE 512 /* Fat definitions for 12 bits fat */ #define FAT12_MAX_NB 4086 #define FAT12_LAST 0x0ff6 #define FAT12_END 0x0fff /* file attributes */ #define ATTR_READONLY 0x01 #define ATTR_HIDDEN 0x02 #define ATTR_SYSTEM 0x04 #define ATTR_VOLUME 0x08 #define ATTR_DIRECTORY 0x10 #define ATTR_ARCHIVE 0x20 #define ATTR_VSE 0x0f /* Name format */ #define EXTCASE 0x10 #define BASECASE 0x8 /* Definition of the boot sector */ #define BANNER_LG 8 #define LABEL_LG 11 typedef struct bootsector { unsigned char jump [3]; /* 0 Jump to boot code */ char banner [BANNER_LG]; /* 3 OEM name & version */ unsigned short secsiz; /* 11 Bytes per sector hopefully 512 */ unsigned char clsiz; /* 13 Cluster size in sectors */ unsigned short nrsvsect; /* 14 Number of reserved (boot) sectors */ unsigned char nfat; /* 16 Number of FAT tables hopefully 2 */ unsigned short dirents; /* 17 Number of directory slots */ unsigned short psect; /* 19 Total sectors on disk */ unsigned char descr; /* 21 Media descriptor=first byte of FAT */ unsigned short fatlen; /* 22 Sectors in FAT */ unsigned short nsect; /* 24 Sectors/track */ unsigned short nheads; /* 26 Heads */ unsigned int nhs; /* 28 number of hidden sectors */ unsigned int bigsect; /* 32 big total sectors */ unsigned char physdrive; /* 36 physical drive ? */ unsigned char reserved; /* 37 reserved */ unsigned char dos4; /* 38 dos > 4.0 diskette */ unsigned int serial; /* 39 serial number */ char label [LABEL_LG]; /* 43 disk label */ char fat_type [8]; /* 54 FAT type */ unsigned char res_2m; /* 62 reserved by 2M */ unsigned char CheckSum; /* 63 2M checksum (not used) */ unsigned char fmt_2mf; /* 64 2MF format version */ unsigned char wt; /* 65 1 if write track after format */ unsigned char rate_0; /* 66 data transfer rate on track 0 */ unsigned char rate_any; /* 67 data transfer rate on track<>0 */ unsigned short BootP; /* 68 offset to boot program */ unsigned short Infp0; /* 70 T1: information for track 0 */ unsigned short InfpX; /* 72 T2: information for track<>0 */ unsigned short InfTm; /* 74 T3: track sectors size table */ unsigned short DateF; /* 76 Format date */ unsigned short TimeF; /* 78 Format time */ unsigned char junk [BOOTSIZE - 80]; /* 80 remaining data */ } __attribute__ ((packed)) BootSector_t; /* Structure d'une entree de repertoire */ typedef struct directory { char name [8]; /* file name */ char ext [3]; /* file extension */ unsigned char attr; /* attribute byte */ unsigned char Case; /* case of short filename */ unsigned char reserved [9]; /* ?? */ unsigned char time [2]; /* time stamp */ unsigned char date [2]; /* date stamp */ unsigned short start; /* starting cluster number */ unsigned int size; /* size of the file */ } __attribute__ ((packed)) Directory_t; #define MAX_VFAT_SUBENTRIES 20 #define VSE_NAMELEN 13 #define VSE1SIZE 5 #define VSE2SIZE 6 #define VSE3SIZE 2 #define VBUFSIZE ((MAX_VFAT_SUBENTRIES * VSE_NAMELEN) + 1) #define MAX_VNAMELEN (255) #define VSE_PRESENT 0x01 #define VSE_LAST 0x40 #define VSE_MASK 0x1f /* Flag used by vfat_lookup */ #define DO_OPEN 1 #define ACCEPT_PLAIN 0x20 #define ACCEPT_DIR 0x10 #define ACCEPT_LABEL 0x08 #define SINGLE 2 #define MATCH_ANY 0x40 struct vfat_subentry { unsigned char id; /* VSE_LAST pour la fin, VSE_MASK */ /* pour un VSE */ char text1 [VSE1SIZE * 2]; /* Caracteres encodes sur 16 bits */ unsigned char attribute; /* 0x0f pour les VFAT */ unsigned char hash1; /* toujours 0 */ unsigned char sum; /* Checksum du nom court */ char text2 [VSE2SIZE * 2]; /* Caracteres encodes sur 16 bits */ unsigned char sector_l; /* 0 pour les VFAT */ unsigned char sector_u; /* 0 pour les VFAT */ char text3 [VSE3SIZE * 2]; /* Caracteres encodes sur 16 bits */ } __attribute__ ((packed)) ; struct vfat_state { char name [VBUFSIZE]; int status; /* is now a bit map of 32 bits */ int subentries; unsigned char sum; /* no need to remember the sum for each */ /* entry, it is the same anyways */ } __attribute__ ((packed)) ; /* Conversion macros */ #define DOS_YEAR(dir) (((dir)->date[1] >> 1) + 1980) #define DOS_MONTH(dir) (((((dir)->date[1]&0x1) << 3) + ((dir)->date[0] >> 5))) #define DOS_DAY(dir) ((dir)->date[0] & 0x1f) #define DOS_HOUR(dir) ((dir)->time[1] >> 3) #define DOS_MINUTE(dir) (((((dir)->time[1]&0x7) << 3) + ((dir)->time[0] >> 5))) #define DOS_SEC(dir) (((dir)->time[0] & 0x1f) * 2) #endif
1001-study-uboot
fs/fdos/dos.h
C
gpl3
8,132
# # (C) Copyright 2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # (C) Copyright 2002 # Stäubli Faverges - <www.staubli.com> # Pierre AUBERT p.aubert@staubli.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 $(TOPDIR)/config.mk LIB = $(obj)libfdos.o AOBJS = COBJS-$(CONFIG_CMD_FDOS) := fat.o vfat.o dev.o fdos.o fs.o subdir.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/fdos/Makefile
Makefile
gpl3
1,517
/* * (C) Copyright 2002 * Stäubli Faverges - <www.staubli.com> * Pierre AUBERT p.aubert@staubli.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 <common.h> #include <config.h> #include <linux/ctype.h> #include "dos.h" #include "fdos.h" static int dir_read (Fs_t *fs, Slot_t *dir, Directory_t *dirent, int num, struct vfat_state *v); static int unicode_read (char *in, char *out, int num); static int match (const char *s, const char *p); static unsigned char sum_shortname (char *name); static int check_vfat (struct vfat_state *v, Directory_t *dir); static char *conv_name (char *name, char *ext, char Case, char *ans); /*----------------------------------------------------------------------------- * clear_vfat -- *----------------------------------------------------------------------------- */ static void clear_vfat (struct vfat_state *v) { v -> subentries = 0; v -> status = 0; } /*----------------------------------------------------------------------------- * vfat_lookup -- *----------------------------------------------------------------------------- */ int vfat_lookup (Slot_t *dir, Fs_t *fs, Directory_t *dirent, int *entry, int *vfat_start, char *filename, int flags, char *outname, Slot_t *file) { int found; struct vfat_state vfat; char newfile [VSE_NAMELEN]; int vfat_present = 0; if (*entry == -1) { return -1; } found = 0; clear_vfat (&vfat); while (1) { if (dir_read (fs, dir, dirent, *entry, &vfat) < 0) { if (vfat_start) { *vfat_start = *entry; } break; } (*entry)++; /* Empty slot */ if (dirent -> name[0] == '\0'){ if (vfat_start == 0) { break; } continue; } if (dirent -> attr == ATTR_VSE) { /* VSE entry, continue */ continue; } if ( (dirent -> name [0] == DELMARK) || ((dirent -> attr & ATTR_DIRECTORY) != 0 && (flags & ACCEPT_DIR) == 0) || ((dirent -> attr & ATTR_VOLUME) != 0 && (flags & ACCEPT_LABEL) == 0) || (((dirent -> attr & (ATTR_DIRECTORY | ATTR_VOLUME)) == 0) && (flags & ACCEPT_PLAIN) == 0)) { clear_vfat (&vfat); continue; } vfat_present = check_vfat (&vfat, dirent); if (vfat_start) { *vfat_start = *entry - 1; if (vfat_present) { *vfat_start -= vfat.subentries; } } if (dirent -> attr & ATTR_VOLUME) { strncpy (newfile, dirent -> name, 8); newfile [8] = '\0'; strncat (newfile, dirent -> ext, 3); newfile [11] = '\0'; } else { conv_name (dirent -> name, dirent -> ext, dirent -> Case, newfile); } if (flags & MATCH_ANY) { found = 1; break; } if ((vfat_present && match (vfat.name, filename)) || (match (newfile, filename))) { found = 1; break; } clear_vfat (&vfat); } if (found) { if ((flags & DO_OPEN) && file) { if (open_file (file, dirent) < 0) { return (-1); } } if (outname) { if (vfat_present) { strcpy (outname, vfat.name); } else { strcpy (outname, newfile); } } return (0); /* File found */ } else { *entry = -1; return -1; /* File not found */ } } /*----------------------------------------------------------------------------- * dir_read -- Read one directory entry *----------------------------------------------------------------------------- */ static int dir_read (Fs_t *fs, Slot_t *dir, Directory_t *dirent, int num, struct vfat_state *v) { /* read the directory entry */ if (read_file (fs, dir, (char *)dirent, num * MDIR_SIZE, MDIR_SIZE) != MDIR_SIZE) { return (-1); } if (v && (dirent -> attr == ATTR_VSE)) { struct vfat_subentry *vse; unsigned char id, last_flag; char *c; vse = (struct vfat_subentry *) dirent; id = vse -> id & VSE_MASK; last_flag = (vse -> id & VSE_LAST); if (id > MAX_VFAT_SUBENTRIES) { /* Invalid VSE entry */ return (-1); } /* Decode VSE */ if(v -> sum != vse -> sum) { clear_vfat (v); v -> sum = vse -> sum; } v -> status |= 1 << (id - 1); if (last_flag) { v -> subentries = id; } c = &(v -> name [VSE_NAMELEN * (id - 1)]); c += unicode_read (vse->text1, c, VSE1SIZE); c += unicode_read (vse->text2, c, VSE2SIZE); c += unicode_read (vse->text3, c, VSE3SIZE); if (last_flag) { *c = '\0'; /* Null terminate long name */ } } return (0); } /*----------------------------------------------------------------------------- * unicode_read -- *----------------------------------------------------------------------------- */ static int unicode_read (char *in, char *out, int num) { int j; for (j = 0; j < num; ++j) { if (in [1]) *out = '_'; else *out = in [0]; out ++; in += 2; } return num; } /*----------------------------------------------------------------------------- * match -- *----------------------------------------------------------------------------- */ static int match (const char *s, const char *p) { for (; *p != '\0'; ) { if (toupper (*s) != toupper (*p)) { return (0); } p++; s++; } if (*s != '\0') { return (0); } else { return (1); } } /*----------------------------------------------------------------------------- * sum_shortname -- *----------------------------------------------------------------------------- */ static unsigned char sum_shortname (char *name) { unsigned char sum; int j; for (j = sum = 0; j < 11; ++j) { sum = ((sum & 1) ? 0x80 : 0) + (sum >> 1) + (name [j] ? name [j] : ' '); } return (sum); } /*----------------------------------------------------------------------------- * check_vfat -- * Return 1 if long name is valid, 0 else *----------------------------------------------------------------------------- */ static int check_vfat (struct vfat_state *v, Directory_t *dir) { char name[12]; if (v -> subentries == 0) { return 0; } strncpy (name, dir -> name, 8); strncpy (name + 8, dir -> ext, 3); name [11] = '\0'; if (v -> sum != sum_shortname (name)) { return 0; } if( (v -> status & ((1 << v -> subentries) - 1)) != (1 << v -> subentries) - 1) { return 0; } v->name [VSE_NAMELEN * v -> subentries] = 0; return 1; } /*----------------------------------------------------------------------------- * conv_name -- *----------------------------------------------------------------------------- */ static char *conv_name (char *name, char *ext, char Case, char *ans) { char tname [9], text [4]; int i; i = 0; while (i < 8 && name [i] != ' ' && name [i] != '\0') { tname [i] = name [i]; i++; } tname [i] = '\0'; if (Case & BASECASE) { for (i = 0; i < 8 && tname [i]; i++) { tname [i] = tolower (tname [i]); } } i = 0; while (i < 3 && ext [i] != ' ' && ext [i] != '\0') { text [i] = ext [i]; i++; } text [i] = '\0'; if (Case & EXTCASE){ for (i = 0; i < 3 && text [i]; i++) { text [i] = tolower (text [i]); } } if (*text) { strcpy (ans, tname); strcat (ans, "."); strcat (ans, text); } else { strcpy(ans, tname); } return (ans); }
1001-study-uboot
fs/fdos/vfat.c
C
gpl3
8,336
/* * (C) Copyright 2002 * Stäubli Faverges - <www.staubli.com> * Pierre AUBERT p.aubert@staubli.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 */ #ifndef _FDOS_H_ #define _FDOS_H_ #undef FDOS_DEBUG #ifdef FDOS_DEBUG #define PRINTF(fmt,args...) printf (fmt ,##args) #else #define PRINTF(fmt,args...) #endif /* Data structure describing media */ typedef struct fs { unsigned long tot_sectors; int cluster_size; int num_clus; int fat_start; int fat_len; int nb_fat; int num_fat; int dir_start; int dir_len; unsigned char *fat_buf; } Fs_t; /* Data structure describing one file system slot */ typedef struct slot { int (*map) (struct fs *fs, struct slot *file, int where, int *len); unsigned long FileSize; unsigned short int FirstAbsCluNr; unsigned short int PreviousAbsCluNr; unsigned short int PreviousRelCluNr; Directory_t dir; } Slot_t; typedef struct file { char *name; int Case; Fs_t *fs; Slot_t subdir; Slot_t file; } File_t; /* dev.c */ int dev_read (void *buffer, int where, int len); int dev_open (void); int check_dev (BootSector_t *boot, Fs_t *fs); /* fat.c */ unsigned int fat_decode (Fs_t *fs, unsigned int num); int read_fat (BootSector_t *boot, Fs_t *fs); /* vfat.c */ int vfat_lookup (Slot_t *dir, Fs_t *fs, Directory_t *dirent, int *entry, int *vfat_start, char *filename, int flags, char *outname, Slot_t *file); /* subdir.c */ char *basename (char *name); int open_subdir (File_t *desc); int open_file (Slot_t *file, Directory_t *dir); int read_file (Fs_t *fs, Slot_t *file, char *buf, int where, int len); void init_subdir (void); /* fs.c */ int fs_init (Fs_t *fs); #endif
1001-study-uboot
fs/fdos/fdos.h
C
gpl3
3,135
/* * (C) Copyright 2002 * Stäubli Faverges - <www.staubli.com> * Pierre AUBERT p.aubert@staubli.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 <common.h> #include <config.h> #include "dos.h" #include "fdos.h" #define NB_HEADS 2 #define NB_TRACKS 80 #define NB_SECTORS 18 static int lastwhere; /*----------------------------------------------------------------------------- * dev_open -- *----------------------------------------------------------------------------- */ int dev_open (void) { lastwhere = 0; return (0); } /*----------------------------------------------------------------------------- * dev_read -- len and where are sectors number *----------------------------------------------------------------------------- */ int dev_read (void *buffer, int where, int len) { PRINTF ("dev_read (len = %d, where = %d)\n", len, where); /* Si on ne desire pas lire a la position courante, il faut un seek */ if (where != lastwhere) { if (!fdc_fdos_seek (where)) { PRINTF ("seek error in dev_read"); lastwhere = -1; return (-1); } } if (!fdc_fdos_read (buffer, len)) { PRINTF ("read error\n"); lastwhere = -1; return (-1); } lastwhere = where + len; return (0); } /*----------------------------------------------------------------------------- * check_dev -- verify the diskette format *----------------------------------------------------------------------------- */ int check_dev (BootSector_t *boot, Fs_t *fs) { unsigned int heads, sectors, tracks; int BootP, Infp0, InfpX, InfTm; int sect_per_track; /* Display Boot header */ PRINTF ("Jump to boot code 0x%02x 0x%02x 0x%02x\n", boot -> jump [0], boot -> jump [1], boot -> jump[2]); PRINTF ("OEM name & version '%*.*s'\n", BANNER_LG, BANNER_LG, boot -> banner ); PRINTF ("Bytes per sector hopefully 512 %d\n", __le16_to_cpu (boot -> secsiz)); PRINTF ("Cluster size in sectors %d\n", boot -> clsiz); PRINTF ("Number of reserved (boot) sectors %d\n", __le16_to_cpu (boot -> nrsvsect)); PRINTF ("Number of FAT tables hopefully 2 %d\n", boot -> nfat); PRINTF ("Number of directory slots %d\n", __le16_to_cpu (boot -> dirents)); PRINTF ("Total sectors on disk %d\n", __le16_to_cpu (boot -> psect)); PRINTF ("Media descriptor=first byte of FAT %d\n", boot -> descr); PRINTF ("Sectors in FAT %d\n", __le16_to_cpu (boot -> fatlen)); PRINTF ("Sectors/track %d\n", __le16_to_cpu (boot -> nsect)); PRINTF ("Heads %d\n", __le16_to_cpu (boot -> nheads)); PRINTF ("number of hidden sectors %d\n", __le32_to_cpu (boot -> nhs)); PRINTF ("big total sectors %d\n", __le32_to_cpu (boot -> bigsect)); PRINTF ("physical drive ? %d\n", boot -> physdrive); PRINTF ("reserved %d\n", boot -> reserved); PRINTF ("dos > 4.0 diskette %d\n", boot -> dos4); PRINTF ("serial number %d\n", __le32_to_cpu (boot -> serial)); PRINTF ("disk label %*.*s\n", LABEL_LG, LABEL_LG, boot -> label); PRINTF ("FAT type %8.8s\n", boot -> fat_type); PRINTF ("reserved by 2M %d\n", boot -> res_2m); PRINTF ("2M checksum (not used) %d\n", boot -> CheckSum); PRINTF ("2MF format version %d\n", boot -> fmt_2mf); PRINTF ("1 if write track after format %d\n", boot -> wt); PRINTF ("data transfer rate on track 0 %d\n", boot -> rate_0); PRINTF ("data transfer rate on track<>0 %d\n", boot -> rate_any); PRINTF ("offset to boot program %d\n", __le16_to_cpu (boot -> BootP)); PRINTF ("T1: information for track 0 %d\n", __le16_to_cpu (boot -> Infp0)); PRINTF ("T2: information for track<>0 %d\n", __le16_to_cpu (boot -> InfpX)); PRINTF ("T3: track sectors size table %d\n", __le16_to_cpu (boot -> InfTm)); PRINTF ("Format date 0x%04x\n", __le16_to_cpu (boot -> DateF)); PRINTF ("Format time 0x%04x\n", __le16_to_cpu (boot -> TimeF)); /* information is extracted from boot sector */ heads = __le16_to_cpu (boot -> nheads); sectors = __le16_to_cpu (boot -> nsect); fs -> tot_sectors = __le32_to_cpu (boot -> bigsect); if (__le16_to_cpu (boot -> psect) != 0) { fs -> tot_sectors = __le16_to_cpu (boot -> psect); } sect_per_track = heads * sectors; tracks = (fs -> tot_sectors + sect_per_track - 1) / sect_per_track; BootP = __le16_to_cpu (boot -> BootP); Infp0 = __le16_to_cpu (boot -> Infp0); InfpX = __le16_to_cpu (boot -> InfpX); InfTm = __le16_to_cpu (boot -> InfTm); if (boot -> dos4 == EXTENDED_BOOT && strncmp( boot->banner,"2M", 2 ) == 0 && BootP < SZ_STD_SECTOR && Infp0 < SZ_STD_SECTOR && InfpX < SZ_STD_SECTOR && InfTm < SZ_STD_SECTOR && BootP >= InfTm + 2 && InfTm >= InfpX && InfpX >= Infp0 && Infp0 >= 76 ) { return (-1); } if (heads != NB_HEADS || tracks != NB_TRACKS || sectors != NB_SECTORS || __le16_to_cpu (boot -> secsiz) != SZ_STD_SECTOR || fs -> tot_sectors == 0 || (fs -> tot_sectors % sectors) != 0) { return (-1); } return (0); }
1001-study-uboot
fs/fdos/dev.c
C
gpl3
6,435
/* * (C) Copyright 2002 * Stäubli Faverges - <www.staubli.com> * Pierre AUBERT p.aubert@staubli.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 <common.h> #include <config.h> #include <malloc.h> #include "dos.h" #include "fdos.h" const char *month [] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; Fs_t fs; File_t file; /*----------------------------------------------------------------------------- * dos_open -- *----------------------------------------------------------------------------- */ int dos_open(char *name) { int lg; int entry; char *fname; /* We need to suppress the " char around the name */ if (name [0] == '"') { name ++; } lg = strlen (name); if (name [lg - 1] == '"') { name [lg - 1] = '\0'; } /* Open file system */ if (fs_init (&fs) < 0) { return -1; } /* Init the file descriptor */ file.name = name; file.fs = &fs; /* find the subdirectory containing the file */ if (open_subdir (&file) < 0) { return (-1); } fname = basename (name); /* if we try to open root directory */ if (*fname == '\0') { file.file = file.subdir; return (0); } /* find the file in the subdir */ entry = 0; if (vfat_lookup (&file.subdir, file.fs, &file.file.dir, &entry, 0, fname, ACCEPT_DIR | ACCEPT_PLAIN | SINGLE | DO_OPEN, 0, &file.file) != 0) { /* File not found */ printf ("File not found\n"); return (-1); } return 0; } /*----------------------------------------------------------------------------- * dos_read -- *----------------------------------------------------------------------------- */ int dos_read (ulong addr) { int read = 0, nb; /* Try to boot a directory ? */ if (file.file.dir.attr & (ATTR_DIRECTORY | ATTR_VOLUME)) { printf ("Unable to boot %s !!\n", file.name); return (-1); } while (read < file.file.FileSize) { PRINTF ("read_file (%ld)\n", (file.file.FileSize - read)); nb = read_file (&fs, &file.file, (char *)addr + read, read, (file.file.FileSize - read)); PRINTF ("read_file -> %d\n", nb); if (nb < 0) { printf ("read error\n"); return (-1); } read += nb; } return (read); } /*----------------------------------------------------------------------------- * dos_dir -- *----------------------------------------------------------------------------- */ int dos_dir (void) { int entry; Directory_t dir; char *name; if ((file.file.dir.attr & ATTR_DIRECTORY) == 0) { printf ("%s: not a directory !!\n", file.name); return (1); } entry = 0; if ((name = malloc (MAX_VNAMELEN + 1)) == NULL) { PRINTF ("Allcation error\n"); return (1); } while (vfat_lookup (&file.file, file.fs, &dir, &entry, 0, NULL, ACCEPT_DIR | ACCEPT_PLAIN | MATCH_ANY, name, NULL) == 0) { /* Display file info */ printf ("%3.3s %9d %s %02d %04d %02d:%02d:%02d %s\n", (dir.attr & ATTR_DIRECTORY) ? "dir" : " ", __le32_to_cpu (dir.size), month [DOS_MONTH (&dir) - 1], DOS_DAY (&dir), DOS_YEAR (&dir), DOS_HOUR (&dir), DOS_MINUTE (&dir), DOS_SEC (&dir), name); } free (name); return (0); }
1001-study-uboot
fs/fdos/fdos.c
C
gpl3
4,418
/* * (C) Copyright 2002 * Stäubli Faverges - <www.staubli.com> * Pierre AUBERT p.aubert@staubli.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 <common.h> #include <config.h> #include <malloc.h> #include "dos.h" #include "fdos.h" /*----------------------------------------------------------------------------- * fat_decode -- *----------------------------------------------------------------------------- */ unsigned int fat_decode (Fs_t *fs, unsigned int num) { unsigned int start = num * 3 / 2; unsigned char *address = fs -> fat_buf + start; if (num < 2 || start + 1 > (fs -> fat_len * SZ_STD_SECTOR)) return 1; if (num & 1) return ((address [1] & 0xff) << 4) | ((address [0] & 0xf0 ) >> 4); else return ((address [1] & 0xf) << 8) | (address [0] & 0xff ); } /*----------------------------------------------------------------------------- * check_fat -- *----------------------------------------------------------------------------- */ static int check_fat (Fs_t *fs) { int i, f; /* Cluster verification */ for (i = 3 ; i < fs -> num_clus; i++){ f = fat_decode (fs, i); if (f < FAT12_LAST && f > fs -> num_clus){ /* Wrong cluster number detected */ return (-1); } } return (0); } /*----------------------------------------------------------------------------- * read_one_fat -- *----------------------------------------------------------------------------- */ static int read_one_fat (BootSector_t *boot, Fs_t *fs, int nfat) { if (dev_read (fs -> fat_buf, (fs -> fat_start + nfat * fs -> fat_len), fs -> fat_len) < 0) { return (-1); } if (fs -> fat_buf [0] || fs -> fat_buf [1] || fs -> fat_buf [2]) { if ((fs -> fat_buf [0] != boot -> descr && (fs -> fat_buf [0] != 0xf9 || boot -> descr != MEDIA_STD)) || fs -> fat_buf [0] < MEDIA_STD){ /* Unknown Media */ return (-1); } if (fs -> fat_buf [1] != 0xff || fs -> fat_buf [2] != 0xff){ /* FAT doesn't start with good values */ return (-1); } } if (fs -> num_clus >= FAT12_MAX_NB) { /* Too much clusters */ return (-1); } return check_fat (fs); } /*----------------------------------------------------------------------------- * read_fat -- *----------------------------------------------------------------------------- */ int read_fat (BootSector_t *boot, Fs_t *fs) { unsigned int buflen; int i; /* Allocate Fat Buffer */ buflen = fs -> fat_len * SZ_STD_SECTOR; if (fs -> fat_buf) { free (fs -> fat_buf); } if ((fs -> fat_buf = malloc (buflen)) == NULL) { return (-1); } /* Try to read each Fat */ for (i = 0; i< fs -> nb_fat; i++){ if (read_one_fat (boot, fs, i) == 0) { /* Fat is OK */ fs -> num_fat = i; break; } } if (i == fs -> nb_fat){ return (-1); } if (fs -> fat_len > (((fs -> num_clus + 2) * (FAT_BITS / 4) -1 ) / 2 / SZ_STD_SECTOR + 1)) { return (-1); } return (0); }
1001-study-uboot
fs/fdos/fat.c
C
gpl3
4,105
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> #include "yaffs_tagsvalidity.h" void yaffs_InitialiseTags(yaffs_ExtendedTags * tags) { memset(tags, 0, sizeof(yaffs_ExtendedTags)); tags->validMarker0 = 0xAAAAAAAA; tags->validMarker1 = 0x55555555; } int yaffs_ValidateTags(yaffs_ExtendedTags * tags) { return (tags->validMarker0 == 0xAAAAAAAA && tags->validMarker1 == 0x55555555); }
1001-study-uboot
fs/yaffs2/yaffs_tagsvalidity.c
C
gpl3
814
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_FLASH_H__ #define __YAFFS_FLASH_H__ #include "yaffs_guts.h" int yflash_EraseBlockInNAND(yaffs_Device *dev, int blockNumber); int yflash_WriteChunkToNAND(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare); int yflash_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND,const __u8 *data, yaffs_ExtendedTags *tags); int yflash_ReadChunkFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *data, yaffs_Spare *spare); int yflash_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *data, yaffs_ExtendedTags *tags); int yflash_EraseBlockInNAND(yaffs_Device *dev, int blockNumber); int yflash_InitialiseNAND(yaffs_Device *dev); int yflash_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo); int yflash_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo, yaffs_BlockState *state, int *sequenceNumber); #endif
1001-study-uboot
fs/yaffs2/yaffs_flashif.h
C
gpl3
1,397
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_TAGS_VALIDITY_H__ #define __YAFFS_TAGS_VALIDITY_H__ #include "yaffs_guts.h" void yaffs_InitialiseTags(yaffs_ExtendedTags * tags); int yaffs_ValidateTags(yaffs_ExtendedTags * tags); #endif
1001-study-uboot
fs/yaffs2/yaffs_tagsvalidity.h
C
gpl3
720
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> const char *yaffs_guts_c_version = "$Id: yaffs_guts.c,v 1.52 2007/10/16 00:45:05 charles Exp $"; #include "yportenv.h" #include "linux/stat.h" #include "yaffsinterface.h" #include "yaffsfs.h" #include "yaffs_guts.h" #include "yaffs_tagsvalidity.h" #include "yaffs_tagscompat.h" #ifndef CONFIG_YAFFS_USE_OWN_SORT #include "yaffs_qsort.h" #endif #include "yaffs_nand.h" #include "yaffs_checkptrw.h" #include "yaffs_nand.h" #include "yaffs_packedtags2.h" #include "malloc.h" #ifdef CONFIG_YAFFS_WINCE void yfsd_LockYAFFS(BOOL fsLockOnly); void yfsd_UnlockYAFFS(BOOL fsLockOnly); #endif #define YAFFS_PASSIVE_GC_CHUNKS 2 #include "yaffs_ecc.h" /* Robustification (if it ever comes about...) */ static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND); static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk); static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_ExtendedTags * tags); static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND, const yaffs_ExtendedTags * tags); /* Other local prototypes */ static int yaffs_UnlinkObject( yaffs_Object *obj); static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj); static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList); static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev, const __u8 * buffer, yaffs_ExtendedTags * tags, int useReserve); static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode, int chunkInNAND, int inScan); static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number, yaffs_ObjectType type); static void yaffs_AddObjectToDirectory(yaffs_Object * directory, yaffs_Object * obj); static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force, int isShrink, int shadows); static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj); static int yaffs_CheckStructures(void); static int yaffs_DoGenericObjectDeletion(yaffs_Object * in); static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo); static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo); static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer, int lineNo); static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev, int chunkInNAND); static int yaffs_UnlinkWorker(yaffs_Object * obj); static void yaffs_DestroyObject(yaffs_Object * obj); static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId, int chunkInObject); loff_t yaffs_GetFileSize(yaffs_Object * obj); static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr); static void yaffs_VerifyFreeChunks(yaffs_Device * dev); static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in); #ifdef YAFFS_PARANOID static int yaffs_CheckFileSanity(yaffs_Object * in); #else #define yaffs_CheckFileSanity(in) #endif static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in); static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId); static void yaffs_InvalidateCheckpoint(yaffs_Device *dev); static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode, yaffs_ExtendedTags * tags); static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos); static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev, yaffs_FileStructure * fStruct, __u32 chunkId); /* Function to calculate chunk and offset */ static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset) { if(dev->chunkShift){ /* Easy-peasy power of 2 case */ *chunk = (__u32)(addr >> dev->chunkShift); *offset = (__u32)(addr & dev->chunkMask); } else if(dev->crumbsPerChunk) { /* Case where we're using "crumbs" */ *offset = (__u32)(addr & dev->crumbMask); addr >>= dev->crumbShift; *chunk = ((__u32)addr)/dev->crumbsPerChunk; *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift); } else YBUG(); } /* Function to return the number of shifts for a power of 2 greater than or equal * to the given number * Note we don't try to cater for all possible numbers and this does not have to * be hellishly efficient. */ static __u32 ShiftsGE(__u32 x) { int extraBits; int nShifts; nShifts = extraBits = 0; while(x>1){ if(x & 1) extraBits++; x>>=1; nShifts++; } if(extraBits) nShifts++; return nShifts; } /* Function to return the number of shifts to get a 1 in bit 0 */ static __u32 ShiftDiv(__u32 x) { int nShifts; nShifts = 0; if(!x) return 0; while( !(x&1)){ x>>=1; nShifts++; } return nShifts; } /* * Temporary buffer manipulations. */ static int yaffs_InitialiseTempBuffers(yaffs_Device *dev) { int i; __u8 *buf = (__u8 *)1; memset(dev->tempBuffer,0,sizeof(dev->tempBuffer)); for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) { dev->tempBuffer[i].line = 0; /* not in use */ dev->tempBuffer[i].buffer = buf = YMALLOC_DMA(dev->nDataBytesPerChunk); } return buf ? YAFFS_OK : YAFFS_FAIL; } static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo) { int i, j; for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) { if (dev->tempBuffer[i].line == 0) { dev->tempBuffer[i].line = lineNo; if ((i + 1) > dev->maxTemp) { dev->maxTemp = i + 1; for (j = 0; j <= i; j++) dev->tempBuffer[j].maxLine = dev->tempBuffer[j].line; } return dev->tempBuffer[i].buffer; } } T(YAFFS_TRACE_BUFFERS, (TSTR("Out of temp buffers at line %d, other held by lines:"), lineNo)); for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) { T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line)); } T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR))); /* * If we got here then we have to allocate an unmanaged one * This is not good. */ dev->unmanagedTempAllocations++; return YMALLOC(dev->nDataBytesPerChunk); } static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer, int lineNo) { int i; for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) { if (dev->tempBuffer[i].buffer == buffer) { dev->tempBuffer[i].line = 0; return; } } if (buffer) { /* assume it is an unmanaged one. */ T(YAFFS_TRACE_BUFFERS, (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR), lineNo)); YFREE(buffer); dev->unmanagedTempDeallocations++; } } /* * Determine if we have a managed buffer. */ int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer) { int i; for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) { if (dev->tempBuffer[i].buffer == buffer) return 1; } for (i = 0; i < dev->nShortOpCaches; i++) { if( dev->srCache[i].data == buffer ) return 1; } if (buffer == dev->checkpointBuffer) return 1; T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR))); return 0; } /* * Chunk bitmap manipulations */ static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk) { if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) { T(YAFFS_TRACE_ERROR, (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR), blk)); YBUG(); } return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->internalStartBlock)); } static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk) { if(blk < dev->internalStartBlock || blk > dev->internalEndBlock || chunk < 0 || chunk >= dev->nChunksPerBlock) { T(YAFFS_TRACE_ERROR, (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk)); YBUG(); } } static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk) { __u8 *blkBits = yaffs_BlockBits(dev, blk); memset(blkBits, 0, dev->chunkBitmapStride); } static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk) { __u8 *blkBits = yaffs_BlockBits(dev, blk); yaffs_VerifyChunkBitId(dev,blk,chunk); blkBits[chunk / 8] &= ~(1 << (chunk & 7)); } static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk) { __u8 *blkBits = yaffs_BlockBits(dev, blk); yaffs_VerifyChunkBitId(dev,blk,chunk); blkBits[chunk / 8] |= (1 << (chunk & 7)); } static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk) { __u8 *blkBits = yaffs_BlockBits(dev, blk); yaffs_VerifyChunkBitId(dev,blk,chunk); return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0; } static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk) { __u8 *blkBits = yaffs_BlockBits(dev, blk); int i; for (i = 0; i < dev->chunkBitmapStride; i++) { if (*blkBits) return 1; blkBits++; } return 0; } static int yaffs_CountChunkBits(yaffs_Device * dev, int blk) { __u8 *blkBits = yaffs_BlockBits(dev, blk); int i; int n = 0; for (i = 0; i < dev->chunkBitmapStride; i++) { __u8 x = *blkBits; while(x){ if(x & 1) n++; x >>=1; } blkBits++; } return n; } /* * Verification code */ static Y_INLINE int yaffs_SkipVerification(yaffs_Device *dev) { return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL)); } static Y_INLINE int yaffs_SkipFullVerification(yaffs_Device *dev) { return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL)); } static Y_INLINE int yaffs_SkipNANDVerification(yaffs_Device *dev) { return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND)); } static const char * blockStateName[] = { "Unknown", "Needs scanning", "Scanning", "Empty", "Allocating", "Full", "Dirty", "Checkpoint", "Collecting", "Dead" }; static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n) { int actuallyUsed; int inUse; if(yaffs_SkipVerification(dev)) return; /* Report illegal runtime states */ if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES) T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState)); switch(bi->blockState){ case YAFFS_BLOCK_STATE_UNKNOWN: case YAFFS_BLOCK_STATE_SCANNING: case YAFFS_BLOCK_STATE_NEEDS_SCANNING: T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR), n,blockStateName[bi->blockState])); } /* Check pages in use and soft deletions are legal */ actuallyUsed = bi->pagesInUse - bi->softDeletions; if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock || bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock || actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock) T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR), n,bi->pagesInUse,bi->softDeletions)); /* Check chunk bitmap legal */ inUse = yaffs_CountChunkBits(dev,n); if(inUse != bi->pagesInUse) T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR), n,bi->pagesInUse,inUse)); /* Check that the sequence number is valid. * Ten million is legal, but is very unlikely */ if(dev->isYaffs2 && (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) && (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 )) T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR), n,bi->sequenceNumber)); } static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n) { yaffs_VerifyBlock(dev,bi,n); /* After collection the block should be in the erased state */ /* TODO: This will need to change if we do partial gc */ if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){ T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR), n,bi->blockState)); } } static void yaffs_VerifyBlocks(yaffs_Device *dev) { int i; int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES]; int nIllegalBlockStates = 0; if(yaffs_SkipVerification(dev)) return; memset(nBlocksPerState,0,sizeof(nBlocksPerState)); for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){ yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i); yaffs_VerifyBlock(dev,bi,i); if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES) nBlocksPerState[bi->blockState]++; else nIllegalBlockStates++; } T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR))); T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR))); T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates)); if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1) T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR))); for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++) T(YAFFS_TRACE_VERIFY, (TSTR("%s %d blocks"TENDSTR), blockStateName[i],nBlocksPerState[i])); if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]) T(YAFFS_TRACE_VERIFY, (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR), dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])); if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]) T(YAFFS_TRACE_VERIFY, (TSTR("Erased block count wrong dev %d count %d"TENDSTR), dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])); if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1) T(YAFFS_TRACE_VERIFY, (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR), nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING])); T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR))); } /* * Verify the object header. oh must be valid, but obj and tags may be NULL in which * case those tests will not be performed. */ static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck) { if(yaffs_SkipVerification(obj->myDev)) return; if(!(tags && obj && oh)){ T(YAFFS_TRACE_VERIFY, (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR), (__u32)tags,(__u32)obj,(__u32)oh)); return; } if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN || oh->type > YAFFS_OBJECT_TYPE_MAX) T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR), tags->objectId, oh->type)); if(tags->objectId != obj->objectId) T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d header mismatch objectId %d"TENDSTR), tags->objectId, obj->objectId)); /* * Check that the object's parent ids match if parentCheck requested. * * Tests do not apply to the root object. */ if(parentCheck && tags->objectId > 1 && !obj->parent) T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR), tags->objectId, oh->parentObjectId)); if(parentCheck && obj->parent && oh->parentObjectId != obj->parent->objectId && (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED || obj->parent->objectId != YAFFS_OBJECTID_DELETED)) T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR), tags->objectId, oh->parentObjectId, obj->parent->objectId)); if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */ T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d header name is NULL"TENDSTR), obj->objectId)); if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */ T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d header name is 0xFF"TENDSTR), obj->objectId)); } static void yaffs_VerifyFile(yaffs_Object *obj) { int requiredTallness; int actualTallness; __u32 lastChunk; __u32 x; __u32 i; yaffs_Device *dev; yaffs_ExtendedTags tags; yaffs_Tnode *tn; __u32 objectId; if(obj && yaffs_SkipVerification(obj->myDev)) return; dev = obj->myDev; objectId = obj->objectId; /* Check file size is consistent with tnode depth */ lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1; x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS; requiredTallness = 0; while (x> 0) { x >>= YAFFS_TNODES_INTERNAL_BITS; requiredTallness++; } actualTallness = obj->variant.fileVariant.topLevel; if(requiredTallness > actualTallness ) T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR), obj->objectId,actualTallness, requiredTallness)); /* Check that the chunks in the tnode tree are all correct. * We do this by scanning through the tnode tree and * checking the tags for every chunk match. */ if(yaffs_SkipNANDVerification(dev)) return; for(i = 1; i <= lastChunk; i++){ tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i); if (tn) { __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i); if(theChunk > 0){ /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */ yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags); if(tags.objectId != objectId || tags.chunkId != i){ T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR), objectId, i, theChunk, tags.objectId, tags.chunkId)); } } } } } static void yaffs_VerifyDirectory(yaffs_Object *obj) { if(obj && yaffs_SkipVerification(obj->myDev)) return; } static void yaffs_VerifyHardLink(yaffs_Object *obj) { if(obj && yaffs_SkipVerification(obj->myDev)) return; /* Verify sane equivalent object */ } static void yaffs_VerifySymlink(yaffs_Object *obj) { if(obj && yaffs_SkipVerification(obj->myDev)) return; /* Verify symlink string */ } static void yaffs_VerifySpecial(yaffs_Object *obj) { if(obj && yaffs_SkipVerification(obj->myDev)) return; } static void yaffs_VerifyObject(yaffs_Object *obj) { yaffs_Device *dev; __u32 chunkMin; __u32 chunkMax; __u32 chunkIdOk; __u32 chunkIsLive; if(!obj) return; dev = obj->myDev; if(yaffs_SkipVerification(dev)) return; /* Check sane object header chunk */ chunkMin = dev->internalStartBlock * dev->nChunksPerBlock; chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1; chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax); chunkIsLive = chunkIdOk && yaffs_CheckChunkBit(dev, obj->chunkId / dev->nChunksPerBlock, obj->chunkId % dev->nChunksPerBlock); if(!obj->fake && (!chunkIdOk || !chunkIsLive)) { T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d has chunkId %d %s %s"TENDSTR), obj->objectId,obj->chunkId, chunkIdOk ? "" : ",out of range", chunkIsLive || !chunkIdOk ? "" : ",marked as deleted")); } if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) { yaffs_ExtendedTags tags; yaffs_ObjectHeader *oh; __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__); oh = (yaffs_ObjectHeader *)buffer; yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags); yaffs_VerifyObjectHeader(obj,oh,&tags,1); yaffs_ReleaseTempBuffer(dev,buffer,__LINE__); } /* Verify it has a parent */ if(obj && !obj->fake && (!obj->parent || obj->parent->myDev != dev)){ T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR), obj->objectId,obj->parent)); } /* Verify parent is a directory */ if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){ T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR), obj->objectId,obj->parent->variantType)); } switch(obj->variantType){ case YAFFS_OBJECT_TYPE_FILE: yaffs_VerifyFile(obj); break; case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_VerifySymlink(obj); break; case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_VerifyDirectory(obj); break; case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_VerifyHardLink(obj); break; case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_VerifySpecial(obj); break; case YAFFS_OBJECT_TYPE_UNKNOWN: default: T(YAFFS_TRACE_VERIFY, (TSTR("Obj %d has illegaltype %d"TENDSTR), obj->objectId,obj->variantType)); break; } } static void yaffs_VerifyObjects(yaffs_Device *dev) { yaffs_Object *obj; int i; struct list_head *lh; if(yaffs_SkipVerification(dev)) return; /* Iterate through the objects in each hash entry */ for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){ list_for_each(lh, &dev->objectBucket[i].list) { if (lh) { obj = list_entry(lh, yaffs_Object, hashLink); yaffs_VerifyObject(obj); } } } } /* * Simple hash function. Needs to have a reasonable spread */ static Y_INLINE int yaffs_HashFunction(int n) { /* XXX U-BOOT XXX */ /*n = abs(n); */ if (n < 0) n = -n; return (n % YAFFS_NOBJECT_BUCKETS); } /* * Access functions to useful fake objects */ yaffs_Object *yaffs_Root(yaffs_Device * dev) { return dev->rootDir; } yaffs_Object *yaffs_LostNFound(yaffs_Device * dev) { return dev->lostNFoundDir; } /* * Erased NAND checking functions */ int yaffs_CheckFF(__u8 * buffer, int nBytes) { /* Horrible, slow implementation */ while (nBytes--) { if (*buffer != 0xFF) return 0; buffer++; } return 1; } static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev, int chunkInNAND) { int retval = YAFFS_OK; __u8 *data = yaffs_GetTempBuffer(dev, __LINE__); yaffs_ExtendedTags tags; yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags); if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR) retval = YAFFS_FAIL; if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) { T(YAFFS_TRACE_NANDACCESS, (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND)); retval = YAFFS_FAIL; } yaffs_ReleaseTempBuffer(dev, data, __LINE__); return retval; } static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev, const __u8 * data, yaffs_ExtendedTags * tags, int useReserve) { int attempts = 0; int writeOk = 0; int chunk; yaffs_InvalidateCheckpoint(dev); do { yaffs_BlockInfo *bi = 0; int erasedOk = 0; chunk = yaffs_AllocateChunk(dev, useReserve, &bi); if (chunk < 0) { /* no space */ break; } /* First check this chunk is erased, if it needs * checking. The checking policy (unless forced * always on) is as follows: * * Check the first page we try to write in a block. * If the check passes then we don't need to check any * more. If the check fails, we check again... * If the block has been erased, we don't need to check. * * However, if the block has been prioritised for gc, * then we think there might be something odd about * this block and stop using it. * * Rationale: We should only ever see chunks that have * not been erased if there was a partially written * chunk due to power loss. This checking policy should * catch that case with very few checks and thus save a * lot of checks that are most likely not needed. */ if (bi->gcPrioritise) { yaffs_DeleteChunk(dev, chunk, 1, __LINE__); /* try another chunk */ continue; } /* let's give it a try */ attempts++; #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED bi->skipErasedCheck = 0; #endif if (!bi->skipErasedCheck) { erasedOk = yaffs_CheckChunkErased(dev, chunk); if (erasedOk != YAFFS_OK) { T(YAFFS_TRACE_ERROR, (TSTR ("**>> yaffs chunk %d was not erased" TENDSTR), chunk)); /* try another chunk */ continue; } bi->skipErasedCheck = 1; } writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk, data, tags); if (writeOk != YAFFS_OK) { yaffs_HandleWriteChunkError(dev, chunk, erasedOk); /* try another chunk */ continue; } /* Copy the data into the robustification buffer */ yaffs_HandleWriteChunkOk(dev, chunk, data, tags); } while (writeOk != YAFFS_OK && (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts)); if(!writeOk) chunk = -1; if (attempts > 1) { T(YAFFS_TRACE_ERROR, (TSTR("**>> yaffs write required %d attempts" TENDSTR), attempts)); dev->nRetriedWrites += (attempts - 1); } return chunk; } /* * Block retiring for handling a broken block. */ static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND) { yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND); yaffs_InvalidateCheckpoint(dev); yaffs_MarkBlockBad(dev, blockInNAND); bi->blockState = YAFFS_BLOCK_STATE_DEAD; bi->gcPrioritise = 0; bi->needsRetiring = 0; dev->nRetiredBlocks++; } /* * Functions for robustisizing TODO * */ static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_ExtendedTags * tags) { } static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND, const yaffs_ExtendedTags * tags) { } void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi) { if(!bi->gcPrioritise){ bi->gcPrioritise = 1; dev->hasPendingPrioritisedGCs = 1; bi->chunkErrorStrikes ++; if(bi->chunkErrorStrikes > 3){ bi->needsRetiring = 1; /* Too many stikes, so retire this */ T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR))); } } } static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk) { int blockInNAND = chunkInNAND / dev->nChunksPerBlock; yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND); yaffs_HandleChunkError(dev,bi); if(erasedOk ) { /* Was an actual write failure, so mark the block for retirement */ bi->needsRetiring = 1; T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS, (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND)); } /* Delete the chunk */ yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__); } /*---------------- Name handling functions ------------*/ static __u16 yaffs_CalcNameSum(const YCHAR * name) { __u16 sum = 0; __u16 i = 1; YUCHAR *bname = (YUCHAR *) name; if (bname) { while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) { #ifdef CONFIG_YAFFS_CASE_INSENSITIVE sum += yaffs_toupper(*bname) * i; #else sum += (*bname) * i; #endif i++; bname++; } } return sum; } static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name) { #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) { yaffs_strcpy(obj->shortName, name); } else { obj->shortName[0] = _Y('\0'); } #endif obj->sum = yaffs_CalcNameSum(name); } /*-------------------- TNODES ------------------- * List of spare tnodes * The list is hooked together using the first pointer * in the tnode. */ /* yaffs_CreateTnodes creates a bunch more tnodes and * adds them to the tnode free list. * Don't use this function directly */ static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes) { int i; int tnodeSize; yaffs_Tnode *newTnodes; __u8 *mem; yaffs_Tnode *curr; yaffs_Tnode *next; yaffs_TnodeList *tnl; if (nTnodes < 1) return YAFFS_OK; /* Calculate the tnode size in bytes for variable width tnode support. * Must be a multiple of 32-bits */ tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8; /* make these things */ newTnodes = YMALLOC(nTnodes * tnodeSize); mem = (__u8 *)newTnodes; if (!newTnodes) { T(YAFFS_TRACE_ERROR, (TSTR("yaffs: Could not allocate Tnodes" TENDSTR))); return YAFFS_FAIL; } /* Hook them into the free list */ #if 0 for (i = 0; i < nTnodes - 1; i++) { newTnodes[i].internal[0] = &newTnodes[i + 1]; #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1; #endif } newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes; #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1; #endif dev->freeTnodes = newTnodes; #else /* New hookup for wide tnodes */ for(i = 0; i < nTnodes -1; i++) { curr = (yaffs_Tnode *) &mem[i * tnodeSize]; next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize]; curr->internal[0] = next; } curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize]; curr->internal[0] = dev->freeTnodes; dev->freeTnodes = (yaffs_Tnode *)mem; #endif dev->nFreeTnodes += nTnodes; dev->nTnodesCreated += nTnodes; /* Now add this bunch of tnodes to a list for freeing up. * NB If we can't add this to the management list it isn't fatal * but it just means we can't free this bunch of tnodes later. */ tnl = YMALLOC(sizeof(yaffs_TnodeList)); if (!tnl) { T(YAFFS_TRACE_ERROR, (TSTR ("yaffs: Could not add tnodes to management list" TENDSTR))); return YAFFS_FAIL; } else { tnl->tnodes = newTnodes; tnl->next = dev->allocatedTnodeList; dev->allocatedTnodeList = tnl; } T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR))); return YAFFS_OK; } /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */ static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev) { yaffs_Tnode *tn = NULL; /* If there are none left make more */ if (!dev->freeTnodes) { yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES); } if (dev->freeTnodes) { tn = dev->freeTnodes; #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) { /* Hoosterman, this thing looks like it isn't in the list */ T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Tnode list bug 1" TENDSTR))); } #endif dev->freeTnodes = dev->freeTnodes->internal[0]; dev->nFreeTnodes--; } return tn; } static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev) { yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev); if(tn) memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8); return tn; } /* FreeTnode frees up a tnode and puts it back on the free list */ static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn) { if (tn) { #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) { /* Hoosterman, this thing looks like it is already in the list */ T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Tnode list bug 2" TENDSTR))); } tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1; #endif tn->internal[0] = dev->freeTnodes; dev->freeTnodes = tn; dev->nFreeTnodes++; } } static void yaffs_DeinitialiseTnodes(yaffs_Device * dev) { /* Free the list of allocated tnodes */ yaffs_TnodeList *tmp; while (dev->allocatedTnodeList) { tmp = dev->allocatedTnodeList->next; YFREE(dev->allocatedTnodeList->tnodes); YFREE(dev->allocatedTnodeList); dev->allocatedTnodeList = tmp; } dev->freeTnodes = NULL; dev->nFreeTnodes = 0; } static void yaffs_InitialiseTnodes(yaffs_Device * dev) { dev->allocatedTnodeList = NULL; dev->freeTnodes = NULL; dev->nFreeTnodes = 0; dev->nTnodesCreated = 0; } void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val) { __u32 *map = (__u32 *)tn; __u32 bitInMap; __u32 bitInWord; __u32 wordInMap; __u32 mask; pos &= YAFFS_TNODES_LEVEL0_MASK; val >>= dev->chunkGroupBits; bitInMap = pos * dev->tnodeWidth; wordInMap = bitInMap /32; bitInWord = bitInMap & (32 -1); mask = dev->tnodeMask << bitInWord; map[wordInMap] &= ~mask; map[wordInMap] |= (mask & (val << bitInWord)); if(dev->tnodeWidth > (32-bitInWord)) { bitInWord = (32 - bitInWord); wordInMap++;; mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord); map[wordInMap] &= ~mask; map[wordInMap] |= (mask & (val >> bitInWord)); } } static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos) { __u32 *map = (__u32 *)tn; __u32 bitInMap; __u32 bitInWord; __u32 wordInMap; __u32 val; pos &= YAFFS_TNODES_LEVEL0_MASK; bitInMap = pos * dev->tnodeWidth; wordInMap = bitInMap /32; bitInWord = bitInMap & (32 -1); val = map[wordInMap] >> bitInWord; if(dev->tnodeWidth > (32-bitInWord)) { bitInWord = (32 - bitInWord); wordInMap++;; val |= (map[wordInMap] << bitInWord); } val &= dev->tnodeMask; val <<= dev->chunkGroupBits; return val; } /* ------------------- End of individual tnode manipulation -----------------*/ /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------ * The look up tree is represented by the top tnode and the number of topLevel * in the tree. 0 means only the level 0 tnode is in the tree. */ /* FindLevel0Tnode finds the level 0 tnode, if one exists. */ static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev, yaffs_FileStructure * fStruct, __u32 chunkId) { yaffs_Tnode *tn = fStruct->top; __u32 i; int requiredTallness; int level = fStruct->topLevel; /* Check sane level and chunk Id */ if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) { return NULL; } if (chunkId > YAFFS_MAX_CHUNK_ID) { return NULL; } /* First check we're tall enough (ie enough topLevel) */ i = chunkId >> YAFFS_TNODES_LEVEL0_BITS; requiredTallness = 0; while (i) { i >>= YAFFS_TNODES_INTERNAL_BITS; requiredTallness++; } if (requiredTallness > fStruct->topLevel) { /* Not tall enough, so we can't find it, return NULL. */ return NULL; } /* Traverse down to level 0 */ while (level > 0 && tn) { tn = tn-> internal[(chunkId >> ( YAFFS_TNODES_LEVEL0_BITS + (level - 1) * YAFFS_TNODES_INTERNAL_BITS) ) & YAFFS_TNODES_INTERNAL_MASK]; level--; } return tn; } /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree. * This happens in two steps: * 1. If the tree isn't tall enough, then make it taller. * 2. Scan down the tree towards the level 0 tnode adding tnodes if required. * * Used when modifying the tree. * * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will * be plugged into the ttree. */ static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev, yaffs_FileStructure * fStruct, __u32 chunkId, yaffs_Tnode *passedTn) { int requiredTallness; int i; int l; yaffs_Tnode *tn; __u32 x; /* Check sane level and page Id */ if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) { return NULL; } if (chunkId > YAFFS_MAX_CHUNK_ID) { return NULL; } /* First check we're tall enough (ie enough topLevel) */ x = chunkId >> YAFFS_TNODES_LEVEL0_BITS; requiredTallness = 0; while (x) { x >>= YAFFS_TNODES_INTERNAL_BITS; requiredTallness++; } if (requiredTallness > fStruct->topLevel) { /* Not tall enough,gotta make the tree taller */ for (i = fStruct->topLevel; i < requiredTallness; i++) { tn = yaffs_GetTnode(dev); if (tn) { tn->internal[0] = fStruct->top; fStruct->top = tn; } else { T(YAFFS_TRACE_ERROR, (TSTR("yaffs: no more tnodes" TENDSTR))); } } fStruct->topLevel = requiredTallness; } /* Traverse down to level 0, adding anything we need */ l = fStruct->topLevel; tn = fStruct->top; if(l > 0) { while (l > 0 && tn) { x = (chunkId >> ( YAFFS_TNODES_LEVEL0_BITS + (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) & YAFFS_TNODES_INTERNAL_MASK; if((l>1) && !tn->internal[x]){ /* Add missing non-level-zero tnode */ tn->internal[x] = yaffs_GetTnode(dev); } else if(l == 1) { /* Looking from level 1 at level 0 */ if (passedTn) { /* If we already have one, then release it.*/ if(tn->internal[x]) yaffs_FreeTnode(dev,tn->internal[x]); tn->internal[x] = passedTn; } else if(!tn->internal[x]) { /* Don't have one, none passed in */ tn->internal[x] = yaffs_GetTnode(dev); } } tn = tn->internal[x]; l--; } } else { /* top is level 0 */ if(passedTn) { memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8); yaffs_FreeTnode(dev,passedTn); } } return tn; } static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk, yaffs_ExtendedTags * tags, int objectId, int chunkInInode) { int j; for (j = 0; theChunk && j < dev->chunkGroupSize; j++) { if (yaffs_CheckChunkBit (dev, theChunk / dev->nChunksPerBlock, theChunk % dev->nChunksPerBlock)) { yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, tags); if (yaffs_TagsMatch(tags, objectId, chunkInInode)) { /* found it; */ return theChunk; } } theChunk++; } return -1; } static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk) { yaffs_BlockInfo *theBlock; T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk)); theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock); if (theBlock) { theBlock->softDeletions++; dev->nFreeChunks++; } } /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file. * All soft deleting does is increment the block's softdelete count and pulls the chunk out * of the tnode. * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted. */ static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level, int chunkOffset) { int i; int theChunk; int allDone = 1; yaffs_Device *dev = in->myDev; if (tn) { if (level > 0) { for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0; i--) { if (tn->internal[i]) { allDone = yaffs_SoftDeleteWorker(in, tn-> internal[i], level - 1, (chunkOffset << YAFFS_TNODES_INTERNAL_BITS) + i); if (allDone) { yaffs_FreeTnode(dev, tn-> internal[i]); tn->internal[i] = NULL; } else { /* Hoosterman... how could this happen? */ } } } return (allDone) ? 1 : 0; } else if (level == 0) { for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) { theChunk = yaffs_GetChunkGroupBase(dev,tn,i); if (theChunk) { /* Note this does not find the real chunk, only the chunk group. * We make an assumption that a chunk group is not larger than * a block. */ yaffs_SoftDeleteChunk(dev, theChunk); yaffs_PutLevel0Tnode(dev,tn,i,0); } } return 1; } } return 1; } static void yaffs_SoftDeleteFile(yaffs_Object * obj) { if (obj->deleted && obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) { if (obj->nDataChunks <= 0) { /* Empty file with no duplicate object headers, just delete it immediately */ yaffs_FreeTnode(obj->myDev, obj->variant.fileVariant.top); obj->variant.fileVariant.top = NULL; T(YAFFS_TRACE_TRACING, (TSTR("yaffs: Deleting empty file %d" TENDSTR), obj->objectId)); yaffs_DoGenericObjectDeletion(obj); } else { yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant. topLevel, 0); obj->softDeleted = 1; } } } /* Pruning removes any part of the file structure tree that is beyond the * bounds of the file (ie that does not point to chunks). * * A file should only get pruned when its size is reduced. * * Before pruning, the chunks must be pulled from the tree and the * level 0 tnode entries must be zeroed out. * Could also use this for file deletion, but that's probably better handled * by a special case. */ static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn, __u32 level, int del0) { int i; int hasData; if (tn) { hasData = 0; for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) { if (tn->internal[i] && level > 0) { tn->internal[i] = yaffs_PruneWorker(dev, tn->internal[i], level - 1, (i == 0) ? del0 : 1); } if (tn->internal[i]) { hasData++; } } if (hasData == 0 && del0) { /* Free and return NULL */ yaffs_FreeTnode(dev, tn); tn = NULL; } } return tn; } static int yaffs_PruneFileStructure(yaffs_Device * dev, yaffs_FileStructure * fStruct) { int i; int hasData; int done = 0; yaffs_Tnode *tn; if (fStruct->topLevel > 0) { fStruct->top = yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0); /* Now we have a tree with all the non-zero branches NULL but the height * is the same as it was. * Let's see if we can trim internal tnodes to shorten the tree. * We can do this if only the 0th element in the tnode is in use * (ie all the non-zero are NULL) */ while (fStruct->topLevel && !done) { tn = fStruct->top; hasData = 0; for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) { if (tn->internal[i]) { hasData++; } } if (!hasData) { fStruct->top = tn->internal[0]; fStruct->topLevel--; yaffs_FreeTnode(dev, tn); } else { done = 1; } } } return YAFFS_OK; } /*-------------------- End of File Structure functions.-------------------*/ /* yaffs_CreateFreeObjects creates a bunch more objects and * adds them to the object free list. */ static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects) { int i; yaffs_Object *newObjects; yaffs_ObjectList *list; if (nObjects < 1) return YAFFS_OK; /* make these things */ newObjects = YMALLOC(nObjects * sizeof(yaffs_Object)); list = YMALLOC(sizeof(yaffs_ObjectList)); if (!newObjects || !list) { if(newObjects) YFREE(newObjects); if(list) YFREE(list); T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Could not allocate more objects" TENDSTR))); return YAFFS_FAIL; } /* Hook them into the free list */ for (i = 0; i < nObjects - 1; i++) { newObjects[i].siblings.next = (struct list_head *)(&newObjects[i + 1]); } newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects; dev->freeObjects = newObjects; dev->nFreeObjects += nObjects; dev->nObjectsCreated += nObjects; /* Now add this bunch of Objects to a list for freeing up. */ list->objects = newObjects; list->next = dev->allocatedObjectList; dev->allocatedObjectList = list; return YAFFS_OK; } /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */ static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev) { yaffs_Object *tn = NULL; /* If there are none left make more */ if (!dev->freeObjects) { yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS); } if (dev->freeObjects) { tn = dev->freeObjects; dev->freeObjects = (yaffs_Object *) (dev->freeObjects->siblings.next); dev->nFreeObjects--; /* Now sweeten it up... */ memset(tn, 0, sizeof(yaffs_Object)); tn->myDev = dev; tn->chunkId = -1; tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN; INIT_LIST_HEAD(&(tn->hardLinks)); INIT_LIST_HEAD(&(tn->hashLink)); INIT_LIST_HEAD(&tn->siblings); /* Add it to the lost and found directory. * NB Can't put root or lostNFound in lostNFound so * check if lostNFound exists first */ if (dev->lostNFoundDir) { yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn); } } return tn; } static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number, __u32 mode) { yaffs_Object *obj = yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY); if (obj) { obj->fake = 1; /* it is fake so it has no NAND presence... */ obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */ obj->unlinkAllowed = 0; /* ... or unlink it */ obj->deleted = 0; obj->unlinked = 0; obj->yst_mode = mode; obj->myDev = dev; obj->chunkId = 0; /* Not a valid chunk. */ } return obj; } static void yaffs_UnhashObject(yaffs_Object * tn) { int bucket; yaffs_Device *dev = tn->myDev; /* If it is still linked into the bucket list, free from the list */ if (!list_empty(&tn->hashLink)) { list_del_init(&tn->hashLink); bucket = yaffs_HashFunction(tn->objectId); dev->objectBucket[bucket].count--; } } /* FreeObject frees up a Object and puts it back on the free list */ static void yaffs_FreeObject(yaffs_Object * tn) { yaffs_Device *dev = tn->myDev; /* XXX U-BOOT XXX */ #if 0 #ifdef __KERNEL__ if (tn->myInode) { /* We're still hooked up to a cached inode. * Don't delete now, but mark for later deletion */ tn->deferedFree = 1; return; } #endif #endif yaffs_UnhashObject(tn); /* Link into the free list. */ tn->siblings.next = (struct list_head *)(dev->freeObjects); dev->freeObjects = tn; dev->nFreeObjects++; } /* XXX U-BOOT XXX */ #if 0 #ifdef __KERNEL__ void yaffs_HandleDeferedFree(yaffs_Object * obj) { if (obj->deferedFree) { yaffs_FreeObject(obj); } } #endif #endif static void yaffs_DeinitialiseObjects(yaffs_Device * dev) { /* Free the list of allocated Objects */ yaffs_ObjectList *tmp; while (dev->allocatedObjectList) { tmp = dev->allocatedObjectList->next; YFREE(dev->allocatedObjectList->objects); YFREE(dev->allocatedObjectList); dev->allocatedObjectList = tmp; } dev->freeObjects = NULL; dev->nFreeObjects = 0; } static void yaffs_InitialiseObjects(yaffs_Device * dev) { int i; dev->allocatedObjectList = NULL; dev->freeObjects = NULL; dev->nFreeObjects = 0; for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) { INIT_LIST_HEAD(&dev->objectBucket[i].list); dev->objectBucket[i].count = 0; } } static int yaffs_FindNiceObjectBucket(yaffs_Device * dev) { static int x = 0; int i; int l = 999; int lowest = 999999; /* First let's see if we can find one that's empty. */ for (i = 0; i < 10 && lowest > 0; i++) { x++; x %= YAFFS_NOBJECT_BUCKETS; if (dev->objectBucket[x].count < lowest) { lowest = dev->objectBucket[x].count; l = x; } } /* If we didn't find an empty list, then try * looking a bit further for a short one */ for (i = 0; i < 10 && lowest > 3; i++) { x++; x %= YAFFS_NOBJECT_BUCKETS; if (dev->objectBucket[x].count < lowest) { lowest = dev->objectBucket[x].count; l = x; } } return l; } static int yaffs_CreateNewObjectNumber(yaffs_Device * dev) { int bucket = yaffs_FindNiceObjectBucket(dev); /* Now find an object value that has not already been taken * by scanning the list. */ int found = 0; struct list_head *i; __u32 n = (__u32) bucket; /* yaffs_CheckObjectHashSanity(); */ while (!found) { found = 1; n += YAFFS_NOBJECT_BUCKETS; if (1 || dev->objectBucket[bucket].count > 0) { list_for_each(i, &dev->objectBucket[bucket].list) { /* If there is already one in the list */ if (i && list_entry(i, yaffs_Object, hashLink)->objectId == n) { found = 0; } } } } return n; } static void yaffs_HashObject(yaffs_Object * in) { int bucket = yaffs_HashFunction(in->objectId); yaffs_Device *dev = in->myDev; list_add(&in->hashLink, &dev->objectBucket[bucket].list); dev->objectBucket[bucket].count++; } yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number) { int bucket = yaffs_HashFunction(number); struct list_head *i; yaffs_Object *in; list_for_each(i, &dev->objectBucket[bucket].list) { /* Look if it is in the list */ if (i) { in = list_entry(i, yaffs_Object, hashLink); if (in->objectId == number) { /* XXX U-BOOT XXX */ #if 0 #ifdef __KERNEL__ /* Don't tell the VFS about this one if it is defered free */ if (in->deferedFree) return NULL; #endif #endif return in; } } } return NULL; } yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number, yaffs_ObjectType type) { yaffs_Object *theObject; yaffs_Tnode *tn = NULL; if (number < 0) { number = yaffs_CreateNewObjectNumber(dev); } theObject = yaffs_AllocateEmptyObject(dev); if(!theObject) return NULL; if(type == YAFFS_OBJECT_TYPE_FILE){ tn = yaffs_GetTnode(dev); if(!tn){ yaffs_FreeObject(theObject); return NULL; } } if (theObject) { theObject->fake = 0; theObject->renameAllowed = 1; theObject->unlinkAllowed = 1; theObject->objectId = number; yaffs_HashObject(theObject); theObject->variantType = type; #ifdef CONFIG_YAFFS_WINCE yfsd_WinFileTimeNow(theObject->win_atime); theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0]; theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1]; #else theObject->yst_atime = theObject->yst_mtime = theObject->yst_ctime = Y_CURRENT_TIME; #endif switch (type) { case YAFFS_OBJECT_TYPE_FILE: theObject->variant.fileVariant.fileSize = 0; theObject->variant.fileVariant.scannedFileSize = 0; theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */ theObject->variant.fileVariant.topLevel = 0; theObject->variant.fileVariant.top = tn; break; case YAFFS_OBJECT_TYPE_DIRECTORY: INIT_LIST_HEAD(&theObject->variant.directoryVariant. children); break; case YAFFS_OBJECT_TYPE_SYMLINK: case YAFFS_OBJECT_TYPE_HARDLINK: case YAFFS_OBJECT_TYPE_SPECIAL: /* No action required */ break; case YAFFS_OBJECT_TYPE_UNKNOWN: /* todo this should not happen */ break; } } return theObject; } static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev, int number, yaffs_ObjectType type) { yaffs_Object *theObject = NULL; if (number > 0) { theObject = yaffs_FindObjectByNumber(dev, number); } if (!theObject) { theObject = yaffs_CreateNewObject(dev, number, type); } return theObject; } static YCHAR *yaffs_CloneString(const YCHAR * str) { YCHAR *newStr = NULL; if (str && *str) { newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR)); if(newStr) yaffs_strcpy(newStr, str); } return newStr; } /* * Mknod (create) a new object. * equivalentObject only has meaning for a hard link; * aliasString only has meaning for a sumlink. * rdev only has meaning for devices (a subset of special objects) */ static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type, yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid, yaffs_Object * equivalentObject, const YCHAR * aliasString, __u32 rdev) { yaffs_Object *in; YCHAR *str = NULL; yaffs_Device *dev = parent->myDev; /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/ if (yaffs_FindObjectByName(parent, name)) { return NULL; } in = yaffs_CreateNewObject(dev, -1, type); if(type == YAFFS_OBJECT_TYPE_SYMLINK){ str = yaffs_CloneString(aliasString); if(!str){ yaffs_FreeObject(in); return NULL; } } if (in) { in->chunkId = -1; in->valid = 1; in->variantType = type; in->yst_mode = mode; #ifdef CONFIG_YAFFS_WINCE yfsd_WinFileTimeNow(in->win_atime); in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0]; in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1]; #else in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME; in->yst_rdev = rdev; in->yst_uid = uid; in->yst_gid = gid; #endif in->nDataChunks = 0; yaffs_SetObjectName(in, name); in->dirty = 1; yaffs_AddObjectToDirectory(parent, in); in->myDev = parent->myDev; switch (type) { case YAFFS_OBJECT_TYPE_SYMLINK: in->variant.symLinkVariant.alias = str; break; case YAFFS_OBJECT_TYPE_HARDLINK: in->variant.hardLinkVariant.equivalentObject = equivalentObject; in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId; list_add(&in->hardLinks, &equivalentObject->hardLinks); break; case YAFFS_OBJECT_TYPE_FILE: case YAFFS_OBJECT_TYPE_DIRECTORY: case YAFFS_OBJECT_TYPE_SPECIAL: case YAFFS_OBJECT_TYPE_UNKNOWN: /* do nothing */ break; } if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) { /* Could not create the object header, fail the creation */ yaffs_DestroyObject(in); in = NULL; } } return in; } yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid) { return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode, uid, gid, NULL, NULL, 0); } yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid) { return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name, mode, uid, gid, NULL, NULL, 0); } yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev) { return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode, uid, gid, NULL, NULL, rdev); } yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid, const YCHAR * alias) { return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode, uid, gid, NULL, alias, 0); } /* yaffs_Link returns the object id of the equivalent object.*/ yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name, yaffs_Object * equivalentObject) { /* Get the real object in case we were fed a hard link as an equivalent object */ equivalentObject = yaffs_GetEquivalentObject(equivalentObject); if (yaffs_MknodObject (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0, equivalentObject, NULL, 0)) { return equivalentObject; } else { return NULL; } } static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir, const YCHAR * newName, int force, int shadows) { int unlinkOp; int deleteOp; yaffs_Object *existingTarget; if (newDir == NULL) { newDir = obj->parent; /* use the old directory */ } if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) { T(YAFFS_TRACE_ALWAYS, (TSTR ("tragendy: yaffs_ChangeObjectName: newDir is not a directory" TENDSTR))); YBUG(); } /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */ if (obj->myDev->isYaffs2) { unlinkOp = (newDir == obj->myDev->unlinkedDir); } else { unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE); } deleteOp = (newDir == obj->myDev->deletedDir); existingTarget = yaffs_FindObjectByName(newDir, newName); /* If the object is a file going into the unlinked directory, * then it is OK to just stuff it in since duplicate names are allowed. * else only proceed if the new name does not exist and if we're putting * it into a directory. */ if ((unlinkOp || deleteOp || force || (shadows > 0) || !existingTarget) && newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) { yaffs_SetObjectName(obj, newName); obj->dirty = 1; yaffs_AddObjectToDirectory(newDir, obj); if (unlinkOp) obj->unlinked = 1; /* If it is a deletion then we mark it as a shrink for gc purposes. */ if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0) return YAFFS_OK; } return YAFFS_FAIL; } int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName, yaffs_Object * newDir, const YCHAR * newName) { yaffs_Object *obj; yaffs_Object *existingTarget; int force = 0; #ifdef CONFIG_YAFFS_CASE_INSENSITIVE /* Special case for case insemsitive systems (eg. WinCE). * While look-up is case insensitive, the name isn't. * Therefore we might want to change x.txt to X.txt */ if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) { force = 1; } #endif obj = yaffs_FindObjectByName(oldDir, oldName); /* Check new name to long. */ if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK && yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH) /* ENAMETOOLONG */ return YAFFS_FAIL; else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK && yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH) /* ENAMETOOLONG */ return YAFFS_FAIL; if (obj && obj->renameAllowed) { /* Now do the handling for an existing target, if there is one */ existingTarget = yaffs_FindObjectByName(newDir, newName); if (existingTarget && existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY && !list_empty(&existingTarget->variant.directoryVariant.children)) { /* There is a target that is a non-empty directory, so we fail */ return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */ } else if (existingTarget && existingTarget != obj) { /* Nuke the target first, using shadowing, * but only if it isn't the same object */ yaffs_ChangeObjectName(obj, newDir, newName, force, existingTarget->objectId); yaffs_UnlinkObject(existingTarget); } return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0); } return YAFFS_FAIL; } /*------------------------- Block Management and Page Allocation ----------------*/ static int yaffs_InitialiseBlocks(yaffs_Device * dev) { int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1; dev->blockInfo = NULL; dev->chunkBits = NULL; dev->allocationBlock = -1; /* force it to get a new one */ /* If the first allocation strategy fails, thry the alternate one */ dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo)); if(!dev->blockInfo){ dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo)); dev->blockInfoAlt = 1; } else dev->blockInfoAlt = 0; if(dev->blockInfo){ /* Set up dynamic blockinfo stuff. */ dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */ dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks); if(!dev->chunkBits){ dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks); dev->chunkBitsAlt = 1; } else dev->chunkBitsAlt = 0; } if (dev->blockInfo && dev->chunkBits) { memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo)); memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks); return YAFFS_OK; } return YAFFS_FAIL; } static void yaffs_DeinitialiseBlocks(yaffs_Device * dev) { if(dev->blockInfoAlt && dev->blockInfo) YFREE_ALT(dev->blockInfo); else if(dev->blockInfo) YFREE(dev->blockInfo); dev->blockInfoAlt = 0; dev->blockInfo = NULL; if(dev->chunkBitsAlt && dev->chunkBits) YFREE_ALT(dev->chunkBits); else if(dev->chunkBits) YFREE(dev->chunkBits); dev->chunkBitsAlt = 0; dev->chunkBits = NULL; } static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev, yaffs_BlockInfo * bi) { int i; __u32 seq; yaffs_BlockInfo *b; if (!dev->isYaffs2) return 1; /* disqualification only applies to yaffs2. */ if (!bi->hasShrinkHeader) return 1; /* can gc */ /* Find the oldest dirty sequence number if we don't know it and save it * so we don't have to keep recomputing it. */ if (!dev->oldestDirtySequence) { seq = dev->sequenceNumber; for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) { b = yaffs_GetBlockInfo(dev, i); if (b->blockState == YAFFS_BLOCK_STATE_FULL && (b->pagesInUse - b->softDeletions) < dev->nChunksPerBlock && b->sequenceNumber < seq) { seq = b->sequenceNumber; } } dev->oldestDirtySequence = seq; } /* Can't do gc of this block if there are any blocks older than this one that have * discarded pages. */ return (bi->sequenceNumber <= dev->oldestDirtySequence); } /* FindDiretiestBlock is used to select the dirtiest block (or close enough) * for garbage collection. */ static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev, int aggressive) { int b = dev->currentDirtyChecker; int i; int iterations; int dirtiest = -1; int pagesInUse = 0; int prioritised=0; yaffs_BlockInfo *bi; int pendingPrioritisedExist = 0; /* First let's see if we need to grab a prioritised block */ if(dev->hasPendingPrioritisedGCs){ for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){ bi = yaffs_GetBlockInfo(dev, i); //yaffs_VerifyBlock(dev,bi,i); if(bi->gcPrioritise) { pendingPrioritisedExist = 1; if(bi->blockState == YAFFS_BLOCK_STATE_FULL && yaffs_BlockNotDisqualifiedFromGC(dev, bi)){ pagesInUse = (bi->pagesInUse - bi->softDeletions); dirtiest = i; prioritised = 1; aggressive = 1; /* Fool the non-aggressive skip logiv below */ } } } if(!pendingPrioritisedExist) /* None found, so we can clear this */ dev->hasPendingPrioritisedGCs = 0; } /* If we're doing aggressive GC then we are happy to take a less-dirty block, and * search harder. * else (we're doing a leasurely gc), then we only bother to do this if the * block has only a few pages in use. */ dev->nonAggressiveSkip--; if (!aggressive && (dev->nonAggressiveSkip > 0)) { return -1; } if(!prioritised) pagesInUse = (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1; if (aggressive) { iterations = dev->internalEndBlock - dev->internalStartBlock + 1; } else { iterations = dev->internalEndBlock - dev->internalStartBlock + 1; iterations = iterations / 16; if (iterations > 200) { iterations = 200; } } for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) { b++; if (b < dev->internalStartBlock || b > dev->internalEndBlock) { b = dev->internalStartBlock; } if (b < dev->internalStartBlock || b > dev->internalEndBlock) { T(YAFFS_TRACE_ERROR, (TSTR("**>> Block %d is not valid" TENDSTR), b)); YBUG(); } bi = yaffs_GetBlockInfo(dev, b); #if 0 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) { dirtiest = b; pagesInUse = 0; } else #endif if (bi->blockState == YAFFS_BLOCK_STATE_FULL && (bi->pagesInUse - bi->softDeletions) < pagesInUse && yaffs_BlockNotDisqualifiedFromGC(dev, bi)) { dirtiest = b; pagesInUse = (bi->pagesInUse - bi->softDeletions); } } dev->currentDirtyChecker = b; if (dirtiest > 0) { T(YAFFS_TRACE_GC, (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest, dev->nChunksPerBlock - pagesInUse,prioritised)); } dev->oldestDirtySequence = 0; if (dirtiest > 0) { dev->nonAggressiveSkip = 4; } return dirtiest; } static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo) { yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo); int erasedOk = 0; /* If the block is still healthy erase it and mark as clean. * If the block has had a data failure, then retire it. */ T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE, (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR), blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : "")); bi->blockState = YAFFS_BLOCK_STATE_DIRTY; if (!bi->needsRetiring) { yaffs_InvalidateCheckpoint(dev); erasedOk = yaffs_EraseBlockInNAND(dev, blockNo); if (!erasedOk) { dev->nErasureFailures++; T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS, (TSTR("**>> Erasure failed %d" TENDSTR), blockNo)); } } if (erasedOk && ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) { int i; for (i = 0; i < dev->nChunksPerBlock; i++) { if (!yaffs_CheckChunkErased (dev, blockNo * dev->nChunksPerBlock + i)) { T(YAFFS_TRACE_ERROR, (TSTR (">>Block %d erasure supposedly OK, but chunk %d not erased" TENDSTR), blockNo, i)); } } } if (erasedOk) { /* Clean it up... */ bi->blockState = YAFFS_BLOCK_STATE_EMPTY; dev->nErasedBlocks++; bi->pagesInUse = 0; bi->softDeletions = 0; bi->hasShrinkHeader = 0; bi->skipErasedCheck = 1; /* This is clean, so no need to check */ bi->gcPrioritise = 0; yaffs_ClearChunkBits(dev, blockNo); T(YAFFS_TRACE_ERASE, (TSTR("Erased block %d" TENDSTR), blockNo)); } else { dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */ yaffs_RetireBlock(dev, blockNo); T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS, (TSTR("**>> Block %d retired" TENDSTR), blockNo)); } } static int yaffs_FindBlockForAllocation(yaffs_Device * dev) { int i; yaffs_BlockInfo *bi; if (dev->nErasedBlocks < 1) { /* Hoosterman we've got a problem. * Can't get space to gc */ T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR))); return -1; } /* Find an empty block. */ for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) { dev->allocationBlockFinder++; if (dev->allocationBlockFinder < dev->internalStartBlock || dev->allocationBlockFinder > dev->internalEndBlock) { dev->allocationBlockFinder = dev->internalStartBlock; } bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder); if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) { bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING; dev->sequenceNumber++; bi->sequenceNumber = dev->sequenceNumber; dev->nErasedBlocks--; T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocated block %d, seq %d, %d left" TENDSTR), dev->allocationBlockFinder, dev->sequenceNumber, dev->nErasedBlocks)); return dev->allocationBlockFinder; } } T(YAFFS_TRACE_ALWAYS, (TSTR ("yaffs tragedy: no more eraased blocks, but there should have been %d" TENDSTR), dev->nErasedBlocks)); return -1; } // Check if there's space to allocate... // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()? static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev) { int reservedChunks; int reservedBlocks = dev->nReservedBlocks; int checkpointBlocks; checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint; if(checkpointBlocks < 0) checkpointBlocks = 0; reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock); return (dev->nFreeChunks > reservedChunks); } static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr) { int retVal; yaffs_BlockInfo *bi; if (dev->allocationBlock < 0) { /* Get next block to allocate off */ dev->allocationBlock = yaffs_FindBlockForAllocation(dev); dev->allocationPage = 0; } if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) { /* Not enough space to allocate unless we're allowed to use the reserve. */ return -1; } if (dev->nErasedBlocks < dev->nReservedBlocks && dev->allocationPage == 0) { T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR))); } /* Next page please.... */ if (dev->allocationBlock >= 0) { bi = yaffs_GetBlockInfo(dev, dev->allocationBlock); retVal = (dev->allocationBlock * dev->nChunksPerBlock) + dev->allocationPage; bi->pagesInUse++; yaffs_SetChunkBit(dev, dev->allocationBlock, dev->allocationPage); dev->allocationPage++; dev->nFreeChunks--; /* If the block is full set the state to full */ if (dev->allocationPage >= dev->nChunksPerBlock) { bi->blockState = YAFFS_BLOCK_STATE_FULL; dev->allocationBlock = -1; } if(blockUsedPtr) *blockUsedPtr = bi; return retVal; } T(YAFFS_TRACE_ERROR, (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR))); return -1; } static int yaffs_GetErasedChunks(yaffs_Device * dev) { int n; n = dev->nErasedBlocks * dev->nChunksPerBlock; if (dev->allocationBlock > 0) { n += (dev->nChunksPerBlock - dev->allocationPage); } return n; } static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block) { int oldChunk; int newChunk; int chunkInBlock; int markNAND; int retVal = YAFFS_OK; int cleanups = 0; int i; int isCheckpointBlock; int matchingChunk; int chunksBefore = yaffs_GetErasedChunks(dev); int chunksAfter; yaffs_ExtendedTags tags; yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block); yaffs_Object *object; isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT); bi->blockState = YAFFS_BLOCK_STATE_COLLECTING; T(YAFFS_TRACE_TRACING, (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block, bi->pagesInUse, bi->hasShrinkHeader)); /*yaffs_VerifyFreeChunks(dev); */ bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */ /* Take off the number of soft deleted entries because * they're going to get really deleted during GC. */ dev->nFreeChunks -= bi->softDeletions; dev->isDoingGC = 1; if (isCheckpointBlock || !yaffs_StillSomeChunkBits(dev, block)) { T(YAFFS_TRACE_TRACING, (TSTR ("Collecting block %d that has no chunks in use" TENDSTR), block)); yaffs_BlockBecameDirty(dev, block); } else { __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__); yaffs_VerifyBlock(dev,bi,block); for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock; chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev, block); chunkInBlock++, oldChunk++) { if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) { /* This page is in use and might need to be copied off */ markNAND = 1; yaffs_InitialiseTags(&tags); yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk, buffer, &tags); object = yaffs_FindObjectByNumber(dev, tags.objectId); T(YAFFS_TRACE_GC_DETAIL, (TSTR ("Collecting page %d, %d %d %d " TENDSTR), chunkInBlock, tags.objectId, tags.chunkId, tags.byteCount)); if(object && !yaffs_SkipVerification(dev)){ if(tags.chunkId == 0) matchingChunk = object->chunkId; else if(object->softDeleted) matchingChunk = oldChunk; /* Defeat the test */ else matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL); if(oldChunk != matchingChunk) T(YAFFS_TRACE_ERROR, (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR), oldChunk,matchingChunk,tags.objectId, tags.chunkId)); } if (!object) { T(YAFFS_TRACE_ERROR, (TSTR ("page %d in gc has no object: %d %d %d " TENDSTR), oldChunk, tags.objectId, tags.chunkId, tags.byteCount)); } if (object && object->deleted && tags.chunkId != 0) { /* Data chunk in a deleted file, throw it away * It's a soft deleted data chunk, * No need to copy this, just forget about it and * fix up the object. */ object->nDataChunks--; if (object->nDataChunks <= 0) { /* remeber to clean up the object */ dev->gcCleanupList[cleanups] = tags.objectId; cleanups++; } markNAND = 0; } else if (0 /* Todo object && object->deleted && object->nDataChunks == 0 */ ) { /* Deleted object header with no data chunks. * Can be discarded and the file deleted. */ object->chunkId = 0; yaffs_FreeTnode(object->myDev, object->variant. fileVariant.top); object->variant.fileVariant.top = NULL; yaffs_DoGenericObjectDeletion(object); } else if (object) { /* It's either a data chunk in a live file or * an ObjectHeader, so we're interested in it. * NB Need to keep the ObjectHeaders of deleted files * until the whole file has been deleted off */ tags.serialNumber++; dev->nGCCopies++; if (tags.chunkId == 0) { /* It is an object Id, * We need to nuke the shrinkheader flags first * We no longer want the shrinkHeader flag since its work is done * and if it is left in place it will mess up scanning. * Also, clear out any shadowing stuff */ yaffs_ObjectHeader *oh; oh = (yaffs_ObjectHeader *)buffer; oh->isShrink = 0; oh->shadowsObject = -1; tags.extraShadows = 0; tags.extraIsShrinkHeader = 0; yaffs_VerifyObjectHeader(object,oh,&tags,1); } newChunk = yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1); if (newChunk < 0) { retVal = YAFFS_FAIL; } else { /* Ok, now fix up the Tnodes etc. */ if (tags.chunkId == 0) { /* It's a header */ object->chunkId = newChunk; object->serial = tags.serialNumber; } else { /* It's a data chunk */ yaffs_PutChunkIntoFile (object, tags.chunkId, newChunk, 0); } } } yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__); } } yaffs_ReleaseTempBuffer(dev, buffer, __LINE__); /* Do any required cleanups */ for (i = 0; i < cleanups; i++) { /* Time to delete the file too */ object = yaffs_FindObjectByNumber(dev, dev->gcCleanupList[i]); if (object) { yaffs_FreeTnode(dev, object->variant.fileVariant. top); object->variant.fileVariant.top = NULL; T(YAFFS_TRACE_GC, (TSTR ("yaffs: About to finally delete object %d" TENDSTR), object->objectId)); yaffs_DoGenericObjectDeletion(object); object->myDev->nDeletedFiles--; } } } yaffs_VerifyCollectedBlock(dev,bi,block); if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) { T(YAFFS_TRACE_GC, (TSTR ("gc did not increase free chunks before %d after %d" TENDSTR), chunksBefore, chunksAfter)); } dev->isDoingGC = 0; return retVal; } /* New garbage collector * If we're very low on erased blocks then we do aggressive garbage collection * otherwise we do "leasurely" garbage collection. * Aggressive gc looks further (whole array) and will accept less dirty blocks. * Passive gc only inspects smaller areas and will only accept more dirty blocks. * * The idea is to help clear out space in a more spread-out manner. * Dunno if it really does anything useful. */ static int yaffs_CheckGarbageCollection(yaffs_Device * dev) { int block; int aggressive; int gcOk = YAFFS_OK; int maxTries = 0; int checkpointBlockAdjust; if (dev->isDoingGC) { /* Bail out so we don't get recursive gc */ return YAFFS_OK; } /* This loop should pass the first time. * We'll only see looping here if the erase of the collected block fails. */ do { maxTries++; checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint); if(checkpointBlockAdjust < 0) checkpointBlockAdjust = 0; if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) { /* We need a block soon...*/ aggressive = 1; } else { /* We're in no hurry */ aggressive = 0; } block = yaffs_FindBlockForGarbageCollection(dev, aggressive); if (block > 0) { dev->garbageCollections++; if (!aggressive) { dev->passiveGarbageCollections++; } T(YAFFS_TRACE_GC, (TSTR ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR), dev->nErasedBlocks, aggressive)); gcOk = yaffs_GarbageCollectBlock(dev, block); } if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) { T(YAFFS_TRACE_GC, (TSTR ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d" TENDSTR), dev->nErasedBlocks, maxTries, block)); } } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0) && (maxTries < 2)); return aggressive ? gcOk : YAFFS_OK; } /*------------------------- TAGS --------------------------------*/ static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId, int chunkInObject) { return (tags->chunkId == chunkInObject && tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0; } /*-------------------- Data file manipulation -----------------*/ static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode, yaffs_ExtendedTags * tags) { /*Get the Tnode, then get the level 0 offset chunk offset */ yaffs_Tnode *tn; int theChunk = -1; yaffs_ExtendedTags localTags; int retVal = -1; yaffs_Device *dev = in->myDev; if (!tags) { /* Passed a NULL, so use our own tags space */ tags = &localTags; } tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode); if (tn) { theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode); retVal = yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId, chunkInInode); } return retVal; } static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode, yaffs_ExtendedTags * tags) { /* Get the Tnode, then get the level 0 offset chunk offset */ yaffs_Tnode *tn; int theChunk = -1; yaffs_ExtendedTags localTags; yaffs_Device *dev = in->myDev; int retVal = -1; if (!tags) { /* Passed a NULL, so use our own tags space */ tags = &localTags; } tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode); if (tn) { theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode); retVal = yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId, chunkInInode); /* Delete the entry in the filestructure (if found) */ if (retVal != -1) { yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0); } } else { /*T(("No level 0 found for %d\n", chunkInInode)); */ } if (retVal == -1) { /* T(("Could not find %d to delete\n",chunkInInode)); */ } return retVal; } #ifdef YAFFS_PARANOID static int yaffs_CheckFileSanity(yaffs_Object * in) { int chunk; int nChunks; int fSize; int failed = 0; int objId; yaffs_Tnode *tn; yaffs_Tags localTags; yaffs_Tags *tags = &localTags; int theChunk; int chunkDeleted; if (in->variantType != YAFFS_OBJECT_TYPE_FILE) { /* T(("Object not a file\n")); */ return YAFFS_FAIL; } objId = in->objectId; fSize = in->variant.fileVariant.fileSize; nChunks = (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk; for (chunk = 1; chunk <= nChunks; chunk++) { tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant, chunk); if (tn) { theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk); if (yaffs_CheckChunkBits (dev, theChunk / dev->nChunksPerBlock, theChunk % dev->nChunksPerBlock)) { yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk, tags, &chunkDeleted); if (yaffs_TagsMatch (tags, in->objectId, chunk, chunkDeleted)) { /* found it; */ } } else { failed = 1; } } else { /* T(("No level 0 found for %d\n", chunk)); */ } } return failed ? YAFFS_FAIL : YAFFS_OK; } #endif static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode, int chunkInNAND, int inScan) { /* NB inScan is zero unless scanning. * For forward scanning, inScan is > 0; * for backward scanning inScan is < 0 */ yaffs_Tnode *tn; yaffs_Device *dev = in->myDev; int existingChunk; yaffs_ExtendedTags existingTags; yaffs_ExtendedTags newTags; unsigned existingSerial, newSerial; if (in->variantType != YAFFS_OBJECT_TYPE_FILE) { /* Just ignore an attempt at putting a chunk into a non-file during scanning * If it is not during Scanning then something went wrong! */ if (!inScan) { T(YAFFS_TRACE_ERROR, (TSTR ("yaffs tragedy:attempt to put data chunk into a non-file" TENDSTR))); YBUG(); } yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__); return YAFFS_OK; } tn = yaffs_AddOrFindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode, NULL); if (!tn) { return YAFFS_FAIL; } existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode); if (inScan != 0) { /* If we're scanning then we need to test for duplicates * NB This does not need to be efficient since it should only ever * happen when the power fails during a write, then only one * chunk should ever be affected. * * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO * Update: For backward scanning we don't need to re-read tags so this is quite cheap. */ if (existingChunk != 0) { /* NB Right now existing chunk will not be real chunkId if the device >= 32MB * thus we have to do a FindChunkInFile to get the real chunk id. * * We have a duplicate now we need to decide which one to use: * * Backwards scanning YAFFS2: The old one is what we use, dump the new one. * Forward scanning YAFFS2: The new one is what we use, dump the old one. * YAFFS1: Get both sets of tags and compare serial numbers. */ if (inScan > 0) { /* Only do this for forward scanning */ yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, NULL, &newTags); /* Do a proper find */ existingChunk = yaffs_FindChunkInFile(in, chunkInInode, &existingTags); } if (existingChunk <= 0) { /*Hoosterman - how did this happen? */ T(YAFFS_TRACE_ERROR, (TSTR ("yaffs tragedy: existing chunk < 0 in scan" TENDSTR))); } /* NB The deleted flags should be false, otherwise the chunks will * not be loaded during a scan */ newSerial = newTags.serialNumber; existingSerial = existingTags.serialNumber; if ((inScan > 0) && (in->myDev->isYaffs2 || existingChunk <= 0 || ((existingSerial + 1) & 3) == newSerial)) { /* Forward scanning. * Use new * Delete the old one and drop through to update the tnode */ yaffs_DeleteChunk(dev, existingChunk, 1, __LINE__); } else { /* Backward scanning or we want to use the existing one * Use existing. * Delete the new one and return early so that the tnode isn't changed */ yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__); return YAFFS_OK; } } } if (existingChunk == 0) { in->nDataChunks++; } yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND); return YAFFS_OK; } static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode, __u8 * buffer) { int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL); if (chunkInNAND >= 0) { return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND, buffer,NULL); } else { T(YAFFS_TRACE_NANDACCESS, (TSTR("Chunk %d not found zero instead" TENDSTR), chunkInNAND)); /* get sane (zero) data if you read a hole */ memset(buffer, 0, in->myDev->nDataBytesPerChunk); return 0; } } void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn) { int block; int page; yaffs_ExtendedTags tags; yaffs_BlockInfo *bi; if (chunkId <= 0) return; dev->nDeletions++; block = chunkId / dev->nChunksPerBlock; page = chunkId % dev->nChunksPerBlock; if(!yaffs_CheckChunkBit(dev,block,page)) T(YAFFS_TRACE_VERIFY, (TSTR("Deleting invalid chunk %d"TENDSTR), chunkId)); bi = yaffs_GetBlockInfo(dev, block); T(YAFFS_TRACE_DELETION, (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId)); if (markNAND && bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) { yaffs_InitialiseTags(&tags); tags.chunkDeleted = 1; yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags); yaffs_HandleUpdateChunk(dev, chunkId, &tags); } else { dev->nUnmarkedDeletions++; } /* Pull out of the management area. * If the whole block became dirty, this will kick off an erasure. */ if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL || bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING || bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) { dev->nFreeChunks++; yaffs_ClearChunkBit(dev, block, page); bi->pagesInUse--; if (bi->pagesInUse == 0 && !bi->hasShrinkHeader && bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING && bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) { yaffs_BlockBecameDirty(dev, block); } } else { /* T(("Bad news deleting chunk %d\n",chunkId)); */ } } static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode, const __u8 * buffer, int nBytes, int useReserve) { /* Find old chunk Need to do this to get serial number * Write new one and patch into tree. * Invalidate old tags. */ int prevChunkId; yaffs_ExtendedTags prevTags; int newChunkId; yaffs_ExtendedTags newTags; yaffs_Device *dev = in->myDev; yaffs_CheckGarbageCollection(dev); /* Get the previous chunk at this location in the file if it exists */ prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags); /* Set up new tags */ yaffs_InitialiseTags(&newTags); newTags.chunkId = chunkInInode; newTags.objectId = in->objectId; newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1; newTags.byteCount = nBytes; newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags, useReserve); if (newChunkId >= 0) { yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0); if (prevChunkId >= 0) { yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__); } yaffs_CheckFileSanity(in); } return newChunkId; } /* UpdateObjectHeader updates the header on NAND for an object. * If name is not NULL, then that new name is used. */ int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force, int isShrink, int shadows) { yaffs_BlockInfo *bi; yaffs_Device *dev = in->myDev; int prevChunkId; int retVal = 0; int newChunkId; yaffs_ExtendedTags newTags; yaffs_ExtendedTags oldTags; __u8 *buffer = NULL; YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1]; yaffs_ObjectHeader *oh = NULL; yaffs_strcpy(oldName,"silly old name"); if (!in->fake || force) { yaffs_CheckGarbageCollection(dev); yaffs_CheckObjectDetailsLoaded(in); buffer = yaffs_GetTempBuffer(in->myDev, __LINE__); oh = (yaffs_ObjectHeader *) buffer; prevChunkId = in->chunkId; if (prevChunkId >= 0) { yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId, buffer, &oldTags); yaffs_VerifyObjectHeader(in,oh,&oldTags,0); memcpy(oldName, oh->name, sizeof(oh->name)); } memset(buffer, 0xFF, dev->nDataBytesPerChunk); oh->type = in->variantType; oh->yst_mode = in->yst_mode; oh->shadowsObject = shadows; #ifdef CONFIG_YAFFS_WINCE oh->win_atime[0] = in->win_atime[0]; oh->win_ctime[0] = in->win_ctime[0]; oh->win_mtime[0] = in->win_mtime[0]; oh->win_atime[1] = in->win_atime[1]; oh->win_ctime[1] = in->win_ctime[1]; oh->win_mtime[1] = in->win_mtime[1]; #else oh->yst_uid = in->yst_uid; oh->yst_gid = in->yst_gid; oh->yst_atime = in->yst_atime; oh->yst_mtime = in->yst_mtime; oh->yst_ctime = in->yst_ctime; oh->yst_rdev = in->yst_rdev; #endif if (in->parent) { oh->parentObjectId = in->parent->objectId; } else { oh->parentObjectId = 0; } if (name && *name) { memset(oh->name, 0, sizeof(oh->name)); yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH); } else if (prevChunkId>=0) { memcpy(oh->name, oldName, sizeof(oh->name)); } else { memset(oh->name, 0, sizeof(oh->name)); } oh->isShrink = isShrink; switch (in->variantType) { case YAFFS_OBJECT_TYPE_UNKNOWN: /* Should not happen */ break; case YAFFS_OBJECT_TYPE_FILE: oh->fileSize = (oh->parentObjectId == YAFFS_OBJECTID_DELETED || oh->parentObjectId == YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant. fileVariant.fileSize; break; case YAFFS_OBJECT_TYPE_HARDLINK: oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId; break; case YAFFS_OBJECT_TYPE_SPECIAL: /* Do nothing */ break; case YAFFS_OBJECT_TYPE_DIRECTORY: /* Do nothing */ break; case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_strncpy(oh->alias, in->variant.symLinkVariant.alias, YAFFS_MAX_ALIAS_LENGTH); oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0; break; } /* Tags */ yaffs_InitialiseTags(&newTags); in->serial++; newTags.chunkId = 0; newTags.objectId = in->objectId; newTags.serialNumber = in->serial; /* Add extra info for file header */ newTags.extraHeaderInfoAvailable = 1; newTags.extraParentObjectId = oh->parentObjectId; newTags.extraFileLength = oh->fileSize; newTags.extraIsShrinkHeader = oh->isShrink; newTags.extraEquivalentObjectId = oh->equivalentObjectId; newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0; newTags.extraObjectType = in->variantType; yaffs_VerifyObjectHeader(in,oh,&newTags,1); /* Create new chunk in NAND */ newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags, (prevChunkId >= 0) ? 1 : 0); if (newChunkId >= 0) { in->chunkId = newChunkId; if (prevChunkId >= 0) { yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__); } if(!yaffs_ObjectHasCachedWriteData(in)) in->dirty = 0; /* If this was a shrink, then mark the block that the chunk lives on */ if (isShrink) { bi = yaffs_GetBlockInfo(in->myDev, newChunkId /in->myDev-> nChunksPerBlock); bi->hasShrinkHeader = 1; } } retVal = newChunkId; } if (buffer) yaffs_ReleaseTempBuffer(dev, buffer, __LINE__); return retVal; } /*------------------------ Short Operations Cache ---------------------------------------- * In many situations where there is no high level buffering (eg WinCE) a lot of * reads might be short sequential reads, and a lot of writes may be short * sequential writes. eg. scanning/writing a jpeg file. * In these cases, a short read/write cache can provide a huge perfomance benefit * with dumb-as-a-rock code. * In Linux, the page cache provides read buffering aand the short op cache provides write * buffering. * * There are a limited number (~10) of cache chunks per device so that we don't * need a very intelligent search. */ static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj) { yaffs_Device *dev = obj->myDev; int i; yaffs_ChunkCache *cache; int nCaches = obj->myDev->nShortOpCaches; for(i = 0; i < nCaches; i++){ cache = &dev->srCache[i]; if (cache->object == obj && cache->dirty) return 1; } return 0; } static void yaffs_FlushFilesChunkCache(yaffs_Object * obj) { yaffs_Device *dev = obj->myDev; int lowest = -99; /* Stop compiler whining. */ int i; yaffs_ChunkCache *cache; int chunkWritten = 0; int nCaches = obj->myDev->nShortOpCaches; if (nCaches > 0) { do { cache = NULL; /* Find the dirty cache for this object with the lowest chunk id. */ for (i = 0; i < nCaches; i++) { if (dev->srCache[i].object == obj && dev->srCache[i].dirty) { if (!cache || dev->srCache[i].chunkId < lowest) { cache = &dev->srCache[i]; lowest = cache->chunkId; } } } if (cache && !cache->locked) { /* Write it out and free it up */ chunkWritten = yaffs_WriteChunkDataToObject(cache->object, cache->chunkId, cache->data, cache->nBytes, 1); cache->dirty = 0; cache->object = NULL; } } while (cache && chunkWritten > 0); if (cache) { /* Hoosterman, disk full while writing cache out. */ T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR))); } } } /*yaffs_FlushEntireDeviceCache(dev) * * */ void yaffs_FlushEntireDeviceCache(yaffs_Device *dev) { yaffs_Object *obj; int nCaches = dev->nShortOpCaches; int i; /* Find a dirty object in the cache and flush it... * until there are no further dirty objects. */ do { obj = NULL; for( i = 0; i < nCaches && !obj; i++) { if (dev->srCache[i].object && dev->srCache[i].dirty) obj = dev->srCache[i].object; } if(obj) yaffs_FlushFilesChunkCache(obj); } while(obj); } /* Grab us a cache chunk for use. * First look for an empty one. * Then look for the least recently used non-dirty one. * Then look for the least recently used dirty one...., flush and look again. */ static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev) { int i; int usage; int theOne; if (dev->nShortOpCaches > 0) { for (i = 0; i < dev->nShortOpCaches; i++) { if (!dev->srCache[i].object) return &dev->srCache[i]; } return NULL; theOne = -1; usage = 0; /* just to stop the compiler grizzling */ for (i = 0; i < dev->nShortOpCaches; i++) { if (!dev->srCache[i].dirty && ((dev->srCache[i].lastUse < usage && theOne >= 0) || theOne < 0)) { usage = dev->srCache[i].lastUse; theOne = i; } } return theOne >= 0 ? &dev->srCache[theOne] : NULL; } else { return NULL; } } static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev) { yaffs_ChunkCache *cache; yaffs_Object *theObj; int usage; int i; if (dev->nShortOpCaches > 0) { /* Try find a non-dirty one... */ cache = yaffs_GrabChunkCacheWorker(dev); if (!cache) { /* They were all dirty, find the last recently used object and flush * its cache, then find again. * NB what's here is not very accurate, we actually flush the object * the last recently used page. */ /* With locking we can't assume we can use entry zero */ theObj = NULL; usage = -1; cache = NULL; for (i = 0; i < dev->nShortOpCaches; i++) { if (dev->srCache[i].object && !dev->srCache[i].locked && (dev->srCache[i].lastUse < usage || !cache)) { usage = dev->srCache[i].lastUse; theObj = dev->srCache[i].object; cache = &dev->srCache[i]; } } if (!cache || cache->dirty) { /* Flush and try again */ yaffs_FlushFilesChunkCache(theObj); cache = yaffs_GrabChunkCacheWorker(dev); } } return cache; } else return NULL; } /* Find a cached chunk */ static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj, int chunkId) { yaffs_Device *dev = obj->myDev; int i; if (dev->nShortOpCaches > 0) { for (i = 0; i < dev->nShortOpCaches; i++) { if (dev->srCache[i].object == obj && dev->srCache[i].chunkId == chunkId) { dev->cacheHits++; return &dev->srCache[i]; } } } return NULL; } /* Mark the chunk for the least recently used algorithym */ static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache, int isAWrite) { if (dev->nShortOpCaches > 0) { if (dev->srLastUse < 0 || dev->srLastUse > 100000000) { /* Reset the cache usages */ int i; for (i = 1; i < dev->nShortOpCaches; i++) { dev->srCache[i].lastUse = 0; } dev->srLastUse = 0; } dev->srLastUse++; cache->lastUse = dev->srLastUse; if (isAWrite) { cache->dirty = 1; } } } /* Invalidate a single cache page. * Do this when a whole page gets written, * ie the short cache for this page is no longer valid. */ static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId) { if (object->myDev->nShortOpCaches > 0) { yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId); if (cache) { cache->object = NULL; } } } /* Invalidate all the cache pages associated with this object * Do this whenever ther file is deleted or resized. */ static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in) { int i; yaffs_Device *dev = in->myDev; if (dev->nShortOpCaches > 0) { /* Invalidate it. */ for (i = 0; i < dev->nShortOpCaches; i++) { if (dev->srCache[i].object == in) { dev->srCache[i].object = NULL; } } } } /*--------------------- Checkpointing --------------------*/ static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head) { yaffs_CheckpointValidity cp; memset(&cp,0,sizeof(cp)); cp.structType = sizeof(cp); cp.magic = YAFFS_MAGIC; cp.version = YAFFS_CHECKPOINT_VERSION; cp.head = (head) ? 1 : 0; return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))? 1 : 0; } static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head) { yaffs_CheckpointValidity cp; int ok; ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp)); if(ok) ok = (cp.structType == sizeof(cp)) && (cp.magic == YAFFS_MAGIC) && (cp.version == YAFFS_CHECKPOINT_VERSION) && (cp.head == ((head) ? 1 : 0)); return ok ? 1 : 0; } static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp, yaffs_Device *dev) { cp->nErasedBlocks = dev->nErasedBlocks; cp->allocationBlock = dev->allocationBlock; cp->allocationPage = dev->allocationPage; cp->nFreeChunks = dev->nFreeChunks; cp->nDeletedFiles = dev->nDeletedFiles; cp->nUnlinkedFiles = dev->nUnlinkedFiles; cp->nBackgroundDeletions = dev->nBackgroundDeletions; cp->sequenceNumber = dev->sequenceNumber; cp->oldestDirtySequence = dev->oldestDirtySequence; } static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev, yaffs_CheckpointDevice *cp) { dev->nErasedBlocks = cp->nErasedBlocks; dev->allocationBlock = cp->allocationBlock; dev->allocationPage = cp->allocationPage; dev->nFreeChunks = cp->nFreeChunks; dev->nDeletedFiles = cp->nDeletedFiles; dev->nUnlinkedFiles = cp->nUnlinkedFiles; dev->nBackgroundDeletions = cp->nBackgroundDeletions; dev->sequenceNumber = cp->sequenceNumber; dev->oldestDirtySequence = cp->oldestDirtySequence; } static int yaffs_WriteCheckpointDevice(yaffs_Device *dev) { yaffs_CheckpointDevice cp; __u32 nBytes; __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1); int ok; /* Write device runtime values*/ yaffs_DeviceToCheckpointDevice(&cp,dev); cp.structType = sizeof(cp); ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp)); /* Write block info */ if(ok) { nBytes = nBlocks * sizeof(yaffs_BlockInfo); ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes); } /* Write chunk bits */ if(ok) { nBytes = nBlocks * dev->chunkBitmapStride; ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes); } return ok ? 1 : 0; } static int yaffs_ReadCheckpointDevice(yaffs_Device *dev) { yaffs_CheckpointDevice cp; __u32 nBytes; __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1); int ok; ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp)); if(!ok) return 0; if(cp.structType != sizeof(cp)) return 0; yaffs_CheckpointDeviceToDevice(dev,&cp); nBytes = nBlocks * sizeof(yaffs_BlockInfo); ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes); if(!ok) return 0; nBytes = nBlocks * dev->chunkBitmapStride; ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes); return ok ? 1 : 0; } static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp, yaffs_Object *obj) { cp->objectId = obj->objectId; cp->parentId = (obj->parent) ? obj->parent->objectId : 0; cp->chunkId = obj->chunkId; cp->variantType = obj->variantType; cp->deleted = obj->deleted; cp->softDeleted = obj->softDeleted; cp->unlinked = obj->unlinked; cp->fake = obj->fake; cp->renameAllowed = obj->renameAllowed; cp->unlinkAllowed = obj->unlinkAllowed; cp->serial = obj->serial; cp->nDataChunks = obj->nDataChunks; if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize; else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId; } static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp) { yaffs_Object *parent; obj->objectId = cp->objectId; if(cp->parentId) parent = yaffs_FindOrCreateObjectByNumber( obj->myDev, cp->parentId, YAFFS_OBJECT_TYPE_DIRECTORY); else parent = NULL; if(parent) yaffs_AddObjectToDirectory(parent, obj); obj->chunkId = cp->chunkId; obj->variantType = cp->variantType; obj->deleted = cp->deleted; obj->softDeleted = cp->softDeleted; obj->unlinked = cp->unlinked; obj->fake = cp->fake; obj->renameAllowed = cp->renameAllowed; obj->unlinkAllowed = cp->unlinkAllowed; obj->serial = cp->serial; obj->nDataChunks = cp->nDataChunks; if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId; else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId; if(obj->objectId >= YAFFS_NOBJECT_BUCKETS) obj->lazyLoaded = 1; } static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level, int chunkOffset) { int i; yaffs_Device *dev = in->myDev; int ok = 1; int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8; if (tn) { if (level > 0) { for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){ if (tn->internal[i]) { ok = yaffs_CheckpointTnodeWorker(in, tn->internal[i], level - 1, (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i); } } } else if (level == 0) { __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS; /* printf("write tnode at %d\n",baseOffset); */ ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset)); if(ok) ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes); } } return ok; } static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj) { __u32 endMarker = ~0; int ok = 1; if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){ ok = yaffs_CheckpointTnodeWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0); if(ok) ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) == sizeof(endMarker)); } return ok ? 1 : 0; } static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj) { __u32 baseChunk; int ok = 1; yaffs_Device *dev = obj->myDev; yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant; yaffs_Tnode *tn; int nread = 0; ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk)); while(ok && (~baseChunk)){ nread++; /* Read level 0 tnode */ /* printf("read tnode at %d\n",baseChunk); */ tn = yaffs_GetTnodeRaw(dev); if(tn) ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) == (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8); else ok = 0; if(tn && ok){ ok = yaffs_AddOrFindLevel0Tnode(dev, fileStructPtr, baseChunk, tn) ? 1 : 0; } if(ok) ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk)); } T(YAFFS_TRACE_CHECKPOINT,( TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR), nread,baseChunk,ok)); return ok ? 1 : 0; } static int yaffs_WriteCheckpointObjects(yaffs_Device *dev) { yaffs_Object *obj; yaffs_CheckpointObject cp; int i; int ok = 1; struct list_head *lh; /* Iterate through the objects in each hash entry, * dumping them to the checkpointing stream. */ for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){ list_for_each(lh, &dev->objectBucket[i].list) { if (lh) { obj = list_entry(lh, yaffs_Object, hashLink); if (!obj->deferedFree) { yaffs_ObjectToCheckpointObject(&cp,obj); cp.structType = sizeof(cp); T(YAFFS_TRACE_CHECKPOINT,( TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR), cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj)); ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp)); if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){ ok = yaffs_WriteCheckpointTnodes(obj); } } } } } /* Dump end of list */ memset(&cp,0xFF,sizeof(yaffs_CheckpointObject)); cp.structType = sizeof(cp); if(ok) ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp)); return ok ? 1 : 0; } static int yaffs_ReadCheckpointObjects(yaffs_Device *dev) { yaffs_Object *obj; yaffs_CheckpointObject cp; int ok = 1; int done = 0; yaffs_Object *hardList = NULL; while(ok && !done) { ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp)); if(cp.structType != sizeof(cp)) { T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR), cp.structType,sizeof(cp),ok)); ok = 0; } T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR), cp.objectId,cp.parentId,cp.variantType,cp.chunkId)); if(ok && cp.objectId == ~0) done = 1; else if(ok){ obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType); if(obj) { yaffs_CheckpointObjectToObject(obj,&cp); if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) { ok = yaffs_ReadCheckpointTnodes(obj); } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) { obj->hardLinks.next = (struct list_head *) hardList; hardList = obj; } } } } if(ok) yaffs_HardlinkFixup(dev,hardList); return ok ? 1 : 0; } static int yaffs_WriteCheckpointSum(yaffs_Device *dev) { __u32 checkpointSum; int ok; yaffs_GetCheckpointSum(dev,&checkpointSum); ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum)); if(!ok) return 0; return 1; } static int yaffs_ReadCheckpointSum(yaffs_Device *dev) { __u32 checkpointSum0; __u32 checkpointSum1; int ok; yaffs_GetCheckpointSum(dev,&checkpointSum0); ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1)); if(!ok) return 0; if(checkpointSum0 != checkpointSum1) return 0; return 1; } static int yaffs_WriteCheckpointData(yaffs_Device *dev) { int ok = 1; if(dev->skipCheckpointWrite || !dev->isYaffs2){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR))); ok = 0; } if(ok) ok = yaffs_CheckpointOpen(dev,1); if(ok){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR))); ok = yaffs_WriteCheckpointValidityMarker(dev,1); } if(ok){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR))); ok = yaffs_WriteCheckpointDevice(dev); } if(ok){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR))); ok = yaffs_WriteCheckpointObjects(dev); } if(ok){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR))); ok = yaffs_WriteCheckpointValidityMarker(dev,0); } if(ok){ ok = yaffs_WriteCheckpointSum(dev); } if(!yaffs_CheckpointClose(dev)) ok = 0; if(ok) dev->isCheckpointed = 1; else dev->isCheckpointed = 0; return dev->isCheckpointed; } static int yaffs_ReadCheckpointData(yaffs_Device *dev) { int ok = 1; if(dev->skipCheckpointRead || !dev->isYaffs2){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR))); ok = 0; } if(ok) ok = yaffs_CheckpointOpen(dev,0); /* open for read */ if(ok){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR))); ok = yaffs_ReadCheckpointValidityMarker(dev,1); } if(ok){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR))); ok = yaffs_ReadCheckpointDevice(dev); } if(ok){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR))); ok = yaffs_ReadCheckpointObjects(dev); } if(ok){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR))); ok = yaffs_ReadCheckpointValidityMarker(dev,0); } if(ok){ ok = yaffs_ReadCheckpointSum(dev); T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok)); } if(!yaffs_CheckpointClose(dev)) ok = 0; if(ok) dev->isCheckpointed = 1; else dev->isCheckpointed = 0; return ok ? 1 : 0; } static void yaffs_InvalidateCheckpoint(yaffs_Device *dev) { if(dev->isCheckpointed || dev->blocksInCheckpoint > 0){ dev->isCheckpointed = 0; yaffs_CheckpointInvalidateStream(dev); if(dev->superBlock && dev->markSuperBlockDirty) dev->markSuperBlockDirty(dev->superBlock); } } int yaffs_CheckpointSave(yaffs_Device *dev) { T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed)); yaffs_VerifyObjects(dev); yaffs_VerifyBlocks(dev); yaffs_VerifyFreeChunks(dev); if(!dev->isCheckpointed) { yaffs_InvalidateCheckpoint(dev); yaffs_WriteCheckpointData(dev); } T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed)); return dev->isCheckpointed; } int yaffs_CheckpointRestore(yaffs_Device *dev) { int retval; T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed)); retval = yaffs_ReadCheckpointData(dev); if(dev->isCheckpointed){ yaffs_VerifyObjects(dev); yaffs_VerifyBlocks(dev); yaffs_VerifyFreeChunks(dev); } T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed)); return retval; } /*--------------------- File read/write ------------------------ * Read and write have very similar structures. * In general the read/write has three parts to it * An incomplete chunk to start with (if the read/write is not chunk-aligned) * Some complete chunks * An incomplete chunk to end off with * * Curve-balls: the first chunk might also be the last chunk. */ int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset, int nBytes) { __u32 chunk = 0; __u32 start = 0; int nToCopy; int n = nBytes; int nDone = 0; yaffs_ChunkCache *cache; yaffs_Device *dev; dev = in->myDev; while (n > 0) { //chunk = offset / dev->nDataBytesPerChunk + 1; //start = offset % dev->nDataBytesPerChunk; yaffs_AddrToChunk(dev,offset,&chunk,&start); chunk++; /* OK now check for the curveball where the start and end are in * the same chunk. */ if ((start + n) < dev->nDataBytesPerChunk) { nToCopy = n; } else { nToCopy = dev->nDataBytesPerChunk - start; } cache = yaffs_FindChunkCache(in, chunk); /* If the chunk is already in the cache or it is less than a whole chunk * then use the cache (if there is caching) * else bypass the cache. */ if (cache || nToCopy != dev->nDataBytesPerChunk) { if (dev->nShortOpCaches > 0) { /* If we can't find the data in the cache, then load it up. */ if (!cache) { cache = yaffs_GrabChunkCache(in->myDev); cache->object = in; cache->chunkId = chunk; cache->dirty = 0; cache->locked = 0; yaffs_ReadChunkDataFromObject(in, chunk, cache-> data); cache->nBytes = 0; } yaffs_UseChunkCache(dev, cache, 0); cache->locked = 1; #ifdef CONFIG_YAFFS_WINCE yfsd_UnlockYAFFS(TRUE); #endif memcpy(buffer, &cache->data[start], nToCopy); #ifdef CONFIG_YAFFS_WINCE yfsd_LockYAFFS(TRUE); #endif cache->locked = 0; } else { /* Read into the local buffer then copy..*/ __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__); yaffs_ReadChunkDataFromObject(in, chunk, localBuffer); #ifdef CONFIG_YAFFS_WINCE yfsd_UnlockYAFFS(TRUE); #endif memcpy(buffer, &localBuffer[start], nToCopy); #ifdef CONFIG_YAFFS_WINCE yfsd_LockYAFFS(TRUE); #endif yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__); } } else { #ifdef CONFIG_YAFFS_WINCE __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__); /* Under WinCE can't do direct transfer. Need to use a local buffer. * This is because we otherwise screw up WinCE's memory mapper */ yaffs_ReadChunkDataFromObject(in, chunk, localBuffer); #ifdef CONFIG_YAFFS_WINCE yfsd_UnlockYAFFS(TRUE); #endif memcpy(buffer, localBuffer, dev->nDataBytesPerChunk); #ifdef CONFIG_YAFFS_WINCE yfsd_LockYAFFS(TRUE); yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__); #endif #else /* A full chunk. Read directly into the supplied buffer. */ yaffs_ReadChunkDataFromObject(in, chunk, buffer); #endif } n -= nToCopy; offset += nToCopy; buffer += nToCopy; nDone += nToCopy; } return nDone; } int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset, int nBytes, int writeThrough) { __u32 chunk = 0; __u32 start = 0; int nToCopy; int n = nBytes; int nDone = 0; int nToWriteBack; int startOfWrite = offset; int chunkWritten = 0; int nBytesRead; yaffs_Device *dev; dev = in->myDev; while (n > 0 && chunkWritten >= 0) { //chunk = offset / dev->nDataBytesPerChunk + 1; //start = offset % dev->nDataBytesPerChunk; yaffs_AddrToChunk(dev,offset,&chunk,&start); chunk++; /* OK now check for the curveball where the start and end are in * the same chunk. */ if ((start + n) < dev->nDataBytesPerChunk) { nToCopy = n; /* Now folks, to calculate how many bytes to write back.... * If we're overwriting and not writing to then end of file then * we need to write back as much as was there before. */ nBytesRead = in->variant.fileVariant.fileSize - ((chunk - 1) * dev->nDataBytesPerChunk); if (nBytesRead > dev->nDataBytesPerChunk) { nBytesRead = dev->nDataBytesPerChunk; } nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start + n); } else { nToCopy = dev->nDataBytesPerChunk - start; nToWriteBack = dev->nDataBytesPerChunk; } if (nToCopy != dev->nDataBytesPerChunk) { /* An incomplete start or end chunk (or maybe both start and end chunk) */ if (dev->nShortOpCaches > 0) { yaffs_ChunkCache *cache; /* If we can't find the data in the cache, then load the cache */ cache = yaffs_FindChunkCache(in, chunk); if (!cache && yaffs_CheckSpaceForAllocation(in-> myDev)) { cache = yaffs_GrabChunkCache(in->myDev); cache->object = in; cache->chunkId = chunk; cache->dirty = 0; cache->locked = 0; yaffs_ReadChunkDataFromObject(in, chunk, cache-> data); } else if(cache && !cache->dirty && !yaffs_CheckSpaceForAllocation(in->myDev)){ /* Drop the cache if it was a read cache item and * no space check has been made for it. */ cache = NULL; } if (cache) { yaffs_UseChunkCache(dev, cache, 1); cache->locked = 1; #ifdef CONFIG_YAFFS_WINCE yfsd_UnlockYAFFS(TRUE); #endif memcpy(&cache->data[start], buffer, nToCopy); #ifdef CONFIG_YAFFS_WINCE yfsd_LockYAFFS(TRUE); #endif cache->locked = 0; cache->nBytes = nToWriteBack; if (writeThrough) { chunkWritten = yaffs_WriteChunkDataToObject (cache->object, cache->chunkId, cache->data, cache->nBytes, 1); cache->dirty = 0; } } else { chunkWritten = -1; /* fail the write */ } } else { /* An incomplete start or end chunk (or maybe both start and end chunk) * Read into the local buffer then copy, then copy over and write back. */ __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__); yaffs_ReadChunkDataFromObject(in, chunk, localBuffer); #ifdef CONFIG_YAFFS_WINCE yfsd_UnlockYAFFS(TRUE); #endif memcpy(&localBuffer[start], buffer, nToCopy); #ifdef CONFIG_YAFFS_WINCE yfsd_LockYAFFS(TRUE); #endif chunkWritten = yaffs_WriteChunkDataToObject(in, chunk, localBuffer, nToWriteBack, 0); yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__); } } else { #ifdef CONFIG_YAFFS_WINCE /* Under WinCE can't do direct transfer. Need to use a local buffer. * This is because we otherwise screw up WinCE's memory mapper */ __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__); #ifdef CONFIG_YAFFS_WINCE yfsd_UnlockYAFFS(TRUE); #endif memcpy(localBuffer, buffer, dev->nDataBytesPerChunk); #ifdef CONFIG_YAFFS_WINCE yfsd_LockYAFFS(TRUE); #endif chunkWritten = yaffs_WriteChunkDataToObject(in, chunk, localBuffer, dev->nDataBytesPerChunk, 0); yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__); #else /* A full chunk. Write directly from the supplied buffer. */ chunkWritten = yaffs_WriteChunkDataToObject(in, chunk, buffer, dev->nDataBytesPerChunk, 0); #endif /* Since we've overwritten the cached data, we better invalidate it. */ yaffs_InvalidateChunkCache(in, chunk); } if (chunkWritten >= 0) { n -= nToCopy; offset += nToCopy; buffer += nToCopy; nDone += nToCopy; } } /* Update file object */ if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) { in->variant.fileVariant.fileSize = (startOfWrite + nDone); } in->dirty = 1; return nDone; } /* ---------------------- File resizing stuff ------------------ */ static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize) { yaffs_Device *dev = in->myDev; int oldFileSize = in->variant.fileVariant.fileSize; int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk; int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) / dev->nDataBytesPerChunk; int i; int chunkId; /* Delete backwards so that we don't end up with holes if * power is lost part-way through the operation. */ for (i = lastDel; i >= startDel; i--) { /* NB this could be optimised somewhat, * eg. could retrieve the tags and write them without * using yaffs_DeleteChunk */ chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL); if (chunkId > 0) { if (chunkId < (dev->internalStartBlock * dev->nChunksPerBlock) || chunkId >= ((dev->internalEndBlock + 1) * dev->nChunksPerBlock)) { T(YAFFS_TRACE_ALWAYS, (TSTR("Found daft chunkId %d for %d" TENDSTR), chunkId, i)); } else { in->nDataChunks--; yaffs_DeleteChunk(dev, chunkId, 1, __LINE__); } } } } int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize) { int oldFileSize = in->variant.fileVariant.fileSize; __u32 newSizeOfPartialChunk = 0; __u32 newFullChunks = 0; yaffs_Device *dev = in->myDev; yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk); yaffs_FlushFilesChunkCache(in); yaffs_InvalidateWholeChunkCache(in); yaffs_CheckGarbageCollection(dev); if (in->variantType != YAFFS_OBJECT_TYPE_FILE) { return yaffs_GetFileSize(in); } if (newSize == oldFileSize) { return oldFileSize; } if (newSize < oldFileSize) { yaffs_PruneResizedChunks(in, newSize); if (newSizeOfPartialChunk != 0) { int lastChunk = 1 + newFullChunks; __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__); /* Got to read and rewrite the last chunk with its new size and zero pad */ yaffs_ReadChunkDataFromObject(in, lastChunk, localBuffer); memset(localBuffer + newSizeOfPartialChunk, 0, dev->nDataBytesPerChunk - newSizeOfPartialChunk); yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer, newSizeOfPartialChunk, 1); yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__); } in->variant.fileVariant.fileSize = newSize; yaffs_PruneFileStructure(dev, &in->variant.fileVariant); } else { /* newsSize > oldFileSize */ in->variant.fileVariant.fileSize = newSize; } /* Write a new object header. * show we've shrunk the file, if need be * Do this only if the file is not in the deleted directories. */ if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED && in->parent->objectId != YAFFS_OBJECTID_DELETED) { yaffs_UpdateObjectHeader(in, NULL, 0, (newSize < oldFileSize) ? 1 : 0, 0); } return YAFFS_OK; } loff_t yaffs_GetFileSize(yaffs_Object * obj) { obj = yaffs_GetEquivalentObject(obj); switch (obj->variantType) { case YAFFS_OBJECT_TYPE_FILE: return obj->variant.fileVariant.fileSize; case YAFFS_OBJECT_TYPE_SYMLINK: return yaffs_strlen(obj->variant.symLinkVariant.alias); default: return 0; } } int yaffs_FlushFile(yaffs_Object * in, int updateTime) { int retVal; if (in->dirty) { yaffs_FlushFilesChunkCache(in); if (updateTime) { #ifdef CONFIG_YAFFS_WINCE yfsd_WinFileTimeNow(in->win_mtime); #else in->yst_mtime = Y_CURRENT_TIME; #endif } retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >= 0) ? YAFFS_OK : YAFFS_FAIL; } else { retVal = YAFFS_OK; } return retVal; } static int yaffs_DoGenericObjectDeletion(yaffs_Object * in) { /* First off, invalidate the file's data in the cache, without flushing. */ yaffs_InvalidateWholeChunkCache(in); if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) { /* Move to the unlinked directory so we have a record that it was deleted. */ yaffs_ChangeObjectName(in, in->myDev->deletedDir,"deleted", 0, 0); } yaffs_RemoveObjectFromDirectory(in); yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__); in->chunkId = -1; yaffs_FreeObject(in); return YAFFS_OK; } /* yaffs_DeleteFile deletes the whole file data * and the inode associated with the file. * It does not delete the links associated with the file. */ static int yaffs_UnlinkFile(yaffs_Object * in) { int retVal; int immediateDeletion = 0; if (1) { /* XXX U-BOOT XXX */ #if 0 #ifdef __KERNEL__ if (!in->myInode) { immediateDeletion = 1; } #endif #else if (in->inUse <= 0) { immediateDeletion = 1; } #endif if (immediateDeletion) { retVal = yaffs_ChangeObjectName(in, in->myDev->deletedDir, "deleted", 0, 0); T(YAFFS_TRACE_TRACING, (TSTR("yaffs: immediate deletion of file %d" TENDSTR), in->objectId)); in->deleted = 1; in->myDev->nDeletedFiles++; if (0 && in->myDev->isYaffs2) { yaffs_ResizeFile(in, 0); } yaffs_SoftDeleteFile(in); } else { retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir, "unlinked", 0, 0); } } return retVal; } int yaffs_DeleteFile(yaffs_Object * in) { int retVal = YAFFS_OK; if (in->nDataChunks > 0) { /* Use soft deletion if there is data in the file */ if (!in->unlinked) { retVal = yaffs_UnlinkFile(in); } if (retVal == YAFFS_OK && in->unlinked && !in->deleted) { in->deleted = 1; in->myDev->nDeletedFiles++; yaffs_SoftDeleteFile(in); } return in->deleted ? YAFFS_OK : YAFFS_FAIL; } else { /* The file has no data chunks so we toss it immediately */ yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top); in->variant.fileVariant.top = NULL; yaffs_DoGenericObjectDeletion(in); return YAFFS_OK; } } static int yaffs_DeleteDirectory(yaffs_Object * in) { /* First check that the directory is empty. */ if (list_empty(&in->variant.directoryVariant.children)) { return yaffs_DoGenericObjectDeletion(in); } return YAFFS_FAIL; } static int yaffs_DeleteSymLink(yaffs_Object * in) { YFREE(in->variant.symLinkVariant.alias); return yaffs_DoGenericObjectDeletion(in); } static int yaffs_DeleteHardLink(yaffs_Object * in) { /* remove this hardlink from the list assocaited with the equivalent * object */ list_del(&in->hardLinks); return yaffs_DoGenericObjectDeletion(in); } static void yaffs_DestroyObject(yaffs_Object * obj) { switch (obj->variantType) { case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break; case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break; case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break; case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break; case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break; case YAFFS_OBJECT_TYPE_UNKNOWN: break; /* should not happen. */ } } static int yaffs_UnlinkWorker(yaffs_Object * obj) { if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) { return yaffs_DeleteHardLink(obj); } else if (!list_empty(&obj->hardLinks)) { /* Curve ball: We're unlinking an object that has a hardlink. * * This problem arises because we are not strictly following * The Linux link/inode model. * * We can't really delete the object. * Instead, we do the following: * - Select a hardlink. * - Unhook it from the hard links * - Unhook it from its parent directory (so that the rename can work) * - Rename the object to the hardlink's name. * - Delete the hardlink */ yaffs_Object *hl; int retVal; YCHAR name[YAFFS_MAX_NAME_LENGTH + 1]; hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks); list_del_init(&hl->hardLinks); list_del_init(&hl->siblings); yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1); retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0); if (retVal == YAFFS_OK) { retVal = yaffs_DoGenericObjectDeletion(hl); } return retVal; } else { switch (obj->variantType) { case YAFFS_OBJECT_TYPE_FILE: return yaffs_UnlinkFile(obj); break; case YAFFS_OBJECT_TYPE_DIRECTORY: return yaffs_DeleteDirectory(obj); break; case YAFFS_OBJECT_TYPE_SYMLINK: return yaffs_DeleteSymLink(obj); break; case YAFFS_OBJECT_TYPE_SPECIAL: return yaffs_DoGenericObjectDeletion(obj); break; case YAFFS_OBJECT_TYPE_HARDLINK: case YAFFS_OBJECT_TYPE_UNKNOWN: default: return YAFFS_FAIL; } } } static int yaffs_UnlinkObject( yaffs_Object *obj) { if (obj && obj->unlinkAllowed) { return yaffs_UnlinkWorker(obj); } return YAFFS_FAIL; } int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name) { yaffs_Object *obj; obj = yaffs_FindObjectByName(dir, name); return yaffs_UnlinkObject(obj); } /*----------------------- Initialisation Scanning ---------------------- */ static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId, int backwardScanning) { yaffs_Object *obj; if (!backwardScanning) { /* Handle YAFFS1 forward scanning case * For YAFFS1 we always do the deletion */ } else { /* Handle YAFFS2 case (backward scanning) * If the shadowed object exists then ignore. */ if (yaffs_FindObjectByNumber(dev, objId)) { return; } } /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc. * We put it in unlinked dir to be cleaned up after the scanning */ obj = yaffs_FindOrCreateObjectByNumber(dev, objId, YAFFS_OBJECT_TYPE_FILE); yaffs_AddObjectToDirectory(dev->unlinkedDir, obj); obj->variant.fileVariant.shrinkSize = 0; obj->valid = 1; /* So that we don't read any other info for this file */ } typedef struct { int seq; int block; } yaffs_BlockIndex; static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList) { yaffs_Object *hl; yaffs_Object *in; while (hardList) { hl = hardList; hardList = (yaffs_Object *) (hardList->hardLinks.next); in = yaffs_FindObjectByNumber(dev, hl->variant.hardLinkVariant. equivalentObjectId); if (in) { /* Add the hardlink pointers */ hl->variant.hardLinkVariant.equivalentObject = in; list_add(&hl->hardLinks, &in->hardLinks); } else { /* Todo Need to report/handle this better. * Got a problem... hardlink to a non-existant object */ hl->variant.hardLinkVariant.equivalentObject = NULL; INIT_LIST_HEAD(&hl->hardLinks); } } } static int ybicmp(const void *a, const void *b){ register int aseq = ((yaffs_BlockIndex *)a)->seq; register int bseq = ((yaffs_BlockIndex *)b)->seq; register int ablock = ((yaffs_BlockIndex *)a)->block; register int bblock = ((yaffs_BlockIndex *)b)->block; if( aseq == bseq ) return ablock - bblock; else return aseq - bseq; } static int yaffs_Scan(yaffs_Device * dev) { yaffs_ExtendedTags tags; int blk; int blockIterator; int startIterator; int endIterator; int nBlocksToScan = 0; int chunk; int c; int deleted; yaffs_BlockState state; yaffs_Object *hardList = NULL; yaffs_BlockInfo *bi; int sequenceNumber; yaffs_ObjectHeader *oh; yaffs_Object *in; yaffs_Object *parent; int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1; int alloc_failed = 0; __u8 *chunkData; yaffs_BlockIndex *blockIndex = NULL; if (dev->isYaffs2) { T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR))); return YAFFS_FAIL; } //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format. T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR), dev->internalStartBlock, dev->internalEndBlock)); chunkData = yaffs_GetTempBuffer(dev, __LINE__); dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER; if (dev->isYaffs2) { blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex)); if(!blockIndex) return YAFFS_FAIL; } /* Scan all the blocks to determine their state */ for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) { bi = yaffs_GetBlockInfo(dev, blk); yaffs_ClearChunkBits(dev, blk); bi->pagesInUse = 0; bi->softDeletions = 0; yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber); bi->blockState = state; bi->sequenceNumber = sequenceNumber; T(YAFFS_TRACE_SCAN_DEBUG, (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk, state, sequenceNumber)); if (state == YAFFS_BLOCK_STATE_DEAD) { T(YAFFS_TRACE_BAD_BLOCKS, (TSTR("block %d is bad" TENDSTR), blk)); } else if (state == YAFFS_BLOCK_STATE_EMPTY) { T(YAFFS_TRACE_SCAN_DEBUG, (TSTR("Block empty " TENDSTR))); dev->nErasedBlocks++; dev->nFreeChunks += dev->nChunksPerBlock; } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) { /* Determine the highest sequence number */ if (dev->isYaffs2 && sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER && sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) { blockIndex[nBlocksToScan].seq = sequenceNumber; blockIndex[nBlocksToScan].block = blk; nBlocksToScan++; if (sequenceNumber >= dev->sequenceNumber) { dev->sequenceNumber = sequenceNumber; } } else if (dev->isYaffs2) { /* TODO: Nasty sequence number! */ T(YAFFS_TRACE_SCAN, (TSTR ("Block scanning block %d has bad sequence number %d" TENDSTR), blk, sequenceNumber)); } } } /* Sort the blocks * Dungy old bubble sort for now... */ if (dev->isYaffs2) { yaffs_BlockIndex temp; int i; int j; for (i = 0; i < nBlocksToScan; i++) for (j = i + 1; j < nBlocksToScan; j++) if (blockIndex[i].seq > blockIndex[j].seq) { temp = blockIndex[j]; blockIndex[j] = blockIndex[i]; blockIndex[i] = temp; } } /* Now scan the blocks looking at the data. */ if (dev->isYaffs2) { startIterator = 0; endIterator = nBlocksToScan - 1; T(YAFFS_TRACE_SCAN_DEBUG, (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan)); } else { startIterator = dev->internalStartBlock; endIterator = dev->internalEndBlock; } /* For each block.... */ for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator; blockIterator++) { if (dev->isYaffs2) { /* get the block to scan in the correct order */ blk = blockIndex[blockIterator].block; } else { blk = blockIterator; } bi = yaffs_GetBlockInfo(dev, blk); state = bi->blockState; deleted = 0; /* For each chunk in each block that needs scanning....*/ for (c = 0; !alloc_failed && c < dev->nChunksPerBlock && state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) { /* Read the tags and decide what to do */ chunk = blk * dev->nChunksPerBlock + c; yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL, &tags); /* Let's have a good look at this chunk... */ if (!dev->isYaffs2 && tags.chunkDeleted) { /* YAFFS1 only... * A deleted chunk */ deleted++; dev->nFreeChunks++; /*T((" %d %d deleted\n",blk,c)); */ } else if (!tags.chunkUsed) { /* An unassigned chunk in the block * This means that either the block is empty or * this is the one being allocated from */ if (c == 0) { /* We're looking at the first chunk in the block so the block is unused */ state = YAFFS_BLOCK_STATE_EMPTY; dev->nErasedBlocks++; } else { /* this is the block being allocated from */ T(YAFFS_TRACE_SCAN, (TSTR (" Allocating from %d %d" TENDSTR), blk, c)); state = YAFFS_BLOCK_STATE_ALLOCATING; dev->allocationBlock = blk; dev->allocationPage = c; dev->allocationBlockFinder = blk; /* Set it to here to encourage the allocator to go forth from here. */ /* Yaffs2 sanity check: * This should be the one with the highest sequence number */ if (dev->isYaffs2 && (dev->sequenceNumber != bi->sequenceNumber)) { T(YAFFS_TRACE_ALWAYS, (TSTR ("yaffs: Allocation block %d was not highest sequence id:" " block seq = %d, dev seq = %d" TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber)); } } dev->nFreeChunks += (dev->nChunksPerBlock - c); } else if (tags.chunkId > 0) { /* chunkId > 0 so it is a data chunk... */ unsigned int endpos; yaffs_SetChunkBit(dev, blk, c); bi->pagesInUse++; in = yaffs_FindOrCreateObjectByNumber(dev, tags. objectId, YAFFS_OBJECT_TYPE_FILE); /* PutChunkIntoFile checks for a clash (two data chunks with * the same chunkId). */ if(!in) alloc_failed = 1; if(in){ if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1)) alloc_failed = 1; } endpos = (tags.chunkId - 1) * dev->nDataBytesPerChunk + tags.byteCount; if (in && in->variantType == YAFFS_OBJECT_TYPE_FILE && in->variant.fileVariant.scannedFileSize < endpos) { in->variant.fileVariant. scannedFileSize = endpos; if (!dev->useHeaderFileSize) { in->variant.fileVariant. fileSize = in->variant.fileVariant. scannedFileSize; } } /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */ } else { /* chunkId == 0, so it is an ObjectHeader. * Thus, we read in the object header and make the object */ yaffs_SetChunkBit(dev, blk, c); bi->pagesInUse++; yaffs_ReadChunkWithTagsFromNAND(dev, chunk, chunkData, NULL); oh = (yaffs_ObjectHeader *) chunkData; in = yaffs_FindObjectByNumber(dev, tags.objectId); if (in && in->variantType != oh->type) { /* This should not happen, but somehow * Wev'e ended up with an objectId that has been reused but not yet * deleted, and worse still it has changed type. Delete the old object. */ yaffs_DestroyObject(in); in = 0; } in = yaffs_FindOrCreateObjectByNumber(dev, tags. objectId, oh->type); if(!in) alloc_failed = 1; if (in && oh->shadowsObject > 0) { yaffs_HandleShadowedObject(dev, oh-> shadowsObject, 0); } if (in && in->valid) { /* We have already filled this one. We have a duplicate and need to resolve it. */ unsigned existingSerial = in->serial; unsigned newSerial = tags.serialNumber; if (dev->isYaffs2 || ((existingSerial + 1) & 3) == newSerial) { /* Use new one - destroy the exisiting one */ yaffs_DeleteChunk(dev, in->chunkId, 1, __LINE__); in->valid = 0; } else { /* Use existing - destroy this one. */ yaffs_DeleteChunk(dev, chunk, 1, __LINE__); } } if (in && !in->valid && (tags.objectId == YAFFS_OBJECTID_ROOT || tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) { /* We only load some info, don't fiddle with directory structure */ in->valid = 1; in->variantType = oh->type; in->yst_mode = oh->yst_mode; #ifdef CONFIG_YAFFS_WINCE in->win_atime[0] = oh->win_atime[0]; in->win_ctime[0] = oh->win_ctime[0]; in->win_mtime[0] = oh->win_mtime[0]; in->win_atime[1] = oh->win_atime[1]; in->win_ctime[1] = oh->win_ctime[1]; in->win_mtime[1] = oh->win_mtime[1]; #else in->yst_uid = oh->yst_uid; in->yst_gid = oh->yst_gid; in->yst_atime = oh->yst_atime; in->yst_mtime = oh->yst_mtime; in->yst_ctime = oh->yst_ctime; in->yst_rdev = oh->yst_rdev; #endif in->chunkId = chunk; } else if (in && !in->valid) { /* we need to load this info */ in->valid = 1; in->variantType = oh->type; in->yst_mode = oh->yst_mode; #ifdef CONFIG_YAFFS_WINCE in->win_atime[0] = oh->win_atime[0]; in->win_ctime[0] = oh->win_ctime[0]; in->win_mtime[0] = oh->win_mtime[0]; in->win_atime[1] = oh->win_atime[1]; in->win_ctime[1] = oh->win_ctime[1]; in->win_mtime[1] = oh->win_mtime[1]; #else in->yst_uid = oh->yst_uid; in->yst_gid = oh->yst_gid; in->yst_atime = oh->yst_atime; in->yst_mtime = oh->yst_mtime; in->yst_ctime = oh->yst_ctime; in->yst_rdev = oh->yst_rdev; #endif in->chunkId = chunk; yaffs_SetObjectName(in, oh->name); in->dirty = 0; /* directory stuff... * hook up to parent */ parent = yaffs_FindOrCreateObjectByNumber (dev, oh->parentObjectId, YAFFS_OBJECT_TYPE_DIRECTORY); if (parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN) { /* Set up as a directory */ parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY; INIT_LIST_HEAD(&parent->variant. directoryVariant. children); } else if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) { /* Hoosterman, another problem.... * We're trying to use a non-directory as a directory */ T(YAFFS_TRACE_ERROR, (TSTR ("yaffs tragedy: attempting to use non-directory as" " a directory in scan. Put in lost+found." TENDSTR))); parent = dev->lostNFoundDir; } yaffs_AddObjectToDirectory(parent, in); if (0 && (parent == dev->deletedDir || parent == dev->unlinkedDir)) { in->deleted = 1; /* If it is unlinked at start up then it wants deleting */ dev->nDeletedFiles++; } /* Note re hardlinks. * Since we might scan a hardlink before its equivalent object is scanned * we put them all in a list. * After scanning is complete, we should have all the objects, so we run through this * list and fix up all the chains. */ switch (in->variantType) { case YAFFS_OBJECT_TYPE_UNKNOWN: /* Todo got a problem */ break; case YAFFS_OBJECT_TYPE_FILE: if (dev->isYaffs2 && oh->isShrink) { /* Prune back the shrunken chunks */ yaffs_PruneResizedChunks (in, oh->fileSize); /* Mark the block as having a shrinkHeader */ bi->hasShrinkHeader = 1; } if (dev->useHeaderFileSize) in->variant.fileVariant. fileSize = oh->fileSize; break; case YAFFS_OBJECT_TYPE_HARDLINK: in->variant.hardLinkVariant. equivalentObjectId = oh->equivalentObjectId; in->hardLinks.next = (struct list_head *) hardList; hardList = in; break; case YAFFS_OBJECT_TYPE_DIRECTORY: /* Do nothing */ break; case YAFFS_OBJECT_TYPE_SPECIAL: /* Do nothing */ break; case YAFFS_OBJECT_TYPE_SYMLINK: in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias); if(!in->variant.symLinkVariant.alias) alloc_failed = 1; break; } if (parent == dev->deletedDir) { yaffs_DestroyObject(in); bi->hasShrinkHeader = 1; } } } } if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) { /* If we got this far while scanning, then the block is fully allocated.*/ state = YAFFS_BLOCK_STATE_FULL; } bi->blockState = state; /* Now let's see if it was dirty */ if (bi->pagesInUse == 0 && !bi->hasShrinkHeader && bi->blockState == YAFFS_BLOCK_STATE_FULL) { yaffs_BlockBecameDirty(dev, blk); } } if (blockIndex) { YFREE(blockIndex); } /* Ok, we've done all the scanning. * Fix up the hard link chains. * We should now have scanned all the objects, now it's time to add these * hardlinks. */ yaffs_HardlinkFixup(dev,hardList); /* Handle the unlinked files. Since they were left in an unlinked state we should * just delete them. */ { struct list_head *i; struct list_head *n; yaffs_Object *l; /* Soft delete all the unlinked files */ list_for_each_safe(i, n, &dev->unlinkedDir->variant.directoryVariant. children) { if (i) { l = list_entry(i, yaffs_Object, siblings); yaffs_DestroyObject(l); } } } yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__); if(alloc_failed){ return YAFFS_FAIL; } T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR))); return YAFFS_OK; } static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in) { __u8 *chunkData; yaffs_ObjectHeader *oh; yaffs_Device *dev = in->myDev; yaffs_ExtendedTags tags; if(!in) return; #if 0 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR), in->objectId, in->lazyLoaded ? "not yet" : "already")); #endif if(in->lazyLoaded){ in->lazyLoaded = 0; chunkData = yaffs_GetTempBuffer(dev, __LINE__); yaffs_ReadChunkWithTagsFromNAND(dev, in->chunkId, chunkData, &tags); oh = (yaffs_ObjectHeader *) chunkData; in->yst_mode = oh->yst_mode; #ifdef CONFIG_YAFFS_WINCE in->win_atime[0] = oh->win_atime[0]; in->win_ctime[0] = oh->win_ctime[0]; in->win_mtime[0] = oh->win_mtime[0]; in->win_atime[1] = oh->win_atime[1]; in->win_ctime[1] = oh->win_ctime[1]; in->win_mtime[1] = oh->win_mtime[1]; #else in->yst_uid = oh->yst_uid; in->yst_gid = oh->yst_gid; in->yst_atime = oh->yst_atime; in->yst_mtime = oh->yst_mtime; in->yst_ctime = oh->yst_ctime; in->yst_rdev = oh->yst_rdev; #endif yaffs_SetObjectName(in, oh->name); if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){ in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias); } yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__); } } static int yaffs_ScanBackwards(yaffs_Device * dev) { yaffs_ExtendedTags tags; int blk; int blockIterator; int startIterator; int endIterator; int nBlocksToScan = 0; int chunk; int c; yaffs_BlockState state; yaffs_Object *hardList = NULL; yaffs_BlockInfo *bi; int sequenceNumber; yaffs_ObjectHeader *oh; yaffs_Object *in; yaffs_Object *parent; int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1; int itsUnlinked; __u8 *chunkData; int fileSize; int isShrink; int foundChunksInBlock; int equivalentObjectId; int alloc_failed = 0; yaffs_BlockIndex *blockIndex = NULL; int altBlockIndex = 0; if (!dev->isYaffs2) { T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR))); return YAFFS_FAIL; } T(YAFFS_TRACE_SCAN, (TSTR ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..." TENDSTR), dev->internalStartBlock, dev->internalEndBlock)); dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER; blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex)); if(!blockIndex) { blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex)); altBlockIndex = 1; } if(!blockIndex) { T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR))); return YAFFS_FAIL; } dev->blocksInCheckpoint = 0; chunkData = yaffs_GetTempBuffer(dev, __LINE__); /* Scan all the blocks to determine their state */ for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) { bi = yaffs_GetBlockInfo(dev, blk); yaffs_ClearChunkBits(dev, blk); bi->pagesInUse = 0; bi->softDeletions = 0; yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber); bi->blockState = state; bi->sequenceNumber = sequenceNumber; if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA) bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT; T(YAFFS_TRACE_SCAN_DEBUG, (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk, state, sequenceNumber)); if(state == YAFFS_BLOCK_STATE_CHECKPOINT){ dev->blocksInCheckpoint++; } else if (state == YAFFS_BLOCK_STATE_DEAD) { T(YAFFS_TRACE_BAD_BLOCKS, (TSTR("block %d is bad" TENDSTR), blk)); } else if (state == YAFFS_BLOCK_STATE_EMPTY) { T(YAFFS_TRACE_SCAN_DEBUG, (TSTR("Block empty " TENDSTR))); dev->nErasedBlocks++; dev->nFreeChunks += dev->nChunksPerBlock; } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) { /* Determine the highest sequence number */ if (dev->isYaffs2 && sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER && sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) { blockIndex[nBlocksToScan].seq = sequenceNumber; blockIndex[nBlocksToScan].block = blk; nBlocksToScan++; if (sequenceNumber >= dev->sequenceNumber) { dev->sequenceNumber = sequenceNumber; } } else if (dev->isYaffs2) { /* TODO: Nasty sequence number! */ T(YAFFS_TRACE_SCAN, (TSTR ("Block scanning block %d has bad sequence number %d" TENDSTR), blk, sequenceNumber)); } } } T(YAFFS_TRACE_SCAN, (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan)); YYIELD(); /* Sort the blocks */ #ifndef CONFIG_YAFFS_USE_OWN_SORT { /* Use qsort now. */ yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp); } #else { /* Dungy old bubble sort... */ yaffs_BlockIndex temp; int i; int j; for (i = 0; i < nBlocksToScan; i++) for (j = i + 1; j < nBlocksToScan; j++) if (blockIndex[i].seq > blockIndex[j].seq) { temp = blockIndex[j]; blockIndex[j] = blockIndex[i]; blockIndex[i] = temp; } } #endif YYIELD(); T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR))); /* Now scan the blocks looking at the data. */ startIterator = 0; endIterator = nBlocksToScan - 1; T(YAFFS_TRACE_SCAN_DEBUG, (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan)); /* For each block.... backwards */ for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator; blockIterator--) { /* Cooperative multitasking! This loop can run for so long that watchdog timers expire. */ YYIELD(); /* get the block to scan in the correct order */ blk = blockIndex[blockIterator].block; bi = yaffs_GetBlockInfo(dev, blk); state = bi->blockState; /* For each chunk in each block that needs scanning.... */ foundChunksInBlock = 0; for (c = dev->nChunksPerBlock - 1; !alloc_failed && c >= 0 && (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING || state == YAFFS_BLOCK_STATE_ALLOCATING); c--) { /* Scan backwards... * Read the tags and decide what to do */ chunk = blk * dev->nChunksPerBlock + c; yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL, &tags); /* Let's have a good look at this chunk... */ if (!tags.chunkUsed) { /* An unassigned chunk in the block. * If there are used chunks after this one, then * it is a chunk that was skipped due to failing the erased * check. Just skip it so that it can be deleted. * But, more typically, We get here when this is an unallocated * chunk and his means that either the block is empty or * this is the one being allocated from */ if(foundChunksInBlock) { /* This is a chunk that was skipped due to failing the erased check */ } else if (c == 0) { /* We're looking at the first chunk in the block so the block is unused */ state = YAFFS_BLOCK_STATE_EMPTY; dev->nErasedBlocks++; } else { if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING || state == YAFFS_BLOCK_STATE_ALLOCATING) { if(dev->sequenceNumber == bi->sequenceNumber) { /* this is the block being allocated from */ T(YAFFS_TRACE_SCAN, (TSTR (" Allocating from %d %d" TENDSTR), blk, c)); state = YAFFS_BLOCK_STATE_ALLOCATING; dev->allocationBlock = blk; dev->allocationPage = c; dev->allocationBlockFinder = blk; } else { /* This is a partially written block that is not * the current allocation block. This block must have * had a write failure, so set up for retirement. */ bi->needsRetiring = 1; bi->gcPrioritise = 1; T(YAFFS_TRACE_ALWAYS, (TSTR("Partially written block %d being set for retirement" TENDSTR), blk)); } } } dev->nFreeChunks++; } else if (tags.chunkId > 0) { /* chunkId > 0 so it is a data chunk... */ unsigned int endpos; __u32 chunkBase = (tags.chunkId - 1) * dev->nDataBytesPerChunk; foundChunksInBlock = 1; yaffs_SetChunkBit(dev, blk, c); bi->pagesInUse++; in = yaffs_FindOrCreateObjectByNumber(dev, tags. objectId, YAFFS_OBJECT_TYPE_FILE); if(!in){ /* Out of memory */ alloc_failed = 1; } if (in && in->variantType == YAFFS_OBJECT_TYPE_FILE && chunkBase < in->variant.fileVariant.shrinkSize) { /* This has not been invalidated by a resize */ if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)){ alloc_failed = 1; } /* File size is calculated by looking at the data chunks if we have not * seen an object header yet. Stop this practice once we find an object header. */ endpos = (tags.chunkId - 1) * dev->nDataBytesPerChunk + tags.byteCount; if (!in->valid && /* have not got an object header yet */ in->variant.fileVariant. scannedFileSize < endpos) { in->variant.fileVariant. scannedFileSize = endpos; in->variant.fileVariant. fileSize = in->variant.fileVariant. scannedFileSize; } } else if(in) { /* This chunk has been invalidated by a resize, so delete */ yaffs_DeleteChunk(dev, chunk, 1, __LINE__); } } else { /* chunkId == 0, so it is an ObjectHeader. * Thus, we read in the object header and make the object */ foundChunksInBlock = 1; yaffs_SetChunkBit(dev, blk, c); bi->pagesInUse++; oh = NULL; in = NULL; if (tags.extraHeaderInfoAvailable) { in = yaffs_FindOrCreateObjectByNumber (dev, tags.objectId, tags.extraObjectType); } if (!in || #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD !in->valid || #endif tags.extraShadows || (!in->valid && (tags.objectId == YAFFS_OBJECTID_ROOT || tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) ) { /* If we don't have valid info then we need to read the chunk * TODO In future we can probably defer reading the chunk and * living with invalid data until needed. */ yaffs_ReadChunkWithTagsFromNAND(dev, chunk, chunkData, NULL); oh = (yaffs_ObjectHeader *) chunkData; if (!in) in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type); } if (!in) { /* TODO Hoosterman we have a problem! */ T(YAFFS_TRACE_ERROR, (TSTR ("yaffs tragedy: Could not make object for object %d " "at chunk %d during scan" TENDSTR), tags.objectId, chunk)); } if (in->valid) { /* We have already filled this one. * We have a duplicate that will be discarded, but * we first have to suck out resize info if it is a file. */ if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) && ((oh && oh-> type == YAFFS_OBJECT_TYPE_FILE)|| (tags.extraHeaderInfoAvailable && tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE)) ) { __u32 thisSize = (oh) ? oh->fileSize : tags. extraFileLength; __u32 parentObjectId = (oh) ? oh-> parentObjectId : tags. extraParentObjectId; unsigned isShrink = (oh) ? oh->isShrink : tags. extraIsShrinkHeader; /* If it is deleted (unlinked at start also means deleted) * we treat the file size as being zeroed at this point. */ if (parentObjectId == YAFFS_OBJECTID_DELETED || parentObjectId == YAFFS_OBJECTID_UNLINKED) { thisSize = 0; isShrink = 1; } if (isShrink && in->variant.fileVariant. shrinkSize > thisSize) { in->variant.fileVariant. shrinkSize = thisSize; } if (isShrink) { bi->hasShrinkHeader = 1; } } /* Use existing - destroy this one. */ yaffs_DeleteChunk(dev, chunk, 1, __LINE__); } if (!in->valid && (tags.objectId == YAFFS_OBJECTID_ROOT || tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) { /* We only load some info, don't fiddle with directory structure */ in->valid = 1; if(oh) { in->variantType = oh->type; in->yst_mode = oh->yst_mode; #ifdef CONFIG_YAFFS_WINCE in->win_atime[0] = oh->win_atime[0]; in->win_ctime[0] = oh->win_ctime[0]; in->win_mtime[0] = oh->win_mtime[0]; in->win_atime[1] = oh->win_atime[1]; in->win_ctime[1] = oh->win_ctime[1]; in->win_mtime[1] = oh->win_mtime[1]; #else in->yst_uid = oh->yst_uid; in->yst_gid = oh->yst_gid; in->yst_atime = oh->yst_atime; in->yst_mtime = oh->yst_mtime; in->yst_ctime = oh->yst_ctime; in->yst_rdev = oh->yst_rdev; #endif } else { in->variantType = tags.extraObjectType; in->lazyLoaded = 1; } in->chunkId = chunk; } else if (!in->valid) { /* we need to load this info */ in->valid = 1; in->chunkId = chunk; if(oh) { in->variantType = oh->type; in->yst_mode = oh->yst_mode; #ifdef CONFIG_YAFFS_WINCE in->win_atime[0] = oh->win_atime[0]; in->win_ctime[0] = oh->win_ctime[0]; in->win_mtime[0] = oh->win_mtime[0]; in->win_atime[1] = oh->win_atime[1]; in->win_ctime[1] = oh->win_ctime[1]; in->win_mtime[1] = oh->win_mtime[1]; #else in->yst_uid = oh->yst_uid; in->yst_gid = oh->yst_gid; in->yst_atime = oh->yst_atime; in->yst_mtime = oh->yst_mtime; in->yst_ctime = oh->yst_ctime; in->yst_rdev = oh->yst_rdev; #endif if (oh->shadowsObject > 0) yaffs_HandleShadowedObject(dev, oh-> shadowsObject, 1); yaffs_SetObjectName(in, oh->name); parent = yaffs_FindOrCreateObjectByNumber (dev, oh->parentObjectId, YAFFS_OBJECT_TYPE_DIRECTORY); fileSize = oh->fileSize; isShrink = oh->isShrink; equivalentObjectId = oh->equivalentObjectId; } else { in->variantType = tags.extraObjectType; parent = yaffs_FindOrCreateObjectByNumber (dev, tags.extraParentObjectId, YAFFS_OBJECT_TYPE_DIRECTORY); fileSize = tags.extraFileLength; isShrink = tags.extraIsShrinkHeader; equivalentObjectId = tags.extraEquivalentObjectId; in->lazyLoaded = 1; } in->dirty = 0; /* directory stuff... * hook up to parent */ if (parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN) { /* Set up as a directory */ parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY; INIT_LIST_HEAD(&parent->variant. directoryVariant. children); } else if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) { /* Hoosterman, another problem.... * We're trying to use a non-directory as a directory */ T(YAFFS_TRACE_ERROR, (TSTR ("yaffs tragedy: attempting to use non-directory as" " a directory in scan. Put in lost+found." TENDSTR))); parent = dev->lostNFoundDir; } yaffs_AddObjectToDirectory(parent, in); itsUnlinked = (parent == dev->deletedDir) || (parent == dev->unlinkedDir); if (isShrink) { /* Mark the block as having a shrinkHeader */ bi->hasShrinkHeader = 1; } /* Note re hardlinks. * Since we might scan a hardlink before its equivalent object is scanned * we put them all in a list. * After scanning is complete, we should have all the objects, so we run * through this list and fix up all the chains. */ switch (in->variantType) { case YAFFS_OBJECT_TYPE_UNKNOWN: /* Todo got a problem */ break; case YAFFS_OBJECT_TYPE_FILE: if (in->variant.fileVariant. scannedFileSize < fileSize) { /* This covers the case where the file size is greater * than where the data is * This will happen if the file is resized to be larger * than its current data extents. */ in->variant.fileVariant.fileSize = fileSize; in->variant.fileVariant.scannedFileSize = in->variant.fileVariant.fileSize; } if (isShrink && in->variant.fileVariant.shrinkSize > fileSize) { in->variant.fileVariant.shrinkSize = fileSize; } break; case YAFFS_OBJECT_TYPE_HARDLINK: if(!itsUnlinked) { in->variant.hardLinkVariant.equivalentObjectId = equivalentObjectId; in->hardLinks.next = (struct list_head *) hardList; hardList = in; } break; case YAFFS_OBJECT_TYPE_DIRECTORY: /* Do nothing */ break; case YAFFS_OBJECT_TYPE_SPECIAL: /* Do nothing */ break; case YAFFS_OBJECT_TYPE_SYMLINK: if(oh){ in->variant.symLinkVariant.alias = yaffs_CloneString(oh-> alias); if(!in->variant.symLinkVariant.alias) alloc_failed = 1; } break; } } } } /* End of scanning for each chunk */ if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) { /* If we got this far while scanning, then the block is fully allocated. */ state = YAFFS_BLOCK_STATE_FULL; } bi->blockState = state; /* Now let's see if it was dirty */ if (bi->pagesInUse == 0 && !bi->hasShrinkHeader && bi->blockState == YAFFS_BLOCK_STATE_FULL) { yaffs_BlockBecameDirty(dev, blk); } } if (altBlockIndex) YFREE_ALT(blockIndex); else YFREE(blockIndex); /* Ok, we've done all the scanning. * Fix up the hard link chains. * We should now have scanned all the objects, now it's time to add these * hardlinks. */ yaffs_HardlinkFixup(dev,hardList); /* * Sort out state of unlinked and deleted objects. */ { struct list_head *i; struct list_head *n; yaffs_Object *l; /* Soft delete all the unlinked files */ list_for_each_safe(i, n, &dev->unlinkedDir->variant.directoryVariant. children) { if (i) { l = list_entry(i, yaffs_Object, siblings); yaffs_DestroyObject(l); } } /* Soft delete all the deletedDir files */ list_for_each_safe(i, n, &dev->deletedDir->variant.directoryVariant. children) { if (i) { l = list_entry(i, yaffs_Object, siblings); yaffs_DestroyObject(l); } } } yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__); if(alloc_failed){ return YAFFS_FAIL; } T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR))); return YAFFS_OK; } /*------------------------------ Directory Functions ----------------------------- */ static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj) { yaffs_Device *dev = obj->myDev; if(dev && dev->removeObjectCallback) dev->removeObjectCallback(obj); list_del_init(&obj->siblings); obj->parent = NULL; } static void yaffs_AddObjectToDirectory(yaffs_Object * directory, yaffs_Object * obj) { if (!directory) { T(YAFFS_TRACE_ALWAYS, (TSTR ("tragedy: Trying to add an object to a null pointer directory" TENDSTR))); YBUG(); } if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) { T(YAFFS_TRACE_ALWAYS, (TSTR ("tragedy: Trying to add an object to a non-directory" TENDSTR))); YBUG(); } if (obj->siblings.prev == NULL) { /* Not initialised */ INIT_LIST_HEAD(&obj->siblings); } else if (!list_empty(&obj->siblings)) { /* If it is holed up somewhere else, un hook it */ yaffs_RemoveObjectFromDirectory(obj); } /* Now add it */ list_add(&obj->siblings, &directory->variant.directoryVariant.children); obj->parent = directory; if (directory == obj->myDev->unlinkedDir || directory == obj->myDev->deletedDir) { obj->unlinked = 1; obj->myDev->nUnlinkedFiles++; obj->renameAllowed = 0; } } yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory, const YCHAR * name) { int sum; struct list_head *i; YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1]; yaffs_Object *l; if (!name) { return NULL; } if (!directory) { T(YAFFS_TRACE_ALWAYS, (TSTR ("tragedy: yaffs_FindObjectByName: null pointer directory" TENDSTR))); YBUG(); } if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) { T(YAFFS_TRACE_ALWAYS, (TSTR ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR))); YBUG(); } sum = yaffs_CalcNameSum(name); list_for_each(i, &directory->variant.directoryVariant.children) { if (i) { l = list_entry(i, yaffs_Object, siblings); yaffs_CheckObjectDetailsLoaded(l); /* Special case for lost-n-found */ if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) { if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) { return l; } } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0) { /* LostnFound cunk called Objxxx * Do a real check */ yaffs_GetObjectName(l, buffer, YAFFS_MAX_NAME_LENGTH); if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) { return l; } } } } return NULL; } #if 0 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir, int (*fn) (yaffs_Object *)) { struct list_head *i; yaffs_Object *l; if (!theDir) { T(YAFFS_TRACE_ALWAYS, (TSTR ("tragedy: yaffs_FindObjectByName: null pointer directory" TENDSTR))); YBUG(); } if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) { T(YAFFS_TRACE_ALWAYS, (TSTR ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR))); YBUG(); } list_for_each(i, &theDir->variant.directoryVariant.children) { if (i) { l = list_entry(i, yaffs_Object, siblings); if (l && !fn(l)) { return YAFFS_FAIL; } } } return YAFFS_OK; } #endif /* GetEquivalentObject dereferences any hard links to get to the * actual object. */ yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj) { if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) { /* We want the object id of the equivalent object, not this one */ obj = obj->variant.hardLinkVariant.equivalentObject; yaffs_CheckObjectDetailsLoaded(obj); } return obj; } int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize) { memset(name, 0, buffSize * sizeof(YCHAR)); yaffs_CheckObjectDetailsLoaded(obj); if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) { yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1); } else if (obj->chunkId <= 0) { YCHAR locName[20]; /* make up a name */ yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX, obj->objectId); yaffs_strncpy(name, locName, buffSize - 1); } #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM else if (obj->shortName[0]) { yaffs_strcpy(name, obj->shortName); } #endif else { __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__); yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer; memset(buffer, 0, obj->myDev->nDataBytesPerChunk); if (obj->chunkId >= 0) { yaffs_ReadChunkWithTagsFromNAND(obj->myDev, obj->chunkId, buffer, NULL); } yaffs_strncpy(name, oh->name, buffSize - 1); yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__); } return yaffs_strlen(name); } int yaffs_GetObjectFileLength(yaffs_Object * obj) { /* Dereference any hard linking */ obj = yaffs_GetEquivalentObject(obj); if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) { return obj->variant.fileVariant.fileSize; } if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) { return yaffs_strlen(obj->variant.symLinkVariant.alias); } else { /* Only a directory should drop through to here */ return obj->myDev->nDataBytesPerChunk; } } int yaffs_GetObjectLinkCount(yaffs_Object * obj) { int count = 0; struct list_head *i; if (!obj->unlinked) { count++; /* the object itself */ } list_for_each(i, &obj->hardLinks) { count++; /* add the hard links; */ } return count; } int yaffs_GetObjectInode(yaffs_Object * obj) { obj = yaffs_GetEquivalentObject(obj); return obj->objectId; } unsigned yaffs_GetObjectType(yaffs_Object * obj) { obj = yaffs_GetEquivalentObject(obj); switch (obj->variantType) { case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break; case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break; case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break; case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break; case YAFFS_OBJECT_TYPE_SPECIAL: if (S_ISFIFO(obj->yst_mode)) return DT_FIFO; if (S_ISCHR(obj->yst_mode)) return DT_CHR; if (S_ISBLK(obj->yst_mode)) return DT_BLK; if (S_ISSOCK(obj->yst_mode)) return DT_SOCK; default: return DT_REG; break; } } YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj) { obj = yaffs_GetEquivalentObject(obj); if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) { return yaffs_CloneString(obj->variant.symLinkVariant.alias); } else { return yaffs_CloneString(_Y("")); } } #ifndef CONFIG_YAFFS_WINCE int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr) { unsigned int valid = attr->ia_valid; if (valid & ATTR_MODE) obj->yst_mode = attr->ia_mode; if (valid & ATTR_UID) obj->yst_uid = attr->ia_uid; if (valid & ATTR_GID) obj->yst_gid = attr->ia_gid; if (valid & ATTR_ATIME) obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime); if (valid & ATTR_CTIME) obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime); if (valid & ATTR_MTIME) obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime); if (valid & ATTR_SIZE) yaffs_ResizeFile(obj, attr->ia_size); yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0); return YAFFS_OK; } int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr) { unsigned int valid = 0; attr->ia_mode = obj->yst_mode; valid |= ATTR_MODE; attr->ia_uid = obj->yst_uid; valid |= ATTR_UID; attr->ia_gid = obj->yst_gid; valid |= ATTR_GID; Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime; valid |= ATTR_ATIME; Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime; valid |= ATTR_CTIME; Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime; valid |= ATTR_MTIME; attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE; attr->ia_valid = valid; return YAFFS_OK; } #endif #if 0 int yaffs_DumpObject(yaffs_Object * obj) { YCHAR name[257]; yaffs_GetObjectName(obj, name, 256); T(YAFFS_TRACE_ALWAYS, (TSTR ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d" " chunk %d type %d size %d\n" TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj))); return YAFFS_OK; } #endif /*---------------------------- Initialisation code -------------------------------------- */ static int yaffs_CheckDevFunctions(const yaffs_Device * dev) { /* Common functions, gotta have */ if (!dev->eraseBlockInNAND || !dev->initialiseNAND) return 0; #ifdef CONFIG_YAFFS_YAFFS2 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */ if (dev->writeChunkWithTagsToNAND && dev->readChunkWithTagsFromNAND && !dev->writeChunkToNAND && !dev->readChunkFromNAND && dev->markNANDBlockBad && dev->queryNANDBlock) return 1; #endif /* Can use the "spare" style interface for yaffs1 */ if (!dev->isYaffs2 && !dev->writeChunkWithTagsToNAND && !dev->readChunkWithTagsFromNAND && dev->writeChunkToNAND && dev->readChunkFromNAND && !dev->markNANDBlockBad && !dev->queryNANDBlock) return 1; return 0; /* bad */ } static int yaffs_CreateInitialDirectories(yaffs_Device *dev) { /* Initialise the unlinked, deleted, root and lost and found directories */ dev->lostNFoundDir = dev->rootDir = NULL; dev->unlinkedDir = dev->deletedDir = NULL; dev->unlinkedDir = yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR); dev->deletedDir = yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR); dev->rootDir = yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT, YAFFS_ROOT_MODE | S_IFDIR); dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND, YAFFS_LOSTNFOUND_MODE | S_IFDIR); if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){ yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir); return YAFFS_OK; } return YAFFS_FAIL; } int yaffs_GutsInitialise(yaffs_Device * dev) { int init_failed = 0; unsigned x; int bits; T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR))); /* Check stuff that must be set */ if (!dev) { T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR))); return YAFFS_FAIL; } dev->internalStartBlock = dev->startBlock; dev->internalEndBlock = dev->endBlock; dev->blockOffset = 0; dev->chunkOffset = 0; dev->nFreeChunks = 0; if (dev->startBlock == 0) { dev->internalStartBlock = dev->startBlock + 1; dev->internalEndBlock = dev->endBlock + 1; dev->blockOffset = 1; dev->chunkOffset = dev->nChunksPerBlock; } /* Check geometry parameters. */ if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) || (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) || dev->nChunksPerBlock < 2 || dev->nReservedBlocks < 2 || dev->internalStartBlock <= 0 || dev->internalEndBlock <= 0 || dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small ) { T(YAFFS_TRACE_ALWAYS, (TSTR ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s " TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : "")); return YAFFS_FAIL; } if (yaffs_InitialiseNAND(dev) != YAFFS_OK) { T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: InitialiseNAND failed" TENDSTR))); return YAFFS_FAIL; } /* Got the right mix of functions? */ if (!yaffs_CheckDevFunctions(dev)) { /* Function missing */ T(YAFFS_TRACE_ALWAYS, (TSTR ("yaffs: device function(s) missing or wrong\n" TENDSTR))); return YAFFS_FAIL; } /* This is really a compilation check. */ if (!yaffs_CheckStructures()) { T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs_CheckStructures failed\n" TENDSTR))); return YAFFS_FAIL; } if (dev->isMounted) { T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: device already mounted\n" TENDSTR))); return YAFFS_FAIL; } /* Finished with most checks. One or two more checks happen later on too. */ dev->isMounted = 1; /* OK now calculate a few things for the device */ /* * Calculate all the chunk size manipulation numbers: */ /* Start off assuming it is a power of 2 */ dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk); dev->chunkMask = (1<<dev->chunkShift) - 1; if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){ /* Yes it is a power of 2, disable crumbs */ dev->crumbMask = 0; dev->crumbShift = 0; dev->crumbsPerChunk = 0; } else { /* Not a power of 2, use crumbs instead */ dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart)); dev->crumbMask = (1<<dev->crumbShift)-1; dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift); dev->chunkShift = 0; dev->chunkMask = 0; } /* * Calculate chunkGroupBits. * We need to find the next power of 2 > than internalEndBlock */ x = dev->nChunksPerBlock * (dev->internalEndBlock + 1); bits = ShiftsGE(x); /* Set up tnode width if wide tnodes are enabled. */ if(!dev->wideTnodesDisabled){ /* bits must be even so that we end up with 32-bit words */ if(bits & 1) bits++; if(bits < 16) dev->tnodeWidth = 16; else dev->tnodeWidth = bits; } else dev->tnodeWidth = 16; dev->tnodeMask = (1<<dev->tnodeWidth)-1; /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled), * so if the bitwidth of the * chunk range we're using is greater than 16 we need * to figure out chunk shift and chunkGroupSize */ if (bits <= dev->tnodeWidth) dev->chunkGroupBits = 0; else dev->chunkGroupBits = bits - dev->tnodeWidth; dev->chunkGroupSize = 1 << dev->chunkGroupBits; if (dev->nChunksPerBlock < dev->chunkGroupSize) { /* We have a problem because the soft delete won't work if * the chunk group size > chunks per block. * This can be remedied by using larger "virtual blocks". */ T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: chunk group too large\n" TENDSTR))); return YAFFS_FAIL; } /* OK, we've finished verifying the device, lets continue with initialisation */ /* More device initialisation */ dev->garbageCollections = 0; dev->passiveGarbageCollections = 0; dev->currentDirtyChecker = 0; dev->bufferedBlock = -1; dev->doingBufferedBlockRewrite = 0; dev->nDeletedFiles = 0; dev->nBackgroundDeletions = 0; dev->nUnlinkedFiles = 0; dev->eccFixed = 0; dev->eccUnfixed = 0; dev->tagsEccFixed = 0; dev->tagsEccUnfixed = 0; dev->nErasureFailures = 0; dev->nErasedBlocks = 0; dev->isDoingGC = 0; dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */ /* Initialise temporary buffers and caches. */ if(!yaffs_InitialiseTempBuffers(dev)) init_failed = 1; dev->srCache = NULL; dev->gcCleanupList = NULL; if (!init_failed && dev->nShortOpCaches > 0) { int i; __u8 *buf; int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache); if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) { dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES; } dev->srCache = YMALLOC(srCacheBytes); buf = (__u8 *)dev->srCache; if(dev->srCache) memset(dev->srCache,0,srCacheBytes); for (i = 0; i < dev->nShortOpCaches && buf; i++) { dev->srCache[i].object = NULL; dev->srCache[i].lastUse = 0; dev->srCache[i].dirty = 0; dev->srCache[i].data = buf = YMALLOC_DMA(dev->nDataBytesPerChunk); } if(!buf) init_failed = 1; dev->srLastUse = 0; } dev->cacheHits = 0; if(!init_failed){ dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32)); if(!dev->gcCleanupList) init_failed = 1; } if (dev->isYaffs2) { dev->useHeaderFileSize = 1; } if(!init_failed && !yaffs_InitialiseBlocks(dev)) init_failed = 1; yaffs_InitialiseTnodes(dev); yaffs_InitialiseObjects(dev); if(!init_failed && !yaffs_CreateInitialDirectories(dev)) init_failed = 1; if(!init_failed){ /* Now scan the flash. */ if (dev->isYaffs2) { if(yaffs_CheckpointRestore(dev)) { T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: restored from checkpoint" TENDSTR))); } else { /* Clean up the mess caused by an aborted checkpoint load * and scan backwards. */ yaffs_DeinitialiseBlocks(dev); yaffs_DeinitialiseTnodes(dev); yaffs_DeinitialiseObjects(dev); dev->nErasedBlocks = 0; dev->nFreeChunks = 0; dev->allocationBlock = -1; dev->allocationPage = -1; dev->nDeletedFiles = 0; dev->nUnlinkedFiles = 0; dev->nBackgroundDeletions = 0; dev->oldestDirtySequence = 0; if(!init_failed && !yaffs_InitialiseBlocks(dev)) init_failed = 1; yaffs_InitialiseTnodes(dev); yaffs_InitialiseObjects(dev); if(!init_failed && !yaffs_CreateInitialDirectories(dev)) init_failed = 1; if(!init_failed && !yaffs_ScanBackwards(dev)) init_failed = 1; } }else if(!yaffs_Scan(dev)) init_failed = 1; } if(init_failed){ /* Clean up the mess */ T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR))); yaffs_Deinitialise(dev); return YAFFS_FAIL; } /* Zero out stats */ dev->nPageReads = 0; dev->nPageWrites = 0; dev->nBlockErasures = 0; dev->nGCCopies = 0; dev->nRetriedWrites = 0; dev->nRetiredBlocks = 0; yaffs_VerifyFreeChunks(dev); yaffs_VerifyBlocks(dev); T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR))); return YAFFS_OK; } void yaffs_Deinitialise(yaffs_Device * dev) { if (dev->isMounted) { int i; yaffs_DeinitialiseBlocks(dev); yaffs_DeinitialiseTnodes(dev); yaffs_DeinitialiseObjects(dev); if (dev->nShortOpCaches > 0 && dev->srCache) { for (i = 0; i < dev->nShortOpCaches; i++) { if(dev->srCache[i].data) YFREE(dev->srCache[i].data); dev->srCache[i].data = NULL; } YFREE(dev->srCache); dev->srCache = NULL; } YFREE(dev->gcCleanupList); for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) { YFREE(dev->tempBuffer[i].buffer); } dev->isMounted = 0; } } static int yaffs_CountFreeChunks(yaffs_Device * dev) { int nFree; int b; yaffs_BlockInfo *blk; for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) { blk = yaffs_GetBlockInfo(dev, b); switch (blk->blockState) { case YAFFS_BLOCK_STATE_EMPTY: case YAFFS_BLOCK_STATE_ALLOCATING: case YAFFS_BLOCK_STATE_COLLECTING: case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse + blk->softDeletions); break; default: break; } } return nFree; } int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev) { /* This is what we report to the outside world */ int nFree; int nDirtyCacheChunks; int blocksForCheckpoint; #if 1 nFree = dev->nFreeChunks; #else nFree = yaffs_CountFreeChunks(dev); #endif nFree += dev->nDeletedFiles; /* Now count the number of dirty chunks in the cache and subtract those */ { int i; for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) { if (dev->srCache[i].dirty) nDirtyCacheChunks++; } } nFree -= nDirtyCacheChunks; nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock); /* Now we figure out how much to reserve for the checkpoint and report that... */ blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint; if(blocksForCheckpoint < 0) blocksForCheckpoint = 0; nFree -= (blocksForCheckpoint * dev->nChunksPerBlock); if (nFree < 0) nFree = 0; return nFree; } static int yaffs_freeVerificationFailures; static void yaffs_VerifyFreeChunks(yaffs_Device * dev) { int counted; int difference; if(yaffs_SkipVerification(dev)) return; counted = yaffs_CountFreeChunks(dev); difference = dev->nFreeChunks - counted; if (difference) { T(YAFFS_TRACE_ALWAYS, (TSTR("Freechunks verification failure %d %d %d" TENDSTR), dev->nFreeChunks, counted, difference)); yaffs_freeVerificationFailures++; } } /*---------------------------------------- YAFFS test code ----------------------*/ #define yaffs_CheckStruct(structure,syze, name) \ if(sizeof(structure) != syze) \ { \ T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\ name,syze,sizeof(structure))); \ return YAFFS_FAIL; \ } static int yaffs_CheckStructures(void) { /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */ /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */ /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */ #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode") #endif yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader") return YAFFS_OK; }
1001-study-uboot
fs/yaffs2/yaffs_guts.c
C
gpl3
178,923
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> #include "yaffs_packedtags1.h" #include "yportenv.h" void yaffs_PackTags1(yaffs_PackedTags1 * pt, const yaffs_ExtendedTags * t) { pt->chunkId = t->chunkId; pt->serialNumber = t->serialNumber; pt->byteCount = t->byteCount; pt->objectId = t->objectId; pt->ecc = 0; pt->deleted = (t->chunkDeleted) ? 0 : 1; pt->unusedStuff = 0; pt->shouldBeFF = 0xFFFFFFFF; } void yaffs_UnpackTags1(yaffs_ExtendedTags * t, const yaffs_PackedTags1 * pt) { static const __u8 allFF[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; if (memcmp(allFF, pt, sizeof(yaffs_PackedTags1))) { t->blockBad = 0; if (pt->shouldBeFF != 0xFFFFFFFF) { t->blockBad = 1; } t->chunkUsed = 1; t->objectId = pt->objectId; t->chunkId = pt->chunkId; t->byteCount = pt->byteCount; t->eccResult = YAFFS_ECC_RESULT_NO_ERROR; t->chunkDeleted = (pt->deleted) ? 0 : 1; t->serialNumber = pt->serialNumber; } else { memset(t, 0, sizeof(yaffs_ExtendedTags)); } }
1001-study-uboot
fs/yaffs2/yaffs_packedtags1.c
C
gpl3
1,458
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_MTDIF_H__ #define __YAFFS_MTDIF_H__ #include "yaffs_guts.h" int nandmtd_WriteChunkToNAND(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_Spare * spare); int nandmtd_ReadChunkFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * data, yaffs_Spare * spare); int nandmtd_EraseBlockInNAND(yaffs_Device * dev, int blockNumber); int nandmtd_InitialiseNAND(yaffs_Device * dev); #endif
1001-study-uboot
fs/yaffs2/yaffs_mtdif.h
C
gpl3
945
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* * ydirectenv.h: Environment wrappers for YAFFS direct. */ #ifndef __YDIRECTENV_H__ #define __YDIRECTENV_H__ /* Direct interface */ #include "devextras.h" /* XXX U-BOOT XXX */ #if 0 #include "stdlib.h" #include "stdio.h" #include "string.h" #include "assert.h" #endif #include "yaffs_malloc.h" /* XXX U-BOOT XXX */ #if 0 #define YBUG() assert(1) #endif #define YCHAR char #define YUCHAR unsigned char #define _Y(x) x #define yaffs_strcpy(a,b) strcpy(a,b) #define yaffs_strncpy(a,b,c) strncpy(a,b,c) #define yaffs_strncmp(a,b,c) strncmp(a,b,c) #define yaffs_strlen(s) strlen(s) #define yaffs_sprintf sprintf #define yaffs_toupper(a) toupper(a) #ifdef NO_Y_INLINE #define Y_INLINE #else #define Y_INLINE inline #endif #define YMALLOC(x) yaffs_malloc(x) #define YFREE(x) free(x) #define YMALLOC_ALT(x) yaffs_malloc(x) #define YFREE_ALT(x) free(x) #define YMALLOC_DMA(x) yaffs_malloc(x) #define YYIELD() do {} while(0) //#define YINFO(s) YPRINTF(( __FILE__ " %d %s\n",__LINE__,s)) //#define YALERT(s) YINFO(s) #define TENDSTR "\n" #define TSTR(x) x #define TOUT(p) printf p #define YAFFS_LOSTNFOUND_NAME "lost+found" #define YAFFS_LOSTNFOUND_PREFIX "obj" //#define YPRINTF(x) printf x #include "yaffscfg.h" #define Y_CURRENT_TIME yaffsfs_CurrentTime() #define Y_TIME_CONVERT(x) x #define YAFFS_ROOT_MODE 0666 #define YAFFS_LOSTNFOUND_MODE 0666 #define yaffs_SumCompare(x,y) ((x) == (y)) #define yaffs_strcmp(a,b) strcmp(a,b) #endif
1001-study-uboot
fs/yaffs2/ydirectenv.h
C
gpl3
1,995
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* This is used to pack YAFFS2 tags, not YAFFS1tags. */ #ifndef __YAFFS_PACKEDTAGS2_H__ #define __YAFFS_PACKEDTAGS2_H__ #include "yaffs_guts.h" #include "yaffs_ecc.h" typedef struct { unsigned sequenceNumber; unsigned objectId; unsigned chunkId; unsigned byteCount; } yaffs_PackedTags2TagsPart; typedef struct { yaffs_PackedTags2TagsPart t; yaffs_ECCOther ecc; } yaffs_PackedTags2; void yaffs_PackTags2(yaffs_PackedTags2 * pt, const yaffs_ExtendedTags * t); void yaffs_UnpackTags2(yaffs_ExtendedTags * t, yaffs_PackedTags2 * pt); #endif
1001-study-uboot
fs/yaffs2/yaffs_packedtags2.h
C
gpl3
1,061
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* * This code implements the ECC algorithm used in SmartMedia. * * The ECC comprises 22 bits of parity information and is stuffed into 3 bytes. * The two unused bit are set to 1. * The ECC can correct single bit errors in a 256-byte page of data. Thus, two such ECC * blocks are used on a 512-byte NAND page. * */ #ifndef __YAFFS_ECC_H__ #define __YAFFS_ECC_H__ typedef struct { unsigned char colParity; unsigned lineParity; unsigned lineParityPrime; } yaffs_ECCOther; void yaffs_ECCCalculate(const unsigned char *data, unsigned char *ecc); int yaffs_ECCCorrect(unsigned char *data, unsigned char *read_ecc, const unsigned char *test_ecc); void yaffs_ECCCalculateOther(const unsigned char *data, unsigned nBytes, yaffs_ECCOther * ecc); int yaffs_ECCCorrectOther(unsigned char *data, unsigned nBytes, yaffs_ECCOther * read_ecc, const yaffs_ECCOther * test_ecc); #endif
1001-study-uboot
fs/yaffs2/yaffs_ecc.h
C
gpl3
1,431
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* * This file is just holds extra declarations used during development. * Most of these are from kernel includes placed here so we can use them in * applications. * */ #ifndef __EXTRAS_H__ #define __EXTRAS_H__ #if defined WIN32 #define __inline__ __inline #define new newHack #endif /* XXX U-BOOT XXX */ #if 1 /* !(defined __KERNEL__) || (defined WIN32) */ /* User space defines */ /* XXX U-BOOT XXX */ #if 0 typedef unsigned char __u8; typedef unsigned short __u16; typedef unsigned __u32; #endif #include <asm/types.h> /* * Simple doubly linked list implementation. * * Some of the internal functions ("__xxx") are useful when * manipulating whole lists rather than single entries, as * sometimes we already know the next/prev entries and we can * generate better code by using them directly rather than * using the generic single-entry routines. */ #define prefetch(x) 1 struct list_head { struct list_head *next, *prev; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name) #define INIT_LIST_HEAD(ptr) do { \ (ptr)->next = (ptr); (ptr)->prev = (ptr); \ } while (0) /* * Insert a new entry between two known consecutive entries. * * This is only for internal list manipulation where we know * the prev/next entries already! */ static __inline__ void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; new->prev = prev; prev->next = new; } /** * list_add - add a new entry * @new: new entry to be added * @head: list head to add it after * * Insert a new entry after the specified head. * This is good for implementing stacks. */ static __inline__ void list_add(struct list_head *new, struct list_head *head) { __list_add(new, head, head->next); } /** * list_add_tail - add a new entry * @new: new entry to be added * @head: list head to add it before * * Insert a new entry before the specified head. * This is useful for implementing queues. */ static __inline__ void list_add_tail(struct list_head *new, struct list_head *head) { __list_add(new, head->prev, head); } /* * Delete a list entry by making the prev/next entries * point to each other. * * This is only for internal list manipulation where we know * the prev/next entries already! */ static __inline__ void __list_del(struct list_head *prev, struct list_head *next) { next->prev = prev; prev->next = next; } /** * list_del - deletes entry from list. * @entry: the element to delete from the list. * Note: list_empty on entry does not return true after this, the entry is * in an undefined state. */ static __inline__ void list_del(struct list_head *entry) { __list_del(entry->prev, entry->next); } /** * list_del_init - deletes entry from list and reinitialize it. * @entry: the element to delete from the list. */ static __inline__ void list_del_init(struct list_head *entry) { __list_del(entry->prev, entry->next); INIT_LIST_HEAD(entry); } /** * list_empty - tests whether a list is empty * @head: the list to test. */ static __inline__ int list_empty(struct list_head *head) { return head->next == head; } /** * list_splice - join two lists * @list: the new list to add. * @head: the place to add it in the first list. */ static __inline__ void list_splice(struct list_head *list, struct list_head *head) { struct list_head *first = list->next; if (first != list) { struct list_head *last = list->prev; struct list_head *at = head->next; first->prev = head; head->next = first; last->next = at; at->prev = last; } } /** * list_entry - get the struct for this entry * @ptr: the &struct list_head pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. */ #define list_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) /** * list_for_each - iterate over a list * @pos: the &struct list_head to use as a loop counter. * @head: the head for your list. */ #define list_for_each(pos, head) \ for (pos = (head)->next, prefetch(pos->next); pos != (head); \ pos = pos->next, prefetch(pos->next)) /** * list_for_each_safe - iterate over a list safe against removal * of list entry * @pos: the &struct list_head to use as a loop counter. * @n: another &struct list_head to use as temporary storage * @head: the head for your list. */ #define list_for_each_safe(pos, n, head) \ for (pos = (head)->next, n = pos->next; pos != (head); \ pos = n, n = pos->next) /* * File types */ #define DT_UNKNOWN 0 #define DT_FIFO 1 #define DT_CHR 2 #define DT_DIR 4 #define DT_BLK 6 #define DT_REG 8 #define DT_LNK 10 #define DT_SOCK 12 #define DT_WHT 14 #ifndef WIN32 /* XXX U-BOOT XXX */ #if 0 #include <sys/stat.h> #else #include "common.h" #endif #endif /* * Attribute flags. These should be or-ed together to figure out what * has been changed! */ #define ATTR_MODE 1 #define ATTR_UID 2 #define ATTR_GID 4 #define ATTR_SIZE 8 #define ATTR_ATIME 16 #define ATTR_MTIME 32 #define ATTR_CTIME 64 #define ATTR_ATIME_SET 128 #define ATTR_MTIME_SET 256 #define ATTR_FORCE 512 /* Not a change, but a change it */ #define ATTR_ATTR_FLAG 1024 struct iattr { unsigned int ia_valid; unsigned ia_mode; unsigned ia_uid; unsigned ia_gid; unsigned ia_size; unsigned ia_atime; unsigned ia_mtime; unsigned ia_ctime; unsigned int ia_attr_flags; }; #define KERN_DEBUG #else #ifndef WIN32 #include <linux/types.h> #include <linux/list.h> #include <linux/fs.h> #include <linux/stat.h> #endif #endif #if defined WIN32 #undef new #endif #endif
1001-study-uboot
fs/yaffs2/devextras.h
C
gpl3
6,253
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> #include <malloc.h> #include "yaffsfs.h" #include "yaffs_guts.h" #include "yaffscfg.h" #include "yportenv.h" /* XXX U-BOOT XXX */ #if 0 #include <string.h> // for memset #endif #define YAFFSFS_MAX_SYMLINK_DEREFERENCES 5 #ifndef NULL #define NULL ((void *)0) #endif const char *yaffsfs_c_version="$Id: yaffsfs.c,v 1.18 2007/07/18 19:40:38 charles Exp $"; // configurationList is the list of devices that are supported static yaffsfs_DeviceConfiguration *yaffsfs_configurationList; /* Some forward references */ static yaffs_Object *yaffsfs_FindObject(yaffs_Object *relativeDirectory, const char *path, int symDepth); static void yaffsfs_RemoveObjectCallback(yaffs_Object *obj); // Handle management. // unsigned int yaffs_wr_attempts; typedef struct { __u8 inUse:1; // this handle is in use __u8 readOnly:1; // this handle is read only __u8 append:1; // append only __u8 exclusive:1; // exclusive __u32 position; // current position in file yaffs_Object *obj; // the object }yaffsfs_Handle; static yaffsfs_Handle yaffsfs_handle[YAFFSFS_N_HANDLES]; // yaffsfs_InitHandle /// Inilitalise handles on start-up. // static int yaffsfs_InitHandles(void) { int i; for(i = 0; i < YAFFSFS_N_HANDLES; i++) { yaffsfs_handle[i].inUse = 0; yaffsfs_handle[i].obj = NULL; } return 0; } yaffsfs_Handle *yaffsfs_GetHandlePointer(int h) { if(h < 0 || h >= YAFFSFS_N_HANDLES) { return NULL; } return &yaffsfs_handle[h]; } yaffs_Object *yaffsfs_GetHandleObject(int handle) { yaffsfs_Handle *h = yaffsfs_GetHandlePointer(handle); if(h && h->inUse) { return h->obj; } return NULL; } //yaffsfs_GetHandle // Grab a handle (when opening a file) // static int yaffsfs_GetHandle(void) { int i; yaffsfs_Handle *h; for(i = 0; i < YAFFSFS_N_HANDLES; i++) { h = yaffsfs_GetHandlePointer(i); if(!h) { // todo bug: should never happen } if(!h->inUse) { memset(h,0,sizeof(yaffsfs_Handle)); h->inUse=1; return i; } } return -1; } // yaffs_PutHandle // Let go of a handle (when closing a file) // static int yaffsfs_PutHandle(int handle) { yaffsfs_Handle *h = yaffsfs_GetHandlePointer(handle); if(h) { h->inUse = 0; h->obj = NULL; } return 0; } // Stuff to search for a directory from a path int yaffsfs_Match(char a, char b) { // case sensitive return (a == b); } // yaffsfs_FindDevice // yaffsfs_FindRoot // Scan the configuration list to find the root. // Curveballs: Should match paths that end in '/' too // Curveball2 Might have "/x/ and "/x/y". Need to return the longest match static yaffs_Device *yaffsfs_FindDevice(const char *path, char **restOfPath) { yaffsfs_DeviceConfiguration *cfg = yaffsfs_configurationList; const char *leftOver; const char *p; yaffs_Device *retval = NULL; int thisMatchLength; int longestMatch = -1; // Check all configs, choose the one that: // 1) Actually matches a prefix (ie /a amd /abc will not match // 2) Matches the longest. while(cfg && cfg->prefix && cfg->dev) { leftOver = path; p = cfg->prefix; thisMatchLength = 0; while(*p && //unmatched part of prefix strcmp(p,"/") && // the rest of the prefix is not / (to catch / at end) *leftOver && yaffsfs_Match(*p,*leftOver)) { p++; leftOver++; thisMatchLength++; } if((!*p || strcmp(p,"/") == 0) && // end of prefix (!*leftOver || *leftOver == '/') && // no more in this path name part (thisMatchLength > longestMatch)) { // Matched prefix *restOfPath = (char *)leftOver; retval = cfg->dev; longestMatch = thisMatchLength; } cfg++; } return retval; } static yaffs_Object *yaffsfs_FindRoot(const char *path, char **restOfPath) { yaffs_Device *dev; dev= yaffsfs_FindDevice(path,restOfPath); if(dev && dev->isMounted) { return dev->rootDir; } return NULL; } static yaffs_Object *yaffsfs_FollowLink(yaffs_Object *obj,int symDepth) { while(obj && obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) { char *alias = obj->variant.symLinkVariant.alias; if(*alias == '/') { // Starts with a /, need to scan from root up obj = yaffsfs_FindObject(NULL,alias,symDepth++); } else { // Relative to here, so use the parent of the symlink as a start obj = yaffsfs_FindObject(obj->parent,alias,symDepth++); } } return obj; } // yaffsfs_FindDirectory // Parse a path to determine the directory and the name within the directory. // // eg. "/data/xx/ff" --> puts name="ff" and returns the directory "/data/xx" static yaffs_Object *yaffsfs_DoFindDirectory(yaffs_Object *startDir,const char *path,char **name,int symDepth) { yaffs_Object *dir; char *restOfPath; char str[YAFFS_MAX_NAME_LENGTH+1]; int i; if(symDepth > YAFFSFS_MAX_SYMLINK_DEREFERENCES) { return NULL; } if(startDir) { dir = startDir; restOfPath = (char *)path; } else { dir = yaffsfs_FindRoot(path,&restOfPath); } while(dir) { // parse off /. // curve ball: also throw away surplus '/' // eg. "/ram/x////ff" gets treated the same as "/ram/x/ff" while(*restOfPath == '/') { restOfPath++; // get rid of '/' } *name = restOfPath; i = 0; while(*restOfPath && *restOfPath != '/') { if (i < YAFFS_MAX_NAME_LENGTH) { str[i] = *restOfPath; str[i+1] = '\0'; i++; } restOfPath++; } if(!*restOfPath) { // got to the end of the string return dir; } else { if(strcmp(str,".") == 0) { // Do nothing } else if(strcmp(str,"..") == 0) { dir = dir->parent; } else { dir = yaffs_FindObjectByName(dir,str); while(dir && dir->variantType == YAFFS_OBJECT_TYPE_SYMLINK) { dir = yaffsfs_FollowLink(dir,symDepth); } if(dir && dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) { dir = NULL; } } } } // directory did not exist. return NULL; } static yaffs_Object *yaffsfs_FindDirectory(yaffs_Object *relativeDirectory,const char *path,char **name,int symDepth) { return yaffsfs_DoFindDirectory(relativeDirectory,path,name,symDepth); } // yaffsfs_FindObject turns a path for an existing object into the object // static yaffs_Object *yaffsfs_FindObject(yaffs_Object *relativeDirectory, const char *path,int symDepth) { yaffs_Object *dir; char *name; dir = yaffsfs_FindDirectory(relativeDirectory,path,&name,symDepth); if(dir && *name) { return yaffs_FindObjectByName(dir,name); } return dir; } int yaffs_open(const char *path, int oflag, int mode) { yaffs_Object *obj = NULL; yaffs_Object *dir = NULL; char *name; int handle = -1; yaffsfs_Handle *h = NULL; int alreadyOpen = 0; int alreadyExclusive = 0; int openDenied = 0; int symDepth = 0; int errorReported = 0; int i; // todo sanity check oflag (eg. can't have O_TRUNC without WRONLY or RDWR yaffsfs_Lock(); handle = yaffsfs_GetHandle(); if(handle >= 0) { h = yaffsfs_GetHandlePointer(handle); // try to find the exisiting object obj = yaffsfs_FindObject(NULL,path,0); if(obj && obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) { obj = yaffsfs_FollowLink(obj,symDepth++); } if(obj) { // Check if the object is already in use alreadyOpen = alreadyExclusive = 0; for(i = 0; i <= YAFFSFS_N_HANDLES; i++) { if(i != handle && yaffsfs_handle[i].inUse && obj == yaffsfs_handle[i].obj) { alreadyOpen = 1; if(yaffsfs_handle[i].exclusive) { alreadyExclusive = 1; } } } if(((oflag & O_EXCL) && alreadyOpen) || alreadyExclusive) { openDenied = 1; } // Open should fail if O_CREAT and O_EXCL are specified if((oflag & O_EXCL) && (oflag & O_CREAT)) { openDenied = 1; yaffsfs_SetError(-EEXIST); errorReported = 1; } // Check file permissions if( (oflag & (O_RDWR | O_WRONLY)) == 0 && // ie O_RDONLY !(obj->yst_mode & S_IREAD)) { openDenied = 1; } if( (oflag & O_RDWR) && !(obj->yst_mode & S_IREAD)) { openDenied = 1; } if( (oflag & (O_RDWR | O_WRONLY)) && !(obj->yst_mode & S_IWRITE)) { openDenied = 1; } } else if((oflag & O_CREAT)) { // Let's see if we can create this file dir = yaffsfs_FindDirectory(NULL,path,&name,0); if(dir) { obj = yaffs_MknodFile(dir,name,mode,0,0); } else { yaffsfs_SetError(-ENOTDIR); } } if(obj && !openDenied) { h->obj = obj; h->inUse = 1; h->readOnly = (oflag & (O_WRONLY | O_RDWR)) ? 0 : 1; h->append = (oflag & O_APPEND) ? 1 : 0; h->exclusive = (oflag & O_EXCL) ? 1 : 0; h->position = 0; obj->inUse++; if((oflag & O_TRUNC) && !h->readOnly) { //todo truncate yaffs_ResizeFile(obj,0); } } else { yaffsfs_PutHandle(handle); if(!errorReported) { yaffsfs_SetError(-EACCESS); errorReported = 1; } handle = -1; } } yaffsfs_Unlock(); return handle; } int yaffs_close(int fd) { yaffsfs_Handle *h = NULL; int retVal = 0; yaffsfs_Lock(); h = yaffsfs_GetHandlePointer(fd); if(h && h->inUse) { // clean up yaffs_FlushFile(h->obj,1); h->obj->inUse--; if(h->obj->inUse <= 0 && h->obj->unlinked) { yaffs_DeleteFile(h->obj); } yaffsfs_PutHandle(fd); retVal = 0; } else { // bad handle yaffsfs_SetError(-EBADF); retVal = -1; } yaffsfs_Unlock(); return retVal; } int yaffs_read(int fd, void *buf, unsigned int nbyte) { yaffsfs_Handle *h = NULL; yaffs_Object *obj = NULL; int pos = 0; int nRead = -1; int maxRead; yaffsfs_Lock(); h = yaffsfs_GetHandlePointer(fd); obj = yaffsfs_GetHandleObject(fd); if(!h || !obj) { // bad handle yaffsfs_SetError(-EBADF); } else if( h && obj) { pos= h->position; if(yaffs_GetObjectFileLength(obj) > pos) { maxRead = yaffs_GetObjectFileLength(obj) - pos; } else { maxRead = 0; } if(nbyte > maxRead) { nbyte = maxRead; } if(nbyte > 0) { nRead = yaffs_ReadDataFromFile(obj,buf,pos,nbyte); if(nRead >= 0) { h->position = pos + nRead; } else { //todo error } } else { nRead = 0; } } yaffsfs_Unlock(); return (nRead >= 0) ? nRead : -1; } int yaffs_write(int fd, const void *buf, unsigned int nbyte) { yaffsfs_Handle *h = NULL; yaffs_Object *obj = NULL; int pos = 0; int nWritten = -1; int writeThrough = 0; yaffsfs_Lock(); h = yaffsfs_GetHandlePointer(fd); obj = yaffsfs_GetHandleObject(fd); if(!h || !obj) { // bad handle yaffsfs_SetError(-EBADF); } else if( h && obj && h->readOnly) { // todo error } else if( h && obj) { if(h->append) { pos = yaffs_GetObjectFileLength(obj); } else { pos = h->position; } nWritten = yaffs_WriteDataToFile(obj,buf,pos,nbyte,writeThrough); if(nWritten >= 0) { h->position = pos + nWritten; } else { //todo error } } yaffsfs_Unlock(); return (nWritten >= 0) ? nWritten : -1; } int yaffs_truncate(int fd, off_t newSize) { yaffsfs_Handle *h = NULL; yaffs_Object *obj = NULL; int result = 0; yaffsfs_Lock(); h = yaffsfs_GetHandlePointer(fd); obj = yaffsfs_GetHandleObject(fd); if(!h || !obj) { // bad handle yaffsfs_SetError(-EBADF); } else { // resize the file result = yaffs_ResizeFile(obj,newSize); } yaffsfs_Unlock(); return (result) ? 0 : -1; } off_t yaffs_lseek(int fd, off_t offset, int whence) { yaffsfs_Handle *h = NULL; yaffs_Object *obj = NULL; int pos = -1; int fSize = -1; yaffsfs_Lock(); h = yaffsfs_GetHandlePointer(fd); obj = yaffsfs_GetHandleObject(fd); if(!h || !obj) { // bad handle yaffsfs_SetError(-EBADF); } else if(whence == SEEK_SET) { if(offset >= 0) { pos = offset; } } else if(whence == SEEK_CUR) { if( (h->position + offset) >= 0) { pos = (h->position + offset); } } else if(whence == SEEK_END) { fSize = yaffs_GetObjectFileLength(obj); if(fSize >= 0 && (fSize + offset) >= 0) { pos = fSize + offset; } } if(pos >= 0) { h->position = pos; } else { // todo error } yaffsfs_Unlock(); return pos; } int yaffsfs_DoUnlink(const char *path,int isDirectory) { yaffs_Object *dir = NULL; yaffs_Object *obj = NULL; char *name; int result = YAFFS_FAIL; yaffsfs_Lock(); obj = yaffsfs_FindObject(NULL,path,0); dir = yaffsfs_FindDirectory(NULL,path,&name,0); if(!dir) { yaffsfs_SetError(-ENOTDIR); } else if(!obj) { yaffsfs_SetError(-ENOENT); } else if(!isDirectory && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) { yaffsfs_SetError(-EISDIR); } else if(isDirectory && obj->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) { yaffsfs_SetError(-ENOTDIR); } else { result = yaffs_Unlink(dir,name); if(result == YAFFS_FAIL && isDirectory) { yaffsfs_SetError(-ENOTEMPTY); } } yaffsfs_Unlock(); // todo error return (result == YAFFS_FAIL) ? -1 : 0; } int yaffs_rmdir(const char *path) { return yaffsfs_DoUnlink(path,1); } int yaffs_unlink(const char *path) { return yaffsfs_DoUnlink(path,0); } int yaffs_rename(const char *oldPath, const char *newPath) { yaffs_Object *olddir = NULL; yaffs_Object *newdir = NULL; yaffs_Object *obj = NULL; char *oldname; char *newname; int result= YAFFS_FAIL; int renameAllowed = 1; yaffsfs_Lock(); olddir = yaffsfs_FindDirectory(NULL,oldPath,&oldname,0); newdir = yaffsfs_FindDirectory(NULL,newPath,&newname,0); obj = yaffsfs_FindObject(NULL,oldPath,0); if(!olddir || !newdir || !obj) { // bad file yaffsfs_SetError(-EBADF); renameAllowed = 0; } else if(olddir->myDev != newdir->myDev) { // oops must be on same device // todo error yaffsfs_SetError(-EXDEV); renameAllowed = 0; } else if(obj && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) { // It is a directory, check that it is not being renamed to // being its own decendent. // Do this by tracing from the new directory back to the root, checking for obj yaffs_Object *xx = newdir; while( renameAllowed && xx) { if(xx == obj) { renameAllowed = 0; } xx = xx->parent; } if(!renameAllowed) yaffsfs_SetError(-EACCESS); } if(renameAllowed) { result = yaffs_RenameObject(olddir,oldname,newdir,newname); } yaffsfs_Unlock(); return (result == YAFFS_FAIL) ? -1 : 0; } static int yaffsfs_DoStat(yaffs_Object *obj,struct yaffs_stat *buf) { int retVal = -1; if(obj) { obj = yaffs_GetEquivalentObject(obj); } if(obj && buf) { buf->st_dev = (int)obj->myDev->genericDevice; buf->st_ino = obj->objectId; buf->st_mode = obj->yst_mode & ~S_IFMT; // clear out file type bits if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) { buf->st_mode |= S_IFDIR; } else if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) { buf->st_mode |= S_IFLNK; } else if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) { buf->st_mode |= S_IFREG; } buf->st_nlink = yaffs_GetObjectLinkCount(obj); buf->st_uid = 0; buf->st_gid = 0;; buf->st_rdev = obj->yst_rdev; buf->st_size = yaffs_GetObjectFileLength(obj); buf->st_blksize = obj->myDev->nDataBytesPerChunk; buf->st_blocks = (buf->st_size + buf->st_blksize -1)/buf->st_blksize; buf->yst_atime = obj->yst_atime; buf->yst_ctime = obj->yst_ctime; buf->yst_mtime = obj->yst_mtime; retVal = 0; } return retVal; } static int yaffsfs_DoStatOrLStat(const char *path, struct yaffs_stat *buf,int doLStat) { yaffs_Object *obj; int retVal = -1; yaffsfs_Lock(); obj = yaffsfs_FindObject(NULL,path,0); if(!doLStat && obj) { obj = yaffsfs_FollowLink(obj,0); } if(obj) { retVal = yaffsfs_DoStat(obj,buf); } else { // todo error not found yaffsfs_SetError(-ENOENT); } yaffsfs_Unlock(); return retVal; } int yaffs_stat(const char *path, struct yaffs_stat *buf) { return yaffsfs_DoStatOrLStat(path,buf,0); } int yaffs_lstat(const char *path, struct yaffs_stat *buf) { return yaffsfs_DoStatOrLStat(path,buf,1); } int yaffs_fstat(int fd, struct yaffs_stat *buf) { yaffs_Object *obj; int retVal = -1; yaffsfs_Lock(); obj = yaffsfs_GetHandleObject(fd); if(obj) { retVal = yaffsfs_DoStat(obj,buf); } else { // bad handle yaffsfs_SetError(-EBADF); } yaffsfs_Unlock(); return retVal; } static int yaffsfs_DoChMod(yaffs_Object *obj,mode_t mode) { int result = YAFFS_FAIL; if(obj) { obj = yaffs_GetEquivalentObject(obj); } if(obj) { obj->yst_mode = mode; obj->dirty = 1; result = yaffs_FlushFile(obj,0); } return result == YAFFS_OK ? 0 : -1; } int yaffs_chmod(const char *path, mode_t mode) { yaffs_Object *obj; int retVal = -1; yaffsfs_Lock(); obj = yaffsfs_FindObject(NULL,path,0); if(obj) { retVal = yaffsfs_DoChMod(obj,mode); } else { // todo error not found yaffsfs_SetError(-ENOENT); } yaffsfs_Unlock(); return retVal; } int yaffs_fchmod(int fd, mode_t mode) { yaffs_Object *obj; int retVal = -1; yaffsfs_Lock(); obj = yaffsfs_GetHandleObject(fd); if(obj) { retVal = yaffsfs_DoChMod(obj,mode); } else { // bad handle yaffsfs_SetError(-EBADF); } yaffsfs_Unlock(); return retVal; } int yaffs_mkdir(const char *path, mode_t mode) { yaffs_Object *parent = NULL; yaffs_Object *dir = NULL; char *name; int retVal= -1; yaffsfs_Lock(); parent = yaffsfs_FindDirectory(NULL,path,&name,0); if(parent) dir = yaffs_MknodDirectory(parent,name,mode,0,0); if(dir) { retVal = 0; } else { yaffsfs_SetError(-ENOSPC); // just assume no space for now retVal = -1; } yaffsfs_Unlock(); return retVal; } int yaffs_mount(const char *path) { int retVal=-1; int result=YAFFS_FAIL; yaffs_Device *dev=NULL; char *dummy; T(YAFFS_TRACE_ALWAYS,("yaffs: Mounting %s\n",path)); yaffsfs_Lock(); dev = yaffsfs_FindDevice(path,&dummy); if(dev) { if(!dev->isMounted) { result = yaffs_GutsInitialise(dev); if(result == YAFFS_FAIL) { // todo error - mount failed yaffsfs_SetError(-ENOMEM); } retVal = result ? 0 : -1; } else { //todo error - already mounted. yaffsfs_SetError(-EBUSY); } } else { // todo error - no device yaffsfs_SetError(-ENODEV); } yaffsfs_Unlock(); return retVal; } int yaffs_unmount(const char *path) { int retVal=-1; yaffs_Device *dev=NULL; char *dummy; yaffsfs_Lock(); dev = yaffsfs_FindDevice(path,&dummy); if(dev) { if(dev->isMounted) { int i; int inUse; yaffs_FlushEntireDeviceCache(dev); yaffs_CheckpointSave(dev); for(i = inUse = 0; i < YAFFSFS_N_HANDLES && !inUse; i++) { if(yaffsfs_handle[i].inUse && yaffsfs_handle[i].obj->myDev == dev) { inUse = 1; // the device is in use, can't unmount } } if(!inUse) { yaffs_Deinitialise(dev); retVal = 0; } else { // todo error can't unmount as files are open yaffsfs_SetError(-EBUSY); } } else { //todo error - not mounted. yaffsfs_SetError(-EINVAL); } } else { // todo error - no device yaffsfs_SetError(-ENODEV); } yaffsfs_Unlock(); return retVal; } loff_t yaffs_freespace(const char *path) { loff_t retVal=-1; yaffs_Device *dev=NULL; char *dummy; yaffsfs_Lock(); dev = yaffsfs_FindDevice(path,&dummy); if(dev && dev->isMounted) { retVal = yaffs_GetNumberOfFreeChunks(dev); retVal *= dev->nDataBytesPerChunk; } else { yaffsfs_SetError(-EINVAL); } yaffsfs_Unlock(); return retVal; } void yaffs_initialise(yaffsfs_DeviceConfiguration *cfgList) { yaffsfs_DeviceConfiguration *cfg; yaffsfs_configurationList = cfgList; yaffsfs_InitHandles(); cfg = yaffsfs_configurationList; while(cfg && cfg->prefix && cfg->dev) { cfg->dev->isMounted = 0; cfg->dev->removeObjectCallback = yaffsfs_RemoveObjectCallback; cfg++; } } // // Directory search stuff. // // Directory search context // // NB this is an opaque structure. typedef struct { __u32 magic; yaffs_dirent de; /* directory entry being used by this dsc */ char name[NAME_MAX+1]; /* name of directory being searched */ yaffs_Object *dirObj; /* ptr to directory being searched */ yaffs_Object *nextReturn; /* obj to be returned by next readddir */ int offset; struct list_head others; } yaffsfs_DirectorySearchContext; static struct list_head search_contexts; static void yaffsfs_SetDirRewound(yaffsfs_DirectorySearchContext *dsc) { if(dsc && dsc->dirObj && dsc->dirObj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){ dsc->offset = 0; if( list_empty(&dsc->dirObj->variant.directoryVariant.children)){ dsc->nextReturn = NULL; } else { dsc->nextReturn = list_entry(dsc->dirObj->variant.directoryVariant.children.next, yaffs_Object,siblings); } } else { /* Hey someone isn't playing nice! */ } } static void yaffsfs_DirAdvance(yaffsfs_DirectorySearchContext *dsc) { if(dsc && dsc->dirObj && dsc->dirObj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){ if( dsc->nextReturn == NULL || list_empty(&dsc->dirObj->variant.directoryVariant.children)){ dsc->nextReturn = NULL; } else { struct list_head *next = dsc->nextReturn->siblings.next; if( next == &dsc->dirObj->variant.directoryVariant.children) dsc->nextReturn = NULL; /* end of list */ else dsc->nextReturn = list_entry(next,yaffs_Object,siblings); } } else { /* Hey someone isn't playing nice! */ } } static void yaffsfs_RemoveObjectCallback(yaffs_Object *obj) { struct list_head *i; yaffsfs_DirectorySearchContext *dsc; /* if search contexts not initilised then skip */ if(!search_contexts.next) return; /* Iteratethrough the directory search contexts. * If any are the one being removed, then advance the dsc to * the next one to prevent a hanging ptr. */ list_for_each(i, &search_contexts) { if (i) { dsc = list_entry(i, yaffsfs_DirectorySearchContext,others); if(dsc->nextReturn == obj) yaffsfs_DirAdvance(dsc); } } } yaffs_DIR *yaffs_opendir(const char *dirname) { yaffs_DIR *dir = NULL; yaffs_Object *obj = NULL; yaffsfs_DirectorySearchContext *dsc = NULL; yaffsfs_Lock(); obj = yaffsfs_FindObject(NULL,dirname,0); if(obj && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) { dsc = YMALLOC(sizeof(yaffsfs_DirectorySearchContext)); dir = (yaffs_DIR *)dsc; if(dsc) { memset(dsc,0,sizeof(yaffsfs_DirectorySearchContext)); dsc->magic = YAFFS_MAGIC; dsc->dirObj = obj; strncpy(dsc->name,dirname,NAME_MAX); INIT_LIST_HEAD(&dsc->others); if(!search_contexts.next) INIT_LIST_HEAD(&search_contexts); list_add(&dsc->others,&search_contexts); yaffsfs_SetDirRewound(dsc); } } yaffsfs_Unlock(); return dir; } struct yaffs_dirent *yaffs_readdir(yaffs_DIR *dirp) { yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp; struct yaffs_dirent *retVal = NULL; yaffsfs_Lock(); if(dsc && dsc->magic == YAFFS_MAGIC){ yaffsfs_SetError(0); if(dsc->nextReturn){ dsc->de.d_ino = yaffs_GetEquivalentObject(dsc->nextReturn)->objectId; dsc->de.d_dont_use = (unsigned)dsc->nextReturn; dsc->de.d_off = dsc->offset++; yaffs_GetObjectName(dsc->nextReturn,dsc->de.d_name,NAME_MAX); if(strlen(dsc->de.d_name) == 0) { // this should not happen! strcpy(dsc->de.d_name,"zz"); } dsc->de.d_reclen = sizeof(struct yaffs_dirent); retVal = &dsc->de; yaffsfs_DirAdvance(dsc); } else retVal = NULL; } else { yaffsfs_SetError(-EBADF); } yaffsfs_Unlock(); return retVal; } void yaffs_rewinddir(yaffs_DIR *dirp) { yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp; yaffsfs_Lock(); yaffsfs_SetDirRewound(dsc); yaffsfs_Unlock(); } int yaffs_closedir(yaffs_DIR *dirp) { yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp; yaffsfs_Lock(); dsc->magic = 0; list_del(&dsc->others); /* unhook from list */ YFREE(dsc); yaffsfs_Unlock(); return 0; } // end of directory stuff int yaffs_symlink(const char *oldpath, const char *newpath) { yaffs_Object *parent = NULL; yaffs_Object *obj; char *name; int retVal= -1; int mode = 0; // ignore for now yaffsfs_Lock(); parent = yaffsfs_FindDirectory(NULL,newpath,&name,0); obj = yaffs_MknodSymLink(parent,name,mode,0,0,oldpath); if(obj) { retVal = 0; } else { yaffsfs_SetError(-ENOSPC); // just assume no space for now retVal = -1; } yaffsfs_Unlock(); return retVal; } int yaffs_readlink(const char *path, char *buf, int bufsiz) { yaffs_Object *obj = NULL; int retVal; yaffsfs_Lock(); obj = yaffsfs_FindObject(NULL,path,0); if(!obj) { yaffsfs_SetError(-ENOENT); retVal = -1; } else if(obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK) { yaffsfs_SetError(-EINVAL); retVal = -1; } else { char *alias = obj->variant.symLinkVariant.alias; memset(buf,0,bufsiz); strncpy(buf,alias,bufsiz - 1); retVal = 0; } yaffsfs_Unlock(); return retVal; } int yaffs_link(const char *oldpath, const char *newpath) { // Creates a link called newpath to existing oldpath yaffs_Object *obj = NULL; yaffs_Object *target = NULL; int retVal = 0; yaffsfs_Lock(); obj = yaffsfs_FindObject(NULL,oldpath,0); target = yaffsfs_FindObject(NULL,newpath,0); if(!obj) { yaffsfs_SetError(-ENOENT); retVal = -1; } else if(target) { yaffsfs_SetError(-EEXIST); retVal = -1; } else { yaffs_Object *newdir = NULL; yaffs_Object *link = NULL; char *newname; newdir = yaffsfs_FindDirectory(NULL,newpath,&newname,0); if(!newdir) { yaffsfs_SetError(-ENOTDIR); retVal = -1; } else if(newdir->myDev != obj->myDev) { yaffsfs_SetError(-EXDEV); retVal = -1; } if(newdir && strlen(newname) > 0) { link = yaffs_Link(newdir,newname,obj); if(link) retVal = 0; else { yaffsfs_SetError(-ENOSPC); retVal = -1; } } } yaffsfs_Unlock(); return retVal; } int yaffs_mknod(const char *pathname, mode_t mode, dev_t dev); int yaffs_DumpDevStruct(const char *path) { char *rest; yaffs_Object *obj = yaffsfs_FindRoot(path,&rest); if(obj) { yaffs_Device *dev = obj->myDev; printf("\n" "nPageWrites.......... %d\n" "nPageReads........... %d\n" "nBlockErasures....... %d\n" "nGCCopies............ %d\n" "garbageCollections... %d\n" "passiveGarbageColl'ns %d\n" "\n", dev->nPageWrites, dev->nPageReads, dev->nBlockErasures, dev->nGCCopies, dev->garbageCollections, dev->passiveGarbageCollections ); } return 0; }
1001-study-uboot
fs/yaffs2/yaffsfs.c
C
gpl3
26,868
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> #include <malloc.h> const char *yaffs_checkptrw_c_version = "$Id: yaffs_checkptrw.c,v 1.14 2007/05/15 20:07:40 charles Exp $"; #include "yaffs_checkptrw.h" static int yaffs_CheckpointSpaceOk(yaffs_Device *dev) { int blocksAvailable = dev->nErasedBlocks - dev->nReservedBlocks; T(YAFFS_TRACE_CHECKPOINT, (TSTR("checkpt blocks available = %d" TENDSTR), blocksAvailable)); return (blocksAvailable <= 0) ? 0 : 1; } static int yaffs_CheckpointErase(yaffs_Device *dev) { int i; if(!dev->eraseBlockInNAND) return 0; T(YAFFS_TRACE_CHECKPOINT,(TSTR("checking blocks %d to %d"TENDSTR), dev->internalStartBlock,dev->internalEndBlock)); for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) { yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i); if(bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT){ T(YAFFS_TRACE_CHECKPOINT,(TSTR("erasing checkpt block %d"TENDSTR),i)); if(dev->eraseBlockInNAND(dev,i- dev->blockOffset /* realign */)){ bi->blockState = YAFFS_BLOCK_STATE_EMPTY; dev->nErasedBlocks++; dev->nFreeChunks += dev->nChunksPerBlock; } else { dev->markNANDBlockBad(dev,i); bi->blockState = YAFFS_BLOCK_STATE_DEAD; } } } dev->blocksInCheckpoint = 0; return 1; } static void yaffs_CheckpointFindNextErasedBlock(yaffs_Device *dev) { int i; int blocksAvailable = dev->nErasedBlocks - dev->nReservedBlocks; T(YAFFS_TRACE_CHECKPOINT, (TSTR("allocating checkpt block: erased %d reserved %d avail %d next %d "TENDSTR), dev->nErasedBlocks,dev->nReservedBlocks,blocksAvailable,dev->checkpointNextBlock)); if(dev->checkpointNextBlock >= 0 && dev->checkpointNextBlock <= dev->internalEndBlock && blocksAvailable > 0){ for(i = dev->checkpointNextBlock; i <= dev->internalEndBlock; i++){ yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i); if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY){ dev->checkpointNextBlock = i + 1; dev->checkpointCurrentBlock = i; T(YAFFS_TRACE_CHECKPOINT,(TSTR("allocating checkpt block %d"TENDSTR),i)); return; } } } T(YAFFS_TRACE_CHECKPOINT,(TSTR("out of checkpt blocks"TENDSTR))); dev->checkpointNextBlock = -1; dev->checkpointCurrentBlock = -1; } static void yaffs_CheckpointFindNextCheckpointBlock(yaffs_Device *dev) { int i; yaffs_ExtendedTags tags; T(YAFFS_TRACE_CHECKPOINT,(TSTR("find next checkpt block: start: blocks %d next %d" TENDSTR), dev->blocksInCheckpoint, dev->checkpointNextBlock)); if(dev->blocksInCheckpoint < dev->checkpointMaxBlocks) for(i = dev->checkpointNextBlock; i <= dev->internalEndBlock; i++){ int chunk = i * dev->nChunksPerBlock; int realignedChunk = chunk - dev->chunkOffset; dev->readChunkWithTagsFromNAND(dev,realignedChunk,NULL,&tags); T(YAFFS_TRACE_CHECKPOINT,(TSTR("find next checkpt block: search: block %d oid %d seq %d eccr %d" TENDSTR), i, tags.objectId,tags.sequenceNumber,tags.eccResult)); if(tags.sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA){ /* Right kind of block */ dev->checkpointNextBlock = tags.objectId; dev->checkpointCurrentBlock = i; dev->checkpointBlockList[dev->blocksInCheckpoint] = i; dev->blocksInCheckpoint++; T(YAFFS_TRACE_CHECKPOINT,(TSTR("found checkpt block %d"TENDSTR),i)); return; } } T(YAFFS_TRACE_CHECKPOINT,(TSTR("found no more checkpt blocks"TENDSTR))); dev->checkpointNextBlock = -1; dev->checkpointCurrentBlock = -1; } int yaffs_CheckpointOpen(yaffs_Device *dev, int forWriting) { /* Got the functions we need? */ if (!dev->writeChunkWithTagsToNAND || !dev->readChunkWithTagsFromNAND || !dev->eraseBlockInNAND || !dev->markNANDBlockBad) return 0; if(forWriting && !yaffs_CheckpointSpaceOk(dev)) return 0; if(!dev->checkpointBuffer) dev->checkpointBuffer = YMALLOC_DMA(dev->nDataBytesPerChunk); if(!dev->checkpointBuffer) return 0; dev->checkpointPageSequence = 0; dev->checkpointOpenForWrite = forWriting; dev->checkpointByteCount = 0; dev->checkpointSum = 0; dev->checkpointXor = 0; dev->checkpointCurrentBlock = -1; dev->checkpointCurrentChunk = -1; dev->checkpointNextBlock = dev->internalStartBlock; /* Erase all the blocks in the checkpoint area */ if(forWriting){ memset(dev->checkpointBuffer,0,dev->nDataBytesPerChunk); dev->checkpointByteOffset = 0; return yaffs_CheckpointErase(dev); } else { int i; /* Set to a value that will kick off a read */ dev->checkpointByteOffset = dev->nDataBytesPerChunk; /* A checkpoint block list of 1 checkpoint block per 16 block is (hopefully) * going to be way more than we need */ dev->blocksInCheckpoint = 0; dev->checkpointMaxBlocks = (dev->internalEndBlock - dev->internalStartBlock)/16 + 2; dev->checkpointBlockList = YMALLOC(sizeof(int) * dev->checkpointMaxBlocks); for(i = 0; i < dev->checkpointMaxBlocks; i++) dev->checkpointBlockList[i] = -1; } return 1; } int yaffs_GetCheckpointSum(yaffs_Device *dev, __u32 *sum) { __u32 compositeSum; compositeSum = (dev->checkpointSum << 8) | (dev->checkpointXor & 0xFF); *sum = compositeSum; return 1; } static int yaffs_CheckpointFlushBuffer(yaffs_Device *dev) { int chunk; int realignedChunk; yaffs_ExtendedTags tags; if(dev->checkpointCurrentBlock < 0){ yaffs_CheckpointFindNextErasedBlock(dev); dev->checkpointCurrentChunk = 0; } if(dev->checkpointCurrentBlock < 0) return 0; tags.chunkDeleted = 0; tags.objectId = dev->checkpointNextBlock; /* Hint to next place to look */ tags.chunkId = dev->checkpointPageSequence + 1; tags.sequenceNumber = YAFFS_SEQUENCE_CHECKPOINT_DATA; tags.byteCount = dev->nDataBytesPerChunk; if(dev->checkpointCurrentChunk == 0){ /* First chunk we write for the block? Set block state to checkpoint */ yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,dev->checkpointCurrentBlock); bi->blockState = YAFFS_BLOCK_STATE_CHECKPOINT; dev->blocksInCheckpoint++; } chunk = dev->checkpointCurrentBlock * dev->nChunksPerBlock + dev->checkpointCurrentChunk; T(YAFFS_TRACE_CHECKPOINT,(TSTR("checkpoint wite buffer nand %d(%d:%d) objid %d chId %d" TENDSTR), chunk, dev->checkpointCurrentBlock, dev->checkpointCurrentChunk,tags.objectId,tags.chunkId)); realignedChunk = chunk - dev->chunkOffset; dev->writeChunkWithTagsToNAND(dev,realignedChunk,dev->checkpointBuffer,&tags); dev->checkpointByteOffset = 0; dev->checkpointPageSequence++; dev->checkpointCurrentChunk++; if(dev->checkpointCurrentChunk >= dev->nChunksPerBlock){ dev->checkpointCurrentChunk = 0; dev->checkpointCurrentBlock = -1; } memset(dev->checkpointBuffer,0,dev->nDataBytesPerChunk); return 1; } int yaffs_CheckpointWrite(yaffs_Device *dev,const void *data, int nBytes) { int i=0; int ok = 1; __u8 * dataBytes = (__u8 *)data; if(!dev->checkpointBuffer) return 0; if(!dev->checkpointOpenForWrite) return -1; while(i < nBytes && ok) { dev->checkpointBuffer[dev->checkpointByteOffset] = *dataBytes ; dev->checkpointSum += *dataBytes; dev->checkpointXor ^= *dataBytes; dev->checkpointByteOffset++; i++; dataBytes++; dev->checkpointByteCount++; if(dev->checkpointByteOffset < 0 || dev->checkpointByteOffset >= dev->nDataBytesPerChunk) ok = yaffs_CheckpointFlushBuffer(dev); } return i; } int yaffs_CheckpointRead(yaffs_Device *dev, void *data, int nBytes) { int i=0; int ok = 1; yaffs_ExtendedTags tags; int chunk; int realignedChunk; __u8 *dataBytes = (__u8 *)data; if(!dev->checkpointBuffer) return 0; if(dev->checkpointOpenForWrite) return -1; while(i < nBytes && ok) { if(dev->checkpointByteOffset < 0 || dev->checkpointByteOffset >= dev->nDataBytesPerChunk) { if(dev->checkpointCurrentBlock < 0){ yaffs_CheckpointFindNextCheckpointBlock(dev); dev->checkpointCurrentChunk = 0; } if(dev->checkpointCurrentBlock < 0) ok = 0; else { chunk = dev->checkpointCurrentBlock * dev->nChunksPerBlock + dev->checkpointCurrentChunk; realignedChunk = chunk - dev->chunkOffset; /* read in the next chunk */ /* printf("read checkpoint page %d\n",dev->checkpointPage); */ dev->readChunkWithTagsFromNAND(dev, realignedChunk, dev->checkpointBuffer, &tags); if(tags.chunkId != (dev->checkpointPageSequence + 1) || tags.sequenceNumber != YAFFS_SEQUENCE_CHECKPOINT_DATA) ok = 0; dev->checkpointByteOffset = 0; dev->checkpointPageSequence++; dev->checkpointCurrentChunk++; if(dev->checkpointCurrentChunk >= dev->nChunksPerBlock) dev->checkpointCurrentBlock = -1; } } if(ok){ *dataBytes = dev->checkpointBuffer[dev->checkpointByteOffset]; dev->checkpointSum += *dataBytes; dev->checkpointXor ^= *dataBytes; dev->checkpointByteOffset++; i++; dataBytes++; dev->checkpointByteCount++; } } return i; } int yaffs_CheckpointClose(yaffs_Device *dev) { if(dev->checkpointOpenForWrite){ if(dev->checkpointByteOffset != 0) yaffs_CheckpointFlushBuffer(dev); } else { int i; for(i = 0; i < dev->blocksInCheckpoint && dev->checkpointBlockList[i] >= 0; i++){ yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,dev->checkpointBlockList[i]); if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY) bi->blockState = YAFFS_BLOCK_STATE_CHECKPOINT; else { // Todo this looks odd... } } YFREE(dev->checkpointBlockList); dev->checkpointBlockList = NULL; } dev->nFreeChunks -= dev->blocksInCheckpoint * dev->nChunksPerBlock; dev->nErasedBlocks -= dev->blocksInCheckpoint; T(YAFFS_TRACE_CHECKPOINT,(TSTR("checkpoint byte count %d" TENDSTR), dev->checkpointByteCount)); if(dev->checkpointBuffer){ /* free the buffer */ YFREE(dev->checkpointBuffer); dev->checkpointBuffer = NULL; return 1; } else return 0; } int yaffs_CheckpointInvalidateStream(yaffs_Device *dev) { /* Erase the first checksum block */ T(YAFFS_TRACE_CHECKPOINT,(TSTR("checkpoint invalidate"TENDSTR))); if(!yaffs_CheckpointSpaceOk(dev)) return 0; return yaffs_CheckpointErase(dev); }
1001-study-uboot
fs/yaffs2/yaffs_checkptrw.c
C
gpl3
10,503
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* This is used to pack YAFFS1 tags, not YAFFS2 tags. */ #ifndef __YAFFS_PACKEDTAGS1_H__ #define __YAFFS_PACKEDTAGS1_H__ #include "yaffs_guts.h" typedef struct { unsigned chunkId:20; unsigned serialNumber:2; unsigned byteCount:10; unsigned objectId:18; unsigned ecc:12; unsigned deleted:1; unsigned unusedStuff:1; unsigned shouldBeFF; } yaffs_PackedTags1; void yaffs_PackTags1(yaffs_PackedTags1 * pt, const yaffs_ExtendedTags * t); void yaffs_UnpackTags1(yaffs_ExtendedTags * t, const yaffs_PackedTags1 * pt); #endif
1001-study-uboot
fs/yaffs2/yaffs_packedtags1.h
C
gpl3
1,043
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_MTDIF2_H__ #define __YAFFS_MTDIF2_H__ #include "yaffs_guts.h" int nandmtd2_WriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_ExtendedTags * tags); int nandmtd2_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * data, yaffs_ExtendedTags * tags); int nandmtd2_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo); int nandmtd2_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo, yaffs_BlockState * state, int *sequenceNumber); #endif
1001-study-uboot
fs/yaffs2/yaffs_mtdif2.h
C
gpl3
1,080
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* mtd interface for YAFFS2 */ /* XXX U-BOOT XXX */ #include <common.h> #include "asm/errno.h" const char *yaffs_mtdif2_c_version = "$Id: yaffs_mtdif2.c,v 1.17 2007/02/14 01:09:06 wookey Exp $"; #include "yportenv.h" #include "yaffs_mtdif2.h" #include "linux/mtd/mtd.h" #include "linux/types.h" #include "linux/time.h" #include "yaffs_packedtags2.h" int nandmtd2_WriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_ExtendedTags * tags) { struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) struct mtd_oob_ops ops; #else size_t dummy; #endif int retval = 0; loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk; yaffs_PackedTags2 pt; T(YAFFS_TRACE_MTD, (TSTR ("nandmtd2_WriteChunkWithTagsToNAND chunk %d data %p tags %p" TENDSTR), chunkInNAND, data, tags)); #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) if (tags) yaffs_PackTags2(&pt, tags); else BUG(); /* both tags and data should always be present */ if (data) { ops.mode = MTD_OOB_AUTO; ops.ooblen = sizeof(pt); ops.len = dev->nDataBytesPerChunk; ops.ooboffs = 0; ops.datbuf = (__u8 *)data; ops.oobbuf = (void *)&pt; retval = mtd->write_oob(mtd, addr, &ops); } else BUG(); /* both tags and data should always be present */ #else if (tags) { yaffs_PackTags2(&pt, tags); } if (data && tags) { if (dev->useNANDECC) retval = mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk, &dummy, data, (__u8 *) & pt, NULL); else retval = mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk, &dummy, data, (__u8 *) & pt, NULL); } else { if (data) retval = mtd->write(mtd, addr, dev->nDataBytesPerChunk, &dummy, data); if (tags) retval = mtd->write_oob(mtd, addr, mtd->oobsize, &dummy, (__u8 *) & pt); } #endif if (retval == 0) return YAFFS_OK; else return YAFFS_FAIL; } int nandmtd2_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * data, yaffs_ExtendedTags * tags) { struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) struct mtd_oob_ops ops; #endif size_t dummy; int retval = 0; loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk; yaffs_PackedTags2 pt; T(YAFFS_TRACE_MTD, (TSTR ("nandmtd2_ReadChunkWithTagsFromNAND chunk %d data %p tags %p" TENDSTR), chunkInNAND, data, tags)); #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) if (data && !tags) retval = mtd->read(mtd, addr, dev->nDataBytesPerChunk, &dummy, data); else if (tags) { ops.mode = MTD_OOB_AUTO; ops.ooblen = sizeof(pt); ops.len = data ? dev->nDataBytesPerChunk : sizeof(pt); ops.ooboffs = 0; ops.datbuf = data; ops.oobbuf = dev->spareBuffer; retval = mtd->read_oob(mtd, addr, &ops); } #else if (data && tags) { if (dev->useNANDECC) { retval = mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk, &dummy, data, dev->spareBuffer, NULL); } else { retval = mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk, &dummy, data, dev->spareBuffer, NULL); } } else { if (data) retval = mtd->read(mtd, addr, dev->nDataBytesPerChunk, &dummy, data); if (tags) retval = mtd->read_oob(mtd, addr, mtd->oobsize, &dummy, dev->spareBuffer); } #endif memcpy(&pt, dev->spareBuffer, sizeof(pt)); if (tags) yaffs_UnpackTags2(tags, &pt); if(tags && retval == -EBADMSG && tags->eccResult == YAFFS_ECC_RESULT_NO_ERROR) tags->eccResult = YAFFS_ECC_RESULT_UNFIXED; if (retval == 0) return YAFFS_OK; else return YAFFS_FAIL; } int nandmtd2_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo) { struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); int retval; T(YAFFS_TRACE_MTD, (TSTR("nandmtd2_MarkNANDBlockBad %d" TENDSTR), blockNo)); retval = mtd->block_markbad(mtd, blockNo * dev->nChunksPerBlock * dev->nDataBytesPerChunk); if (retval == 0) return YAFFS_OK; else return YAFFS_FAIL; } int nandmtd2_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo, yaffs_BlockState * state, int *sequenceNumber) { struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); int retval; T(YAFFS_TRACE_MTD, (TSTR("nandmtd2_QueryNANDBlock %d" TENDSTR), blockNo)); retval = mtd->block_isbad(mtd, blockNo * dev->nChunksPerBlock * dev->nDataBytesPerChunk); if (retval) { T(YAFFS_TRACE_MTD, (TSTR("block is bad" TENDSTR))); *state = YAFFS_BLOCK_STATE_DEAD; *sequenceNumber = 0; } else { yaffs_ExtendedTags t; nandmtd2_ReadChunkWithTagsFromNAND(dev, blockNo * dev->nChunksPerBlock, NULL, &t); if (t.chunkUsed) { *sequenceNumber = t.sequenceNumber; *state = YAFFS_BLOCK_STATE_NEEDS_SCANNING; } else { *sequenceNumber = 0; *state = YAFFS_BLOCK_STATE_EMPTY; } } T(YAFFS_TRACE_MTD, (TSTR("block is bad seq %d state %d" TENDSTR), *sequenceNumber, *state)); if (retval == 0) return YAFFS_OK; else return YAFFS_FAIL; }
1001-study-uboot
fs/yaffs2/yaffs_mtdif2.c
C
gpl3
5,636
#ifndef __YAFFS_MALLOC_H__ /* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* XXX U-BOOT XXX */ #if 0 #include <stdlib.h> #endif void *yaffs_malloc(size_t size); void yaffs_free(void *ptr); #endif
1001-study-uboot
fs/yaffs2/yaffs_malloc.h
C
gpl3
664
# Makefile for YAFFS direct test # # # YAFFS: Yet another Flash File System. A NAND-flash specific file system. # # Copyright (C) 2003 Aleph One Ltd. # # # Created by Charles Manning <charles@aleph1.co.uk> # # 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. # # NB Warning this Makefile does not include header dependencies. # # $Id: Makefile,v 1.15 2007/07/18 19:40:38 charles Exp $ #EXTRA_COMPILE_FLAGS = -DYAFFS_IGNORE_TAGS_ECC include $(TOPDIR)/config.mk LIB = $(obj)libyaffs2.o COBJS-$(CONFIG_YAFFS2) := \ yaffscfg.o yaffs_ecc.o yaffsfs.o yaffs_guts.o yaffs_packedtags1.o \ yaffs_tagscompat.o yaffs_packedtags2.o yaffs_tagsvalidity.o \ yaffs_nand.o yaffs_checkptrw.o yaffs_qsort.o yaffs_mtdif.o \ yaffs_mtdif2.o SRCS := $(COBJS-y:.o=.c) OBJS := $(addprefix $(obj),$(COBJS-y)) # -DCONFIG_YAFFS_NO_YAFFS1 CFLAGS += -DCONFIG_YAFFS_DIRECT -DCONFIG_YAFFS_SHORT_NAMES_IN_RAM -DCONFIG_YAFFS_YAFFS2 -DLINUX_VERSION_CODE=0x20622 all: $(LIB) $(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/yaffs2/Makefile
Makefile
gpl3
1,392
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> #include "yaffs_guts.h" #include "yaffs_tagscompat.h" #include "yaffs_ecc.h" static void yaffs_HandleReadDataError(yaffs_Device * dev, int chunkInNAND); #ifdef NOTYET static void yaffs_CheckWrittenBlock(yaffs_Device * dev, int chunkInNAND); static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_Spare * spare); static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND, const yaffs_Spare * spare); static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND); #endif static const char yaffs_countBitsTable[256] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 }; int yaffs_CountBits(__u8 x) { int retVal; retVal = yaffs_countBitsTable[x]; return retVal; } /********** Tags ECC calculations *********/ void yaffs_CalcECC(const __u8 * data, yaffs_Spare * spare) { yaffs_ECCCalculate(data, spare->ecc1); yaffs_ECCCalculate(&data[256], spare->ecc2); } void yaffs_CalcTagsECC(yaffs_Tags * tags) { /* Calculate an ecc */ unsigned char *b = ((yaffs_TagsUnion *) tags)->asBytes; unsigned i, j; unsigned ecc = 0; unsigned bit = 0; tags->ecc = 0; for (i = 0; i < 8; i++) { for (j = 1; j & 0xff; j <<= 1) { bit++; if (b[i] & j) { ecc ^= bit; } } } tags->ecc = ecc; } int yaffs_CheckECCOnTags(yaffs_Tags * tags) { unsigned ecc = tags->ecc; yaffs_CalcTagsECC(tags); ecc ^= tags->ecc; if (ecc && ecc <= 64) { /* TODO: Handle the failure better. Retire? */ unsigned char *b = ((yaffs_TagsUnion *) tags)->asBytes; ecc--; b[ecc / 8] ^= (1 << (ecc & 7)); /* Now recvalc the ecc */ yaffs_CalcTagsECC(tags); return 1; /* recovered error */ } else if (ecc) { /* Wierd ecc failure value */ /* TODO Need to do somethiong here */ return -1; /* unrecovered error */ } return 0; } /********** Tags **********/ static void yaffs_LoadTagsIntoSpare(yaffs_Spare * sparePtr, yaffs_Tags * tagsPtr) { yaffs_TagsUnion *tu = (yaffs_TagsUnion *) tagsPtr; yaffs_CalcTagsECC(tagsPtr); sparePtr->tagByte0 = tu->asBytes[0]; sparePtr->tagByte1 = tu->asBytes[1]; sparePtr->tagByte2 = tu->asBytes[2]; sparePtr->tagByte3 = tu->asBytes[3]; sparePtr->tagByte4 = tu->asBytes[4]; sparePtr->tagByte5 = tu->asBytes[5]; sparePtr->tagByte6 = tu->asBytes[6]; sparePtr->tagByte7 = tu->asBytes[7]; } static void yaffs_GetTagsFromSpare(yaffs_Device * dev, yaffs_Spare * sparePtr, yaffs_TagsUnion *tu) { int result; tu->asBytes[0] = sparePtr->tagByte0; tu->asBytes[1] = sparePtr->tagByte1; tu->asBytes[2] = sparePtr->tagByte2; tu->asBytes[3] = sparePtr->tagByte3; tu->asBytes[4] = sparePtr->tagByte4; tu->asBytes[5] = sparePtr->tagByte5; tu->asBytes[6] = sparePtr->tagByte6; tu->asBytes[7] = sparePtr->tagByte7; result = yaffs_CheckECCOnTags(&tu->asTags); if (result > 0) { dev->tagsEccFixed++; } else if (result < 0) { dev->tagsEccUnfixed++; } } static void yaffs_SpareInitialise(yaffs_Spare * spare) { memset(spare, 0xFF, sizeof(yaffs_Spare)); } static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev, int chunkInNAND, const __u8 * data, yaffs_Spare * spare) { if (chunkInNAND < dev->startBlock * dev->nChunksPerBlock) { T(YAFFS_TRACE_ERROR, (TSTR("**>> yaffs chunk %d is not valid" TENDSTR), chunkInNAND)); return YAFFS_FAIL; } dev->nPageWrites++; return dev->writeChunkToNAND(dev, chunkInNAND, data, spare); } static int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev, int chunkInNAND, __u8 * data, yaffs_Spare * spare, yaffs_ECCResult * eccResult, int doErrorCorrection) { int retVal; yaffs_Spare localSpare; dev->nPageReads++; if (!spare && data) { /* If we don't have a real spare, then we use a local one. */ /* Need this for the calculation of the ecc */ spare = &localSpare; } if (!dev->useNANDECC) { retVal = dev->readChunkFromNAND(dev, chunkInNAND, data, spare); if (data && doErrorCorrection) { /* Do ECC correction */ /* Todo handle any errors */ int eccResult1, eccResult2; __u8 calcEcc[3]; yaffs_ECCCalculate(data, calcEcc); eccResult1 = yaffs_ECCCorrect(data, spare->ecc1, calcEcc); yaffs_ECCCalculate(&data[256], calcEcc); eccResult2 = yaffs_ECCCorrect(&data[256], spare->ecc2, calcEcc); if (eccResult1 > 0) { T(YAFFS_TRACE_ERROR, (TSTR ("**>>yaffs ecc error fix performed on chunk %d:0" TENDSTR), chunkInNAND)); dev->eccFixed++; } else if (eccResult1 < 0) { T(YAFFS_TRACE_ERROR, (TSTR ("**>>yaffs ecc error unfixed on chunk %d:0" TENDSTR), chunkInNAND)); dev->eccUnfixed++; } if (eccResult2 > 0) { T(YAFFS_TRACE_ERROR, (TSTR ("**>>yaffs ecc error fix performed on chunk %d:1" TENDSTR), chunkInNAND)); dev->eccFixed++; } else if (eccResult2 < 0) { T(YAFFS_TRACE_ERROR, (TSTR ("**>>yaffs ecc error unfixed on chunk %d:1" TENDSTR), chunkInNAND)); dev->eccUnfixed++; } if (eccResult1 || eccResult2) { /* We had a data problem on this page */ yaffs_HandleReadDataError(dev, chunkInNAND); } if (eccResult1 < 0 || eccResult2 < 0) *eccResult = YAFFS_ECC_RESULT_UNFIXED; else if (eccResult1 > 0 || eccResult2 > 0) *eccResult = YAFFS_ECC_RESULT_FIXED; else *eccResult = YAFFS_ECC_RESULT_NO_ERROR; } } else { /* Must allocate enough memory for spare+2*sizeof(int) */ /* for ecc results from device. */ struct yaffs_NANDSpare nspare; retVal = dev->readChunkFromNAND(dev, chunkInNAND, data, (yaffs_Spare *) & nspare); memcpy(spare, &nspare, sizeof(yaffs_Spare)); if (data && doErrorCorrection) { if (nspare.eccres1 > 0) { T(YAFFS_TRACE_ERROR, (TSTR ("**>>mtd ecc error fix performed on chunk %d:0" TENDSTR), chunkInNAND)); } else if (nspare.eccres1 < 0) { T(YAFFS_TRACE_ERROR, (TSTR ("**>>mtd ecc error unfixed on chunk %d:0" TENDSTR), chunkInNAND)); } if (nspare.eccres2 > 0) { T(YAFFS_TRACE_ERROR, (TSTR ("**>>mtd ecc error fix performed on chunk %d:1" TENDSTR), chunkInNAND)); } else if (nspare.eccres2 < 0) { T(YAFFS_TRACE_ERROR, (TSTR ("**>>mtd ecc error unfixed on chunk %d:1" TENDSTR), chunkInNAND)); } if (nspare.eccres1 || nspare.eccres2) { /* We had a data problem on this page */ yaffs_HandleReadDataError(dev, chunkInNAND); } if (nspare.eccres1 < 0 || nspare.eccres2 < 0) *eccResult = YAFFS_ECC_RESULT_UNFIXED; else if (nspare.eccres1 > 0 || nspare.eccres2 > 0) *eccResult = YAFFS_ECC_RESULT_FIXED; else *eccResult = YAFFS_ECC_RESULT_NO_ERROR; } } return retVal; } #ifdef NOTYET static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev, int chunkInNAND) { static int init = 0; static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK]; static __u8 data[YAFFS_BYTES_PER_CHUNK]; /* Might as well always allocate the larger size for */ /* dev->useNANDECC == true; */ static __u8 spare[sizeof(struct yaffs_NANDSpare)]; dev->readChunkFromNAND(dev, chunkInNAND, data, (yaffs_Spare *) spare); if (!init) { memset(cmpbuf, 0xff, YAFFS_BYTES_PER_CHUNK); init = 1; } if (memcmp(cmpbuf, data, YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL; if (memcmp(cmpbuf, spare, 16)) return YAFFS_FAIL; return YAFFS_OK; } #endif /* * Functions for robustisizing */ static void yaffs_HandleReadDataError(yaffs_Device * dev, int chunkInNAND) { int blockInNAND = chunkInNAND / dev->nChunksPerBlock; /* Mark the block for retirement */ yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1; T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS, (TSTR("**>>Block %d marked for retirement" TENDSTR), blockInNAND)); /* TODO: * Just do a garbage collection on the affected block * then retire the block * NB recursion */ } #ifdef NOTYET static void yaffs_CheckWrittenBlock(yaffs_Device * dev, int chunkInNAND) { } static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_Spare * spare) { } static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND, const yaffs_Spare * spare) { } static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND) { int blockInNAND = chunkInNAND / dev->nChunksPerBlock; /* Mark the block for retirement */ yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1; /* Delete the chunk */ yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__); } static int yaffs_VerifyCompare(const __u8 * d0, const __u8 * d1, const yaffs_Spare * s0, const yaffs_Spare * s1) { if (memcmp(d0, d1, YAFFS_BYTES_PER_CHUNK) != 0 || s0->tagByte0 != s1->tagByte0 || s0->tagByte1 != s1->tagByte1 || s0->tagByte2 != s1->tagByte2 || s0->tagByte3 != s1->tagByte3 || s0->tagByte4 != s1->tagByte4 || s0->tagByte5 != s1->tagByte5 || s0->tagByte6 != s1->tagByte6 || s0->tagByte7 != s1->tagByte7 || s0->ecc1[0] != s1->ecc1[0] || s0->ecc1[1] != s1->ecc1[1] || s0->ecc1[2] != s1->ecc1[2] || s0->ecc2[0] != s1->ecc2[0] || s0->ecc2[1] != s1->ecc2[1] || s0->ecc2[2] != s1->ecc2[2]) { return 0; } return 1; } #endif /* NOTYET */ int yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_ExtendedTags * eTags) { yaffs_Spare spare; yaffs_Tags tags; yaffs_SpareInitialise(&spare); if (eTags->chunkDeleted) { spare.pageStatus = 0; } else { tags.objectId = eTags->objectId; tags.chunkId = eTags->chunkId; tags.byteCount = eTags->byteCount; tags.serialNumber = eTags->serialNumber; if (!dev->useNANDECC && data) { yaffs_CalcECC(data, &spare); } yaffs_LoadTagsIntoSpare(&spare, &tags); } return yaffs_WriteChunkToNAND(dev, chunkInNAND, data, &spare); } int yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * data, yaffs_ExtendedTags * eTags) { yaffs_Spare spare; yaffs_TagsUnion tags; yaffs_ECCResult eccResult; static yaffs_Spare spareFF; static int init; if (!init) { memset(&spareFF, 0xFF, sizeof(spareFF)); init = 1; } if (yaffs_ReadChunkFromNAND (dev, chunkInNAND, data, &spare, &eccResult, 1)) { /* eTags may be NULL */ if (eTags) { int deleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0; eTags->chunkDeleted = deleted; eTags->eccResult = eccResult; eTags->blockBad = 0; /* We're reading it */ /* therefore it is not a bad block */ eTags->chunkUsed = (memcmp(&spareFF, &spare, sizeof(spareFF)) != 0) ? 1 : 0; if (eTags->chunkUsed) { yaffs_GetTagsFromSpare(dev, &spare, &tags); eTags->objectId = tags.asTags.objectId; eTags->chunkId = tags.asTags.chunkId; eTags->byteCount = tags.asTags.byteCount; eTags->serialNumber = tags.asTags.serialNumber; } } return YAFFS_OK; } else { return YAFFS_FAIL; } } int yaffs_TagsCompatabilityMarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockInNAND) { yaffs_Spare spare; memset(&spare, 0xff, sizeof(yaffs_Spare)); spare.blockStatus = 'Y'; yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock, NULL, &spare); yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock + 1, NULL, &spare); return YAFFS_OK; } int yaffs_TagsCompatabilityQueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo, yaffs_BlockState * state, int *sequenceNumber) { yaffs_Spare spare0, spare1; static yaffs_Spare spareFF; static int init; yaffs_ECCResult dummy; if (!init) { memset(&spareFF, 0xFF, sizeof(spareFF)); init = 1; } *sequenceNumber = 0; yaffs_ReadChunkFromNAND(dev, blockNo * dev->nChunksPerBlock, NULL, &spare0, &dummy, 1); yaffs_ReadChunkFromNAND(dev, blockNo * dev->nChunksPerBlock + 1, NULL, &spare1, &dummy, 1); if (yaffs_CountBits(spare0.blockStatus & spare1.blockStatus) < 7) *state = YAFFS_BLOCK_STATE_DEAD; else if (memcmp(&spareFF, &spare0, sizeof(spareFF)) == 0) *state = YAFFS_BLOCK_STATE_EMPTY; else *state = YAFFS_BLOCK_STATE_NEEDS_SCANNING; return YAFFS_OK; }
1001-study-uboot
fs/yaffs2/yaffs_tagscompat.c
C
gpl3
13,538
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_CHECKPTRW_H__ #define __YAFFS_CHECKPTRW_H__ #include "yaffs_guts.h" int yaffs_CheckpointOpen(yaffs_Device *dev, int forWriting); int yaffs_CheckpointWrite(yaffs_Device *dev,const void *data, int nBytes); int yaffs_CheckpointRead(yaffs_Device *dev,void *data, int nBytes); int yaffs_GetCheckpointSum(yaffs_Device *dev, __u32 *sum); int yaffs_CheckpointClose(yaffs_Device *dev); int yaffs_CheckpointInvalidateStream(yaffs_Device *dev); #endif
1001-study-uboot
fs/yaffs2/yaffs_checkptrw.h
C
gpl3
979
/* * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* XXX U-BOOT XXX */ #include <common.h> #include "yportenv.h" //#include <linux/string.h> /* * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function". */ #define swapcode(TYPE, parmi, parmj, n) { \ long i = (n) / sizeof (TYPE); \ register TYPE *pi = (TYPE *) (parmi); \ register TYPE *pj = (TYPE *) (parmj); \ do { \ register TYPE t = *pi; \ *pi++ = *pj; \ *pj++ = t; \ } while (--i > 0); \ } #define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \ es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1; static __inline void swapfunc(char *a, char *b, int n, int swaptype) { if (swaptype <= 1) swapcode(long, a, b, n) else swapcode(char, a, b, n) } #define swap(a, b) \ if (swaptype == 0) { \ long t = *(long *)(a); \ *(long *)(a) = *(long *)(b); \ *(long *)(b) = t; \ } else \ swapfunc(a, b, es, swaptype) #define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype) static __inline char * med3(char *a, char *b, char *c, int (*cmp)(const void *, const void *)) { return cmp(a, b) < 0 ? (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a )) :(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c )); } #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif void yaffs_qsort(void *aa, size_t n, size_t es, int (*cmp)(const void *, const void *)) { char *pa, *pb, *pc, *pd, *pl, *pm, *pn; int d, r, swaptype, swap_cnt; register char *a = aa; loop: SWAPINIT(a, es); swap_cnt = 0; if (n < 7) { for (pm = (char *)a + es; pm < (char *) a + n * es; pm += es) for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0; pl -= es) swap(pl, pl - es); return; } pm = (char *)a + (n / 2) * es; if (n > 7) { pl = (char *)a; pn = (char *)a + (n - 1) * es; if (n > 40) { d = (n / 8) * es; pl = med3(pl, pl + d, pl + 2 * d, cmp); pm = med3(pm - d, pm, pm + d, cmp); pn = med3(pn - 2 * d, pn - d, pn, cmp); } pm = med3(pl, pm, pn, cmp); } swap(a, pm); pa = pb = (char *)a + es; pc = pd = (char *)a + (n - 1) * es; for (;;) { while (pb <= pc && (r = cmp(pb, a)) <= 0) { if (r == 0) { swap_cnt = 1; swap(pa, pb); pa += es; } pb += es; } while (pb <= pc && (r = cmp(pc, a)) >= 0) { if (r == 0) { swap_cnt = 1; swap(pc, pd); pd -= es; } pc -= es; } if (pb > pc) break; swap(pb, pc); swap_cnt = 1; pb += es; pc -= es; } if (swap_cnt == 0) { /* Switch to insertion sort */ for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es) for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0; pl -= es) swap(pl, pl - es); return; } pn = (char *)a + n * es; r = min(pa - (char *)a, pb - pa); vecswap(a, pb - r, r); r = min((long)(pd - pc), (long)(pn - pd - es)); vecswap(pb, pn - r, r); if ((r = pb - pa) > es) yaffs_qsort(a, r / es, es, cmp); if ((r = pd - pc) > es) { /* Iterate rather than recurse to save stack space */ a = pn - r; n = r / es; goto loop; } /* yaffs_qsort(pn - r, r / es, es, cmp);*/ }
1001-study-uboot
fs/yaffs2/yaffs_qsort.c
C
gpl3
4,661
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YPORTENV_H__ #define __YPORTENV_H__ /* XXX U-BOOT XXX */ #ifndef CONFIG_YAFFS_DIRECT #define CONFIG_YAFFS_DIRECT #endif #if defined CONFIG_YAFFS_WINCE #include "ywinceenv.h" /* XXX U-BOOT XXX */ #elif 0 /* defined __KERNEL__ */ #include "moduleconfig.h" /* Linux kernel */ #include <linux/version.h> #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)) #include <linux/config.h> #endif #include <linux/kernel.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/vmalloc.h> #define YCHAR char #define YUCHAR unsigned char #define _Y(x) x #define yaffs_strcpy(a,b) strcpy(a,b) #define yaffs_strncpy(a,b,c) strncpy(a,b,c) #define yaffs_strncmp(a,b,c) strncmp(a,b,c) #define yaffs_strlen(s) strlen(s) #define yaffs_sprintf sprintf #define yaffs_toupper(a) toupper(a) #define Y_INLINE inline #define YAFFS_LOSTNFOUND_NAME "lost+found" #define YAFFS_LOSTNFOUND_PREFIX "obj" /* #define YPRINTF(x) printk x */ #define YMALLOC(x) kmalloc(x,GFP_KERNEL) #define YFREE(x) kfree(x) #define YMALLOC_ALT(x) vmalloc(x) #define YFREE_ALT(x) vfree(x) #define YMALLOC_DMA(x) YMALLOC(x) // KR - added for use in scan so processes aren't blocked indefinitely. #define YYIELD() schedule() #define YAFFS_ROOT_MODE 0666 #define YAFFS_LOSTNFOUND_MODE 0666 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)) #define Y_CURRENT_TIME CURRENT_TIME.tv_sec #define Y_TIME_CONVERT(x) (x).tv_sec #else #define Y_CURRENT_TIME CURRENT_TIME #define Y_TIME_CONVERT(x) (x) #endif #define yaffs_SumCompare(x,y) ((x) == (y)) #define yaffs_strcmp(a,b) strcmp(a,b) #define TENDSTR "\n" #define TSTR(x) KERN_WARNING x #define TOUT(p) printk p #define yaffs_trace(mask, fmt, args...) \ do { if ((mask) & (yaffs_traceMask|YAFFS_TRACE_ERROR)) \ printk(KERN_WARNING "yaffs: " fmt, ## args); \ } while (0) #define compile_time_assertion(assertion) \ ({ int x = __builtin_choose_expr(assertion, 0, (void)0); (void) x; }) #elif defined CONFIG_YAFFS_DIRECT /* Direct interface */ #include "ydirectenv.h" #elif defined CONFIG_YAFFS_UTIL /* Stuff for YAFFS utilities */ #include "stdlib.h" #include "stdio.h" #include "string.h" #include "devextras.h" #define YMALLOC(x) malloc(x) #define YFREE(x) free(x) #define YMALLOC_ALT(x) malloc(x) #define YFREE_ALT(x) free(x) #define YCHAR char #define YUCHAR unsigned char #define _Y(x) x #define yaffs_strcpy(a,b) strcpy(a,b) #define yaffs_strncpy(a,b,c) strncpy(a,b,c) #define yaffs_strlen(s) strlen(s) #define yaffs_sprintf sprintf #define yaffs_toupper(a) toupper(a) #define Y_INLINE inline /* #define YINFO(s) YPRINTF(( __FILE__ " %d %s\n",__LINE__,s)) */ /* #define YALERT(s) YINFO(s) */ #define TENDSTR "\n" #define TSTR(x) x #define TOUT(p) printf p #define YAFFS_LOSTNFOUND_NAME "lost+found" #define YAFFS_LOSTNFOUND_PREFIX "obj" /* #define YPRINTF(x) printf x */ #define YAFFS_ROOT_MODE 0666 #define YAFFS_LOSTNFOUND_MODE 0666 #define yaffs_SumCompare(x,y) ((x) == (y)) #define yaffs_strcmp(a,b) strcmp(a,b) #else /* Should have specified a configuration type */ #error Unknown configuration #endif /* see yaffs_fs.c */ extern unsigned int yaffs_traceMask; extern unsigned int yaffs_wr_attempts; /* * Tracing flags. * The flags masked in YAFFS_TRACE_ALWAYS are always traced. */ #define YAFFS_TRACE_OS 0x00000002 #define YAFFS_TRACE_ALLOCATE 0x00000004 #define YAFFS_TRACE_SCAN 0x00000008 #define YAFFS_TRACE_BAD_BLOCKS 0x00000010 #define YAFFS_TRACE_ERASE 0x00000020 #define YAFFS_TRACE_GC 0x00000040 #define YAFFS_TRACE_WRITE 0x00000080 #define YAFFS_TRACE_TRACING 0x00000100 #define YAFFS_TRACE_DELETION 0x00000200 #define YAFFS_TRACE_BUFFERS 0x00000400 #define YAFFS_TRACE_NANDACCESS 0x00000800 #define YAFFS_TRACE_GC_DETAIL 0x00001000 #define YAFFS_TRACE_SCAN_DEBUG 0x00002000 #define YAFFS_TRACE_MTD 0x00004000 #define YAFFS_TRACE_CHECKPOINT 0x00008000 #define YAFFS_TRACE_VERIFY 0x00010000 #define YAFFS_TRACE_VERIFY_NAND 0x00020000 #define YAFFS_TRACE_VERIFY_FULL 0x00040000 #define YAFFS_TRACE_VERIFY_ALL 0x000F0000 #define YAFFS_TRACE_ERROR 0x40000000 #define YAFFS_TRACE_BUG 0x80000000 #define YAFFS_TRACE_ALWAYS 0xF0000000 #define T(mask,p) do{ if((mask) & (yaffs_traceMask | YAFFS_TRACE_ALWAYS)) TOUT(p);} while(0) #ifndef CONFIG_YAFFS_WINCE #define YBUG() T(YAFFS_TRACE_BUG,(TSTR("==>> yaffs bug: " __FILE__ " %d" TENDSTR),__LINE__)) #endif #endif
1001-study-uboot
fs/yaffs2/yportenv.h
C
gpl3
4,980
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_GUTS_H__ #define __YAFFS_GUTS_H__ #include "devextras.h" #include "yportenv.h" #define YAFFS_OK 1 #define YAFFS_FAIL 0 /* Give us a Y=0x59, * Give us an A=0x41, * Give us an FF=0xFF * Give us an S=0x53 * And what have we got... */ #define YAFFS_MAGIC 0x5941FF53 #define YAFFS_NTNODES_LEVEL0 16 #define YAFFS_TNODES_LEVEL0_BITS 4 #define YAFFS_TNODES_LEVEL0_MASK 0xf #define YAFFS_NTNODES_INTERNAL (YAFFS_NTNODES_LEVEL0 / 2) #define YAFFS_TNODES_INTERNAL_BITS (YAFFS_TNODES_LEVEL0_BITS - 1) #define YAFFS_TNODES_INTERNAL_MASK 0x7 #define YAFFS_TNODES_MAX_LEVEL 6 #ifndef CONFIG_YAFFS_NO_YAFFS1 #define YAFFS_BYTES_PER_SPARE 16 #define YAFFS_BYTES_PER_CHUNK 512 #define YAFFS_CHUNK_SIZE_SHIFT 9 #define YAFFS_CHUNKS_PER_BLOCK 32 #define YAFFS_BYTES_PER_BLOCK (YAFFS_CHUNKS_PER_BLOCK*YAFFS_BYTES_PER_CHUNK) #endif #define YAFFS_MIN_YAFFS2_CHUNK_SIZE 1024 #define YAFFS_MIN_YAFFS2_SPARE_SIZE 32 #define YAFFS_MAX_CHUNK_ID 0x000FFFFF #define YAFFS_UNUSED_OBJECT_ID 0x0003FFFF #define YAFFS_ALLOCATION_NOBJECTS 100 #define YAFFS_ALLOCATION_NTNODES 100 #define YAFFS_ALLOCATION_NLINKS 100 #define YAFFS_NOBJECT_BUCKETS 256 #define YAFFS_OBJECT_SPACE 0x40000 #define YAFFS_CHECKPOINT_VERSION 3 #ifdef CONFIG_YAFFS_UNICODE #define YAFFS_MAX_NAME_LENGTH 127 #define YAFFS_MAX_ALIAS_LENGTH 79 #else #define YAFFS_MAX_NAME_LENGTH 255 #define YAFFS_MAX_ALIAS_LENGTH 159 #endif #define YAFFS_SHORT_NAME_LENGTH 15 /* Some special object ids for pseudo objects */ #define YAFFS_OBJECTID_ROOT 1 #define YAFFS_OBJECTID_LOSTNFOUND 2 #define YAFFS_OBJECTID_UNLINKED 3 #define YAFFS_OBJECTID_DELETED 4 /* Sseudo object ids for checkpointing */ #define YAFFS_OBJECTID_SB_HEADER 0x10 #define YAFFS_OBJECTID_CHECKPOINT_DATA 0x20 #define YAFFS_SEQUENCE_CHECKPOINT_DATA 0x21 /* */ #define YAFFS_MAX_SHORT_OP_CACHES 20 #define YAFFS_N_TEMP_BUFFERS 4 /* We limit the number attempts at sucessfully saving a chunk of data. * Small-page devices have 32 pages per block; large-page devices have 64. * Default to something in the order of 5 to 10 blocks worth of chunks. */ #define YAFFS_WR_ATTEMPTS (5*64) /* Sequence numbers are used in YAFFS2 to determine block allocation order. * The range is limited slightly to help distinguish bad numbers from good. * This also allows us to perhaps in the future use special numbers for * special purposes. * EFFFFF00 allows the allocation of 8 blocks per second (~1Mbytes) for 15 years, * and is a larger number than the lifetime of a 2GB device. */ #define YAFFS_LOWEST_SEQUENCE_NUMBER 0x00001000 #define YAFFS_HIGHEST_SEQUENCE_NUMBER 0xEFFFFF00 /* ChunkCache is used for short read/write operations.*/ typedef struct { struct yaffs_ObjectStruct *object; int chunkId; int lastUse; int dirty; int nBytes; /* Only valid if the cache is dirty */ int locked; /* Can't push out or flush while locked. */ #ifdef CONFIG_YAFFS_YAFFS2 __u8 *data; #else __u8 data[YAFFS_BYTES_PER_CHUNK]; #endif } yaffs_ChunkCache; /* Tags structures in RAM * NB This uses bitfield. Bitfields should not straddle a u32 boundary otherwise * the structure size will get blown out. */ #ifndef CONFIG_YAFFS_NO_YAFFS1 typedef struct { unsigned chunkId:20; unsigned serialNumber:2; unsigned byteCount:10; unsigned objectId:18; unsigned ecc:12; unsigned unusedStuff:2; } yaffs_Tags; typedef union { yaffs_Tags asTags; __u8 asBytes[8]; } yaffs_TagsUnion; #endif /* Stuff used for extended tags in YAFFS2 */ typedef enum { YAFFS_ECC_RESULT_UNKNOWN, YAFFS_ECC_RESULT_NO_ERROR, YAFFS_ECC_RESULT_FIXED, YAFFS_ECC_RESULT_UNFIXED } yaffs_ECCResult; typedef enum { YAFFS_OBJECT_TYPE_UNKNOWN, YAFFS_OBJECT_TYPE_FILE, YAFFS_OBJECT_TYPE_SYMLINK, YAFFS_OBJECT_TYPE_DIRECTORY, YAFFS_OBJECT_TYPE_HARDLINK, YAFFS_OBJECT_TYPE_SPECIAL } yaffs_ObjectType; #define YAFFS_OBJECT_TYPE_MAX YAFFS_OBJECT_TYPE_SPECIAL typedef struct { unsigned validMarker0; unsigned chunkUsed; /* Status of the chunk: used or unused */ unsigned objectId; /* If 0 then this is not part of an object (unused) */ unsigned chunkId; /* If 0 then this is a header, else a data chunk */ unsigned byteCount; /* Only valid for data chunks */ /* The following stuff only has meaning when we read */ yaffs_ECCResult eccResult; unsigned blockBad; /* YAFFS 1 stuff */ unsigned chunkDeleted; /* The chunk is marked deleted */ unsigned serialNumber; /* Yaffs1 2-bit serial number */ /* YAFFS2 stuff */ unsigned sequenceNumber; /* The sequence number of this block */ /* Extra info if this is an object header (YAFFS2 only) */ unsigned extraHeaderInfoAvailable; /* There is extra info available if this is not zero */ unsigned extraParentObjectId; /* The parent object */ unsigned extraIsShrinkHeader; /* Is it a shrink header? */ unsigned extraShadows; /* Does this shadow another object? */ yaffs_ObjectType extraObjectType; /* What object type? */ unsigned extraFileLength; /* Length if it is a file */ unsigned extraEquivalentObjectId; /* Equivalent object Id if it is a hard link */ unsigned validMarker1; } yaffs_ExtendedTags; /* Spare structure for YAFFS1 */ typedef struct { __u8 tagByte0; __u8 tagByte1; __u8 tagByte2; __u8 tagByte3; __u8 pageStatus; /* set to 0 to delete the chunk */ __u8 blockStatus; __u8 tagByte4; __u8 tagByte5; __u8 ecc1[3]; __u8 tagByte6; __u8 tagByte7; __u8 ecc2[3]; } yaffs_Spare; /*Special structure for passing through to mtd */ struct yaffs_NANDSpare { yaffs_Spare spare; int eccres1; int eccres2; }; /* Block data in RAM */ typedef enum { YAFFS_BLOCK_STATE_UNKNOWN = 0, YAFFS_BLOCK_STATE_SCANNING, YAFFS_BLOCK_STATE_NEEDS_SCANNING, /* The block might have something on it (ie it is allocating or full, perhaps empty) * but it needs to be scanned to determine its true state. * This state is only valid during yaffs_Scan. * NB We tolerate empty because the pre-scanner might be incapable of deciding * However, if this state is returned on a YAFFS2 device, then we expect a sequence number */ YAFFS_BLOCK_STATE_EMPTY, /* This block is empty */ YAFFS_BLOCK_STATE_ALLOCATING, /* This block is partially allocated. * At least one page holds valid data. * This is the one currently being used for page * allocation. Should never be more than one of these */ YAFFS_BLOCK_STATE_FULL, /* All the pages in this block have been allocated. */ YAFFS_BLOCK_STATE_DIRTY, /* All pages have been allocated and deleted. * Erase me, reuse me. */ YAFFS_BLOCK_STATE_CHECKPOINT, /* This block is assigned to holding checkpoint data. */ YAFFS_BLOCK_STATE_COLLECTING, /* This block is being garbage collected */ YAFFS_BLOCK_STATE_DEAD /* This block has failed and is not in use */ } yaffs_BlockState; #define YAFFS_NUMBER_OF_BLOCK_STATES (YAFFS_BLOCK_STATE_DEAD + 1) typedef struct { int softDeletions:10; /* number of soft deleted pages */ int pagesInUse:10; /* number of pages in use */ unsigned blockState:4; /* One of the above block states. NB use unsigned because enum is sometimes an int */ __u32 needsRetiring:1; /* Data has failed on this block, need to get valid data off */ /* and retire the block. */ __u32 skipErasedCheck: 1; /* If this is set we can skip the erased check on this block */ __u32 gcPrioritise: 1; /* An ECC check or blank check has failed on this block. It should be prioritised for GC */ __u32 chunkErrorStrikes:3; /* How many times we've had ecc etc failures on this block and tried to reuse it */ #ifdef CONFIG_YAFFS_YAFFS2 __u32 hasShrinkHeader:1; /* This block has at least one shrink object header */ __u32 sequenceNumber; /* block sequence number for yaffs2 */ #endif } yaffs_BlockInfo; /* -------------------------- Object structure -------------------------------*/ /* This is the object structure as stored on NAND */ typedef struct { yaffs_ObjectType type; /* Apply to everything */ int parentObjectId; __u16 sum__NoLongerUsed; /* checksum of name. No longer used */ YCHAR name[YAFFS_MAX_NAME_LENGTH + 1]; /* Thes following apply to directories, files, symlinks - not hard links */ __u32 yst_mode; /* protection */ #ifdef CONFIG_YAFFS_WINCE __u32 notForWinCE[5]; #else __u32 yst_uid; __u32 yst_gid; __u32 yst_atime; __u32 yst_mtime; __u32 yst_ctime; #endif /* File size applies to files only */ int fileSize; /* Equivalent object id applies to hard links only. */ int equivalentObjectId; /* Alias is for symlinks only. */ YCHAR alias[YAFFS_MAX_ALIAS_LENGTH + 1]; __u32 yst_rdev; /* device stuff for block and char devices (major/min) */ #ifdef CONFIG_YAFFS_WINCE __u32 win_ctime[2]; __u32 win_atime[2]; __u32 win_mtime[2]; __u32 roomToGrow[4]; #else __u32 roomToGrow[10]; #endif int shadowsObject; /* This object header shadows the specified object if > 0 */ /* isShrink applies to object headers written when we shrink the file (ie resize) */ __u32 isShrink; } yaffs_ObjectHeader; /*--------------------------- Tnode -------------------------- */ union yaffs_Tnode_union { #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG union yaffs_Tnode_union *internal[YAFFS_NTNODES_INTERNAL + 1]; #else union yaffs_Tnode_union *internal[YAFFS_NTNODES_INTERNAL]; #endif /* __u16 level0[YAFFS_NTNODES_LEVEL0]; */ }; typedef union yaffs_Tnode_union yaffs_Tnode; struct yaffs_TnodeList_struct { struct yaffs_TnodeList_struct *next; yaffs_Tnode *tnodes; }; typedef struct yaffs_TnodeList_struct yaffs_TnodeList; /*------------------------ Object -----------------------------*/ /* An object can be one of: * - a directory (no data, has children links * - a regular file (data.... not prunes :->). * - a symlink [symbolic link] (the alias). * - a hard link */ typedef struct { __u32 fileSize; __u32 scannedFileSize; __u32 shrinkSize; int topLevel; yaffs_Tnode *top; } yaffs_FileStructure; typedef struct { struct list_head children; /* list of child links */ } yaffs_DirectoryStructure; typedef struct { YCHAR *alias; } yaffs_SymLinkStructure; typedef struct { struct yaffs_ObjectStruct *equivalentObject; __u32 equivalentObjectId; } yaffs_HardLinkStructure; typedef union { yaffs_FileStructure fileVariant; yaffs_DirectoryStructure directoryVariant; yaffs_SymLinkStructure symLinkVariant; yaffs_HardLinkStructure hardLinkVariant; } yaffs_ObjectVariant; struct yaffs_ObjectStruct { __u8 deleted:1; /* This should only apply to unlinked files. */ __u8 softDeleted:1; /* it has also been soft deleted */ __u8 unlinked:1; /* An unlinked file. The file should be in the unlinked directory.*/ __u8 fake:1; /* A fake object has no presence on NAND. */ __u8 renameAllowed:1; /* Some objects are not allowed to be renamed. */ __u8 unlinkAllowed:1; __u8 dirty:1; /* the object needs to be written to flash */ __u8 valid:1; /* When the file system is being loaded up, this * object might be created before the data * is available (ie. file data records appear before the header). */ __u8 lazyLoaded:1; /* This object has been lazy loaded and is missing some detail */ __u8 deferedFree:1; /* For Linux kernel. Object is removed from NAND, but is * still in the inode cache. Free of object is defered. * until the inode is released. */ __u8 serial; /* serial number of chunk in NAND. Cached here */ __u16 sum; /* sum of the name to speed searching */ struct yaffs_DeviceStruct *myDev; /* The device I'm on */ struct list_head hashLink; /* list of objects in this hash bucket */ struct list_head hardLinks; /* all the equivalent hard linked objects */ /* directory structure stuff */ /* also used for linking up the free list */ struct yaffs_ObjectStruct *parent; struct list_head siblings; /* Where's my object header in NAND? */ int chunkId; int nDataChunks; /* Number of data chunks attached to the file. */ __u32 objectId; /* the object id value */ __u32 yst_mode; #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM YCHAR shortName[YAFFS_SHORT_NAME_LENGTH + 1]; #endif /* XXX U-BOOT XXX */ /* #ifndef __KERNEL__ */ __u32 inUse; /* #endif */ #ifdef CONFIG_YAFFS_WINCE __u32 win_ctime[2]; __u32 win_mtime[2]; __u32 win_atime[2]; #else __u32 yst_uid; __u32 yst_gid; __u32 yst_atime; __u32 yst_mtime; __u32 yst_ctime; #endif __u32 yst_rdev; /* XXX U-BOOT XXX */ /* #ifndef __KERNEL__ */ struct inode *myInode; /* #endif */ yaffs_ObjectType variantType; yaffs_ObjectVariant variant; }; typedef struct yaffs_ObjectStruct yaffs_Object; struct yaffs_ObjectList_struct { yaffs_Object *objects; struct yaffs_ObjectList_struct *next; }; typedef struct yaffs_ObjectList_struct yaffs_ObjectList; typedef struct { struct list_head list; int count; } yaffs_ObjectBucket; /* yaffs_CheckpointObject holds the definition of an object as dumped * by checkpointing. */ typedef struct { int structType; __u32 objectId; __u32 parentId; int chunkId; yaffs_ObjectType variantType:3; __u8 deleted:1; __u8 softDeleted:1; __u8 unlinked:1; __u8 fake:1; __u8 renameAllowed:1; __u8 unlinkAllowed:1; __u8 serial; int nDataChunks; __u32 fileSizeOrEquivalentObjectId; }yaffs_CheckpointObject; /*--------------------- Temporary buffers ---------------- * * These are chunk-sized working buffers. Each device has a few */ typedef struct { __u8 *buffer; int line; /* track from whence this buffer was allocated */ int maxLine; } yaffs_TempBuffer; /*----------------- Device ---------------------------------*/ struct yaffs_DeviceStruct { struct list_head devList; const char *name; /* Entry parameters set up way early. Yaffs sets up the rest.*/ int nDataBytesPerChunk; /* Should be a power of 2 >= 512 */ int nChunksPerBlock; /* does not need to be a power of 2 */ int nBytesPerSpare; /* spare area size */ int startBlock; /* Start block we're allowed to use */ int endBlock; /* End block we're allowed to use */ int nReservedBlocks; /* We want this tuneable so that we can reduce */ /* reserved blocks on NOR and RAM. */ /* Stuff used by the shared space checkpointing mechanism */ /* If this value is zero, then this mechanism is disabled */ int nCheckpointReservedBlocks; /* Blocks to reserve for checkpoint data */ int nShortOpCaches; /* If <= 0, then short op caching is disabled, else * the number of short op caches (don't use too many) */ int useHeaderFileSize; /* Flag to determine if we should use file sizes from the header */ int useNANDECC; /* Flag to decide whether or not to use NANDECC */ void *genericDevice; /* Pointer to device context * On an mtd this holds the mtd pointer. */ void *superBlock; /* NAND access functions (Must be set before calling YAFFS)*/ int (*writeChunkToNAND) (struct yaffs_DeviceStruct * dev, int chunkInNAND, const __u8 * data, const yaffs_Spare * spare); int (*readChunkFromNAND) (struct yaffs_DeviceStruct * dev, int chunkInNAND, __u8 * data, yaffs_Spare * spare); int (*eraseBlockInNAND) (struct yaffs_DeviceStruct * dev, int blockInNAND); int (*initialiseNAND) (struct yaffs_DeviceStruct * dev); #ifdef CONFIG_YAFFS_YAFFS2 int (*writeChunkWithTagsToNAND) (struct yaffs_DeviceStruct * dev, int chunkInNAND, const __u8 * data, const yaffs_ExtendedTags * tags); int (*readChunkWithTagsFromNAND) (struct yaffs_DeviceStruct * dev, int chunkInNAND, __u8 * data, yaffs_ExtendedTags * tags); int (*markNANDBlockBad) (struct yaffs_DeviceStruct * dev, int blockNo); int (*queryNANDBlock) (struct yaffs_DeviceStruct * dev, int blockNo, yaffs_BlockState * state, int *sequenceNumber); #endif int isYaffs2; /* The removeObjectCallback function must be supplied by OS flavours that * need it. The Linux kernel does not use this, but yaffs direct does use * it to implement the faster readdir */ void (*removeObjectCallback)(struct yaffs_ObjectStruct *obj); /* Callback to mark the superblock dirsty */ void (*markSuperBlockDirty)(void * superblock); int wideTnodesDisabled; /* Set to disable wide tnodes */ /* End of stuff that must be set before initialisation. */ /* Checkpoint control. Can be set before or after initialisation */ __u8 skipCheckpointRead; __u8 skipCheckpointWrite; /* Runtime parameters. Set up by YAFFS. */ __u16 chunkGroupBits; /* 0 for devices <= 32MB. else log2(nchunks) - 16 */ __u16 chunkGroupSize; /* == 2^^chunkGroupBits */ /* Stuff to support wide tnodes */ __u32 tnodeWidth; __u32 tnodeMask; /* Stuff to support various file offses to chunk/offset translations */ /* "Crumbs" for nDataBytesPerChunk not being a power of 2 */ __u32 crumbMask; __u32 crumbShift; __u32 crumbsPerChunk; /* Straight shifting for nDataBytesPerChunk being a power of 2 */ __u32 chunkShift; __u32 chunkMask; /* XXX U-BOOT XXX */ #if 0 #ifndef __KERNEL__ struct semaphore sem; /* Semaphore for waiting on erasure.*/ struct semaphore grossLock; /* Gross locking semaphore */ void (*putSuperFunc) (struct super_block * sb); #endif #endif __u8 *spareBuffer; /* For mtdif2 use. Don't know the size of the buffer * at compile time so we have to allocate it. */ int isMounted; int isCheckpointed; /* Stuff to support block offsetting to support start block zero */ int internalStartBlock; int internalEndBlock; int blockOffset; int chunkOffset; /* Runtime checkpointing stuff */ int checkpointPageSequence; /* running sequence number of checkpoint pages */ int checkpointByteCount; int checkpointByteOffset; __u8 *checkpointBuffer; int checkpointOpenForWrite; int blocksInCheckpoint; int checkpointCurrentChunk; int checkpointCurrentBlock; int checkpointNextBlock; int *checkpointBlockList; int checkpointMaxBlocks; __u32 checkpointSum; __u32 checkpointXor; /* Block Info */ yaffs_BlockInfo *blockInfo; __u8 *chunkBits; /* bitmap of chunks in use */ unsigned blockInfoAlt:1; /* was allocated using alternative strategy */ unsigned chunkBitsAlt:1; /* was allocated using alternative strategy */ int chunkBitmapStride; /* Number of bytes of chunkBits per block. * Must be consistent with nChunksPerBlock. */ int nErasedBlocks; int allocationBlock; /* Current block being allocated off */ __u32 allocationPage; int allocationBlockFinder; /* Used to search for next allocation block */ /* Runtime state */ int nTnodesCreated; yaffs_Tnode *freeTnodes; int nFreeTnodes; yaffs_TnodeList *allocatedTnodeList; int isDoingGC; int nObjectsCreated; yaffs_Object *freeObjects; int nFreeObjects; yaffs_ObjectList *allocatedObjectList; yaffs_ObjectBucket objectBucket[YAFFS_NOBJECT_BUCKETS]; int nFreeChunks; int currentDirtyChecker; /* Used to find current dirtiest block */ __u32 *gcCleanupList; /* objects to delete at the end of a GC. */ int nonAggressiveSkip; /* GC state/mode */ /* Statistcs */ int nPageWrites; int nPageReads; int nBlockErasures; int nErasureFailures; int nGCCopies; int garbageCollections; int passiveGarbageCollections; int nRetriedWrites; int nRetiredBlocks; int eccFixed; int eccUnfixed; int tagsEccFixed; int tagsEccUnfixed; int nDeletions; int nUnmarkedDeletions; int hasPendingPrioritisedGCs; /* We think this device might have pending prioritised gcs */ /* Special directories */ yaffs_Object *rootDir; yaffs_Object *lostNFoundDir; /* Buffer areas for storing data to recover from write failures TODO * __u8 bufferedData[YAFFS_CHUNKS_PER_BLOCK][YAFFS_BYTES_PER_CHUNK]; * yaffs_Spare bufferedSpare[YAFFS_CHUNKS_PER_BLOCK]; */ int bufferedBlock; /* Which block is buffered here? */ int doingBufferedBlockRewrite; yaffs_ChunkCache *srCache; int srLastUse; int cacheHits; /* Stuff for background deletion and unlinked files.*/ yaffs_Object *unlinkedDir; /* Directory where unlinked and deleted files live. */ yaffs_Object *deletedDir; /* Directory where deleted objects are sent to disappear. */ yaffs_Object *unlinkedDeletion; /* Current file being background deleted.*/ int nDeletedFiles; /* Count of files awaiting deletion;*/ int nUnlinkedFiles; /* Count of unlinked files. */ int nBackgroundDeletions; /* Count of background deletions. */ yaffs_TempBuffer tempBuffer[YAFFS_N_TEMP_BUFFERS]; int maxTemp; int unmanagedTempAllocations; int unmanagedTempDeallocations; /* yaffs2 runtime stuff */ unsigned sequenceNumber; /* Sequence number of currently allocating block */ unsigned oldestDirtySequence; }; typedef struct yaffs_DeviceStruct yaffs_Device; /* The static layout of bllock usage etc is stored in the super block header */ typedef struct { int StructType; int version; int checkpointStartBlock; int checkpointEndBlock; int startBlock; int endBlock; int rfu[100]; } yaffs_SuperBlockHeader; /* The CheckpointDevice structure holds the device information that changes at runtime and * must be preserved over unmount/mount cycles. */ typedef struct { int structType; int nErasedBlocks; int allocationBlock; /* Current block being allocated off */ __u32 allocationPage; int nFreeChunks; int nDeletedFiles; /* Count of files awaiting deletion;*/ int nUnlinkedFiles; /* Count of unlinked files. */ int nBackgroundDeletions; /* Count of background deletions. */ /* yaffs2 runtime stuff */ unsigned sequenceNumber; /* Sequence number of currently allocating block */ unsigned oldestDirtySequence; } yaffs_CheckpointDevice; typedef struct { int structType; __u32 magic; __u32 version; __u32 head; } yaffs_CheckpointValidity; /* Function to manipulate block info */ static Y_INLINE yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blk) { if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) { T(YAFFS_TRACE_ERROR, (TSTR ("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR), blk)); YBUG(); } return &dev->blockInfo[blk - dev->internalStartBlock]; } /*----------------------- YAFFS Functions -----------------------*/ int yaffs_GutsInitialise(yaffs_Device * dev); void yaffs_Deinitialise(yaffs_Device * dev); int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev); int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName, yaffs_Object * newDir, const YCHAR * newName); int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name); int yaffs_DeleteFile(yaffs_Object * obj); int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize); int yaffs_GetObjectFileLength(yaffs_Object * obj); int yaffs_GetObjectInode(yaffs_Object * obj); unsigned yaffs_GetObjectType(yaffs_Object * obj); int yaffs_GetObjectLinkCount(yaffs_Object * obj); int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr); int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr); /* File operations */ int yaffs_ReadDataFromFile(yaffs_Object * obj, __u8 * buffer, loff_t offset, int nBytes); int yaffs_WriteDataToFile(yaffs_Object * obj, const __u8 * buffer, loff_t offset, int nBytes, int writeThrough); int yaffs_ResizeFile(yaffs_Object * obj, loff_t newSize); yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid); int yaffs_FlushFile(yaffs_Object * obj, int updateTime); /* Flushing and checkpointing */ void yaffs_FlushEntireDeviceCache(yaffs_Device *dev); int yaffs_CheckpointSave(yaffs_Device *dev); int yaffs_CheckpointRestore(yaffs_Device *dev); /* Directory operations */ yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid); yaffs_Object *yaffs_FindObjectByName(yaffs_Object * theDir, const YCHAR * name); int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir, int (*fn) (yaffs_Object *)); yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number); /* Link operations */ yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name, yaffs_Object * equivalentObject); yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj); /* Symlink operations */ yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid, const YCHAR * alias); YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj); /* Special inodes (fifos, sockets and devices) */ yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev); /* Special directories */ yaffs_Object *yaffs_Root(yaffs_Device * dev); yaffs_Object *yaffs_LostNFound(yaffs_Device * dev); #ifdef CONFIG_YAFFS_WINCE /* CONFIG_YAFFS_WINCE special stuff */ void yfsd_WinFileTimeNow(__u32 target[2]); #endif /* XXX U-BOOT XXX */ #if 0 #ifndef __KERNEL__ void yaffs_HandleDeferedFree(yaffs_Object * obj); #endif #endif /* Debug dump */ int yaffs_DumpObject(yaffs_Object * obj); void yaffs_GutsTest(yaffs_Device * dev); /* A few useful functions */ void yaffs_InitialiseTags(yaffs_ExtendedTags * tags); void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn); int yaffs_CheckFF(__u8 * buffer, int nBytes); void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi); #endif
1001-study-uboot
fs/yaffs2/yaffs_guts.h
C
gpl3
25,645
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> #include "yaffs_packedtags2.h" #include "yportenv.h" #include "yaffs_tagsvalidity.h" /* This code packs a set of extended tags into a binary structure for * NAND storage */ /* Some of the information is "extra" struff which can be packed in to * speed scanning * This is defined by having the EXTRA_HEADER_INFO_FLAG set. */ /* Extra flags applied to chunkId */ #define EXTRA_HEADER_INFO_FLAG 0x80000000 #define EXTRA_SHRINK_FLAG 0x40000000 #define EXTRA_SHADOWS_FLAG 0x20000000 #define EXTRA_SPARE_FLAGS 0x10000000 #define ALL_EXTRA_FLAGS 0xF0000000 /* Also, the top 4 bits of the object Id are set to the object type. */ #define EXTRA_OBJECT_TYPE_SHIFT (28) #define EXTRA_OBJECT_TYPE_MASK ((0x0F) << EXTRA_OBJECT_TYPE_SHIFT) static void yaffs_DumpPackedTags2(const yaffs_PackedTags2 * pt) { T(YAFFS_TRACE_MTD, (TSTR("packed tags obj %d chunk %d byte %d seq %d" TENDSTR), pt->t.objectId, pt->t.chunkId, pt->t.byteCount, pt->t.sequenceNumber)); } static void yaffs_DumpTags2(const yaffs_ExtendedTags * t) { T(YAFFS_TRACE_MTD, (TSTR ("ext.tags eccres %d blkbad %d chused %d obj %d chunk%d byte " "%d del %d ser %d seq %d" TENDSTR), t->eccResult, t->blockBad, t->chunkUsed, t->objectId, t->chunkId, t->byteCount, t->chunkDeleted, t->serialNumber, t->sequenceNumber)); } void yaffs_PackTags2(yaffs_PackedTags2 * pt, const yaffs_ExtendedTags * t) { pt->t.chunkId = t->chunkId; pt->t.sequenceNumber = t->sequenceNumber; pt->t.byteCount = t->byteCount; pt->t.objectId = t->objectId; if (t->chunkId == 0 && t->extraHeaderInfoAvailable) { /* Store the extra header info instead */ /* We save the parent object in the chunkId */ pt->t.chunkId = EXTRA_HEADER_INFO_FLAG | t->extraParentObjectId; if (t->extraIsShrinkHeader) { pt->t.chunkId |= EXTRA_SHRINK_FLAG; } if (t->extraShadows) { pt->t.chunkId |= EXTRA_SHADOWS_FLAG; } pt->t.objectId &= ~EXTRA_OBJECT_TYPE_MASK; pt->t.objectId |= (t->extraObjectType << EXTRA_OBJECT_TYPE_SHIFT); if (t->extraObjectType == YAFFS_OBJECT_TYPE_HARDLINK) { pt->t.byteCount = t->extraEquivalentObjectId; } else if (t->extraObjectType == YAFFS_OBJECT_TYPE_FILE) { pt->t.byteCount = t->extraFileLength; } else { pt->t.byteCount = 0; } } yaffs_DumpPackedTags2(pt); yaffs_DumpTags2(t); #ifndef YAFFS_IGNORE_TAGS_ECC { yaffs_ECCCalculateOther((unsigned char *)&pt->t, sizeof(yaffs_PackedTags2TagsPart), &pt->ecc); } #endif } void yaffs_UnpackTags2(yaffs_ExtendedTags * t, yaffs_PackedTags2 * pt) { memset(t, 0, sizeof(yaffs_ExtendedTags)); yaffs_InitialiseTags(t); if (pt->t.sequenceNumber != 0xFFFFFFFF) { /* Page is in use */ #ifdef YAFFS_IGNORE_TAGS_ECC { t->eccResult = YAFFS_ECC_RESULT_NO_ERROR; } #else { yaffs_ECCOther ecc; int result; yaffs_ECCCalculateOther((unsigned char *)&pt->t, sizeof (yaffs_PackedTags2TagsPart), &ecc); result = yaffs_ECCCorrectOther((unsigned char *)&pt->t, sizeof (yaffs_PackedTags2TagsPart), &pt->ecc, &ecc); switch(result){ case 0: t->eccResult = YAFFS_ECC_RESULT_NO_ERROR; break; case 1: t->eccResult = YAFFS_ECC_RESULT_FIXED; break; case -1: t->eccResult = YAFFS_ECC_RESULT_UNFIXED; break; default: t->eccResult = YAFFS_ECC_RESULT_UNKNOWN; } } #endif t->blockBad = 0; t->chunkUsed = 1; t->objectId = pt->t.objectId; t->chunkId = pt->t.chunkId; t->byteCount = pt->t.byteCount; t->chunkDeleted = 0; t->serialNumber = 0; t->sequenceNumber = pt->t.sequenceNumber; /* Do extra header info stuff */ if (pt->t.chunkId & EXTRA_HEADER_INFO_FLAG) { t->chunkId = 0; t->byteCount = 0; t->extraHeaderInfoAvailable = 1; t->extraParentObjectId = pt->t.chunkId & (~(ALL_EXTRA_FLAGS)); t->extraIsShrinkHeader = (pt->t.chunkId & EXTRA_SHRINK_FLAG) ? 1 : 0; t->extraShadows = (pt->t.chunkId & EXTRA_SHADOWS_FLAG) ? 1 : 0; t->extraObjectType = pt->t.objectId >> EXTRA_OBJECT_TYPE_SHIFT; t->objectId &= ~EXTRA_OBJECT_TYPE_MASK; if (t->extraObjectType == YAFFS_OBJECT_TYPE_HARDLINK) { t->extraEquivalentObjectId = pt->t.byteCount; } else { t->extraFileLength = pt->t.byteCount; } } } yaffs_DumpPackedTags2(pt); yaffs_DumpTags2(t); }
1001-study-uboot
fs/yaffs2/yaffs_packedtags2.c
C
gpl3
4,808
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFSINTERFACE_H__ #define __YAFFSINTERFACE_H__ int yaffs_Initialise(unsigned nBlocks); #endif
1001-study-uboot
fs/yaffs2/yaffsinterface.h
C
gpl3
620
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_QSORT_H__ #define __YAFFS_QSORT_H__ extern void yaffs_qsort (void *const base, size_t total_elems, size_t size, int (*cmp)(const void *, const void *)); #endif
1001-study-uboot
fs/yaffs2/yaffs_qsort.h
C
gpl3
697
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> const char *yaffs_mtdif_c_version = "$Id: yaffs_mtdif.c,v 1.19 2007/02/14 01:09:06 wookey Exp $"; #include "yportenv.h" #include "yaffs_mtdif.h" #include "linux/mtd/mtd.h" #include "linux/types.h" #include "linux/time.h" #include "linux/mtd/nand.h" #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18)) static struct nand_oobinfo yaffs_oobinfo = { .useecc = 1, .eccbytes = 6, .eccpos = {8, 9, 10, 13, 14, 15} }; static struct nand_oobinfo yaffs_noeccinfo = { .useecc = 0, }; #endif #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) static inline void translate_spare2oob(const yaffs_Spare *spare, __u8 *oob) { oob[0] = spare->tagByte0; oob[1] = spare->tagByte1; oob[2] = spare->tagByte2; oob[3] = spare->tagByte3; oob[4] = spare->tagByte4; oob[5] = spare->tagByte5 & 0x3f; oob[5] |= spare->blockStatus == 'Y' ? 0: 0x80; oob[5] |= spare->pageStatus == 0 ? 0: 0x40; oob[6] = spare->tagByte6; oob[7] = spare->tagByte7; } static inline void translate_oob2spare(yaffs_Spare *spare, __u8 *oob) { struct yaffs_NANDSpare *nspare = (struct yaffs_NANDSpare *)spare; spare->tagByte0 = oob[0]; spare->tagByte1 = oob[1]; spare->tagByte2 = oob[2]; spare->tagByte3 = oob[3]; spare->tagByte4 = oob[4]; spare->tagByte5 = oob[5] == 0xff ? 0xff : oob[5] & 0x3f; spare->blockStatus = oob[5] & 0x80 ? 0xff : 'Y'; spare->pageStatus = oob[5] & 0x40 ? 0xff : 0; spare->ecc1[0] = spare->ecc1[1] = spare->ecc1[2] = 0xff; spare->tagByte6 = oob[6]; spare->tagByte7 = oob[7]; spare->ecc2[0] = spare->ecc2[1] = spare->ecc2[2] = 0xff; nspare->eccres1 = nspare->eccres2 = 0; /* FIXME */ } #endif int nandmtd_WriteChunkToNAND(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_Spare * spare) { struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) struct mtd_oob_ops ops; #endif size_t dummy; int retval = 0; loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk; #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) __u8 spareAsBytes[8]; /* OOB */ if (data && !spare) retval = mtd->write(mtd, addr, dev->nDataBytesPerChunk, &dummy, data); else if (spare) { if (dev->useNANDECC) { translate_spare2oob(spare, spareAsBytes); ops.mode = MTD_OOB_AUTO; ops.ooblen = 8; /* temp hack */ } else { ops.mode = MTD_OOB_RAW; ops.ooblen = YAFFS_BYTES_PER_SPARE; } ops.len = data ? dev->nDataBytesPerChunk : ops.ooblen; ops.datbuf = (u8 *)data; ops.ooboffs = 0; ops.oobbuf = spareAsBytes; retval = mtd->write_oob(mtd, addr, &ops); } #else __u8 *spareAsBytes = (__u8 *) spare; if (data && spare) { if (dev->useNANDECC) retval = mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk, &dummy, data, spareAsBytes, &yaffs_oobinfo); else retval = mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk, &dummy, data, spareAsBytes, &yaffs_noeccinfo); } else { if (data) retval = mtd->write(mtd, addr, dev->nDataBytesPerChunk, &dummy, data); if (spare) retval = mtd->write_oob(mtd, addr, YAFFS_BYTES_PER_SPARE, &dummy, spareAsBytes); } #endif if (retval == 0) return YAFFS_OK; else return YAFFS_FAIL; } int nandmtd_ReadChunkFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * data, yaffs_Spare * spare) { struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) struct mtd_oob_ops ops; #endif size_t dummy; int retval = 0; loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk; #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) __u8 spareAsBytes[8]; /* OOB */ if (data && !spare) retval = mtd->read(mtd, addr, dev->nDataBytesPerChunk, &dummy, data); else if (spare) { if (dev->useNANDECC) { ops.mode = MTD_OOB_AUTO; ops.ooblen = 8; /* temp hack */ } else { ops.mode = MTD_OOB_RAW; ops.ooblen = YAFFS_BYTES_PER_SPARE; } ops.len = data ? dev->nDataBytesPerChunk : ops.ooblen; ops.datbuf = data; ops.ooboffs = 0; ops.oobbuf = spareAsBytes; retval = mtd->read_oob(mtd, addr, &ops); if (dev->useNANDECC) translate_oob2spare(spare, spareAsBytes); } #else __u8 *spareAsBytes = (__u8 *) spare; if (data && spare) { if (dev->useNANDECC) { /* Careful, this call adds 2 ints */ /* to the end of the spare data. Calling function */ /* should allocate enough memory for spare, */ /* i.e. [YAFFS_BYTES_PER_SPARE+2*sizeof(int)]. */ retval = mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk, &dummy, data, spareAsBytes, &yaffs_oobinfo); } else { retval = mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk, &dummy, data, spareAsBytes, &yaffs_noeccinfo); } } else { if (data) retval = mtd->read(mtd, addr, dev->nDataBytesPerChunk, &dummy, data); if (spare) retval = mtd->read_oob(mtd, addr, YAFFS_BYTES_PER_SPARE, &dummy, spareAsBytes); } #endif if (retval == 0) return YAFFS_OK; else return YAFFS_FAIL; } int nandmtd_EraseBlockInNAND(yaffs_Device * dev, int blockNumber) { struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); __u32 addr = ((loff_t) blockNumber) * dev->nDataBytesPerChunk * dev->nChunksPerBlock; struct erase_info ei; int retval = 0; ei.mtd = mtd; ei.addr = addr; ei.len = dev->nDataBytesPerChunk * dev->nChunksPerBlock; ei.time = 1000; ei.retries = 2; ei.callback = NULL; ei.priv = (u_long) dev; /* Todo finish off the ei if required */ /* XXX U-BOOT XXX */ #if 0 sema_init(&dev->sem, 0); #endif retval = mtd->erase(mtd, &ei); if (retval == 0) return YAFFS_OK; else return YAFFS_FAIL; } int nandmtd_InitialiseNAND(yaffs_Device * dev) { return YAFFS_OK; }
1001-study-uboot
fs/yaffs2/yaffs_mtdif.c
C
gpl3
6,243
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_NAND_H__ #define __YAFFS_NAND_H__ #include "yaffs_guts.h" int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * buffer, yaffs_ExtendedTags * tags); int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND, const __u8 * buffer, yaffs_ExtendedTags * tags); int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo); int yaffs_QueryInitialBlockState(yaffs_Device * dev, int blockNo, yaffs_BlockState * state, int *sequenceNumber); int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev, int blockInNAND); int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev); #endif
1001-study-uboot
fs/yaffs2/yaffs_nand.h
C
gpl3
1,216
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ #ifndef __YAFFS_TAGSCOMPAT_H__ #define __YAFFS_TAGSCOMPAT_H__ #include "yaffs_guts.h" int yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND, const __u8 * data, const yaffs_ExtendedTags * tags); int yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * data, yaffs_ExtendedTags * tags); int yaffs_TagsCompatabilityMarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo); int yaffs_TagsCompatabilityQueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo, yaffs_BlockState * state, int *sequenceNumber); void yaffs_CalcTagsECC(yaffs_Tags * tags); int yaffs_CheckECCOnTags(yaffs_Tags * tags); int yaffs_CountBits(__u8 byte); #endif
1001-study-uboot
fs/yaffs2/yaffs_tagscompat.h
C
gpl3
1,334
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* * Header file for using yaffs in an application via * a direct interface. */ #ifndef __YAFFSFS_H__ #define __YAFFSFS_H__ #include "yaffscfg.h" #include "yportenv.h" //typedef long off_t; //typedef long dev_t; //typedef unsigned long mode_t; #ifndef NAME_MAX #define NAME_MAX 256 #endif #ifndef O_RDONLY #define O_RDONLY 00 #endif #ifndef O_WRONLY #define O_WRONLY 01 #endif #ifndef O_RDWR #define O_RDWR 02 #endif #ifndef O_CREAT #define O_CREAT 0100 #endif #ifndef O_EXCL #define O_EXCL 0200 #endif #ifndef O_TRUNC #define O_TRUNC 01000 #endif #ifndef O_APPEND #define O_APPEND 02000 #endif #ifndef SEEK_SET #define SEEK_SET 0 #endif #ifndef SEEK_CUR #define SEEK_CUR 1 #endif #ifndef SEEK_END #define SEEK_END 2 #endif #ifndef EBUSY #define EBUSY 16 #endif #ifndef ENODEV #define ENODEV 19 #endif #ifndef EINVAL #define EINVAL 22 #endif #ifndef EBADF #define EBADF 9 #endif #ifndef EACCESS #define EACCESS 13 #endif #ifndef EXDEV #define EXDEV 18 #endif #ifndef ENOENT #define ENOENT 2 #endif #ifndef ENOSPC #define ENOSPC 28 #endif #ifndef ENOTEMPTY #define ENOTEMPTY 39 #endif #ifndef ENOMEM #define ENOMEM 12 #endif #ifndef EEXIST #define EEXIST 17 #endif #ifndef ENOTDIR #define ENOTDIR 20 #endif #ifndef EISDIR #define EISDIR 21 #endif // Mode flags #ifndef S_IFMT #define S_IFMT 0170000 #endif #ifndef S_IFLNK #define S_IFLNK 0120000 #endif #ifndef S_IFDIR #define S_IFDIR 0040000 #endif #ifndef S_IFREG #define S_IFREG 0100000 #endif #ifndef S_IREAD #define S_IREAD 0000400 #endif #ifndef S_IWRITE #define S_IWRITE 0000200 #endif struct yaffs_dirent{ long d_ino; /* inode number */ off_t d_off; /* offset to this dirent */ unsigned short d_reclen; /* length of this d_name */ char d_name [NAME_MAX+1]; /* file name (null-terminated) */ unsigned d_dont_use; /* debug pointer, not for public consumption */ }; typedef struct yaffs_dirent yaffs_dirent; typedef struct __opaque yaffs_DIR; struct yaffs_stat{ int st_dev; /* device */ int st_ino; /* inode */ mode_t st_mode; /* protection */ int st_nlink; /* number of hard links */ int st_uid; /* user ID of owner */ int st_gid; /* group ID of owner */ unsigned st_rdev; /* device type (if inode device) */ off_t st_size; /* total size, in bytes */ unsigned long st_blksize; /* blocksize for filesystem I/O */ unsigned long st_blocks; /* number of blocks allocated */ unsigned long yst_atime; /* time of last access */ unsigned long yst_mtime; /* time of last modification */ unsigned long yst_ctime; /* time of last change */ }; int yaffs_open(const char *path, int oflag, int mode) ; int yaffs_read(int fd, void *buf, unsigned int nbyte) ; int yaffs_write(int fd, const void *buf, unsigned int nbyte) ; int yaffs_close(int fd) ; off_t yaffs_lseek(int fd, off_t offset, int whence) ; int yaffs_truncate(int fd, off_t newSize); int yaffs_unlink(const char *path) ; int yaffs_rename(const char *oldPath, const char *newPath) ; int yaffs_stat(const char *path, struct yaffs_stat *buf) ; int yaffs_lstat(const char *path, struct yaffs_stat *buf) ; int yaffs_fstat(int fd, struct yaffs_stat *buf) ; int yaffs_chmod(const char *path, mode_t mode); int yaffs_fchmod(int fd, mode_t mode); int yaffs_mkdir(const char *path, mode_t mode) ; int yaffs_rmdir(const char *path) ; yaffs_DIR *yaffs_opendir(const char *dirname) ; struct yaffs_dirent *yaffs_readdir(yaffs_DIR *dirp) ; void yaffs_rewinddir(yaffs_DIR *dirp) ; int yaffs_closedir(yaffs_DIR *dirp) ; int yaffs_mount(const char *path) ; int yaffs_unmount(const char *path) ; int yaffs_symlink(const char *oldpath, const char *newpath); int yaffs_readlink(const char *path, char *buf, int bufsiz); int yaffs_link(const char *oldpath, const char *newpath); int yaffs_mknod(const char *pathname, mode_t mode, dev_t dev); loff_t yaffs_freespace(const char *path); void yaffs_initialise(yaffsfs_DeviceConfiguration *configList); int yaffs_StartUp(void); #endif
1001-study-uboot
fs/yaffs2/yaffsfs.h
C
gpl3
4,667
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* * yaffs_ramdisk.h: yaffs ram disk component */ #ifndef __YAFFS_RAMDISK_H__ #define __YAFFS_RAMDISK_H__ #include "yaffs_guts.h" int yramdisk_EraseBlockInNAND(yaffs_Device *dev, int blockNumber); int yramdisk_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND,const __u8 *data, yaffs_ExtendedTags *tags); int yramdisk_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *data, yaffs_ExtendedTags *tags); int yramdisk_EraseBlockInNAND(yaffs_Device *dev, int blockNumber); int yramdisk_InitialiseNAND(yaffs_Device *dev); int yramdisk_MarkNANDBlockBad(yaffs_Device *dev,int blockNumber); int yramdisk_QueryNANDBlock(yaffs_Device *dev, int blockNo, yaffs_BlockState *state, int *sequenceNumber); #endif
1001-study-uboot
fs/yaffs2/yaffs_ramdisk.h
C
gpl3
1,240
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* * Header file for using yaffs in an application via * a direct interface. */ #ifndef __YAFFSCFG_H__ #define __YAFFSCFG_H__ #include "devextras.h" #define YAFFSFS_N_HANDLES 200 typedef struct { const char *prefix; struct yaffs_DeviceStruct *dev; } yaffsfs_DeviceConfiguration; void yaffsfs_Lock(void); void yaffsfs_Unlock(void); __u32 yaffsfs_CurrentTime(void); void yaffsfs_SetError(int err); int yaffsfs_GetError(void); #endif
1001-study-uboot
fs/yaffs2/yaffscfg.h
C
gpl3
961
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* XXX U-BOOT XXX */ #include <common.h> const char *yaffs_nand_c_version = "$Id: yaffs_nand.c,v 1.7 2007/02/14 01:09:06 wookey Exp $"; #include "yaffs_nand.h" #include "yaffs_tagscompat.h" #include "yaffs_tagsvalidity.h" int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND, __u8 * buffer, yaffs_ExtendedTags * tags) { int result; yaffs_ExtendedTags localTags; int realignedChunkInNAND = chunkInNAND - dev->chunkOffset; /* If there are no tags provided, use local tags to get prioritised gc working */ if(!tags) tags = &localTags; if (dev->readChunkWithTagsFromNAND) result = dev->readChunkWithTagsFromNAND(dev, realignedChunkInNAND, buffer, tags); else result = yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev, realignedChunkInNAND, buffer, tags); if(tags && tags->eccResult > YAFFS_ECC_RESULT_NO_ERROR){ yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, chunkInNAND/dev->nChunksPerBlock); yaffs_HandleChunkError(dev,bi); } return result; } int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND, const __u8 * buffer, yaffs_ExtendedTags * tags) { chunkInNAND -= dev->chunkOffset; if (tags) { tags->sequenceNumber = dev->sequenceNumber; tags->chunkUsed = 1; if (!yaffs_ValidateTags(tags)) { T(YAFFS_TRACE_ERROR, (TSTR("Writing uninitialised tags" TENDSTR))); YBUG(); } T(YAFFS_TRACE_WRITE, (TSTR("Writing chunk %d tags %d %d" TENDSTR), chunkInNAND, tags->objectId, tags->chunkId)); } else { T(YAFFS_TRACE_ERROR, (TSTR("Writing with no tags" TENDSTR))); YBUG(); } if (dev->writeChunkWithTagsToNAND) return dev->writeChunkWithTagsToNAND(dev, chunkInNAND, buffer, tags); else return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev, chunkInNAND, buffer, tags); } int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo) { blockNo -= dev->blockOffset; ; if (dev->markNANDBlockBad) return dev->markNANDBlockBad(dev, blockNo); else return yaffs_TagsCompatabilityMarkNANDBlockBad(dev, blockNo); } int yaffs_QueryInitialBlockState(yaffs_Device * dev, int blockNo, yaffs_BlockState * state, int *sequenceNumber) { blockNo -= dev->blockOffset; if (dev->queryNANDBlock) return dev->queryNANDBlock(dev, blockNo, state, sequenceNumber); else return yaffs_TagsCompatabilityQueryNANDBlock(dev, blockNo, state, sequenceNumber); } int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev, int blockInNAND) { int result; blockInNAND -= dev->blockOffset; dev->nBlockErasures++; result = dev->eraseBlockInNAND(dev, blockInNAND); return result; } int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev) { return dev->initialiseNAND(dev); }
1001-study-uboot
fs/yaffs2/yaffs_nand.c
C
gpl3
3,295
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* Interface to emulated NAND functions (2k page size) */ #ifndef __YAFFS_NANDEMUL2K_H__ #define __YAFFS_NANDEMUL2K_H__ #include "yaffs_guts.h" int nandemul2k_WriteChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev, int chunkInNAND, const __u8 * data, yaffs_ExtendedTags * tags); int nandemul2k_ReadChunkWithTagsFromNAND(struct yaffs_DeviceStruct *dev, int chunkInNAND, __u8 * data, yaffs_ExtendedTags * tags); int nandemul2k_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo); int nandemul2k_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo, yaffs_BlockState * state, int *sequenceNumber); int nandemul2k_EraseBlockInNAND(struct yaffs_DeviceStruct *dev, int blockInNAND); int nandemul2k_InitialiseNAND(struct yaffs_DeviceStruct *dev); int nandemul2k_GetBytesPerChunk(void); int nandemul2k_GetChunksPerBlock(void); int nandemul2k_GetNumberOfBlocks(void); #endif
1001-study-uboot
fs/yaffs2/yaffs_nandemul2k.h
C
gpl3
1,435
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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 code implements the ECC algorithm used in SmartMedia. * * The ECC comprises 22 bits of parity information and is stuffed into 3 bytes. * The two unused bit are set to 1. * The ECC can correct single bit errors in a 256-byte page of data. Thus, two such ECC * blocks are used on a 512-byte NAND page. * */ /* Table generated by gen-ecc.c * Using a table means we do not have to calculate p1..p4 and p1'..p4' * for each byte of data. These are instead provided in a table in bits7..2. * Bit 0 of each entry indicates whether the entry has an odd or even parity, and therefore * this bytes influence on the line parity. */ /* XXX U-BOOT XXX */ #include <common.h> const char *yaffs_ecc_c_version = "$Id: yaffs_ecc.c,v 1.9 2007/02/14 01:09:06 wookey Exp $"; #include "yportenv.h" #include "yaffs_ecc.h" static const unsigned char column_parity_table[] = { 0x00, 0x55, 0x59, 0x0c, 0x65, 0x30, 0x3c, 0x69, 0x69, 0x3c, 0x30, 0x65, 0x0c, 0x59, 0x55, 0x00, 0x95, 0xc0, 0xcc, 0x99, 0xf0, 0xa5, 0xa9, 0xfc, 0xfc, 0xa9, 0xa5, 0xf0, 0x99, 0xcc, 0xc0, 0x95, 0x99, 0xcc, 0xc0, 0x95, 0xfc, 0xa9, 0xa5, 0xf0, 0xf0, 0xa5, 0xa9, 0xfc, 0x95, 0xc0, 0xcc, 0x99, 0x0c, 0x59, 0x55, 0x00, 0x69, 0x3c, 0x30, 0x65, 0x65, 0x30, 0x3c, 0x69, 0x00, 0x55, 0x59, 0x0c, 0xa5, 0xf0, 0xfc, 0xa9, 0xc0, 0x95, 0x99, 0xcc, 0xcc, 0x99, 0x95, 0xc0, 0xa9, 0xfc, 0xf0, 0xa5, 0x30, 0x65, 0x69, 0x3c, 0x55, 0x00, 0x0c, 0x59, 0x59, 0x0c, 0x00, 0x55, 0x3c, 0x69, 0x65, 0x30, 0x3c, 0x69, 0x65, 0x30, 0x59, 0x0c, 0x00, 0x55, 0x55, 0x00, 0x0c, 0x59, 0x30, 0x65, 0x69, 0x3c, 0xa9, 0xfc, 0xf0, 0xa5, 0xcc, 0x99, 0x95, 0xc0, 0xc0, 0x95, 0x99, 0xcc, 0xa5, 0xf0, 0xfc, 0xa9, 0xa9, 0xfc, 0xf0, 0xa5, 0xcc, 0x99, 0x95, 0xc0, 0xc0, 0x95, 0x99, 0xcc, 0xa5, 0xf0, 0xfc, 0xa9, 0x3c, 0x69, 0x65, 0x30, 0x59, 0x0c, 0x00, 0x55, 0x55, 0x00, 0x0c, 0x59, 0x30, 0x65, 0x69, 0x3c, 0x30, 0x65, 0x69, 0x3c, 0x55, 0x00, 0x0c, 0x59, 0x59, 0x0c, 0x00, 0x55, 0x3c, 0x69, 0x65, 0x30, 0xa5, 0xf0, 0xfc, 0xa9, 0xc0, 0x95, 0x99, 0xcc, 0xcc, 0x99, 0x95, 0xc0, 0xa9, 0xfc, 0xf0, 0xa5, 0x0c, 0x59, 0x55, 0x00, 0x69, 0x3c, 0x30, 0x65, 0x65, 0x30, 0x3c, 0x69, 0x00, 0x55, 0x59, 0x0c, 0x99, 0xcc, 0xc0, 0x95, 0xfc, 0xa9, 0xa5, 0xf0, 0xf0, 0xa5, 0xa9, 0xfc, 0x95, 0xc0, 0xcc, 0x99, 0x95, 0xc0, 0xcc, 0x99, 0xf0, 0xa5, 0xa9, 0xfc, 0xfc, 0xa9, 0xa5, 0xf0, 0x99, 0xcc, 0xc0, 0x95, 0x00, 0x55, 0x59, 0x0c, 0x65, 0x30, 0x3c, 0x69, 0x69, 0x3c, 0x30, 0x65, 0x0c, 0x59, 0x55, 0x00, }; /* Count the bits in an unsigned char or a U32 */ static int yaffs_CountBits(unsigned char x) { int r = 0; while (x) { if (x & 1) r++; x >>= 1; } return r; } static int yaffs_CountBits32(unsigned x) { int r = 0; while (x) { if (x & 1) r++; x >>= 1; } return r; } /* Calculate the ECC for a 256-byte block of data */ void yaffs_ECCCalculate(const unsigned char *data, unsigned char *ecc) { unsigned int i; unsigned char col_parity = 0; unsigned char line_parity = 0; unsigned char line_parity_prime = 0; unsigned char t; unsigned char b; for (i = 0; i < 256; i++) { b = column_parity_table[*data++]; col_parity ^= b; if (b & 0x01) // odd number of bits in the byte { line_parity ^= i; line_parity_prime ^= ~i; } } ecc[2] = (~col_parity) | 0x03; t = 0; if (line_parity & 0x80) t |= 0x80; if (line_parity_prime & 0x80) t |= 0x40; if (line_parity & 0x40) t |= 0x20; if (line_parity_prime & 0x40) t |= 0x10; if (line_parity & 0x20) t |= 0x08; if (line_parity_prime & 0x20) t |= 0x04; if (line_parity & 0x10) t |= 0x02; if (line_parity_prime & 0x10) t |= 0x01; ecc[1] = ~t; t = 0; if (line_parity & 0x08) t |= 0x80; if (line_parity_prime & 0x08) t |= 0x40; if (line_parity & 0x04) t |= 0x20; if (line_parity_prime & 0x04) t |= 0x10; if (line_parity & 0x02) t |= 0x08; if (line_parity_prime & 0x02) t |= 0x04; if (line_parity & 0x01) t |= 0x02; if (line_parity_prime & 0x01) t |= 0x01; ecc[0] = ~t; #ifdef CONFIG_YAFFS_ECC_WRONG_ORDER // Swap the bytes into the wrong order t = ecc[0]; ecc[0] = ecc[1]; ecc[1] = t; #endif } /* Correct the ECC on a 256 byte block of data */ int yaffs_ECCCorrect(unsigned char *data, unsigned char *read_ecc, const unsigned char *test_ecc) { unsigned char d0, d1, d2; /* deltas */ d0 = read_ecc[0] ^ test_ecc[0]; d1 = read_ecc[1] ^ test_ecc[1]; d2 = read_ecc[2] ^ test_ecc[2]; if ((d0 | d1 | d2) == 0) return 0; /* no error */ if (((d0 ^ (d0 >> 1)) & 0x55) == 0x55 && ((d1 ^ (d1 >> 1)) & 0x55) == 0x55 && ((d2 ^ (d2 >> 1)) & 0x54) == 0x54) { /* Single bit (recoverable) error in data */ unsigned byte; unsigned bit; #ifdef CONFIG_YAFFS_ECC_WRONG_ORDER // swap the bytes to correct for the wrong order unsigned char t; t = d0; d0 = d1; d1 = t; #endif bit = byte = 0; if (d1 & 0x80) byte |= 0x80; if (d1 & 0x20) byte |= 0x40; if (d1 & 0x08) byte |= 0x20; if (d1 & 0x02) byte |= 0x10; if (d0 & 0x80) byte |= 0x08; if (d0 & 0x20) byte |= 0x04; if (d0 & 0x08) byte |= 0x02; if (d0 & 0x02) byte |= 0x01; if (d2 & 0x80) bit |= 0x04; if (d2 & 0x20) bit |= 0x02; if (d2 & 0x08) bit |= 0x01; data[byte] ^= (1 << bit); return 1; /* Corrected the error */ } if ((yaffs_CountBits(d0) + yaffs_CountBits(d1) + yaffs_CountBits(d2)) == 1) { /* Reccoverable error in ecc */ read_ecc[0] = test_ecc[0]; read_ecc[1] = test_ecc[1]; read_ecc[2] = test_ecc[2]; return 1; /* Corrected the error */ } /* Unrecoverable error */ return -1; } /* * ECCxxxOther does ECC calcs on arbitrary n bytes of data */ void yaffs_ECCCalculateOther(const unsigned char *data, unsigned nBytes, yaffs_ECCOther * eccOther) { unsigned int i; unsigned char col_parity = 0; unsigned line_parity = 0; unsigned line_parity_prime = 0; unsigned char b; for (i = 0; i < nBytes; i++) { b = column_parity_table[*data++]; col_parity ^= b; if (b & 0x01) { /* odd number of bits in the byte */ line_parity ^= i; line_parity_prime ^= ~i; } } eccOther->colParity = (col_parity >> 2) & 0x3f; eccOther->lineParity = line_parity; eccOther->lineParityPrime = line_parity_prime; } int yaffs_ECCCorrectOther(unsigned char *data, unsigned nBytes, yaffs_ECCOther * read_ecc, const yaffs_ECCOther * test_ecc) { unsigned char cDelta; /* column parity delta */ unsigned lDelta; /* line parity delta */ unsigned lDeltaPrime; /* line parity delta */ unsigned bit; cDelta = read_ecc->colParity ^ test_ecc->colParity; lDelta = read_ecc->lineParity ^ test_ecc->lineParity; lDeltaPrime = read_ecc->lineParityPrime ^ test_ecc->lineParityPrime; if ((cDelta | lDelta | lDeltaPrime) == 0) return 0; /* no error */ if (lDelta == ~lDeltaPrime && (((cDelta ^ (cDelta >> 1)) & 0x15) == 0x15)) { /* Single bit (recoverable) error in data */ bit = 0; if (cDelta & 0x20) bit |= 0x04; if (cDelta & 0x08) bit |= 0x02; if (cDelta & 0x02) bit |= 0x01; if(lDelta >= nBytes) return -1; data[lDelta] ^= (1 << bit); return 1; /* corrected */ } if ((yaffs_CountBits32(lDelta) + yaffs_CountBits32(lDeltaPrime) + yaffs_CountBits(cDelta)) == 1) { /* Reccoverable error in ecc */ *read_ecc = *test_ecc; return 1; /* corrected */ } /* Unrecoverable error */ return -1; }
1001-study-uboot
fs/yaffs2/yaffs_ecc.c
C
gpl3
7,776
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2007 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * 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. */ /* * yaffscfg.c The configuration for the "direct" use of yaffs. * * This file is intended to be modified to your requirements. * There is no need to redistribute this file. */ /* XXX U-BOOT XXX */ #include <common.h> #include <config.h> #include "nand.h" #include "yaffscfg.h" #include "yaffsfs.h" #include "yaffs_packedtags2.h" #include "yaffs_mtdif.h" #include "yaffs_mtdif2.h" #if 0 #include <errno.h> #else #include "malloc.h" #endif unsigned yaffs_traceMask = 0x0; /* Disable logging */ static int yaffs_errno = 0; void yaffsfs_SetError(int err) { //Do whatever to set error yaffs_errno = err; } int yaffsfs_GetError(void) { return yaffs_errno; } void yaffsfs_Lock(void) { } void yaffsfs_Unlock(void) { } __u32 yaffsfs_CurrentTime(void) { return 0; } void *yaffs_malloc(size_t size) { return malloc(size); } void yaffs_free(void *ptr) { free(ptr); } void yaffsfs_LocalInitialisation(void) { // Define locking semaphore. } // Configuration for: // /ram 2MB ramdisk // /boot 2MB boot disk (flash) // /flash 14MB flash disk (flash) // NB Though /boot and /flash occupy the same physical device they // are still disticnt "yaffs_Devices. You may think of these as "partitions" // using non-overlapping areas in the same device. // #include "yaffs_ramdisk.h" #include "yaffs_flashif.h" static int isMounted = 0; #define MOUNT_POINT "/flash" extern nand_info_t nand_info[]; /* XXX U-BOOT XXX */ #if 0 static yaffs_Device ramDev; static yaffs_Device bootDev; static yaffs_Device flashDev; #endif static yaffsfs_DeviceConfiguration yaffsfs_config[] = { /* XXX U-BOOT XXX */ #if 0 { "/ram", &ramDev}, { "/boot", &bootDev}, { "/flash", &flashDev}, #else { MOUNT_POINT, 0}, #endif {(void *)0,(void *)0} }; int yaffs_StartUp(void) { struct mtd_info *mtd = &nand_info[0]; int yaffsVersion = 2; int nBlocks; yaffs_Device *flashDev = calloc(1, sizeof(yaffs_Device)); yaffsfs_config[0].dev = flashDev; /* store the mtd device for later use */ flashDev->genericDevice = mtd; // Stuff to configure YAFFS // Stuff to initialise anything special (eg lock semaphore). yaffsfs_LocalInitialisation(); // Set up devices /* XXX U-BOOT XXX */ #if 0 // /ram ramDev.nBytesPerChunk = 512; ramDev.nChunksPerBlock = 32; ramDev.nReservedBlocks = 2; // Set this smaller for RAM ramDev.startBlock = 1; // Can't use block 0 ramDev.endBlock = 127; // Last block in 2MB. ramDev.useNANDECC = 1; ramDev.nShortOpCaches = 0; // Disable caching on this device. ramDev.genericDevice = (void *) 0; // Used to identify the device in fstat. ramDev.writeChunkWithTagsToNAND = yramdisk_WriteChunkWithTagsToNAND; ramDev.readChunkWithTagsFromNAND = yramdisk_ReadChunkWithTagsFromNAND; ramDev.eraseBlockInNAND = yramdisk_EraseBlockInNAND; ramDev.initialiseNAND = yramdisk_InitialiseNAND; // /boot bootDev.nBytesPerChunk = 612; bootDev.nChunksPerBlock = 32; bootDev.nReservedBlocks = 5; bootDev.startBlock = 1; // Can't use block 0 bootDev.endBlock = 127; // Last block in 2MB. bootDev.useNANDECC = 0; // use YAFFS's ECC bootDev.nShortOpCaches = 10; // Use caches bootDev.genericDevice = (void *) 1; // Used to identify the device in fstat. bootDev.writeChunkToNAND = yflash_WriteChunkToNAND; bootDev.readChunkFromNAND = yflash_ReadChunkFromNAND; bootDev.eraseBlockInNAND = yflash_EraseBlockInNAND; bootDev.initialiseNAND = yflash_InitialiseNAND; #endif // /flash flashDev->nReservedBlocks = 5; // flashDev->nShortOpCaches = (options.no_cache) ? 0 : 10; flashDev->nShortOpCaches = 10; // Use caches flashDev->useNANDECC = 0; // do not use YAFFS's ECC if (yaffsVersion == 2) { flashDev->writeChunkWithTagsToNAND = nandmtd2_WriteChunkWithTagsToNAND; flashDev->readChunkWithTagsFromNAND = nandmtd2_ReadChunkWithTagsFromNAND; flashDev->markNANDBlockBad = nandmtd2_MarkNANDBlockBad; flashDev->queryNANDBlock = nandmtd2_QueryNANDBlock; flashDev->spareBuffer = YMALLOC(mtd->oobsize); flashDev->isYaffs2 = 1; #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) flashDev->nDataBytesPerChunk = mtd->writesize; flashDev->nChunksPerBlock = mtd->erasesize / mtd->writesize; #else flashDev->nDataBytesPerChunk = mtd->oobblock; flashDev->nChunksPerBlock = mtd->erasesize / mtd->oobblock; #endif nBlocks = mtd->size / mtd->erasesize; flashDev->nCheckpointReservedBlocks = 10; flashDev->startBlock = 0; flashDev->endBlock = nBlocks - 1; } else { flashDev->writeChunkToNAND = nandmtd_WriteChunkToNAND; flashDev->readChunkFromNAND = nandmtd_ReadChunkFromNAND; flashDev->isYaffs2 = 0; nBlocks = mtd->size / (YAFFS_CHUNKS_PER_BLOCK * YAFFS_BYTES_PER_CHUNK); flashDev->startBlock = 320; flashDev->endBlock = nBlocks - 1; flashDev->nChunksPerBlock = YAFFS_CHUNKS_PER_BLOCK; flashDev->nDataBytesPerChunk = YAFFS_BYTES_PER_CHUNK; } /* ... and common functions */ flashDev->eraseBlockInNAND = nandmtd_EraseBlockInNAND; flashDev->initialiseNAND = nandmtd_InitialiseNAND; yaffs_initialise(yaffsfs_config); return 0; } void make_a_file(char *yaffsName,char bval,int sizeOfFile) { int outh; int i; unsigned char buffer[100]; outh = yaffs_open(yaffsName, O_CREAT | O_RDWR | O_TRUNC, S_IREAD | S_IWRITE); if (outh < 0) { printf("Error opening file: %d\n", outh); return; } memset(buffer,bval,100); do{ i = sizeOfFile; if(i > 100) i = 100; sizeOfFile -= i; yaffs_write(outh,buffer,i); } while (sizeOfFile > 0); yaffs_close(outh); } void read_a_file(char *fn) { int h; int i = 0; unsigned char b; h = yaffs_open(fn, O_RDWR,0); if(h<0) { printf("File not found\n"); return; } while(yaffs_read(h,&b,1)> 0) { printf("%02x ",b); i++; if(i > 32) { printf("\n"); i = 0;; } } printf("\n"); yaffs_close(h); } void cmd_yaffs_mount(char *mp) { yaffs_StartUp(); int retval = yaffs_mount(mp); if( retval != -1) isMounted = 1; else printf("Error mounting %s, return value: %d\n", mp, yaffsfs_GetError()); } static void checkMount(void) { if( !isMounted ) { cmd_yaffs_mount(MOUNT_POINT); } } void cmd_yaffs_umount(char *mp) { checkMount(); if( yaffs_unmount(mp) == -1) printf("Error umounting %s, return value: %d\n", mp, yaffsfs_GetError()); } void cmd_yaffs_write_file(char *yaffsName,char bval,int sizeOfFile) { checkMount(); make_a_file(yaffsName,bval,sizeOfFile); } void cmd_yaffs_read_file(char *fn) { checkMount(); read_a_file(fn); } void cmd_yaffs_mread_file(char *fn, char *addr) { int h; struct yaffs_stat s; checkMount(); yaffs_stat(fn,&s); printf ("Copy %s to 0x%p... ", fn, addr); h = yaffs_open(fn, O_RDWR,0); if(h<0) { printf("File not found\n"); return; } yaffs_read(h,addr,(int)s.st_size); printf("\t[DONE]\n"); yaffs_close(h); } void cmd_yaffs_mwrite_file(char *fn, char *addr, int size) { int outh; checkMount(); outh = yaffs_open(fn, O_CREAT | O_RDWR | O_TRUNC, S_IREAD | S_IWRITE); if (outh < 0) { printf("Error opening file: %d\n", outh); } yaffs_write(outh,addr,size); yaffs_close(outh); } void cmd_yaffs_ls(const char *mountpt, int longlist) { int i; yaffs_DIR *d; yaffs_dirent *de; struct yaffs_stat stat; char tempstr[255]; checkMount(); d = yaffs_opendir(mountpt); if(!d) { printf("opendir failed\n"); } else { for(i = 0; (de = yaffs_readdir(d)) != NULL; i++) { if (longlist) { sprintf(tempstr, "%s/%s", mountpt, de->d_name); yaffs_stat(tempstr, &stat); printf("%-25s\t%7ld\n",de->d_name, stat.st_size); } else { printf("%s\n",de->d_name); } } } } void cmd_yaffs_mkdir(const char *dir) { checkMount(); int retval = yaffs_mkdir(dir, 0); if ( retval < 0) printf("yaffs_mkdir returning error: %d\n", retval); } void cmd_yaffs_rmdir(const char *dir) { checkMount(); int retval = yaffs_rmdir(dir); if ( retval < 0) printf("yaffs_rmdir returning error: %d\n", retval); } void cmd_yaffs_rm(const char *path) { checkMount(); int retval = yaffs_unlink(path); if ( retval < 0) printf("yaffs_unlink returning error: %d\n", retval); } void cmd_yaffs_mv(const char *oldPath, const char *newPath) { checkMount(); int retval = yaffs_rename(newPath, oldPath); if ( retval < 0) printf("yaffs_unlink returning error: %d\n", retval); }
1001-study-uboot
fs/yaffs2/yaffscfg.c
C
gpl3
8,654
# # Copyright (c) 2011 The Chromium OS Authors. # # 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 Foundatio; 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 # # This Makefile builds the internal U-Boot fdt if CONFIG_OF_CONTROL is # enabled. See doc/README.fdt-control for more details. include $(TOPDIR)/config.mk LIB = $(obj)libdts.o $(if $(CONFIG_DEFAULT_DEVICE_TREE),,\ $(error Please define CONFIG_DEFAULT_DEVICE_TREE in your board header file)) DEVICE_TREE = $(subst ",,$(CONFIG_DEFAULT_DEVICE_TREE)) $(if $(CONFIG_ARCH_DEVICE_TREE),,\ $(error Your architecture does not have device tree support enabled. \ Please define CONFIG_ARCH_DEVICE_TREE)) # We preprocess the device tree file provide a useful define DTS_CPPFLAGS := -DARCH_CPU_DTS=\"../arch/$(ARCH)/dts/$(CONFIG_ARCH_DEVICE_TREE).dtsi\" all: $(obj).depend $(LIB) # Use a constant name for this so we can access it from C code. # objcopy doesn't seem to allow us to set the symbol name independently of # the filename. DT_BIN := $(obj)dt.dtb $(DT_BIN): $(TOPDIR)/board/$(VENDOR)/dts/$(DEVICE_TREE).dts cat $< | $(CPP) -P $(DTS_CPPFLAGS) - >$@.tmp $(DTC) -R 4 -p 0x1000 -O dtb -o ${DT_BIN} $@.tmp rm $@.tmp process_lds = \ $(1) | sed -r -n 's/^OUTPUT_$(2)[ ("]*([^")]*).*/\1/p' # Run the compiler and get the link script from the linker GET_LDS = $(CC) $(CFLAGS) $(LDFLAGS) -Wl,--verbose 2>&1 $(obj)dt.o: $(DT_BIN) # We want the output format and arch. # We also hope to win a prize for ugliest Makefile / shell interaction # We look in the LDSCRIPT first. # Then try the linker which should give us the answer. # Then check it worked. oformat=`$(call process_lds,cat $(LDSCRIPT),FORMAT)` ;\ oarch=`$(call process_lds,cat $(LDSCRIPT),ARCH)` ;\ \ [ -z $${oformat} ] && \ oformat=`$(call process_lds,$(GET_LDS),FORMAT)` ;\ [ -z $${oarch} ] && \ oarch=`$(call process_lds,$(GET_LDS),ARCH)` ;\ \ [ -z $${oformat} ] && \ echo "Cannot read OUTPUT_FORMAT from lds file $(LDSCRIPT)" && \ exit 1 || true ;\ [ -z $${oarch} ] && \ echo "Cannot read OUTPUT_ARCH from lds file $(LDSCRIPT)" && \ exit 1 || true ;\ \ cd $(dir ${DT_BIN}) && \ $(OBJCOPY) -I binary -O $${oformat} -B $${oarch} \ $(notdir ${DT_BIN}) $@ rm $(DT_BIN) OBJS-$(CONFIG_OF_EMBED) := dt.o COBJS := $(OBJS-y) OBJS := $(addprefix $(obj),$(COBJS)) binary: $(DT_BIN) $(LIB): $(OBJS) $(DTB) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
dts/Makefile
Makefile
gpl3
3,292
# # (C) Copyright 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 # ######################################################################### _depend: $(obj).depend # Split the source files into two camps: those in the current directory, and # those somewhere else. For the first camp we want to support CPPFLAGS_<fname> # and for the second we don't / can't. PWD_SRCS := $(filter $(notdir $(SRCS)),$(SRCS)) OTHER_SRCS := $(filter-out $(notdir $(SRCS)),$(SRCS)) # This is a list of dependency files to generate DEPS := $(basename $(patsubst %,$(obj).depend.%,$(PWD_SRCS))) # Join all the dependencies into a single file, in three parts # 1 .Concatenate all the generated depend files together # 2. Add in the deps from OTHER_SRCS which we couldn't process # 3. Add in the HOSTSRCS $(obj).depend: $(src)Makefile $(TOPDIR)/config.mk $(DEPS) $(OTHER_SRCS) \ $(HOSTSRCS) cat /dev/null $(DEPS) >$@ @for f in $(OTHER_SRCS); do \ g=`basename $$f | sed -e 's/\(.*\)\.[[:alnum:]_]/\1.o/'`; \ $(CC) -M $(CPPFLAGS) -MQ $(obj)$$g $$f >> $@ ; \ done @for f in $(HOSTSRCS); do \ g=`basename $$f | sed -e 's/\(.*\)\.[[:alnum:]_]/\1.o/'`; \ $(HOSTCC) -M $(HOSTCPPFLAGS) -MQ $(obj)$$g $$f >> $@ ; \ done MAKE_DEPEND = $(CC) -M $(CPPFLAGS) $(EXTRA_CPPFLAGS_DEP) \ -MQ $(addsuffix .o,$(obj)$(basename $<)) $< >$@ $(obj).depend.%: %.c $(MAKE_DEPEND) $(obj).depend.%: %.S $(MAKE_DEPEND) $(HOSTOBJS): $(obj)%.o: %.c $(HOSTCC) $(HOSTCFLAGS) $(HOSTCFLAGS_$(@F)) $(HOSTCFLAGS_$(BCURDIR)) -o $@ $< -c $(NOPEDOBJS): $(obj)%.o: %.c $(HOSTCC) $(HOSTCFLAGS_NOPED) $(HOSTCFLAGS_$(@F)) $(HOSTCFLAGS_$(BCURDIR)) -o $@ $< -c #########################################################################
1001-study-uboot
rules.mk
Makefile
gpl3
2,487
/* * (C) Copyright 2011 * eInfochips Ltd. <www.einfochips.com> * Written-by: Ajay Bhargav <ajay.bhargav@einfochips.com> * * (C) Copyright 2010 * Marvell Semiconductor <www.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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <common.h> #include <asm/io.h> #include <asm/errno.h> #include "mvgpio.h" #include <asm/gpio.h> #ifndef MV_MAX_GPIO #define MV_MAX_GPIO 128 #endif int gpio_request(int gp, const char *label) { if (gp >= MV_MAX_GPIO) { printf("%s: Invalid GPIO requested %d\n", __func__, gp); return -EINVAL; } return 0; } void gpio_free(int gp) { } void gpio_toggle_value(int gp) { gpio_set_value(gp, !gpio_get_value(gp)); } int gpio_direction_input(int gp) { struct gpio_reg *gpio_reg_bank; if (gp >= MV_MAX_GPIO) { printf("%s: Invalid GPIO %d\n", __func__, gp); return -EINVAL; } gpio_reg_bank = get_gpio_base(GPIO_TO_REG(gp)); writel(GPIO_TO_BIT(gp), &gpio_reg_bank->gcdr); return 0; } int gpio_direction_output(int gp, int value) { struct gpio_reg *gpio_reg_bank; if (gp >= MV_MAX_GPIO) { printf("%s: Invalid GPIO %d\n", __func__, gp); return -EINVAL; } gpio_reg_bank = get_gpio_base(GPIO_TO_REG(gp)); writel(GPIO_TO_BIT(gp), &gpio_reg_bank->gsdr); gpio_set_value(gp, value); return 0; } int gpio_get_value(int gp) { struct gpio_reg *gpio_reg_bank; u32 gp_val; if (gp >= MV_MAX_GPIO) { printf("%s: Invalid GPIO %d\n", __func__, gp); return -EINVAL; } gpio_reg_bank = get_gpio_base(GPIO_TO_REG(gp)); gp_val = readl(&gpio_reg_bank->gplr); return GPIO_VAL(gp, gp_val); } void gpio_set_value(int gp, int value) { struct gpio_reg *gpio_reg_bank; if (gp >= MV_MAX_GPIO) { printf("%s: Invalid GPIO %d\n", __func__, gp); return; } gpio_reg_bank = get_gpio_base(GPIO_TO_REG(gp)); if (value) writel(GPIO_TO_BIT(gp), &gpio_reg_bank->gpsr); else writel(GPIO_TO_BIT(gp), &gpio_reg_bank->gpcr); }
1001-study-uboot
drivers/gpio/mvgpio.c
C
gpl3
2,645
/* * (C) Copyright 2010 * 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <common.h> #include <asm/io.h> #include <mvmfp.h> #include <asm/arch/mfp.h> /* * mfp_config * * On most of Marvell SoCs (ex. ARMADA100) there is Multi-Funtion-Pin * configuration registers to configure each GPIO/Function pin on the * SoC. * * This function reads the array of values for * MFPR_X registers and programms them into respective * Multi-Function Pin registers. * It supports - Alternate Function Selection programming. * * Whereas, * The Configureation value is constructed using MFP() * array consists of 32bit values as defined in MFP(xx,xx..) macro */ void mfp_config(u32 *mfp_cfgs) { u32 *p_mfpr = NULL; u32 cfg_val, val; do { cfg_val = *mfp_cfgs++; /* exit if End of configuration table detected */ if (cfg_val == MFP_EOC) break; p_mfpr = (u32 *)(MV_MFPR_BASE + MFP_REG_GET_OFFSET(cfg_val)); /* Write a mfg register as per configuration */ val = 0; if (cfg_val & MFP_AF_FLAG) /* Abstract and program Afternate-Func Selection */ val |= cfg_val & MFP_AF_MASK; if (cfg_val & MFP_EDGE_FLAG) /* Abstract and program Edge configuration */ val |= cfg_val & MFP_LPM_EDGE_MASK; if (cfg_val & MFP_DRIVE_FLAG) /* Abstract and program Drive configuration */ val |= cfg_val & MFP_DRIVE_MASK; if (cfg_val & MFP_PULL_FLAG) /* Abstract and program Pullup/down configuration */ val |= cfg_val & MFP_PULL_MASK; writel(val, p_mfpr); } while (1); /* * perform a read-back of any MFPR register to make sure the * previous writings are finished */ readl(p_mfpr); }
1001-study-uboot
drivers/gpio/mvmfp.c
C
gpl3
2,483
/* * (C) Copyright 2011 * Dirk Eibach, Guntermann & Drunck GmbH, eibach@gdsys.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 */ /* * Driver for NXP's pca9698 40 bit I2C gpio expander */ #include <common.h> #include <i2c.h> #include <asm/errno.h> #include <pca9698.h> /* * The pca9698 registers */ #define PCA9698_REG_INPUT 0x00 #define PCA9698_REG_OUTPUT 0x08 #define PCA9698_REG_POLARITY 0x10 #define PCA9698_REG_CONFIG 0x18 #define PCA9698_BUFFER_SIZE 5 #define PCA9698_GPIO_COUNT 40 static int pca9698_read40(u8 addr, u8 offset, u8 *buffer) { u8 command = offset | 0x80; /* autoincrement */ return i2c_read(addr, command, 1, buffer, PCA9698_BUFFER_SIZE); } static int pca9698_write40(u8 addr, u8 offset, u8 *buffer) { u8 command = offset | 0x80; /* autoincrement */ return i2c_write(addr, command, 1, buffer, PCA9698_BUFFER_SIZE); } static void pca9698_set_bit(unsigned gpio, u8 *buffer, unsigned value) { unsigned byte = gpio / 8; unsigned bit = gpio % 8; if (value) buffer[byte] |= (1 << bit); else buffer[byte] &= ~(1 << bit); } int pca9698_request(unsigned gpio, const char *label) { if (gpio >= PCA9698_GPIO_COUNT) return -EINVAL; return 0; } void pca9698_free(unsigned gpio) { } int pca9698_direction_input(u8 addr, unsigned gpio) { u8 data[PCA9698_BUFFER_SIZE]; int res; res = pca9698_read40(addr, PCA9698_REG_CONFIG, data); if (res) return res; pca9698_set_bit(gpio, data, 1); return pca9698_write40(addr, PCA9698_REG_CONFIG, data); } int pca9698_direction_output(u8 addr, unsigned gpio, int value) { u8 data[PCA9698_BUFFER_SIZE]; int res; res = pca9698_set_value(addr, gpio, value); if (res) return res; res = pca9698_read40(addr, PCA9698_REG_CONFIG, data); if (res) return res; pca9698_set_bit(gpio, data, 0); return pca9698_write40(addr, PCA9698_REG_CONFIG, data); } int pca9698_get_value(u8 addr, unsigned gpio) { unsigned config_byte = gpio / 8; unsigned config_bit = gpio % 8; unsigned value; u8 data[PCA9698_BUFFER_SIZE]; int res; res = pca9698_read40(addr, PCA9698_REG_INPUT, data); if (res) return -1; value = data[config_byte] & (1 << config_bit); return !!value; } int pca9698_set_value(u8 addr, unsigned gpio, int value) { u8 data[PCA9698_BUFFER_SIZE]; int res; res = pca9698_read40(addr, PCA9698_REG_OUTPUT, data); if (res) return res; pca9698_set_bit(gpio, data, value); return pca9698_write40(addr, PCA9698_REG_OUTPUT, data); }
1001-study-uboot
drivers/gpio/pca9698.c
C
gpl3
3,207
/* * 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 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* * Driver for NXP's 4, 8 and 16 bit I2C gpio expanders (eg pca9537, pca9557, * pca9539, etc) */ #include <common.h> #include <i2c.h> #include <pca953x.h> /* Default to an address that hopefully won't corrupt other i2c devices */ #ifndef CONFIG_SYS_I2C_PCA953X_ADDR #define CONFIG_SYS_I2C_PCA953X_ADDR (~0) #endif enum { PCA953X_CMD_INFO, PCA953X_CMD_DEVICE, PCA953X_CMD_OUTPUT, PCA953X_CMD_INPUT, PCA953X_CMD_INVERT, }; #ifdef CONFIG_SYS_I2C_PCA953X_WIDTH struct pca953x_chip_ngpio { uint8_t chip; uint8_t ngpio; }; static struct pca953x_chip_ngpio pca953x_chip_ngpios[] = CONFIG_SYS_I2C_PCA953X_WIDTH; #define NUM_CHIP_GPIOS (sizeof(pca953x_chip_ngpios) / \ sizeof(struct pca953x_chip_ngpio)) /* * Determine the number of GPIO pins supported. If we don't know we assume * 8 pins. */ static int pca953x_ngpio(uint8_t chip) { int i; for (i = 0; i < NUM_CHIP_GPIOS; i++) if (pca953x_chip_ngpios[i].chip == chip) return pca953x_chip_ngpios[i].ngpio; return 8; } #else static int pca953x_ngpio(uint8_t chip) { return 8; } #endif /* * Modify masked bits in register */ static int pca953x_reg_write(uint8_t chip, uint addr, uint mask, uint data) { uint8_t valb; uint16_t valw; if (pca953x_ngpio(chip) <= 8) { if (i2c_read(chip, addr, 1, &valb, 1)) return -1; valb &= ~mask; valb |= data; return i2c_write(chip, addr, 1, &valb, 1); } else { if (i2c_read(chip, addr << 1, 1, (u8*)&valw, 2)) return -1; valw &= ~mask; valw |= data; return i2c_write(chip, addr << 1, 1, (u8*)&valw, 2); } } static int pca953x_reg_read(uint8_t chip, uint addr, uint *data) { uint8_t valb; uint16_t valw; if (pca953x_ngpio(chip) <= 8) { if (i2c_read(chip, addr, 1, &valb, 1)) return -1; *data = (int)valb; } else { if (i2c_read(chip, addr << 1, 1, (u8*)&valw, 2)) return -1; *data = (int)valw; } return 0; } /* * Set output value of IO pins in 'mask' to corresponding value in 'data' * 0 = low, 1 = high */ int pca953x_set_val(uint8_t chip, uint mask, uint data) { return pca953x_reg_write(chip, PCA953X_OUT, mask, data); } /* * Set read polarity of IO pins in 'mask' to corresponding value in 'data' * 0 = read pin value, 1 = read inverted pin value */ int pca953x_set_pol(uint8_t chip, uint mask, uint data) { return pca953x_reg_write(chip, PCA953X_POL, mask, data); } /* * Set direction of IO pins in 'mask' to corresponding value in 'data' * 0 = output, 1 = input */ int pca953x_set_dir(uint8_t chip, uint mask, uint data) { return pca953x_reg_write(chip, PCA953X_CONF, mask, data); } /* * Read current logic level of all IO pins */ int pca953x_get_val(uint8_t chip) { uint val; if (pca953x_reg_read(chip, PCA953X_IN, &val) < 0) return -1; return (int)val; } #ifdef CONFIG_CMD_PCA953X #ifdef CONFIG_CMD_PCA953X_INFO /* * Display pca953x information */ static int pca953x_info(uint8_t chip) { int i; uint data; int nr_gpio = pca953x_ngpio(chip); int msb = nr_gpio - 1; printf("pca953x@ 0x%x (%d pins):\n\n", chip, nr_gpio); printf("gpio pins: "); for (i = msb; i >= 0; i--) printf("%x", i); printf("\n"); for (i = 11 + nr_gpio; i > 0; i--) printf("-"); printf("\n"); if (pca953x_reg_read(chip, PCA953X_CONF, &data) < 0) return -1; printf("conf: "); for (i = msb; i >= 0; i--) printf("%c", data & (1 << i) ? 'i' : 'o'); printf("\n"); if (pca953x_reg_read(chip, PCA953X_POL, &data) < 0) return -1; printf("invert: "); for (i = msb; i >= 0; i--) printf("%c", data & (1 << i) ? '1' : '0'); printf("\n"); if (pca953x_reg_read(chip, PCA953X_IN, &data) < 0) return -1; printf("input: "); for (i = msb; i >= 0; i--) printf("%c", data & (1 << i) ? '1' : '0'); printf("\n"); if (pca953x_reg_read(chip, PCA953X_OUT, &data) < 0) return -1; printf("output: "); for (i = msb; i >= 0; i--) printf("%c", data & (1 << i) ? '1' : '0'); printf("\n"); return 0; } #endif /* CONFIG_CMD_PCA953X_INFO */ cmd_tbl_t cmd_pca953x[] = { U_BOOT_CMD_MKENT(device, 3, 0, (void *)PCA953X_CMD_DEVICE, "", ""), U_BOOT_CMD_MKENT(output, 4, 0, (void *)PCA953X_CMD_OUTPUT, "", ""), U_BOOT_CMD_MKENT(input, 3, 0, (void *)PCA953X_CMD_INPUT, "", ""), U_BOOT_CMD_MKENT(invert, 4, 0, (void *)PCA953X_CMD_INVERT, "", ""), #ifdef CONFIG_CMD_PCA953X_INFO U_BOOT_CMD_MKENT(info, 2, 0, (void *)PCA953X_CMD_INFO, "", ""), #endif }; int do_pca953x(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { static uint8_t chip = CONFIG_SYS_I2C_PCA953X_ADDR; int val; ulong ul_arg2 = 0; ulong ul_arg3 = 0; cmd_tbl_t *c; c = find_cmd_tbl(argv[1], cmd_pca953x, ARRAY_SIZE(cmd_pca953x)); /* All commands but "device" require 'maxargs' arguments */ if (!c || !((argc == (c->maxargs)) || (((int)c->cmd == PCA953X_CMD_DEVICE) && (argc == (c->maxargs - 1))))) { return cmd_usage(cmdtp); } /* arg2 used as chip number or pin number */ if (argc > 2) ul_arg2 = simple_strtoul(argv[2], NULL, 16); /* arg3 used as pin or invert value */ if (argc > 3) ul_arg3 = simple_strtoul(argv[3], NULL, 16) & 0x1; switch ((int)c->cmd) { #ifdef CONFIG_CMD_PCA953X_INFO case PCA953X_CMD_INFO: return pca953x_info(chip); #endif case PCA953X_CMD_DEVICE: if (argc == 3) chip = (uint8_t)ul_arg2; printf("Current device address: 0x%x\n", chip); return 0; case PCA953X_CMD_INPUT: pca953x_set_dir(chip, (1 << ul_arg2), PCA953X_DIR_IN << ul_arg2); val = (pca953x_get_val(chip) & (1 << ul_arg2)) != 0; printf("chip 0x%02x, pin 0x%lx = %d\n", chip, ul_arg2, val); return val; case PCA953X_CMD_OUTPUT: pca953x_set_dir(chip, (1 << ul_arg2), (PCA953X_DIR_OUT << ul_arg2)); return pca953x_set_val(chip, (1 << ul_arg2), (ul_arg3 << ul_arg2)); case PCA953X_CMD_INVERT: return pca953x_set_pol(chip, (1 << ul_arg2), (ul_arg3 << ul_arg2)); default: /* We should never get here */ return 1; } } U_BOOT_CMD( pca953x, 5, 1, do_pca953x, "pca953x gpio access", "device [dev]\n" " - show or set current device address\n" #ifdef CONFIG_CMD_PCA953X_INFO "pca953x info\n" " - display info for current chip\n" #endif "pca953x output pin 0|1\n" " - set pin as output and drive low or high\n" "pca953x invert pin 0|1\n" " - disable/enable polarity inversion for reads\n" "pca953x intput pin\n" " - set pin as input and read value" ); #endif /* CONFIG_CMD_PCA953X */
1001-study-uboot
drivers/gpio/pca953x.c
C
gpl3
7,048
# # Copyright 2000-2008 # 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)libgpio.o COBJS-$(CONFIG_AT91_GPIO) += at91_gpio.o COBJS-$(CONFIG_KIRKWOOD_GPIO) += kw_gpio.o COBJS-$(CONFIG_MARVELL_GPIO) += mvgpio.o COBJS-$(CONFIG_MARVELL_MFP) += mvmfp.o COBJS-$(CONFIG_MXC_GPIO) += mxc_gpio.o COBJS-$(CONFIG_MXS_GPIO) += mxs_gpio.o COBJS-$(CONFIG_PCA953X) += pca953x.o COBJS-$(CONFIG_PCA9698) += pca9698.o COBJS-$(CONFIG_S5P) += s5p_gpio.o COBJS-$(CONFIG_TEGRA2_GPIO) += tegra2_gpio.o COBJS-$(CONFIG_DA8XX_GPIO) += da8xx_gpio.o COBJS-$(CONFIG_ALTERA_PIO) += altera_pio.o COBJS := $(COBJS-y) SRCS := $(COBJS:.o=.c) OBJS := $(addprefix $(obj),$(COBJS)) all: $(LIB) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend ########################################################################
1001-study-uboot
drivers/gpio/Makefile
Makefile
gpl3
1,794
/* * Freescale i.MX28 GPIO control code * * 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 <common.h> #include <netdev.h> #include <asm/errno.h> #include <asm/io.h> #include <asm/arch/iomux.h> #include <asm/arch/imx-regs.h> #if defined(CONFIG_MX23) #define PINCTRL_BANKS 3 #define PINCTRL_DOUT(n) (0x0500 + ((n) * 0x10)) #define PINCTRL_DIN(n) (0x0600 + ((n) * 0x10)) #define PINCTRL_DOE(n) (0x0700 + ((n) * 0x10)) #define PINCTRL_PIN2IRQ(n) (0x0800 + ((n) * 0x10)) #define PINCTRL_IRQEN(n) (0x0900 + ((n) * 0x10)) #define PINCTRL_IRQSTAT(n) (0x0c00 + ((n) * 0x10)) #elif defined(CONFIG_MX28) #define PINCTRL_BANKS 5 #define PINCTRL_DOUT(n) (0x0700 + ((n) * 0x10)) #define PINCTRL_DIN(n) (0x0900 + ((n) * 0x10)) #define PINCTRL_DOE(n) (0x0b00 + ((n) * 0x10)) #define PINCTRL_PIN2IRQ(n) (0x1000 + ((n) * 0x10)) #define PINCTRL_IRQEN(n) (0x1100 + ((n) * 0x10)) #define PINCTRL_IRQSTAT(n) (0x1400 + ((n) * 0x10)) #else #error "Please select CONFIG_MX23 or CONFIG_MX28" #endif #define GPIO_INT_FALL_EDGE 0x0 #define GPIO_INT_LOW_LEV 0x1 #define GPIO_INT_RISE_EDGE 0x2 #define GPIO_INT_HIGH_LEV 0x3 #define GPIO_INT_LEV_MASK (1 << 0) #define GPIO_INT_POL_MASK (1 << 1) void mxs_gpio_init(void) { int i; for (i = 0; i < PINCTRL_BANKS; i++) { writel(0, MXS_PINCTRL_BASE + PINCTRL_PIN2IRQ(i)); writel(0, MXS_PINCTRL_BASE + PINCTRL_IRQEN(i)); /* Use SCT address here to clear the IRQSTAT bits */ writel(0xffffffff, MXS_PINCTRL_BASE + PINCTRL_IRQSTAT(i) + 8); } } int gpio_get_value(int gp) { uint32_t bank = PAD_BANK(gp); uint32_t offset = PINCTRL_DIN(bank); struct mx28_register *reg = (struct mx28_register *)(MXS_PINCTRL_BASE + offset); return (readl(&reg->reg) >> PAD_PIN(gp)) & 1; } void gpio_set_value(int gp, int value) { uint32_t bank = PAD_BANK(gp); uint32_t offset = PINCTRL_DOUT(bank); struct mx28_register *reg = (struct mx28_register *)(MXS_PINCTRL_BASE + offset); if (value) writel(1 << PAD_PIN(gp), &reg->reg_set); else writel(1 << PAD_PIN(gp), &reg->reg_clr); } int gpio_direction_input(int gp) { uint32_t bank = PAD_BANK(gp); uint32_t offset = PINCTRL_DOE(bank); struct mx28_register *reg = (struct mx28_register *)(MXS_PINCTRL_BASE + offset); writel(1 << PAD_PIN(gp), &reg->reg_clr); return 0; } int gpio_direction_output(int gp, int value) { uint32_t bank = PAD_BANK(gp); uint32_t offset = PINCTRL_DOE(bank); struct mx28_register *reg = (struct mx28_register *)(MXS_PINCTRL_BASE + offset); writel(1 << PAD_PIN(gp), &reg->reg_set); gpio_set_value(gp, value); return 0; } int gpio_request(int gp, const char *label) { if (PAD_BANK(gp) >= PINCTRL_BANKS) return -EINVAL; return 0; } void gpio_free(int gp) { } void gpio_toggle_value(int gp) { gpio_set_value(gp, !gpio_get_value(gp)); }
1001-study-uboot
drivers/gpio/mxs_gpio.c
C
gpl3
3,634
/* * NVIDIA Tegra2 GPIO handling. * (C) Copyright 2010,2011 * NVIDIA Corporation <www.nvidia.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 */ /* * Based on (mostly copied from) kw_gpio.c based Linux 2.6 kernel driver. * Tom Warren (twarren@nvidia.com) */ #include <common.h> #include <asm/io.h> #include <asm/bitops.h> #include <asm/arch/tegra2.h> #include <asm/gpio.h> enum { TEGRA2_CMD_INFO, TEGRA2_CMD_PORT, TEGRA2_CMD_OUTPUT, TEGRA2_CMD_INPUT, }; static struct gpio_names { char name[GPIO_NAME_SIZE]; } gpio_names[MAX_NUM_GPIOS]; static char *get_name(int i) { return *gpio_names[i].name ? gpio_names[i].name : "UNKNOWN"; } /* Return config of pin 'gp' as GPIO (1) or SFPIO (0) */ static int get_config(int gp) { struct gpio_ctlr *gpio = (struct gpio_ctlr *)NV_PA_GPIO_BASE; struct gpio_ctlr_bank *bank = &gpio->gpio_bank[GPIO_BANK(gp)]; u32 u; int type; u = readl(&bank->gpio_config[GPIO_PORT(gp)]); type = (u >> GPIO_BIT(gp)) & 1; debug("get_config: port = %d, bit = %d is %s\n", GPIO_FULLPORT(gp), GPIO_BIT(gp), type ? "GPIO" : "SFPIO"); return type; } /* Config pin 'gp' as GPIO or SFPIO, based on 'type' */ static void set_config(int gp, int type) { struct gpio_ctlr *gpio = (struct gpio_ctlr *)NV_PA_GPIO_BASE; struct gpio_ctlr_bank *bank = &gpio->gpio_bank[GPIO_BANK(gp)]; u32 u; debug("set_config: port = %d, bit = %d, %s\n", GPIO_FULLPORT(gp), GPIO_BIT(gp), type ? "GPIO" : "SFPIO"); u = readl(&bank->gpio_config[GPIO_PORT(gp)]); if (type) /* GPIO */ u |= 1 << GPIO_BIT(gp); else u &= ~(1 << GPIO_BIT(gp)); writel(u, &bank->gpio_config[GPIO_PORT(gp)]); } /* Return GPIO pin 'gp' direction - 0 = input or 1 = output */ static int get_direction(int gp) { struct gpio_ctlr *gpio = (struct gpio_ctlr *)NV_PA_GPIO_BASE; struct gpio_ctlr_bank *bank = &gpio->gpio_bank[GPIO_BANK(gp)]; u32 u; int dir; u = readl(&bank->gpio_dir_out[GPIO_PORT(gp)]); dir = (u >> GPIO_BIT(gp)) & 1; debug("get_direction: port = %d, bit = %d, %s\n", GPIO_FULLPORT(gp), GPIO_BIT(gp), dir ? "OUT" : "IN"); return dir; } /* Config GPIO pin 'gp' as input or output (OE) as per 'output' */ static void set_direction(int gp, int output) { struct gpio_ctlr *gpio = (struct gpio_ctlr *)NV_PA_GPIO_BASE; struct gpio_ctlr_bank *bank = &gpio->gpio_bank[GPIO_BANK(gp)]; u32 u; debug("set_direction: port = %d, bit = %d, %s\n", GPIO_FULLPORT(gp), GPIO_BIT(gp), output ? "OUT" : "IN"); u = readl(&bank->gpio_dir_out[GPIO_PORT(gp)]); if (output) u |= 1 << GPIO_BIT(gp); else u &= ~(1 << GPIO_BIT(gp)); writel(u, &bank->gpio_dir_out[GPIO_PORT(gp)]); } /* set GPIO pin 'gp' output bit as 0 or 1 as per 'high' */ static void set_level(int gp, int high) { struct gpio_ctlr *gpio = (struct gpio_ctlr *)NV_PA_GPIO_BASE; struct gpio_ctlr_bank *bank = &gpio->gpio_bank[GPIO_BANK(gp)]; u32 u; debug("set_level: port = %d, bit %d == %d\n", GPIO_FULLPORT(gp), GPIO_BIT(gp), high); u = readl(&bank->gpio_out[GPIO_PORT(gp)]); if (high) u |= 1 << GPIO_BIT(gp); else u &= ~(1 << GPIO_BIT(gp)); writel(u, &bank->gpio_out[GPIO_PORT(gp)]); } /* * Generic_GPIO primitives. */ int gpio_request(int gp, const char *label) { if (gp >= MAX_NUM_GPIOS) return -1; if (label != NULL) { strncpy(gpio_names[gp].name, label, GPIO_NAME_SIZE); gpio_names[gp].name[GPIO_NAME_SIZE - 1] = '\0'; } /* Configure as a GPIO */ set_config(gp, 1); return 0; } void gpio_free(int gp) { } /* read GPIO OUT value of pin 'gp' */ static int gpio_get_output_value(int gp) { struct gpio_ctlr *gpio = (struct gpio_ctlr *)NV_PA_GPIO_BASE; struct gpio_ctlr_bank *bank = &gpio->gpio_bank[GPIO_BANK(gp)]; int val; debug("gpio_get_output_value: pin = %d (port %d:bit %d)\n", gp, GPIO_FULLPORT(gp), GPIO_BIT(gp)); val = readl(&bank->gpio_out[GPIO_PORT(gp)]); return (val >> GPIO_BIT(gp)) & 1; } void gpio_toggle_value(int gp) { gpio_set_value(gp, !gpio_get_output_value(gp)); } /* set GPIO pin 'gp' as an input */ int gpio_direction_input(int gp) { debug("gpio_direction_input: pin = %d (port %d:bit %d)\n", gp, GPIO_FULLPORT(gp), GPIO_BIT(gp)); /* Configure GPIO direction as input. */ set_direction(gp, 0); return 0; } /* set GPIO pin 'gp' as an output, with polarity 'value' */ int gpio_direction_output(int gp, int value) { debug("gpio_direction_output: pin = %d (port %d:bit %d) = %s\n", gp, GPIO_FULLPORT(gp), GPIO_BIT(gp), value ? "HIGH" : "LOW"); /* Configure GPIO output value. */ set_level(gp, value); /* Configure GPIO direction as output. */ set_direction(gp, 1); return 0; } /* read GPIO IN value of pin 'gp' */ int gpio_get_value(int gp) { struct gpio_ctlr *gpio = (struct gpio_ctlr *)NV_PA_GPIO_BASE; struct gpio_ctlr_bank *bank = &gpio->gpio_bank[GPIO_BANK(gp)]; int val; debug("gpio_get_value: pin = %d (port %d:bit %d)\n", gp, GPIO_FULLPORT(gp), GPIO_BIT(gp)); val = readl(&bank->gpio_in[GPIO_PORT(gp)]); return (val >> GPIO_BIT(gp)) & 1; } /* write GPIO OUT value to pin 'gp' */ void gpio_set_value(int gp, int value) { debug("gpio_set_value: pin = %d (port %d:bit %d), value = %d\n", gp, GPIO_FULLPORT(gp), GPIO_BIT(gp), value); /* Configure GPIO output value. */ set_level(gp, value); } /* * Display Tegra GPIO information */ void gpio_info(void) { int c, type; for (c = 0; c < MAX_NUM_GPIOS; c++) { type = get_config(c); /* GPIO, not SFPIO */ if (type) { printf("GPIO_%d:\t%s is an %s, ", c, get_name(c), get_direction(c) ? "OUTPUT" : "INPUT"); if (get_direction(c)) printf("value = %d", gpio_get_output_value(c)); else printf("value = %d", gpio_get_value(c)); printf("\n"); } else continue; } }
1001-study-uboot
drivers/gpio/tegra2_gpio.c
C
gpl3
6,411
/* * Memory Setup stuff - taken from blob memsetup.S * * Copyright (C) 2009 Jens Scharsig (js_at_ng@scharsoft.de) * * Copyright (C) 2005 HP Labs * * 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 */ /* * WARNING: * * As the code is right now, it expects all PIO ports A,B,C,... * to be evenly spaced in the memory map: * ATMEL_BASE_PIOA + port * sizeof at91pio_t * This might not necessaryly be true in future Atmel SoCs. * This code should be fixed to use a pointer array to the ports. */ #include <config.h> #include <common.h> #include <asm/io.h> #include <asm/sizes.h> #include <asm/arch/hardware.h> #include <asm/arch/at91_pio.h> int at91_set_pio_pullup(unsigned port, unsigned pin, int use_pullup) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; if (use_pullup) writel(1 << pin, &pio->port[port].puer); else writel(1 << pin, &pio->port[port].pudr); writel(mask, &pio->port[port].per); } return 0; } /* * mux the pin to the "GPIO" peripheral role. */ int at91_set_pio_periph(unsigned port, unsigned pin, int use_pullup) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; writel(mask, &pio->port[port].idr); at91_set_pio_pullup(port, pin, use_pullup); writel(mask, &pio->port[port].per); } return 0; } /* * mux the pin to the "A" internal peripheral role. */ int at91_set_a_periph(unsigned port, unsigned pin, int use_pullup) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; writel(mask, &pio->port[port].idr); at91_set_pio_pullup(port, pin, use_pullup); writel(mask, &pio->port[port].asr); writel(mask, &pio->port[port].pdr); } return 0; } /* * mux the pin to the "B" internal peripheral role. */ int at91_set_b_periph(unsigned port, unsigned pin, int use_pullup) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; writel(mask, &pio->port[port].idr); at91_set_pio_pullup(port, pin, use_pullup); writel(mask, &pio->port[port].bsr); writel(mask, &pio->port[port].pdr); } return 0; } /* * mux the pin to the gpio controller (instead of "A" or "B" peripheral), and * configure it for an input. */ int at91_set_pio_input(unsigned port, u32 pin, int use_pullup) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; writel(mask, &pio->port[port].idr); at91_set_pio_pullup(port, pin, use_pullup); writel(mask, &pio->port[port].odr); writel(mask, &pio->port[port].per); } return 0; } /* * mux the pin to the gpio controller (instead of "A" or "B" peripheral), * and configure it for an output. */ int at91_set_pio_output(unsigned port, u32 pin, int value) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; writel(mask, &pio->port[port].idr); writel(mask, &pio->port[port].pudr); if (value) writel(mask, &pio->port[port].sodr); else writel(mask, &pio->port[port].codr); writel(mask, &pio->port[port].oer); writel(mask, &pio->port[port].per); } return 0; } /* * enable/disable the glitch filter. mostly used with IRQ handling. */ int at91_set_pio_deglitch(unsigned port, unsigned pin, int is_on) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; if (is_on) writel(mask, &pio->port[port].ifer); else writel(mask, &pio->port[port].ifdr); } return 0; } /* * enable/disable the multi-driver. This is only valid for output and * allows the output pin to run as an open collector output. */ int at91_set_pio_multi_drive(unsigned port, unsigned pin, int is_on) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; if (is_on) writel(mask, &pio->port[port].mder); else writel(mask, &pio->port[port].mddr); } return 0; } /* * assuming the pin is muxed as a gpio output, set its value. */ int at91_set_pio_value(unsigned port, unsigned pin, int value) { at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; if (value) writel(mask, &pio->port[port].sodr); else writel(mask, &pio->port[port].codr); } return 0; } /* * read the pin's value (works even if it's not muxed as a gpio). */ int at91_get_pio_value(unsigned port, unsigned pin) { u32 pdsr = 0; at91_pio_t *pio = (at91_pio_t *) ATMEL_BASE_PIOA; u32 mask; if ((port < ATMEL_PIO_PORTS) && (pin < 32)) { mask = 1 << pin; pdsr = readl(&pio->port[port].pdsr) & mask; } return pdsr != 0; }
1001-study-uboot
drivers/gpio/at91_gpio.c
C
gpl3
5,662
/* * (C) Copyright 2011 * eInfochips Ltd. <www.einfochips.com> * Written-by: Ajay Bhargav <ajay.bhargav@einfochips.com> * * (C) Copyright 2010 * Marvell Semiconductor <www.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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifndef __MVGPIO_H__ #define __MVGPIO_H__ #include <common.h> #ifdef CONFIG_SHEEVA_88SV331xV5 /* * GPIO Register map for SHEEVA 88SV331xV5 */ struct gpio_reg { u32 gplr; /* Pin Level Register - 0x0000 */ u32 pad0[2]; u32 gpdr; /* Pin Direction Register - 0x000C */ u32 pad1[2]; u32 gpsr; /* Pin Output Set Register - 0x0018 */ u32 pad2[2]; u32 gpcr; /* Pin Output Clear Register - 0x0024 */ u32 pad3[2]; u32 grer; /* Rising-Edge Detect Enable Register - 0x0030 */ u32 pad4[2]; u32 gfer; /* Falling-Edge Detect Enable Register - 0x003C */ u32 pad5[2]; u32 gedr; /* Edge Detect Status Register - 0x0048 */ u32 pad6[2]; u32 gsdr; /* Bitwise Set of GPIO Direction Register - 0x0054 */ u32 pad7[2]; u32 gcdr; /* Bitwise Clear of GPIO Direction Register - 0x0060 */ u32 pad8[2]; u32 gsrer; /* Bitwise Set of Rising-Edge Detect Enable Register - 0x006C */ u32 pad9[2]; u32 gcrer; /* Bitwise Clear of Rising-Edge Detect Enable Register - 0x0078 */ u32 pad10[2]; u32 gsfer; /* Bitwise Set of Falling-Edge Detect Enable Register - 0x0084 */ u32 pad11[2]; u32 gcfer; /* Bitwise Clear of Falling-Edge Detect Enable Register - 0x0090 */ u32 pad12[2]; u32 apmask; /* Bitwise Mask of Edge Detect Register - 0x009C */ }; #else #error "CPU core subversion not defined" #endif #endif /* __MVGPIO_H__ */
1001-study-uboot
drivers/gpio/mvgpio.h
C
gpl3
2,336
/* * arch/arm/plat-orion/gpio.c * * Marvell Orion SoC GPIO handling. * * 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ /* * Based on (mostly copied from) plat-orion based Linux 2.6 kernel driver. * Removed orion_gpiochip struct and kernel level irq handling. * * Dieter Kiermaier dk-arm-linux@gmx.de */ #include <common.h> #include <asm/bitops.h> #include <asm/io.h> #include <asm/arch/kirkwood.h> #include <asm/arch/gpio.h> static unsigned long gpio_valid_input[BITS_TO_LONGS(GPIO_MAX)]; static unsigned long gpio_valid_output[BITS_TO_LONGS(GPIO_MAX)]; void __set_direction(unsigned pin, int input) { u32 u; u = readl(GPIO_IO_CONF(pin)); if (input) u |= 1 << (pin & 31); else u &= ~(1 << (pin & 31)); writel(u, GPIO_IO_CONF(pin)); u = readl(GPIO_IO_CONF(pin)); } void __set_level(unsigned pin, int high) { u32 u; u = readl(GPIO_OUT(pin)); if (high) u |= 1 << (pin & 31); else u &= ~(1 << (pin & 31)); writel(u, GPIO_OUT(pin)); } void __set_blinking(unsigned pin, int blink) { u32 u; u = readl(GPIO_BLINK_EN(pin)); if (blink) u |= 1 << (pin & 31); else u &= ~(1 << (pin & 31)); writel(u, GPIO_BLINK_EN(pin)); } int kw_gpio_is_valid(unsigned pin, int mode) { if (pin < GPIO_MAX) { if ((mode & GPIO_INPUT_OK) && !test_bit(pin, gpio_valid_input)) goto err_out; if ((mode & GPIO_OUTPUT_OK) && !test_bit(pin, gpio_valid_output)) goto err_out; return 0; } err_out: printf("%s: invalid GPIO %d\n", __func__, pin); return 1; } void kw_gpio_set_valid(unsigned pin, int mode) { if (mode == 1) mode = GPIO_INPUT_OK | GPIO_OUTPUT_OK; if (mode & GPIO_INPUT_OK) __set_bit(pin, gpio_valid_input); else __clear_bit(pin, gpio_valid_input); if (mode & GPIO_OUTPUT_OK) __set_bit(pin, gpio_valid_output); else __clear_bit(pin, gpio_valid_output); } /* * GENERIC_GPIO primitives. */ int kw_gpio_direction_input(unsigned pin) { if (kw_gpio_is_valid(pin, GPIO_INPUT_OK) != 0) return 1; /* Configure GPIO direction. */ __set_direction(pin, 1); return 0; } int kw_gpio_direction_output(unsigned pin, int value) { if (kw_gpio_is_valid(pin, GPIO_OUTPUT_OK) != 0) { printf("%s: invalid GPIO %d\n", __func__, pin); return 1; } __set_blinking(pin, 0); /* Configure GPIO output value. */ __set_level(pin, value); /* Configure GPIO direction. */ __set_direction(pin, 0); return 0; } int kw_gpio_get_value(unsigned pin) { int val; if (readl(GPIO_IO_CONF(pin)) & (1 << (pin & 31))) val = readl(GPIO_DATA_IN(pin)) ^ readl(GPIO_IN_POL(pin)); else val = readl(GPIO_OUT(pin)); return (val >> (pin & 31)) & 1; } void kw_gpio_set_value(unsigned pin, int value) { /* Configure GPIO output value. */ __set_level(pin, value); } void kw_gpio_set_blink(unsigned pin, int blink) { /* Set output value to zero. */ __set_level(pin, 0); /* Set blinking. */ __set_blinking(pin, blink); }
1001-study-uboot
drivers/gpio/kw_gpio.c
C
gpl3
3,621
/* * GPIO driver for TI DaVinci DA8xx SOCs. * * (C) Copyright 2011 Guralp Systems Ltd. * Laurence Withers <lwithers@guralp.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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <asm/io.h> #include <asm/gpio.h> #include <asm/arch/gpio.h> #include <asm/arch/hardware.h> #include <asm/arch/davinci_misc.h> static struct gpio_registry { int is_registered; char name[GPIO_NAME_SIZE]; } gpio_registry[MAX_NUM_GPIOS]; #define pinmux(x) (&davinci_syscfg_regs->pinmux[x]) static const struct pinmux_config gpio_pinmux[] = { { pinmux(1), 8, 7 }, /* GP0[0] */ { pinmux(1), 8, 6 }, { pinmux(1), 8, 5 }, { pinmux(1), 8, 4 }, { pinmux(1), 8, 3 }, { pinmux(1), 8, 2 }, { pinmux(1), 8, 1 }, { pinmux(1), 8, 0 }, { pinmux(0), 8, 7 }, { pinmux(0), 8, 6 }, { pinmux(0), 8, 5 }, { pinmux(0), 8, 4 }, { pinmux(0), 8, 3 }, { pinmux(0), 8, 2 }, { pinmux(0), 8, 1 }, { pinmux(0), 8, 0 }, { pinmux(4), 8, 7 }, /* GP1[0] */ { pinmux(4), 8, 6 }, { pinmux(4), 8, 5 }, { pinmux(4), 8, 4 }, { pinmux(4), 8, 3 }, { pinmux(4), 8, 2 }, { pinmux(4), 4, 1 }, { pinmux(4), 4, 0 }, { pinmux(3), 4, 0 }, { pinmux(2), 4, 6 }, { pinmux(2), 4, 5 }, { pinmux(2), 4, 4 }, { pinmux(2), 4, 3 }, { pinmux(2), 4, 2 }, { pinmux(2), 4, 1 }, { pinmux(2), 8, 0 }, { pinmux(6), 8, 7 }, /* GP2[0] */ { pinmux(6), 8, 6 }, { pinmux(6), 8, 5 }, { pinmux(6), 8, 4 }, { pinmux(6), 8, 3 }, { pinmux(6), 8, 2 }, { pinmux(6), 8, 1 }, { pinmux(6), 8, 0 }, { pinmux(5), 8, 7 }, { pinmux(5), 8, 6 }, { pinmux(5), 8, 5 }, { pinmux(5), 8, 4 }, { pinmux(5), 8, 3 }, { pinmux(5), 8, 2 }, { pinmux(5), 8, 1 }, { pinmux(5), 8, 0 }, { pinmux(8), 8, 7 }, /* GP3[0] */ { pinmux(8), 8, 6 }, { pinmux(8), 8, 5 }, { pinmux(8), 8, 4 }, { pinmux(8), 8, 3 }, { pinmux(8), 8, 2 }, { pinmux(8), 8, 1 }, { pinmux(8), 8, 0 }, { pinmux(7), 8, 7 }, { pinmux(7), 8, 6 }, { pinmux(7), 8, 5 }, { pinmux(7), 8, 4 }, { pinmux(7), 8, 3 }, { pinmux(7), 8, 2 }, { pinmux(7), 8, 1 }, { pinmux(7), 8, 0 }, { pinmux(10), 8, 7 }, /* GP4[0] */ { pinmux(10), 8, 6 }, { pinmux(10), 8, 5 }, { pinmux(10), 8, 4 }, { pinmux(10), 8, 3 }, { pinmux(10), 8, 2 }, { pinmux(10), 8, 1 }, { pinmux(10), 8, 0 }, { pinmux(9), 8, 7 }, { pinmux(9), 8, 6 }, { pinmux(9), 8, 5 }, { pinmux(9), 8, 4 }, { pinmux(9), 8, 3 }, { pinmux(9), 8, 2 }, { pinmux(9), 8, 1 }, { pinmux(9), 8, 0 }, { pinmux(12), 8, 7 }, /* GP5[0] */ { pinmux(12), 8, 6 }, { pinmux(12), 8, 5 }, { pinmux(12), 8, 4 }, { pinmux(12), 8, 3 }, { pinmux(12), 8, 2 }, { pinmux(12), 8, 1 }, { pinmux(12), 8, 0 }, { pinmux(11), 8, 7 }, { pinmux(11), 8, 6 }, { pinmux(11), 8, 5 }, { pinmux(11), 8, 4 }, { pinmux(11), 8, 3 }, { pinmux(11), 8, 2 }, { pinmux(11), 8, 1 }, { pinmux(11), 8, 0 }, { pinmux(19), 8, 6 }, /* GP6[0] */ { pinmux(19), 8, 5 }, { pinmux(19), 8, 4 }, { pinmux(19), 8, 3 }, { pinmux(19), 8, 2 }, { pinmux(16), 8, 1 }, { pinmux(14), 8, 1 }, { pinmux(14), 8, 0 }, { pinmux(13), 8, 7 }, { pinmux(13), 8, 6 }, { pinmux(13), 8, 5 }, { pinmux(13), 8, 4 }, { pinmux(13), 8, 3 }, { pinmux(13), 8, 2 }, { pinmux(13), 8, 1 }, { pinmux(13), 8, 0 }, { pinmux(18), 8, 1 }, /* GP7[0] */ { pinmux(18), 8, 0 }, { pinmux(17), 8, 7 }, { pinmux(17), 8, 6 }, { pinmux(17), 8, 5 }, { pinmux(17), 8, 4 }, { pinmux(17), 8, 3 }, { pinmux(17), 8, 2 }, { pinmux(17), 8, 1 }, { pinmux(17), 8, 0 }, { pinmux(16), 8, 7 }, { pinmux(16), 8, 6 }, { pinmux(16), 8, 5 }, { pinmux(16), 8, 4 }, { pinmux(16), 8, 3 }, { pinmux(16), 8, 2 }, { pinmux(19), 8, 0 }, /* GP8[0] */ { pinmux(3), 4, 7 }, { pinmux(3), 4, 6 }, { pinmux(3), 4, 5 }, { pinmux(3), 4, 4 }, { pinmux(3), 4, 3 }, { pinmux(3), 4, 2 }, { pinmux(2), 4, 7 }, { pinmux(19), 8, 1 }, { pinmux(19), 8, 0 }, { pinmux(18), 8, 7 }, { pinmux(18), 8, 6 }, { pinmux(18), 8, 5 }, { pinmux(18), 8, 4 }, { pinmux(18), 8, 3 }, { pinmux(18), 8, 2 }, }; int gpio_request(int gp, const char *label) { if (gp >= MAX_NUM_GPIOS) return -1; if (gpio_registry[gp].is_registered) return -1; gpio_registry[gp].is_registered = 1; strncpy(gpio_registry[gp].name, label, GPIO_NAME_SIZE); gpio_registry[gp].name[GPIO_NAME_SIZE - 1] = 0; davinci_configure_pin_mux(&gpio_pinmux[gp], 1); return 0; } void gpio_free(int gp) { gpio_registry[gp].is_registered = 0; } void gpio_toggle_value(int gp) { gpio_set_value(gp, !gpio_get_value(gp)); } int gpio_direction_input(int gp) { struct davinci_gpio *bank; bank = GPIO_BANK(gp); setbits_le32(&bank->dir, 1U << GPIO_BIT(gp)); return 0; } int gpio_direction_output(int gp, int value) { struct davinci_gpio *bank; bank = GPIO_BANK(gp); clrbits_le32(&bank->dir, 1U << GPIO_BIT(gp)); gpio_set_value(gp, value); return 0; } int gpio_get_value(int gp) { struct davinci_gpio *bank; unsigned int ip; bank = GPIO_BANK(gp); ip = in_le32(&bank->in_data) & (1U << GPIO_BIT(gp)); return ip ? 1 : 0; } void gpio_set_value(int gp, int value) { struct davinci_gpio *bank; bank = GPIO_BANK(gp); if (value) bank->set_data = 1U << GPIO_BIT(gp); else bank->clr_data = 1U << GPIO_BIT(gp); } void gpio_info(void) { int gp, dir, val; struct davinci_gpio *bank; for (gp = 0; gp < MAX_NUM_GPIOS; ++gp) { bank = GPIO_BANK(gp); dir = in_le32(&bank->dir) & (1U << GPIO_BIT(gp)); val = gpio_get_value(gp); printf("% 4d: %s: %d [%c] %s\n", gp, dir ? " in" : "out", val, gpio_registry[gp].is_registered ? 'x' : ' ', gpio_registry[gp].name); } }
1001-study-uboot
drivers/gpio/da8xx_gpio.c
C
gpl3
6,149
/* * Driver for Altera's PIO ip core * * Copyright (C) 2011 Missing Link Electronics * Joachim Foerster <joachim@missinglinkelectronics.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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * To use this driver, in your board's config. header: * #define CONFIG_ALTERA_PIO * #define CONFIG_SYS_ALTERA_PIO_NUM <number-of-pio-cores> * #define CONFIG_SYS_ALTERA_PIO_GPIO_NUM <total-number-of-gpios> * And in your board's early setup routine: * altera_pio_init(<baseaddr>, <width>, 'i'|'o'|'t', * <reset-value>, <neg-mask>, "label"); * - 'i'|'o'|'t': PIO is input-only/output-only/tri-state * - <reset-value>: for correct initial status display, output-only * - <neg-mask> is meant to be used to in cases of active-low * GPIOs, such as LEDs and buttons (on/pressed == 0). Each bit * which is 1 in <neg-mask> inverts the corresponding GPIO's value * before set/after get. So: gpio_set_value(gpio, 1) => LED on . * * Do NOT define CONFIG_SYS_GPIO_BASE ! * * Optionally, in your board's config. header: * - To force a GPIO numbering scheme like in Linux ... * #define CONFIG_GPIO_DOWNTO_NUMBERING * ... starting with 255 (default) * #define CONFIG_GPIO_DOWNTO_MAX 255 */ #include <common.h> #include <asm/io.h> #include <asm/gpio.h> #ifdef CONFIG_GPIO_DOWNTO_NUMBERING #ifndef CONFIG_GPIO_DOWNTO_MAX #define CONFIG_GPIO_DOWNTO_MAX 255 #endif #endif #define ALTERA_PIO_DATA 0x0 #define ALTERA_PIO_DIR 0x4 #define GPIO_LABEL_SIZE 9 static struct altera_pio { u32 base; u8 width; char iot; u32 negmask; u32 sh_data; u32 sh_dir; int gidx; char label[GPIO_LABEL_SIZE]; } pios[CONFIG_SYS_ALTERA_PIO_NUM]; static int pio_num; static struct altera_pio_gpio { unsigned num; struct altera_pio *pio; char reqlabel[GPIO_LABEL_SIZE]; } gpios[CONFIG_SYS_ALTERA_PIO_GPIO_NUM]; static int pio_gpio_num; static int altera_pio_gidx(unsigned gpio) { int i; for (i = 0; i < pio_gpio_num; ++i) { if (gpio == gpios[i].num) break; } if (i >= pio_gpio_num) return -1; return i; } static struct altera_pio *altera_pio_get_and_mask(unsigned gpio, u32 *mask) { int gidx = altera_pio_gidx(gpio); if (gidx < 0) return NULL; if (mask) *mask = 1 << (gidx - gpios[gidx].pio->gidx); return gpios[gidx].pio; } #define altera_pio_use_gidx(_gidx, _reqlabel) \ { strncpy(gpios[_gidx].reqlabel, _reqlabel, GPIO_LABEL_SIZE); } #define altera_pio_unuse_gidx(_gidx) { gpios[_gidx].reqlabel[0] = '\0'; } #define altera_pio_is_gidx_used(_gidx) (gpios[_gidx].reqlabel[0] != '\0') static int altera_pio_gpio_init(struct altera_pio *pio, u8 width) { u8 gidx = pio_gpio_num; int i; if (!width) return -1; if ((pio_gpio_num + width) > CONFIG_SYS_ALTERA_PIO_GPIO_NUM) return -1; for (i = 0; i < width; ++i) { #ifdef CONFIG_GPIO_DOWNTO_NUMBERING gpios[pio_gpio_num + i].num = \ CONFIG_GPIO_DOWNTO_MAX + 1 - gidx - width + i; #else gpios[pio_gpio_num + i].num = pio_gpio_num + i; #endif gpios[pio_gpio_num + i].pio = pio; altera_pio_unuse_gidx(pio_gpio_num + i); } pio_gpio_num += width; return gidx; } int altera_pio_init(u32 base, u8 width, char iot, u32 rstval, u32 negmask, const char *label) { if (pio_num >= CONFIG_SYS_ALTERA_PIO_NUM) return -1; pios[pio_num].base = base; pios[pio_num].width = width; pios[pio_num].iot = iot; switch (iot) { case 'i': /* input only */ pios[pio_num].sh_dir = 0; pios[pio_num].sh_data = readl(base + ALTERA_PIO_DATA); break; case 'o': /* output only */ pios[pio_num].sh_dir = 0xffffffff & ((1 << width) - 1); pios[pio_num].sh_data = rstval; break; case 't': /* bidir, tri-state */ pios[pio_num].sh_dir = readl(base + ALTERA_PIO_DIR); pios[pio_num].sh_data = readl(base + ALTERA_PIO_DATA); break; default: return -1; } pios[pio_num].negmask = negmask & ((1 << width) - 1); pios[pio_num].gidx = altera_pio_gpio_init(&pios[pio_num], width); if (pios[pio_num].gidx < 0) return -1; strncpy(pios[pio_num].label, label, GPIO_LABEL_SIZE); return pio_num++; } void altera_pio_info(void) { int i; int j; int gidx; u32 mask; for (i = 0; i < pio_num; ++i) { printf("Altera PIO % 2d, @0x%08x, " "width: %u, label: %s\n", i, pios[i].base, pios[i].width, pios[i].label); gidx = pios[i].gidx; for (j = gidx; j < (gidx + pios[i].width); ++j) { mask = 1 << (j - gidx); printf("\tGPIO % 4d: %s %s [%c] %s\n", gpios[j].num, gpios[j].pio->sh_dir & mask ? "out" : " in", gpio_get_value(gpios[j].num) ? "set" : "clr", altera_pio_is_gidx_used(j) ? 'x' : ' ', gpios[j].reqlabel); } } } int gpio_request(unsigned gpio, const char *label) { int gidx = altera_pio_gidx(gpio); if (gidx < 0) return gidx; if (altera_pio_is_gidx_used(gidx)) return -1; altera_pio_use_gidx(gidx, label); return 0; } int gpio_free(unsigned gpio) { int gidx = altera_pio_gidx(gpio); if (gidx < 0) return gidx; if (!altera_pio_is_gidx_used(gidx)) return -1; altera_pio_unuse_gidx(gidx); return 0; } int gpio_direction_input(unsigned gpio) { u32 mask; struct altera_pio *pio; pio = altera_pio_get_and_mask(gpio, &mask); if (!pio) return -1; if (pio->iot == 'o') return -1; writel(pio->sh_dir &= ~mask, pio->base + ALTERA_PIO_DIR); return 0; } int gpio_direction_output(unsigned gpio, int value) { u32 mask; struct altera_pio *pio; pio = altera_pio_get_and_mask(gpio, &mask); if (!pio) return -1; if (pio->iot == 'i') return -1; value = (pio->negmask & mask) ? !value : value; if (value) pio->sh_data |= mask; else pio->sh_data &= ~mask; writel(pio->sh_data, pio->base + ALTERA_PIO_DATA); writel(pio->sh_dir |= mask, pio->base + ALTERA_PIO_DIR); return 0; } int gpio_get_value(unsigned gpio) { u32 mask; struct altera_pio *pio; u32 val; pio = altera_pio_get_and_mask(gpio, &mask); if (!pio) return -1; if ((pio->sh_dir & mask) || (pio->iot == 'o')) val = pio->sh_data & mask; else val = readl(pio->base + ALTERA_PIO_DATA) & mask; return (pio->negmask & mask) ? !val : val; } void gpio_set_value(unsigned gpio, int value) { u32 mask; struct altera_pio *pio; pio = altera_pio_get_and_mask(gpio, &mask); if (!pio) return; if (pio->iot == 'i') return; value = (pio->negmask & mask) ? !value : value; if (value) pio->sh_data |= mask; else pio->sh_data &= ~mask; writel(pio->sh_data, pio->base + ALTERA_PIO_DATA); return; } int gpio_is_valid(int number) { int gidx = altera_pio_gidx(number); if (gidx < 0) return 1; return 0; }
1001-study-uboot
drivers/gpio/altera_pio.c
C
gpl3
7,175
/* * (C) Copyright 2009 Samsung Electronics * Minkyu Kang <mk7.kang@samsung.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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <asm/io.h> #include <asm/arch/gpio.h> #define CON_MASK(x) (0xf << ((x) << 2)) #define CON_SFR(x, v) ((v) << ((x) << 2)) #define DAT_MASK(x) (0x1 << (x)) #define DAT_SET(x) (0x1 << (x)) #define PULL_MASK(x) (0x3 << ((x) << 1)) #define PULL_MODE(x, v) ((v) << ((x) << 1)) #define DRV_MASK(x) (0x3 << ((x) << 1)) #define DRV_SET(x, m) ((m) << ((x) << 1)) #define RATE_MASK(x) (0x1 << (x + 16)) #define RATE_SET(x) (0x1 << (x + 16)) void s5p_gpio_cfg_pin(struct s5p_gpio_bank *bank, int gpio, int cfg) { unsigned int value; value = readl(&bank->con); value &= ~CON_MASK(gpio); value |= CON_SFR(gpio, cfg); writel(value, &bank->con); } void s5p_gpio_direction_output(struct s5p_gpio_bank *bank, int gpio, int en) { unsigned int value; s5p_gpio_cfg_pin(bank, gpio, GPIO_OUTPUT); value = readl(&bank->dat); value &= ~DAT_MASK(gpio); if (en) value |= DAT_SET(gpio); writel(value, &bank->dat); } void s5p_gpio_direction_input(struct s5p_gpio_bank *bank, int gpio) { s5p_gpio_cfg_pin(bank, gpio, GPIO_INPUT); } void s5p_gpio_set_value(struct s5p_gpio_bank *bank, int gpio, int en) { unsigned int value; value = readl(&bank->dat); value &= ~DAT_MASK(gpio); if (en) value |= DAT_SET(gpio); writel(value, &bank->dat); } unsigned int s5p_gpio_get_value(struct s5p_gpio_bank *bank, int gpio) { unsigned int value; value = readl(&bank->dat); return !!(value & DAT_MASK(gpio)); } void s5p_gpio_set_pull(struct s5p_gpio_bank *bank, int gpio, int mode) { unsigned int value; value = readl(&bank->pull); value &= ~PULL_MASK(gpio); switch (mode) { case GPIO_PULL_DOWN: case GPIO_PULL_UP: value |= PULL_MODE(gpio, mode); break; default: break; } writel(value, &bank->pull); } void s5p_gpio_set_drv(struct s5p_gpio_bank *bank, int gpio, int mode) { unsigned int value; value = readl(&bank->drv); value &= ~DRV_MASK(gpio); switch (mode) { case GPIO_DRV_1X: case GPIO_DRV_2X: case GPIO_DRV_3X: case GPIO_DRV_4X: value |= DRV_SET(gpio, mode); break; default: return; } writel(value, &bank->drv); } void s5p_gpio_set_rate(struct s5p_gpio_bank *bank, int gpio, int mode) { unsigned int value; value = readl(&bank->drv); value &= ~RATE_MASK(gpio); switch (mode) { case GPIO_DRV_FAST: case GPIO_DRV_SLOW: value |= RATE_SET(gpio); break; default: return; } writel(value, &bank->drv); } struct s5p_gpio_bank *s5p_gpio_get_bank(int nr) { int bank = nr / GPIO_PER_BANK; bank *= sizeof(struct s5p_gpio_bank); return (struct s5p_gpio_bank *) (s5p_gpio_base(nr) + bank); } int s5p_gpio_get_pin(int nr) { return nr % GPIO_PER_BANK; } int gpio_request(int gpio, const char *label) { return 0; } int gpio_direction_input(int nr) { s5p_gpio_direction_input(s5p_gpio_get_bank(nr), s5p_gpio_get_pin(nr)); return 0; } int gpio_direction_output(int nr, int value) { s5p_gpio_direction_output(s5p_gpio_get_bank(nr), s5p_gpio_get_pin(nr), value); return 0; } int gpio_get_value(int nr) { return (int) s5p_gpio_get_value(s5p_gpio_get_bank(nr), s5p_gpio_get_pin(nr)); } void gpio_set_value(int nr, int value) { s5p_gpio_set_value(s5p_gpio_get_bank(nr), s5p_gpio_get_pin(nr), value); }
1001-study-uboot
drivers/gpio/s5p_gpio.c
C
gpl3
4,021
/* * Copyright (C) 2009 * Guennadi Liakhovetski, DENX Software Engineering, <lg@denx.de> * * Copyright (C) 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 */ #include <common.h> #include <asm/arch/imx-regs.h> #include <asm/gpio.h> #include <asm/io.h> #include <errno.h> enum mxc_gpio_direction { MXC_GPIO_DIRECTION_IN, MXC_GPIO_DIRECTION_OUT, }; /* GPIO port description */ static unsigned long gpio_ports[] = { [0] = GPIO1_BASE_ADDR, [1] = GPIO2_BASE_ADDR, [2] = GPIO3_BASE_ADDR, #if defined(CONFIG_MX51) || defined(CONFIG_MX53) || defined(CONFIG_MX6Q) [3] = GPIO4_BASE_ADDR, #endif #if defined(CONFIG_MX53) || defined(CONFIG_MX6Q) [4] = GPIO5_BASE_ADDR, [5] = GPIO6_BASE_ADDR, [6] = GPIO7_BASE_ADDR, #endif }; static int mxc_gpio_direction(unsigned int gpio, enum mxc_gpio_direction direction) { unsigned int port = gpio >> 5; struct gpio_regs *regs; u32 l; if (port >= ARRAY_SIZE(gpio_ports)) return -EINVAL; gpio &= 0x1f; regs = (struct gpio_regs *)gpio_ports[port]; l = readl(&regs->gpio_dir); switch (direction) { case MXC_GPIO_DIRECTION_OUT: l |= 1 << gpio; break; case MXC_GPIO_DIRECTION_IN: l &= ~(1 << gpio); } writel(l, &regs->gpio_dir); return 0; } void gpio_set_value(int gpio, int value) { unsigned int port = gpio >> 5; struct gpio_regs *regs; u32 l; if (port >= ARRAY_SIZE(gpio_ports)) return; gpio &= 0x1f; regs = (struct gpio_regs *)gpio_ports[port]; l = readl(&regs->gpio_dr); if (value) l |= 1 << gpio; else l &= ~(1 << gpio); writel(l, &regs->gpio_dr); } int gpio_get_value(int gpio) { unsigned int port = gpio >> 5; struct gpio_regs *regs; u32 l; if (port >= ARRAY_SIZE(gpio_ports)) return -EINVAL; gpio &= 0x1f; regs = (struct gpio_regs *)gpio_ports[port]; l = (readl(&regs->gpio_dr) >> gpio) & 0x01; return l; } int gpio_request(int gp, const char *label) { unsigned int port = gp >> 5; if (port >= ARRAY_SIZE(gpio_ports)) return -EINVAL; return 0; } void gpio_free(int gp) { } void gpio_toggle_value(int gp) { gpio_set_value(gp, !gpio_get_value(gp)); } int gpio_direction_input(int gp) { return mxc_gpio_direction(gp, MXC_GPIO_DIRECTION_IN); } int gpio_direction_output(int gp, int value) { int ret = mxc_gpio_direction(gp, MXC_GPIO_DIRECTION_OUT); if (ret < 0) return ret; gpio_set_value(gp, value); return 0; }
1001-study-uboot
drivers/gpio/mxc_gpio.c
C
gpl3
3,155
# # (C) Copyright 2009 # Detlev Zundel, DENX Software Engineering, dzu@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)libtws.o COBJS-$(CONFIG_SOFT_TWS) += soft_tws.o COBJS := $(COBJS-y) SRCS := $(COBJS:.o=.c) OBJS := $(addprefix $(obj),$(COBJS)) all: $(LIB) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
drivers/twserial/Makefile
Makefile
gpl3
1,345
/* * (C) Copyright 2009 * Detlev Zundel, DENX Software Engineering, dzu@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 * */ #define TWS_IMPLEMENTATION #include <common.h> /*=====================================================================*/ /* Public Functions */ /*=====================================================================*/ /*----------------------------------------------------------------------- * Read bits */ int tws_read(uchar *buffer, int len) { int rem = len; uchar accu, shift; debug("tws_read: buffer %p len %d\n", buffer, len); /* Configure the data pin for input */ tws_data_config_output(0); /* Disable WR, i.e. setup a read */ tws_wr(0); udelay(1); /* Rise CE */ tws_ce(1); udelay(1); for (; rem > 0; ) { for (shift = 0, accu = 0; (rem > 0) && (shift < 8); rem--, shift++) { tws_clk(1); udelay(10); accu |= (tws_data_read() << shift); /* LSB first */ tws_clk(0); udelay(10); } *buffer++ = accu; } /* Lower CE */ tws_ce(0); return len - rem; } /*----------------------------------------------------------------------- * Write bits */ int tws_write(uchar *buffer, int len) { int rem = len; uchar accu, shift; debug("tws_write: buffer %p len %d\n", buffer, len); /* Configure the data pin for output */ tws_data_config_output(1); /* Enable WR, i.e. setup a write */ tws_wr(1); udelay(1); /* Rise CE */ tws_ce(1); udelay(1); for (; rem > 0; ) { for (shift = 0, accu = *buffer++; (rem > 0) && (shift < 8); rem--, shift++) { tws_data(accu & 0x01); /* LSB first */ tws_clk(1); udelay(10); tws_clk(0); udelay(10); accu >>= 1; } } /* Lower CE */ tws_ce(0); return len - rem; }
1001-study-uboot
drivers/twserial/soft_tws.c
C
gpl3
2,537
/* * Copyright (C) 2011 Renesas Solutions Corp. * Copyright (C) 2011 Nobuhiro Iwamatsu <nobuhiro.iwamatsu.yj@renesas.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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <asm/io.h> /* Every register is 32bit aligned, but only 8bits in size */ #define ureg(name) u8 name; u8 __pad_##name##0; u16 __pad_##name##1; struct sh_i2c { ureg(icdr); ureg(iccr); ureg(icsr); ureg(icic); ureg(iccl); ureg(icch); }; #undef ureg static struct sh_i2c *base; /* ICCR */ #define SH_I2C_ICCR_ICE (1 << 7) #define SH_I2C_ICCR_RACK (1 << 6) #define SH_I2C_ICCR_RTS (1 << 4) #define SH_I2C_ICCR_BUSY (1 << 2) #define SH_I2C_ICCR_SCP (1 << 0) /* ICSR / ICIC */ #define SH_IC_BUSY (1 << 3) #define SH_IC_TACK (1 << 2) #define SH_IC_WAIT (1 << 1) #define SH_IC_DTE (1 << 0) static u8 iccl, icch; #define IRQ_WAIT 1000 static void irq_wait(struct sh_i2c *base) { int i; u8 status; for (i = 0 ; i < IRQ_WAIT ; i++) { status = readb(&base->icsr); if (SH_IC_WAIT & status) break; udelay(10); } writeb(status & ~SH_IC_WAIT, &base->icsr); } static void irq_dte(struct sh_i2c *base) { int i; for (i = 0 ; i < IRQ_WAIT ; i++) { if (SH_IC_DTE & readb(&base->icsr)) break; udelay(10); } } static void irq_busy(struct sh_i2c *base) { int i; for (i = 0 ; i < IRQ_WAIT ; i++) { if (!(SH_IC_BUSY & readb(&base->icsr))) break; udelay(10); } } static void i2c_set_addr(struct sh_i2c *base, u8 id, u8 reg, int stop) { writeb(readb(&base->iccr) & ~SH_I2C_ICCR_ICE, &base->iccr); writeb(readb(&base->iccr) | SH_I2C_ICCR_ICE, &base->iccr); writeb(iccl, &base->iccl); writeb(icch, &base->icch); writeb(0, &base->icic); writeb((SH_I2C_ICCR_ICE|SH_I2C_ICCR_RTS|SH_I2C_ICCR_BUSY), &base->iccr); irq_dte(base); writeb(id << 1, &base->icdr); irq_dte(base); writeb(reg, &base->icdr); if (stop) writeb((SH_I2C_ICCR_ICE|SH_I2C_ICCR_RTS), &base->iccr); irq_dte(base); } static void i2c_finish(struct sh_i2c *base) { writeb(0, &base->icsr); writeb(readb(&base->iccr) & ~SH_I2C_ICCR_ICE, &base->iccr); } static void i2c_raw_write(struct sh_i2c *base, u8 id, u8 reg, u8 val) { i2c_set_addr(base, id, reg, 0); udelay(10); writeb(val, &base->icdr); irq_dte(base); writeb((SH_I2C_ICCR_ICE | SH_I2C_ICCR_RTS), &base->iccr); irq_dte(base); irq_busy(base); i2c_finish(base); } static u8 i2c_raw_read(struct sh_i2c *base, u8 id, u8 reg) { u8 ret; i2c_set_addr(base, id, reg, 1); udelay(100); writeb((SH_I2C_ICCR_ICE|SH_I2C_ICCR_RTS|SH_I2C_ICCR_BUSY), &base->iccr); irq_dte(base); writeb(id << 1 | 0x01, &base->icdr); irq_dte(base); writeb((SH_I2C_ICCR_ICE|SH_I2C_ICCR_SCP), &base->iccr); irq_dte(base); ret = readb(&base->icdr); writeb((SH_I2C_ICCR_ICE|SH_I2C_ICCR_RACK), &base->iccr); readb(&base->icdr); /* Dummy read */ irq_busy(base); i2c_finish(base); return ret; } #ifdef CONFIG_I2C_MULTI_BUS static unsigned int current_bus; /** * i2c_set_bus_num - change active I2C bus * @bus: bus index, zero based * @returns: 0 on success, non-0 on failure */ int i2c_set_bus_num(unsigned int bus) { if ((bus < 0) || (bus >= CONFIG_SYS_MAX_I2C_BUS)) { printf("Bad bus: %d\n", bus); return -1; } switch (bus) { case 0: base = (void *)CONFIG_SH_I2C_BASE0; break; case 1: base = (void *)CONFIG_SH_I2C_BASE1; break; default: return -1; } current_bus = bus; return 0; } /** * i2c_get_bus_num - returns index of active I2C bus */ unsigned int i2c_get_bus_num(void) { return current_bus; } #endif #define SH_I2C_ICCL_CALC(clk, date, t_low, t_high) \ ((clk / rate) * (t_low / t_low + t_high)) #define SH_I2C_ICCH_CALC(clk, date, t_low, t_high) \ ((clk / rate) * (t_high / t_low + t_high)) void i2c_init(int speed, int slaveaddr) { int num, denom, tmp; #ifdef CONFIG_I2C_MULTI_BUS current_bus = 0; #endif base = (struct sh_i2c *)CONFIG_SH_I2C_BASE0; /* * Calculate the value for iccl. From the data sheet: * iccl = (p-clock / transfer-rate) * (L / (L + H)) * where L and H are the SCL low and high ratio. */ num = CONFIG_SH_I2C_CLOCK * CONFIG_SH_I2C_DATA_LOW; denom = speed * (CONFIG_SH_I2C_DATA_HIGH + CONFIG_SH_I2C_DATA_LOW); tmp = num * 10 / denom; if (tmp % 10 >= 5) iccl = (u8)((num/denom) + 1); else iccl = (u8)(num/denom); /* Calculate the value for icch. From the data sheet: icch = (p clock / transfer rate) * (H / (L + H)) */ num = CONFIG_SH_I2C_CLOCK * CONFIG_SH_I2C_DATA_HIGH; tmp = num * 10 / denom; if (tmp % 10 >= 5) icch = (u8)((num/denom) + 1); else icch = (u8)(num/denom); } /* * i2c_read: - Read multiple bytes from an i2c device * * The higher level routines take into account that this function is only * called with len < page length of the device (see configuration file) * * @chip: address of the chip which is to be read * @addr: i2c data address within the chip * @alen: length of the i2c data address (1..2 bytes) * @buffer: where to write the data * @len: how much byte do we want to read * @return: 0 in case of success */ int i2c_read(u8 chip, u32 addr, int alen, u8 *buffer, int len) { int i = 0; for (i = 0 ; i < len ; i++) buffer[i] = i2c_raw_read(base, chip, addr + i); return 0; } /* * i2c_write: - Write multiple bytes to an i2c device * * The higher level routines take into account that this function is only * called with len < page length of the device (see configuration file) * * @chip: address of the chip which is to be written * @addr: i2c data address within the chip * @alen: length of the i2c data address (1..2 bytes) * @buffer: where to find the data to be written * @len: how much byte do we want to read * @return: 0 in case of success */ int i2c_write(u8 chip, u32 addr, int alen, u8 *buffer, int len) { int i = 0; for (i = 0; i < len ; i++) i2c_raw_write(base, chip, addr + i, buffer[i]); return 0; } /* * i2c_probe: - Test if a chip answers for a given i2c address * * @chip: address of the chip which is searched for * @return: 0 if a chip was found, -1 otherwhise */ int i2c_probe(u8 chip) { return 0; }
1001-study-uboot
drivers/i2c/sh_i2c.c
C
gpl3
6,747
/* * (C) Copyright 2002 * David Mueller, ELSOFT AG, d.mueller@elsoft.ch * * 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 */ /* This code should work for both the S3C2400 and the S3C2410 * as they seem to have the same I2C controller inside. * The different address mapping is handled by the s3c24xx.h files below. */ #include <common.h> #include <asm/arch/s3c24x0_cpu.h> #include <asm/io.h> #include <i2c.h> #ifdef CONFIG_HARD_I2C #define I2C_WRITE 0 #define I2C_READ 1 #define I2C_OK 0 #define I2C_NOK 1 #define I2C_NACK 2 #define I2C_NOK_LA 3 /* Lost arbitration */ #define I2C_NOK_TOUT 4 /* time out */ #define I2CSTAT_BSY 0x20 /* Busy bit */ #define I2CSTAT_NACK 0x01 /* Nack bit */ #define I2CCON_IRPND 0x10 /* Interrupt pending bit */ #define I2C_MODE_MT 0xC0 /* Master Transmit Mode */ #define I2C_MODE_MR 0x80 /* Master Receive Mode */ #define I2C_START_STOP 0x20 /* START / STOP */ #define I2C_TXRX_ENA 0x10 /* I2C Tx/Rx enable */ #define I2C_TIMEOUT 1 /* 1 second */ static int GetI2CSDA(void) { struct s3c24x0_gpio *gpio = s3c24x0_get_base_gpio(); #if defined(CONFIG_S3C2410) || defined (CONFIG_S3C2440) return (readl(&gpio->gpedat) & 0x8000) >> 15; #endif #ifdef CONFIG_S3C2400 return (readl(&gpio->pgdat) & 0x0020) >> 5; #endif } #if 0 static void SetI2CSDA(int x) { rGPEDAT = (rGPEDAT & ~0x8000) | (x & 1) << 15; } #endif static void SetI2CSCL(int x) { struct s3c24x0_gpio *gpio = s3c24x0_get_base_gpio(); #if defined(CONFIG_S3C2410) || defined (CONFIG_S3C2440) writel((readl(&gpio->gpedat) & ~0x4000) | (x & 1) << 14, &gpio->gpedat); #endif #ifdef CONFIG_S3C2400 writel((readl(&gpio->pgdat) & ~0x0040) | (x & 1) << 6, &gpio->pgdat); #endif } static int WaitForXfer(void) { struct s3c24x0_i2c *i2c = s3c24x0_get_base_i2c(); int i; i = I2C_TIMEOUT * 10000; while (!(readl(&i2c->iiccon) & I2CCON_IRPND) && (i > 0)) { udelay(100); i--; } return (readl(&i2c->iiccon) & I2CCON_IRPND) ? I2C_OK : I2C_NOK_TOUT; } static int IsACK(void) { struct s3c24x0_i2c *i2c = s3c24x0_get_base_i2c(); return !(readl(&i2c->iicstat) & I2CSTAT_NACK); } static void ReadWriteByte(void) { struct s3c24x0_i2c *i2c = s3c24x0_get_base_i2c(); writel(readl(&i2c->iiccon) & ~I2CCON_IRPND, &i2c->iiccon); } void i2c_init(int speed, int slaveadd) { struct s3c24x0_i2c *i2c = s3c24x0_get_base_i2c(); struct s3c24x0_gpio *gpio = s3c24x0_get_base_gpio(); ulong freq, pres = 16, div; int i; /* wait for some time to give previous transfer a chance to finish */ i = I2C_TIMEOUT * 1000; while ((readl(&i2c->iicstat) && I2CSTAT_BSY) && (i > 0)) { udelay(1000); i--; } if ((readl(&i2c->iicstat) & I2CSTAT_BSY) || GetI2CSDA() == 0) { #if defined(CONFIG_S3C2410) || defined (CONFIG_S3C2440) ulong old_gpecon = readl(&gpio->gpecon); #endif #ifdef CONFIG_S3C2400 ulong old_gpecon = readl(&gpio->pgcon); #endif /* bus still busy probably by (most) previously interrupted transfer */ #if defined(CONFIG_S3C2410) || defined (CONFIG_S3C2440) /* set I2CSDA and I2CSCL (GPE15, GPE14) to GPIO */ writel((readl(&gpio->gpecon) & ~0xF0000000) | 0x10000000, &gpio->gpecon); #endif #ifdef CONFIG_S3C2400 /* set I2CSDA and I2CSCL (PG5, PG6) to GPIO */ writel((readl(&gpio->pgcon) & ~0x00003c00) | 0x00001000, &gpio->pgcon); #endif /* toggle I2CSCL until bus idle */ SetI2CSCL(0); udelay(1000); i = 10; while ((i > 0) && (GetI2CSDA() != 1)) { SetI2CSCL(1); udelay(1000); SetI2CSCL(0); udelay(1000); i--; } SetI2CSCL(1); udelay(1000); /* restore pin functions */ #if defined(CONFIG_S3C2410) || defined (CONFIG_S3C2440) writel(old_gpecon, &gpio->gpecon); #endif #ifdef CONFIG_S3C2400 writel(old_gpecon, &gpio->pgcon); #endif } /* calculate prescaler and divisor values */ freq = get_PCLK(); if ((freq / pres / (16 + 1)) > speed) /* set prescaler to 512 */ pres = 512; div = 0; while ((freq / pres / (div + 1)) > speed) div++; /* set prescaler, divisor according to freq, also set * ACKGEN, IRQ */ writel((div & 0x0F) | 0xA0 | ((pres == 512) ? 0x40 : 0), &i2c->iiccon); /* init to SLAVE REVEIVE and set slaveaddr */ writel(0, &i2c->iicstat); writel(slaveadd, &i2c->iicadd); /* program Master Transmit (and implicit STOP) */ writel(I2C_MODE_MT | I2C_TXRX_ENA, &i2c->iicstat); } /* * cmd_type is 0 for write, 1 for read. * * addr_len can take any value from 0-255, it is only limited * by the char, we could make it larger if needed. If it is * 0 we skip the address write cycle. */ static int i2c_transfer(unsigned char cmd_type, unsigned char chip, unsigned char addr[], unsigned char addr_len, unsigned char data[], unsigned short data_len) { struct s3c24x0_i2c *i2c = s3c24x0_get_base_i2c(); int i, result; if (data == 0 || data_len == 0) { /*Don't support data transfer of no length or to address 0 */ printf("i2c_transfer: bad call\n"); return I2C_NOK; } /* Check I2C bus idle */ i = I2C_TIMEOUT * 1000; while ((readl(&i2c->iicstat) & I2CSTAT_BSY) && (i > 0)) { udelay(1000); i--; } if (readl(&i2c->iicstat) & I2CSTAT_BSY) return I2C_NOK_TOUT; writel(readl(&i2c->iiccon) | 0x80, &i2c->iiccon); result = I2C_OK; switch (cmd_type) { case I2C_WRITE: if (addr && addr_len) { writel(chip, &i2c->iicds); /* send START */ writel(I2C_MODE_MT | I2C_TXRX_ENA | I2C_START_STOP, &i2c->iicstat); i = 0; while ((i < addr_len) && (result == I2C_OK)) { result = WaitForXfer(); writel(addr[i], &i2c->iicds); ReadWriteByte(); i++; } i = 0; while ((i < data_len) && (result == I2C_OK)) { result = WaitForXfer(); writel(data[i], &i2c->iicds); ReadWriteByte(); i++; } } else { writel(chip, &i2c->iicds); /* send START */ writel(I2C_MODE_MT | I2C_TXRX_ENA | I2C_START_STOP, &i2c->iicstat); i = 0; while ((i < data_len) && (result = I2C_OK)) { result = WaitForXfer(); writel(data[i], &i2c->iicds); ReadWriteByte(); i++; } } if (result == I2C_OK) result = WaitForXfer(); /* send STOP */ writel(I2C_MODE_MR | I2C_TXRX_ENA, &i2c->iicstat); ReadWriteByte(); break; case I2C_READ: if (addr && addr_len) { writel(I2C_MODE_MT | I2C_TXRX_ENA, &i2c->iicstat); writel(chip, &i2c->iicds); /* send START */ writel(readl(&i2c->iicstat) | I2C_START_STOP, &i2c->iicstat); result = WaitForXfer(); if (IsACK()) { i = 0; while ((i < addr_len) && (result == I2C_OK)) { writel(addr[i], &i2c->iicds); ReadWriteByte(); result = WaitForXfer(); i++; } writel(chip, &i2c->iicds); /* resend START */ writel(I2C_MODE_MR | I2C_TXRX_ENA | I2C_START_STOP, &i2c->iicstat); ReadWriteByte(); result = WaitForXfer(); i = 0; while ((i < data_len) && (result == I2C_OK)) { /* disable ACK for final READ */ if (i == data_len - 1) writel(readl(&i2c->iiccon) & ~0x80, &i2c->iiccon); ReadWriteByte(); result = WaitForXfer(); data[i] = readl(&i2c->iicds); i++; } } else { result = I2C_NACK; } } else { writel(I2C_MODE_MR | I2C_TXRX_ENA, &i2c->iicstat); writel(chip, &i2c->iicds); /* send START */ writel(readl(&i2c->iicstat) | I2C_START_STOP, &i2c->iicstat); result = WaitForXfer(); if (IsACK()) { i = 0; while ((i < data_len) && (result == I2C_OK)) { /* disable ACK for final READ */ if (i == data_len - 1) writel(readl(&i2c->iiccon) & ~0x80, &i2c->iiccon); ReadWriteByte(); result = WaitForXfer(); data[i] = readl(&i2c->iicds); i++; } } else { result = I2C_NACK; } } /* send STOP */ writel(I2C_MODE_MR | I2C_TXRX_ENA, &i2c->iicstat); ReadWriteByte(); break; default: printf("i2c_transfer: bad call\n"); result = I2C_NOK; break; } return (result); } int i2c_probe(uchar chip) { uchar buf[1]; buf[0] = 0; /* * What is needed is to send the chip address and verify that the * address was <ACK>ed (i.e. there was a chip at that address which * drove the data line low). */ return i2c_transfer(I2C_READ, chip << 1, 0, 0, buf, 1) != I2C_OK; } int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { uchar xaddr[4]; int ret; if (alen > 4) { printf("I2C read: addr len %d not supported\n", alen); return 1; } if (alen > 0) { xaddr[0] = (addr >> 24) & 0xFF; xaddr[1] = (addr >> 16) & 0xFF; xaddr[2] = (addr >> 8) & 0xFF; xaddr[3] = addr & 0xFF; } #ifdef CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW /* * EEPROM chips that implement "address overflow" are ones * like Catalyst 24WC04/08/16 which has 9/10/11 bits of * address and the extra bits end up in the "chip address" * bit slots. This makes a 24WC08 (1Kbyte) chip look like * four 256 byte chips. * * Note that we consider the length of the address field to * still be one byte because the extra address bits are * hidden in the chip address. */ if (alen > 0) chip |= ((addr >> (alen * 8)) & CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW); #endif if ((ret = i2c_transfer(I2C_READ, chip << 1, &xaddr[4 - alen], alen, buffer, len)) != 0) { printf("I2c read: failed %d\n", ret); return 1; } return 0; } int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { uchar xaddr[4]; if (alen > 4) { printf("I2C write: addr len %d not supported\n", alen); return 1; } if (alen > 0) { xaddr[0] = (addr >> 24) & 0xFF; xaddr[1] = (addr >> 16) & 0xFF; xaddr[2] = (addr >> 8) & 0xFF; xaddr[3] = addr & 0xFF; } #ifdef CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW /* * EEPROM chips that implement "address overflow" are ones * like Catalyst 24WC04/08/16 which has 9/10/11 bits of * address and the extra bits end up in the "chip address" * bit slots. This makes a 24WC08 (1Kbyte) chip look like * four 256 byte chips. * * Note that we consider the length of the address field to * still be one byte because the extra address bits are * hidden in the chip address. */ if (alen > 0) chip |= ((addr >> (alen * 8)) & CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW); #endif return (i2c_transfer (I2C_WRITE, chip << 1, &xaddr[4 - alen], alen, buffer, len) != 0); } #endif /* CONFIG_HARD_I2C */
1001-study-uboot
drivers/i2c/s3c24x0_i2c.c
C
gpl3
11,032
/* * Freescale i.MX28 I2C Driver * * Copyright (C) 2011 Marek Vasut <marek.vasut@gmail.com> * on behalf of DENX Software Engineering GmbH * * Partly based on Linux kernel i2c-mxs.c driver: * Copyright (C) 2011 Wolfram Sang, Pengutronix e.K. * * Which was based on a (non-working) driver which was: * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. 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 <common.h> #include <malloc.h> #include <asm/errno.h> #include <asm/io.h> #include <asm/arch/clock.h> #include <asm/arch/imx-regs.h> #include <asm/arch/sys_proto.h> #define MXS_I2C_MAX_TIMEOUT 1000000 void mxs_i2c_reset(void) { struct mx28_i2c_regs *i2c_regs = (struct mx28_i2c_regs *)MXS_I2C0_BASE; int ret; ret = mx28_reset_block(&i2c_regs->hw_i2c_ctrl0_reg); if (ret) { debug("MXS I2C: Block reset timeout\n"); return; } writel(I2C_CTRL1_DATA_ENGINE_CMPLT_IRQ | I2C_CTRL1_NO_SLAVE_ACK_IRQ | I2C_CTRL1_EARLY_TERM_IRQ | I2C_CTRL1_MASTER_LOSS_IRQ | I2C_CTRL1_SLAVE_STOP_IRQ | I2C_CTRL1_SLAVE_IRQ, &i2c_regs->hw_i2c_ctrl1_clr); writel(I2C_QUEUECTRL_PIO_QUEUE_MODE, &i2c_regs->hw_i2c_queuectrl_set); } void mxs_i2c_setup_read(uint8_t chip, int len) { struct mx28_i2c_regs *i2c_regs = (struct mx28_i2c_regs *)MXS_I2C0_BASE; writel(I2C_QUEUECMD_RETAIN_CLOCK | I2C_QUEUECMD_PRE_SEND_START | I2C_QUEUECMD_MASTER_MODE | I2C_QUEUECMD_DIRECTION | (1 << I2C_QUEUECMD_XFER_COUNT_OFFSET), &i2c_regs->hw_i2c_queuecmd); writel((chip << 1) | 1, &i2c_regs->hw_i2c_data); writel(I2C_QUEUECMD_SEND_NAK_ON_LAST | I2C_QUEUECMD_MASTER_MODE | (len << I2C_QUEUECMD_XFER_COUNT_OFFSET) | I2C_QUEUECMD_POST_SEND_STOP, &i2c_regs->hw_i2c_queuecmd); writel(I2C_QUEUECTRL_QUEUE_RUN, &i2c_regs->hw_i2c_queuectrl_set); } void mxs_i2c_write(uchar chip, uint addr, int alen, uchar *buf, int blen, int stop) { struct mx28_i2c_regs *i2c_regs = (struct mx28_i2c_regs *)MXS_I2C0_BASE; uint32_t data; int i, remain, off; if ((alen > 4) || (alen == 0)) { debug("MXS I2C: Invalid address length\n"); return; } if (stop) stop = I2C_QUEUECMD_POST_SEND_STOP; writel(I2C_QUEUECMD_PRE_SEND_START | I2C_QUEUECMD_MASTER_MODE | I2C_QUEUECMD_DIRECTION | ((blen + alen + 1) << I2C_QUEUECMD_XFER_COUNT_OFFSET) | stop, &i2c_regs->hw_i2c_queuecmd); data = (chip << 1) << 24; for (i = 0; i < alen; i++) { data >>= 8; data |= ((char *)&addr)[i] << 24; if ((i & 3) == 2) writel(data, &i2c_regs->hw_i2c_data); } off = i; for (; i < off + blen; i++) { data >>= 8; data |= buf[i - off] << 24; if ((i & 3) == 2) writel(data, &i2c_regs->hw_i2c_data); } remain = 24 - ((i & 3) * 8); if (remain) writel(data >> remain, &i2c_regs->hw_i2c_data); writel(I2C_QUEUECTRL_QUEUE_RUN, &i2c_regs->hw_i2c_queuectrl_set); } int mxs_i2c_wait_for_ack(void) { struct mx28_i2c_regs *i2c_regs = (struct mx28_i2c_regs *)MXS_I2C0_BASE; uint32_t tmp; int timeout = MXS_I2C_MAX_TIMEOUT; for (;;) { tmp = readl(&i2c_regs->hw_i2c_ctrl1); if (tmp & I2C_CTRL1_NO_SLAVE_ACK_IRQ) { debug("MXS I2C: No slave ACK\n"); goto err; } if (tmp & ( I2C_CTRL1_EARLY_TERM_IRQ | I2C_CTRL1_MASTER_LOSS_IRQ | I2C_CTRL1_SLAVE_STOP_IRQ | I2C_CTRL1_SLAVE_IRQ)) { debug("MXS I2C: Error (CTRL1 = %08x)\n", tmp); goto err; } if (tmp & I2C_CTRL1_DATA_ENGINE_CMPLT_IRQ) break; if (!timeout--) { debug("MXS I2C: Operation timed out\n"); goto err; } udelay(1); } return 0; err: mxs_i2c_reset(); return 1; } int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { struct mx28_i2c_regs *i2c_regs = (struct mx28_i2c_regs *)MXS_I2C0_BASE; uint32_t tmp = 0; int ret; int i; mxs_i2c_write(chip, addr, alen, NULL, 0, 0); ret = mxs_i2c_wait_for_ack(); if (ret) { debug("MXS I2C: Failed writing address\n"); return ret; } mxs_i2c_setup_read(chip, len); ret = mxs_i2c_wait_for_ack(); if (ret) { debug("MXS I2C: Failed reading address\n"); return ret; } for (i = 0; i < len; i++) { if (!(i & 3)) { while (readl(&i2c_regs->hw_i2c_queuestat) & I2C_QUEUESTAT_RD_QUEUE_EMPTY) ; tmp = readl(&i2c_regs->hw_i2c_queuedata); } buffer[i] = tmp & 0xff; tmp >>= 8; } return 0; } int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { int ret; mxs_i2c_write(chip, addr, alen, buffer, len, 1); ret = mxs_i2c_wait_for_ack(); if (ret) debug("MXS I2C: Failed writing address\n"); return ret; } int i2c_probe(uchar chip) { int ret; mxs_i2c_write(chip, 0, 1, NULL, 0, 1); ret = mxs_i2c_wait_for_ack(); mxs_i2c_reset(); return ret; } void i2c_init(int speed, int slaveadd) { struct mx28_i2c_regs *i2c_regs = (struct mx28_i2c_regs *)MXS_I2C0_BASE; mxs_i2c_reset(); switch (speed) { case 100000: writel((0x0078 << I2C_TIMING0_HIGH_COUNT_OFFSET) | (0x0030 << I2C_TIMING0_RCV_COUNT_OFFSET), &i2c_regs->hw_i2c_timing0); writel((0x0080 << I2C_TIMING1_LOW_COUNT_OFFSET) | (0x0030 << I2C_TIMING1_XMIT_COUNT_OFFSET), &i2c_regs->hw_i2c_timing1); break; case 400000: writel((0x000f << I2C_TIMING0_HIGH_COUNT_OFFSET) | (0x0007 << I2C_TIMING0_RCV_COUNT_OFFSET), &i2c_regs->hw_i2c_timing0); writel((0x001f << I2C_TIMING1_LOW_COUNT_OFFSET) | (0x000f << I2C_TIMING1_XMIT_COUNT_OFFSET), &i2c_regs->hw_i2c_timing1); break; default: printf("MXS I2C: Invalid speed selected (%d Hz)\n", speed); return; } writel((0x0015 << I2C_TIMING2_BUS_FREE_OFFSET) | (0x000d << I2C_TIMING2_LEADIN_COUNT_OFFSET), &i2c_regs->hw_i2c_timing2); return; }
1001-study-uboot
drivers/i2c/mxs_i2c.c
C
gpl3
6,207
/* * (C) Copyright 2001, 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 * * This has been changed substantially by Gerald Van Baren, Custom IDEAS, * vanbaren@cideas.com. It was heavily influenced by LiMon, written by * Neil Russell. */ #include <common.h> #ifdef CONFIG_MPC8260 /* only valid for MPC8260 */ #include <ioports.h> #include <asm/io.h> #endif #if defined(CONFIG_AT91FAMILY) #include <asm/io.h> #include <asm/arch/hardware.h> #include <asm/arch/at91_pio.h> #ifdef CONFIG_AT91_LEGACY #include <asm/arch/gpio.h> #endif #endif #ifdef CONFIG_IXP425 /* only valid for IXP425 */ #include <asm/arch/ixp425.h> #endif #ifdef CONFIG_LPC2292 #include <asm/arch/hardware.h> #endif #if defined(CONFIG_MPC852T) || defined(CONFIG_MPC866) #include <asm/io.h> #endif #include <i2c.h> #if defined(CONFIG_SOFT_I2C_GPIO_SCL) # include <asm/gpio.h> # ifndef I2C_GPIO_SYNC # define I2C_GPIO_SYNC # endif # ifndef I2C_INIT # define I2C_INIT \ do { \ gpio_request(CONFIG_SOFT_I2C_GPIO_SCL, "soft_i2c"); \ gpio_request(CONFIG_SOFT_I2C_GPIO_SDA, "soft_i2c"); \ } while (0) # endif # ifndef I2C_ACTIVE # define I2C_ACTIVE do { } while (0) # endif # ifndef I2C_TRISTATE # define I2C_TRISTATE do { } while (0) # endif # ifndef I2C_READ # define I2C_READ gpio_get_value(CONFIG_SOFT_I2C_GPIO_SDA) # endif # ifndef I2C_SDA # define I2C_SDA(bit) \ do { \ if (bit) \ gpio_direction_input(CONFIG_SOFT_I2C_GPIO_SDA); \ else \ gpio_direction_output(CONFIG_SOFT_I2C_GPIO_SDA, 0); \ I2C_GPIO_SYNC; \ } while (0) # endif # ifndef I2C_SCL # define I2C_SCL(bit) \ do { \ gpio_direction_output(CONFIG_SOFT_I2C_GPIO_SCL, bit); \ I2C_GPIO_SYNC; \ } while (0) # endif # ifndef I2C_DELAY # define I2C_DELAY udelay(5) /* 1/4 I2C clock duration */ # endif #endif /* #define DEBUG_I2C */ #ifdef DEBUG_I2C DECLARE_GLOBAL_DATA_PTR; #endif /*----------------------------------------------------------------------- * Definitions */ #define RETRIES 0 #define I2C_ACK 0 /* PD_SDA level to ack a byte */ #define I2C_NOACK 1 /* PD_SDA level to noack a byte */ #ifdef DEBUG_I2C #define PRINTD(fmt,args...) do { \ printf (fmt ,##args); \ } while (0) #else #define PRINTD(fmt,args...) #endif #if defined(CONFIG_I2C_MULTI_BUS) static unsigned int i2c_bus_num __attribute__ ((section (".data"))) = 0; #endif /* CONFIG_I2C_MULTI_BUS */ /*----------------------------------------------------------------------- * Local functions */ #if !defined(CONFIG_SYS_I2C_INIT_BOARD) static void send_reset (void); #endif static void send_start (void); static void send_stop (void); static void send_ack (int); static int write_byte (uchar byte); static uchar read_byte (int); #if !defined(CONFIG_SYS_I2C_INIT_BOARD) /*----------------------------------------------------------------------- * Send a reset sequence consisting of 9 clocks with the data signal high * to clock any confused device back into an idle state. Also send a * <stop> at the end of the sequence for belts & suspenders. */ static void send_reset(void) { I2C_SOFT_DECLARATIONS /* intentional without ';' */ int j; I2C_SCL(1); I2C_SDA(1); #ifdef I2C_INIT I2C_INIT; #endif I2C_TRISTATE; for(j = 0; j < 9; j++) { I2C_SCL(0); I2C_DELAY; I2C_DELAY; I2C_SCL(1); I2C_DELAY; I2C_DELAY; } send_stop(); I2C_TRISTATE; } #endif /*----------------------------------------------------------------------- * START: High -> Low on SDA while SCL is High */ static void send_start(void) { I2C_SOFT_DECLARATIONS /* intentional without ';' */ I2C_DELAY; I2C_SDA(1); I2C_ACTIVE; I2C_DELAY; I2C_SCL(1); I2C_DELAY; I2C_SDA(0); I2C_DELAY; } /*----------------------------------------------------------------------- * STOP: Low -> High on SDA while SCL is High */ static void send_stop(void) { I2C_SOFT_DECLARATIONS /* intentional without ';' */ I2C_SCL(0); I2C_DELAY; I2C_SDA(0); I2C_ACTIVE; I2C_DELAY; I2C_SCL(1); I2C_DELAY; I2C_SDA(1); I2C_DELAY; I2C_TRISTATE; } /*----------------------------------------------------------------------- * ack should be I2C_ACK or I2C_NOACK */ static void send_ack(int ack) { I2C_SOFT_DECLARATIONS /* intentional without ';' */ I2C_SCL(0); I2C_DELAY; I2C_ACTIVE; I2C_SDA(ack); I2C_DELAY; I2C_SCL(1); I2C_DELAY; I2C_DELAY; I2C_SCL(0); I2C_DELAY; } /*----------------------------------------------------------------------- * Send 8 bits and look for an acknowledgement. */ static int write_byte(uchar data) { I2C_SOFT_DECLARATIONS /* intentional without ';' */ int j; int nack; I2C_ACTIVE; for(j = 0; j < 8; j++) { I2C_SCL(0); I2C_DELAY; I2C_SDA(data & 0x80); I2C_DELAY; I2C_SCL(1); I2C_DELAY; I2C_DELAY; data <<= 1; } /* * Look for an <ACK>(negative logic) and return it. */ I2C_SCL(0); I2C_DELAY; I2C_SDA(1); I2C_TRISTATE; I2C_DELAY; I2C_SCL(1); I2C_DELAY; I2C_DELAY; nack = I2C_READ; I2C_SCL(0); I2C_DELAY; I2C_ACTIVE; return(nack); /* not a nack is an ack */ } #if defined(CONFIG_I2C_MULTI_BUS) /* * Functions for multiple I2C bus handling */ unsigned int i2c_get_bus_num(void) { return i2c_bus_num; } int i2c_set_bus_num(unsigned int bus) { #if defined(CONFIG_I2C_MUX) if (bus < CONFIG_SYS_MAX_I2C_BUS) { i2c_bus_num = bus; } else { int ret; ret = i2x_mux_select_mux(bus); i2c_init_board(); if (ret == 0) i2c_bus_num = bus; else return ret; } #else if (bus >= CONFIG_SYS_MAX_I2C_BUS) return -1; i2c_bus_num = bus; #endif return 0; } #endif /*----------------------------------------------------------------------- * if ack == I2C_ACK, ACK the byte so can continue reading, else * send I2C_NOACK to end the read. */ static uchar read_byte(int ack) { I2C_SOFT_DECLARATIONS /* intentional without ';' */ int data; int j; /* * Read 8 bits, MSB first. */ I2C_TRISTATE; I2C_SDA(1); data = 0; for(j = 0; j < 8; j++) { I2C_SCL(0); I2C_DELAY; I2C_SCL(1); I2C_DELAY; data <<= 1; data |= I2C_READ; I2C_DELAY; } send_ack(ack); return(data); } /*=====================================================================*/ /* Public Functions */ /*=====================================================================*/ /*----------------------------------------------------------------------- * Initialization */ void i2c_init (int speed, int slaveaddr) { #if defined(CONFIG_SYS_I2C_INIT_BOARD) /* call board specific i2c bus reset routine before accessing the */ /* environment, which might be in a chip on that bus. For details */ /* about this problem see doc/I2C_Edge_Conditions. */ i2c_init_board(); #else /* * WARNING: Do NOT save speed in a static variable: if the * I2C routines are called before RAM is initialized (to read * the DIMM SPD, for instance), RAM won't be usable and your * system will crash. */ send_reset (); #endif } /*----------------------------------------------------------------------- * Probe to see if a chip is present. Also good for checking for the * completion of EEPROM writes since the chip stops responding until * the write completes (typically 10mSec). */ int i2c_probe(uchar addr) { int rc; /* * perform 1 byte write transaction with just address byte * (fake write) */ send_start(); rc = write_byte ((addr << 1) | 0); send_stop(); return (rc ? 1 : 0); } /*----------------------------------------------------------------------- * Read bytes */ int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { int shift; PRINTD("i2c_read: chip %02X addr %02X alen %d buffer %p len %d\n", chip, addr, alen, buffer, len); #ifdef CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW /* * EEPROM chips that implement "address overflow" are ones * like Catalyst 24WC04/08/16 which has 9/10/11 bits of * address and the extra bits end up in the "chip address" * bit slots. This makes a 24WC08 (1Kbyte) chip look like * four 256 byte chips. * * Note that we consider the length of the address field to * still be one byte because the extra address bits are * hidden in the chip address. */ chip |= ((addr >> (alen * 8)) & CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW); PRINTD("i2c_read: fix addr_overflow: chip %02X addr %02X\n", chip, addr); #endif /* * Do the addressing portion of a write cycle to set the * chip's address pointer. If the address length is zero, * don't do the normal write cycle to set the address pointer, * there is no address pointer in this chip. */ send_start(); if(alen > 0) { if(write_byte(chip << 1)) { /* write cycle */ send_stop(); PRINTD("i2c_read, no chip responded %02X\n", chip); return(1); } shift = (alen-1) * 8; while(alen-- > 0) { if(write_byte(addr >> shift)) { PRINTD("i2c_read, address not <ACK>ed\n"); return(1); } shift -= 8; } /* Some I2C chips need a stop/start sequence here, * other chips don't work with a full stop and need * only a start. Default behaviour is to send the * stop/start sequence. */ #ifdef CONFIG_SOFT_I2C_READ_REPEATED_START send_start(); #else send_stop(); send_start(); #endif } /* * Send the chip address again, this time for a read cycle. * Then read the data. On the last byte, we do a NACK instead * of an ACK(len == 0) to terminate the read. */ write_byte((chip << 1) | 1); /* read cycle */ while(len-- > 0) { *buffer++ = read_byte(len == 0); } send_stop(); return(0); } /*----------------------------------------------------------------------- * Write bytes */ int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { int shift, failures = 0; PRINTD("i2c_write: chip %02X addr %02X alen %d buffer %p len %d\n", chip, addr, alen, buffer, len); send_start(); if(write_byte(chip << 1)) { /* write cycle */ send_stop(); PRINTD("i2c_write, no chip responded %02X\n", chip); return(1); } shift = (alen-1) * 8; while(alen-- > 0) { if(write_byte(addr >> shift)) { PRINTD("i2c_write, address not <ACK>ed\n"); return(1); } shift -= 8; } while(len-- > 0) { if(write_byte(*buffer++)) { failures++; } } send_stop(); return(failures); }
1001-study-uboot
drivers/i2c/soft_i2c.c
C
gpl3
10,994
/* * Basic I2C functions * * Copyright (c) 2004 Texas Instruments * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Author: Jian Zhang jzhang@ti.com, Texas Instruments * * Copyright (c) 2003 Wolfgang Denk, wd@denx.de * Rewritten to fit into the current U-Boot framework * * Adapted for OMAP2420 I2C, r-woodruff2@ti.com * */ #include <common.h> #include <asm/arch/i2c.h> #include <asm/io.h> #include "omap24xx_i2c.h" DECLARE_GLOBAL_DATA_PTR; #define I2C_TIMEOUT 1000 static void wait_for_bb(void); static u16 wait_for_pin(void); static void flush_fifo(void); static struct i2c *i2c_base = (struct i2c *)I2C_DEFAULT_BASE; static unsigned int bus_initialized[I2C_BUS_MAX]; static unsigned int current_bus; void i2c_init(int speed, int slaveadd) { int psc, fsscll, fssclh; int hsscll = 0, hssclh = 0; u32 scll, sclh; int timeout = I2C_TIMEOUT; /* Only handle standard, fast and high speeds */ if ((speed != OMAP_I2C_STANDARD) && (speed != OMAP_I2C_FAST_MODE) && (speed != OMAP_I2C_HIGH_SPEED)) { printf("Error : I2C unsupported speed %d\n", speed); return; } psc = I2C_IP_CLK / I2C_INTERNAL_SAMPLING_CLK; psc -= 1; if (psc < I2C_PSC_MIN) { printf("Error : I2C unsupported prescalar %d\n", psc); return; } if (speed == OMAP_I2C_HIGH_SPEED) { /* High speed */ /* For first phase of HS mode */ fsscll = fssclh = I2C_INTERNAL_SAMPLING_CLK / (2 * OMAP_I2C_FAST_MODE); fsscll -= I2C_HIGHSPEED_PHASE_ONE_SCLL_TRIM; fssclh -= I2C_HIGHSPEED_PHASE_ONE_SCLH_TRIM; if (((fsscll < 0) || (fssclh < 0)) || ((fsscll > 255) || (fssclh > 255))) { printf("Error : I2C initializing first phase clock\n"); return; } /* For second phase of HS mode */ hsscll = hssclh = I2C_INTERNAL_SAMPLING_CLK / (2 * speed); hsscll -= I2C_HIGHSPEED_PHASE_TWO_SCLL_TRIM; hssclh -= I2C_HIGHSPEED_PHASE_TWO_SCLH_TRIM; if (((fsscll < 0) || (fssclh < 0)) || ((fsscll > 255) || (fssclh > 255))) { printf("Error : I2C initializing second phase clock\n"); return; } scll = (unsigned int)hsscll << 8 | (unsigned int)fsscll; sclh = (unsigned int)hssclh << 8 | (unsigned int)fssclh; } else { /* Standard and fast speed */ fsscll = fssclh = I2C_INTERNAL_SAMPLING_CLK / (2 * speed); fsscll -= I2C_FASTSPEED_SCLL_TRIM; fssclh -= I2C_FASTSPEED_SCLH_TRIM; if (((fsscll < 0) || (fssclh < 0)) || ((fsscll > 255) || (fssclh > 255))) { printf("Error : I2C initializing clock\n"); return; } scll = (unsigned int)fsscll; sclh = (unsigned int)fssclh; } if (readw(&i2c_base->con) & I2C_CON_EN) { writew(0, &i2c_base->con); udelay(50000); } writew(0x2, &i2c_base->sysc); /* for ES2 after soft reset */ udelay(1000); writew(I2C_CON_EN, &i2c_base->con); while (!(readw(&i2c_base->syss) & I2C_SYSS_RDONE) && timeout--) { if (timeout <= 0) { printf("ERROR: Timeout in soft-reset\n"); return; } udelay(1000); } writew(0, &i2c_base->con); writew(psc, &i2c_base->psc); writew(scll, &i2c_base->scll); writew(sclh, &i2c_base->sclh); /* own address */ writew(slaveadd, &i2c_base->oa); writew(I2C_CON_EN, &i2c_base->con); /* have to enable intrrupts or OMAP i2c module doesn't work */ writew(I2C_IE_XRDY_IE | I2C_IE_RRDY_IE | I2C_IE_ARDY_IE | I2C_IE_NACK_IE | I2C_IE_AL_IE, &i2c_base->ie); udelay(1000); flush_fifo(); writew(0xFFFF, &i2c_base->stat); writew(0, &i2c_base->cnt); if (gd->flags & GD_FLG_RELOC) bus_initialized[current_bus] = 1; } static int i2c_read_byte(u8 devaddr, u8 regoffset, u8 *value) { int i2c_error = 0; u16 status; /* wait until bus not busy */ wait_for_bb(); /* one byte only */ writew(1, &i2c_base->cnt); /* set slave address */ writew(devaddr, &i2c_base->sa); /* no stop bit needed here */ writew(I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_TRX, &i2c_base->con); /* send register offset */ while (1) { status = wait_for_pin(); if (status == 0 || status & I2C_STAT_NACK) { i2c_error = 1; goto read_exit; } if (status & I2C_STAT_XRDY) { /* Important: have to use byte access */ writeb(regoffset, &i2c_base->data); writew(I2C_STAT_XRDY, &i2c_base->stat); } if (status & I2C_STAT_ARDY) { writew(I2C_STAT_ARDY, &i2c_base->stat); break; } } /* set slave address */ writew(devaddr, &i2c_base->sa); /* read one byte from slave */ writew(1, &i2c_base->cnt); /* need stop bit here */ writew(I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_STP, &i2c_base->con); /* receive data */ while (1) { status = wait_for_pin(); if (status == 0 || status & I2C_STAT_NACK) { i2c_error = 1; goto read_exit; } if (status & I2C_STAT_RRDY) { #if defined(CONFIG_OMAP243X) || defined(CONFIG_OMAP34XX) || \ defined(CONFIG_OMAP44XX) *value = readb(&i2c_base->data); #else *value = readw(&i2c_base->data); #endif writew(I2C_STAT_RRDY, &i2c_base->stat); } if (status & I2C_STAT_ARDY) { writew(I2C_STAT_ARDY, &i2c_base->stat); break; } } read_exit: flush_fifo(); writew(0xFFFF, &i2c_base->stat); writew(0, &i2c_base->cnt); return i2c_error; } static void flush_fifo(void) { u16 stat; /* note: if you try and read data when its not there or ready * you get a bus error */ while (1) { stat = readw(&i2c_base->stat); if (stat == I2C_STAT_RRDY) { #if defined(CONFIG_OMAP243X) || defined(CONFIG_OMAP34XX) || \ defined(CONFIG_OMAP44XX) readb(&i2c_base->data); #else readw(&i2c_base->data); #endif writew(I2C_STAT_RRDY, &i2c_base->stat); udelay(1000); } else break; } } int i2c_probe(uchar chip) { u16 status; int res = 1; /* default = fail */ if (chip == readw(&i2c_base->oa)) return res; /* wait until bus not busy */ wait_for_bb(); /* try to write one byte */ writew(1, &i2c_base->cnt); /* set slave address */ writew(chip, &i2c_base->sa); /* stop bit needed here */ writew(I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_TRX | I2C_CON_STP, &i2c_base->con); status = wait_for_pin(); /* check for ACK (!NAK) */ if (!(status & I2C_STAT_NACK)) res = 0; /* abort transfer (force idle state) */ writew(0, &i2c_base->con); flush_fifo(); /* don't allow any more data in... we don't want it. */ writew(0, &i2c_base->cnt); writew(0xFFFF, &i2c_base->stat); return res; } int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { int i; if (alen > 1) { printf("I2C read: addr len %d not supported\n", alen); return 1; } if (addr + len > 256) { printf("I2C read: address out of range\n"); return 1; } for (i = 0; i < len; i++) { if (i2c_read_byte(chip, addr + i, &buffer[i])) { printf("I2C read: I/O error\n"); i2c_init(CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE); return 1; } } return 0; } int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { int i; u16 status; int i2c_error = 0; if (alen > 1) { printf("I2C write: addr len %d not supported\n", alen); return 1; } if (addr + len > 256) { printf("I2C write: address 0x%x + 0x%x out of range\n", addr, len); return 1; } /* wait until bus not busy */ wait_for_bb(); /* start address phase - will write regoffset + len bytes data */ /* TODO consider case when !CONFIG_OMAP243X/34XX/44XX */ writew(alen + len, &i2c_base->cnt); /* set slave address */ writew(chip, &i2c_base->sa); /* stop bit needed here */ writew(I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_TRX | I2C_CON_STP, &i2c_base->con); /* Send address byte */ status = wait_for_pin(); if (status == 0 || status & I2C_STAT_NACK) { i2c_error = 1; printf("error waiting for i2c address ACK (status=0x%x)\n", status); goto write_exit; } if (status & I2C_STAT_XRDY) { writeb(addr & 0xFF, &i2c_base->data); writew(I2C_STAT_XRDY, &i2c_base->stat); } else { i2c_error = 1; printf("i2c bus not ready for transmit (status=0x%x)\n", status); goto write_exit; } /* address phase is over, now write data */ for (i = 0; i < len; i++) { status = wait_for_pin(); if (status == 0 || status & I2C_STAT_NACK) { i2c_error = 1; printf("i2c error waiting for data ACK (status=0x%x)\n", status); goto write_exit; } if (status & I2C_STAT_XRDY) { writeb(buffer[i], &i2c_base->data); writew(I2C_STAT_XRDY, &i2c_base->stat); } else { i2c_error = 1; printf("i2c bus not ready for Tx (i=%d)\n", i); goto write_exit; } } write_exit: flush_fifo(); writew(0xFFFF, &i2c_base->stat); return i2c_error; } static void wait_for_bb(void) { int timeout = I2C_TIMEOUT; u16 stat; writew(0xFFFF, &i2c_base->stat); /* clear current interrupts...*/ while ((stat = readw(&i2c_base->stat) & I2C_STAT_BB) && timeout--) { writew(stat, &i2c_base->stat); udelay(1000); } if (timeout <= 0) { printf("timed out in wait_for_bb: I2C_STAT=%x\n", readw(&i2c_base->stat)); } writew(0xFFFF, &i2c_base->stat); /* clear delayed stuff*/ } static u16 wait_for_pin(void) { u16 status; int timeout = I2C_TIMEOUT; do { udelay(1000); status = readw(&i2c_base->stat); } while (!(status & (I2C_STAT_ROVR | I2C_STAT_XUDF | I2C_STAT_XRDY | I2C_STAT_RRDY | I2C_STAT_ARDY | I2C_STAT_NACK | I2C_STAT_AL)) && timeout--); if (timeout <= 0) { printf("timed out in wait_for_pin: I2C_STAT=%x\n", readw(&i2c_base->stat)); writew(0xFFFF, &i2c_base->stat); status = 0; } return status; } int i2c_set_bus_num(unsigned int bus) { if ((bus < 0) || (bus >= I2C_BUS_MAX)) { printf("Bad bus: %d\n", bus); return -1; } #if I2C_BUS_MAX == 3 if (bus == 2) i2c_base = (struct i2c *)I2C_BASE3; else #endif if (bus == 1) i2c_base = (struct i2c *)I2C_BASE2; else i2c_base = (struct i2c *)I2C_BASE1; current_bus = bus; if (!bus_initialized[current_bus]) i2c_init(CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE); return 0; } int i2c_get_bus_num(void) { return (int) current_bus; }
1001-study-uboot
drivers/i2c/omap24xx_i2c.c
C
gpl3
10,215
/* * (C) Copyright 2004 Tundra Semiconductor Corp. * Author: Alex Bounine * * 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 <config.h> #include <common.h> #include <tsi108.h> #if defined(CONFIG_CMD_I2C) #define I2C_DELAY 100000 #undef DEBUG_I2C #ifdef DEBUG_I2C #define DPRINT(x) printf (x) #else #define DPRINT(x) #endif /* All functions assume that Tsi108 I2C block is the only master on the bus */ /* I2C read helper function */ void i2c_init(int speed, int slaveaddr) { /* * The TSI108 has a fixed I2C clock rate and doesn't support slave * operation. This function only exists as a stub to fit into the * U-Boot I2C API. */ } static int i2c_read_byte ( uint i2c_chan, /* I2C channel number: 0 - main, 1 - SDC SPD */ uchar chip_addr,/* I2C device address on the bus */ uint byte_addr, /* Byte address within I2C device */ uchar * buffer /* pointer to data buffer */ ) { u32 temp; u32 to_count = I2C_DELAY; u32 op_status = TSI108_I2C_TIMEOUT_ERR; u32 chan_offset = TSI108_I2C_OFFSET; DPRINT (("I2C read_byte() %d 0x%02x 0x%02x\n", i2c_chan, chip_addr, byte_addr)); if (0 != i2c_chan) chan_offset = TSI108_I2C_SDRAM_OFFSET; /* Check if I2C operation is in progress */ temp = *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + chan_offset + I2C_CNTRL2); if (0 == (temp & (I2C_CNTRL2_RD_STATUS | I2C_CNTRL2_WR_STATUS | I2C_CNTRL2_START))) { /* Set device address and operation (read = 0) */ temp = (byte_addr << 16) | ((chip_addr & 0x07) << 8) | ((chip_addr >> 3) & 0x0F); *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + chan_offset + I2C_CNTRL1) = temp; /* Issue the read command * (at this moment all other parameters are 0 * (size = 1 byte, lane = 0) */ *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + chan_offset + I2C_CNTRL2) = (I2C_CNTRL2_START); /* Wait until operation completed */ do { /* Read I2C operation status */ temp = *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + chan_offset + I2C_CNTRL2); if (0 == (temp & (I2C_CNTRL2_RD_STATUS | I2C_CNTRL2_START))) { if (0 == (temp & (I2C_CNTRL2_I2C_CFGERR | I2C_CNTRL2_I2C_TO_ERR)) ) { op_status = TSI108_I2C_SUCCESS; temp = *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + chan_offset + I2C_RD_DATA); *buffer = (u8) (temp & 0xFF); } else { /* report HW error */ op_status = TSI108_I2C_IF_ERROR; DPRINT (("I2C HW error reported: 0x%02x\n", temp)); } break; } } while (to_count--); } else { op_status = TSI108_I2C_IF_BUSY; DPRINT (("I2C Transaction start failed: 0x%02x\n", temp)); } DPRINT (("I2C read_byte() status: 0x%02x\n", op_status)); return op_status; } /* * I2C Read interface as defined in "include/i2c.h" : * chip_addr: I2C chip address, range 0..127 * (to read from SPD channel EEPROM use (0xD0 ... 0xD7) * NOTE: The bit 7 in the chip_addr serves as a channel select. * This hack is for enabling "i2c sdram" command on Tsi108 boards * without changes to common code. Used for I2C reads only. * byte_addr: Memory or register address within the chip * alen: Number of bytes to use for addr (typically 1, 2 for larger * memories, 0 for register type devices with only one * register) * buffer: Pointer to destination buffer for data to be read * len: How many bytes to read * * Returns: 0 on success, not 0 on failure */ int i2c_read (uchar chip_addr, uint byte_addr, int alen, uchar * buffer, int len) { u32 op_status = TSI108_I2C_PARAM_ERR; u32 i2c_if = 0; /* Hack to support second (SPD) I2C controller (SPD EEPROM read only).*/ if (0xD0 == (chip_addr & ~0x07)) { i2c_if = 1; chip_addr &= 0x7F; } /* Check for valid I2C address */ if (chip_addr <= 0x7F && (byte_addr + len) <= (0x01 << (alen * 8))) { while (len--) { op_status = i2c_read_byte(i2c_if, chip_addr, byte_addr++, buffer++); if (TSI108_I2C_SUCCESS != op_status) { DPRINT (("I2C read_byte() failed: 0x%02x (%d left)\n", op_status, len)); break; } } } DPRINT (("I2C read() status: 0x%02x\n", op_status)); return op_status; } /* I2C write helper function */ static int i2c_write_byte (uchar chip_addr,/* I2C device address on the bus */ uint byte_addr, /* Byte address within I2C device */ uchar * buffer /* pointer to data buffer */ ) { u32 temp; u32 to_count = I2C_DELAY; u32 op_status = TSI108_I2C_TIMEOUT_ERR; /* Check if I2C operation is in progress */ temp = *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + TSI108_I2C_OFFSET + I2C_CNTRL2); if (0 == (temp & (I2C_CNTRL2_RD_STATUS | I2C_CNTRL2_WR_STATUS | I2C_CNTRL2_START))) { /* Place data into the I2C Tx Register */ *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + TSI108_I2C_OFFSET + I2C_TX_DATA) = (u32) * buffer; /* Set device address and operation */ temp = I2C_CNTRL1_I2CWRITE | (byte_addr << 16) | ((chip_addr & 0x07) << 8) | ((chip_addr >> 3) & 0x0F); *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + TSI108_I2C_OFFSET + I2C_CNTRL1) = temp; /* Issue the write command (at this moment all other parameters * are 0 (size = 1 byte, lane = 0) */ *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + TSI108_I2C_OFFSET + I2C_CNTRL2) = (I2C_CNTRL2_START); op_status = TSI108_I2C_TIMEOUT_ERR; /* Wait until operation completed */ do { /* Read I2C operation status */ temp = *(u32 *) (CONFIG_SYS_TSI108_CSR_BASE + TSI108_I2C_OFFSET + I2C_CNTRL2); if (0 == (temp & (I2C_CNTRL2_WR_STATUS | I2C_CNTRL2_START))) { if (0 == (temp & (I2C_CNTRL2_I2C_CFGERR | I2C_CNTRL2_I2C_TO_ERR))) { op_status = TSI108_I2C_SUCCESS; } else { /* report detected HW error */ op_status = TSI108_I2C_IF_ERROR; DPRINT (("I2C HW error reported: 0x%02x\n", temp)); } break; } } while (to_count--); } else { op_status = TSI108_I2C_IF_BUSY; DPRINT (("I2C Transaction start failed: 0x%02x\n", temp)); } return op_status; } /* * I2C Write interface as defined in "include/i2c.h" : * chip_addr: I2C chip address, range 0..127 * byte_addr: Memory or register address within the chip * alen: Number of bytes to use for addr (typically 1, 2 for larger * memories, 0 for register type devices with only one * register) * buffer: Pointer to data to be written * len: How many bytes to write * * Returns: 0 on success, not 0 on failure */ int i2c_write (uchar chip_addr, uint byte_addr, int alen, uchar * buffer, int len) { u32 op_status = TSI108_I2C_PARAM_ERR; /* Check for valid I2C address */ if (chip_addr <= 0x7F && (byte_addr + len) <= (0x01 << (alen * 8))) { while (len--) { op_status = i2c_write_byte (chip_addr, byte_addr++, buffer++); if (TSI108_I2C_SUCCESS != op_status) { DPRINT (("I2C write_byte() failed: 0x%02x (%d left)\n", op_status, len)); break; } } } return op_status; } /* * I2C interface function as defined in "include/i2c.h". * Probe the given I2C chip address by reading single byte from offset 0. * Returns 0 if a chip responded, not 0 on failure. */ int i2c_probe (uchar chip) { u32 tmp; /* * Try to read the first location of the chip. * The Tsi108 HW doesn't support sending just the chip address * and checkong for an <ACK> back. */ return i2c_read (chip, 0, 1, (uchar *)&tmp, 1); } #endif
1001-study-uboot
drivers/i2c/tsi108_i2c.c
C
gpl3
8,207
# # (C) Copyright 2000-2007 # 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)libi2c.o COBJS-$(CONFIG_BFIN_TWI_I2C) += bfin-twi_i2c.o COBJS-$(CONFIG_DRIVER_DAVINCI_I2C) += davinci_i2c.o COBJS-$(CONFIG_FSL_I2C) += fsl_i2c.o COBJS-$(CONFIG_I2C_MVTWSI) += mvtwsi.o COBJS-$(CONFIG_I2C_MV) += mv_i2c.o COBJS-$(CONFIG_I2C_MXC) += mxc_i2c.o COBJS-$(CONFIG_I2C_MXS) += mxs_i2c.o COBJS-$(CONFIG_DRIVER_OMAP1510_I2C) += omap1510_i2c.o COBJS-$(CONFIG_DRIVER_OMAP24XX_I2C) += omap24xx_i2c.o COBJS-$(CONFIG_DRIVER_OMAP34XX_I2C) += omap24xx_i2c.o COBJS-$(CONFIG_PCA9564_I2C) += pca9564_i2c.o COBJS-$(CONFIG_PPC4XX_I2C) += ppc4xx_i2c.o COBJS-$(CONFIG_DRIVER_S3C24X0_I2C) += s3c24x0_i2c.o COBJS-$(CONFIG_S3C44B0_I2C) += s3c44b0_i2c.o COBJS-$(CONFIG_SOFT_I2C) += soft_i2c.o COBJS-$(CONFIG_SPEAR_I2C) += spr_i2c.o COBJS-$(CONFIG_TSI108_I2C) += tsi108_i2c.o COBJS-$(CONFIG_U8500_I2C) += u8500_i2c.o COBJS-$(CONFIG_SH_I2C) += sh_i2c.o COBJS := $(COBJS-y) SRCS := $(COBJS:.o=.c) OBJS := $(addprefix $(obj),$(COBJS)) all: $(LIB) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
drivers/i2c/Makefile
Makefile
gpl3
2,138
/* * Driver for the TWSI (i2c) controller found on the Marvell * orion5x and kirkwood SoC families. * * Author: Albert Aribaud <albert.u.boot@aribaud.net> * Copyright (c) 2010 Albert Aribaud. * * 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <common.h> #include <i2c.h> #include <asm/errno.h> #include <asm/io.h> /* * include a file that will provide CONFIG_I2C_MVTWSI_BASE * and possibly other settings */ #if defined(CONFIG_ORION5X) #include <asm/arch/orion5x.h> #elif defined(CONFIG_KIRKWOOD) #include <asm/arch/kirkwood.h> #else #error Driver mvtwsi not supported by SoC or board #endif /* * TWSI register structure */ struct mvtwsi_registers { u32 slave_address; u32 data; u32 control; union { u32 status; /* when reading */ u32 baudrate; /* when writing */ }; u32 xtnd_slave_addr; u32 reserved[2]; u32 soft_reset; }; /* * Control register fields */ #define MVTWSI_CONTROL_ACK 0x00000004 #define MVTWSI_CONTROL_IFLG 0x00000008 #define MVTWSI_CONTROL_STOP 0x00000010 #define MVTWSI_CONTROL_START 0x00000020 #define MVTWSI_CONTROL_TWSIEN 0x00000040 #define MVTWSI_CONTROL_INTEN 0x00000080 /* * Status register values -- only those expected in normal master * operation on non-10-bit-address devices; whatever status we don't * expect in nominal conditions (bus errors, arbitration losses, * missing ACKs...) we just pass back to the caller as an error * code. */ #define MVTWSI_STATUS_START 0x08 #define MVTWSI_STATUS_REPEATED_START 0x10 #define MVTWSI_STATUS_ADDR_W_ACK 0x18 #define MVTWSI_STATUS_DATA_W_ACK 0x28 #define MVTWSI_STATUS_ADDR_R_ACK 0x40 #define MVTWSI_STATUS_ADDR_R_NAK 0x48 #define MVTWSI_STATUS_DATA_R_ACK 0x50 #define MVTWSI_STATUS_DATA_R_NAK 0x58 #define MVTWSI_STATUS_IDLE 0xF8 /* * The single instance of the controller we'll be dealing with */ static struct mvtwsi_registers *twsi = (struct mvtwsi_registers *) CONFIG_I2C_MVTWSI_BASE; /* * Returned statuses are 0 for success and nonzero otherwise. * Currently, cmd_i2c and cmd_eeprom do not interpret an error status. * Thus to ease debugging, the return status contains some debug info: * - bits 31..24 are error class: 1 is timeout, 2 is 'status mismatch'. * - bits 23..16 are the last value of the control register. * - bits 15..8 are the last value of the status register. * - bits 7..0 are the expected value of the status register. */ #define MVTWSI_ERROR_WRONG_STATUS 0x01 #define MVTWSI_ERROR_TIMEOUT 0x02 #define MVTWSI_ERROR(ec, lc, ls, es) (((ec << 24) & 0xFF000000) | \ ((lc << 16) & 0x00FF0000) | ((ls<<8) & 0x0000FF00) | (es & 0xFF)) /* * Wait for IFLG to raise, or return 'timeout'; then if status is as expected, * return 0 (ok) or return 'wrong status'. */ static int twsi_wait(int expected_status) { int control, status; int timeout = 1000; do { control = readl(&twsi->control); if (control & MVTWSI_CONTROL_IFLG) { status = readl(&twsi->status); if (status == expected_status) return 0; else return MVTWSI_ERROR( MVTWSI_ERROR_WRONG_STATUS, control, status, expected_status); } udelay(10); /* one clock cycle at 100 kHz */ } while (timeout--); status = readl(&twsi->status); return MVTWSI_ERROR( MVTWSI_ERROR_TIMEOUT, control, status, expected_status); } /* * These flags are ORed to any write to the control register * They allow global setting of TWSIEN and ACK. * By default none are set. * twsi_start() sets TWSIEN (in case the controller was disabled) * twsi_recv() sets ACK or resets it depending on expected status. */ static u8 twsi_control_flags = MVTWSI_CONTROL_TWSIEN; /* * Assert the START condition, either in a single I2C transaction * or inside back-to-back ones (repeated starts). */ static int twsi_start(int expected_status) { /* globally set TWSIEN in case it was not */ twsi_control_flags |= MVTWSI_CONTROL_TWSIEN; /* assert START */ writel(twsi_control_flags | MVTWSI_CONTROL_START, &twsi->control); /* wait for controller to process START */ return twsi_wait(expected_status); } /* * Send a byte (i2c address or data). */ static int twsi_send(u8 byte, int expected_status) { /* put byte in data register for sending */ writel(byte, &twsi->data); /* clear any pending interrupt -- that'll cause sending */ writel(twsi_control_flags, &twsi->control); /* wait for controller to receive byte and check ACK */ return twsi_wait(expected_status); } /* * Receive a byte. * Global mvtwsi_control_flags variable says if we should ack or nak. */ static int twsi_recv(u8 *byte) { int expected_status, status; /* compute expected status based on ACK bit in global control flags */ if (twsi_control_flags & MVTWSI_CONTROL_ACK) expected_status = MVTWSI_STATUS_DATA_R_ACK; else expected_status = MVTWSI_STATUS_DATA_R_NAK; /* acknowledge *previous state* and launch receive */ writel(twsi_control_flags, &twsi->control); /* wait for controller to receive byte and assert ACK or NAK */ status = twsi_wait(expected_status); /* if we did receive expected byte then store it */ if (status == 0) *byte = readl(&twsi->data); /* return status */ return status; } /* * Assert the STOP condition. * This is also used to force the bus back in idle (SDA=SCL=1). */ static int twsi_stop(int status) { int control, stop_status; int timeout = 1000; /* assert STOP */ control = MVTWSI_CONTROL_TWSIEN | MVTWSI_CONTROL_STOP; writel(control, &twsi->control); /* wait for IDLE; IFLG won't rise so twsi_wait() is no use. */ do { stop_status = readl(&twsi->status); if (stop_status == MVTWSI_STATUS_IDLE) break; udelay(10); /* one clock cycle at 100 kHz */ } while (timeout--); control = readl(&twsi->control); if (stop_status != MVTWSI_STATUS_IDLE) if (status == 0) status = MVTWSI_ERROR( MVTWSI_ERROR_TIMEOUT, control, status, MVTWSI_STATUS_IDLE); return status; } /* * Ugly formula to convert m and n values to a frequency comes from * TWSI specifications */ #define TWSI_FREQUENCY(m, n) \ ((u8) (CONFIG_SYS_TCLK / (10 * (m + 1) * 2 * (1 << n)))) /* * These are required to be reprogrammed before enabling the controller * because a reset loses them. * Default values come from the spec, but a twsi_reset will change them. * twsi_slave_address left uninitialized lest checkpatch.pl complains. */ /* Baudrate generator: m (bits 7..4) =4, n (bits 3..0) =4 */ static u8 twsi_baud_rate = 0x44; /* baudrate at controller reset */ /* Default frequency corresponding to default m=4, n=4 */ static u8 twsi_actual_speed = TWSI_FREQUENCY(4, 4); /* Default slave address is 0 (so is an uninitialized static) */ static u8 twsi_slave_address; /* * Reset controller. * Called at end of i2c_init unsuccessful i2c transactions. * Controller reset also resets the baud rate and slave address, so * re-establish them. */ static void twsi_reset(void) { /* ensure controller will be enabled by any twsi*() function */ twsi_control_flags = MVTWSI_CONTROL_TWSIEN; /* reset controller */ writel(0, &twsi->soft_reset); /* wait 2 ms -- this is what the Marvell LSP does */ udelay(20000); /* set baud rate */ writel(twsi_baud_rate, &twsi->baudrate); /* set slave address even though we don't use it */ writel(twsi_slave_address, &twsi->slave_address); writel(0, &twsi->xtnd_slave_addr); /* assert STOP but don't care for the result */ (void) twsi_stop(0); } /* * I2C init called by cmd_i2c when doing 'i2c reset'. * Sets baud to the highest possible value not exceeding requested one. */ void i2c_init(int requested_speed, int slaveadd) { int tmp_speed, highest_speed, n, m; int baud = 0x44; /* baudrate at controller reset */ /* use actual speed to collect progressively higher values */ highest_speed = 0; /* compute m, n setting for highest speed not above requested speed */ for (n = 0; n < 8; n++) { for (m = 0; m < 16; m++) { tmp_speed = TWSI_FREQUENCY(m, n); if ((tmp_speed <= requested_speed) && (tmp_speed > highest_speed)) { highest_speed = tmp_speed; baud = (m << 3) | n; } } } /* save baud rate and slave for later calls to twsi_reset */ twsi_baud_rate = baud; twsi_actual_speed = highest_speed; twsi_slave_address = slaveadd; /* reset controller */ twsi_reset(); } /* * Begin I2C transaction with expected start status, at given address. * Common to i2c_probe, i2c_read and i2c_write. * Expected address status will derive from direction bit (bit 0) in addr. */ static int i2c_begin(int expected_start_status, u8 addr) { int status, expected_addr_status; /* compute expected address status from direction bit in addr */ if (addr & 1) /* reading */ expected_addr_status = MVTWSI_STATUS_ADDR_R_ACK; else /* writing */ expected_addr_status = MVTWSI_STATUS_ADDR_W_ACK; /* assert START */ status = twsi_start(expected_start_status); /* send out the address if the start went well */ if (status == 0) status = twsi_send(addr, expected_addr_status); /* return ok or status of first failure to caller */ return status; } /* * I2C probe called by cmd_i2c when doing 'i2c probe'. * Begin read, nak data byte, end. */ int i2c_probe(uchar chip) { u8 dummy_byte; int status; /* begin i2c read */ status = i2c_begin(MVTWSI_STATUS_START, (chip << 1) | 1); /* dummy read was accepted: receive byte but NAK it. */ if (status == 0) status = twsi_recv(&dummy_byte); /* Stop transaction */ twsi_stop(0); /* return 0 or status of first failure */ return status; } /* * I2C read called by cmd_i2c when doing 'i2c read' and by cmd_eeprom.c * Begin write, send address byte(s), begin read, receive data bytes, end. * * NOTE: some EEPROMS want a stop right before the second start, while * some will choke if it is there. Deciding which we should do is eeprom * stuff, not i2c, but at the moment the APIs won't let us put it in * cmd_eeprom, so we have to choose here, and for the moment that'll be * a repeated start without a preceding stop. */ int i2c_read(u8 dev, uint addr, int alen, u8 *data, int length) { int status; /* begin i2c write to send the address bytes */ status = i2c_begin(MVTWSI_STATUS_START, (dev << 1)); /* send addr bytes */ while ((status == 0) && alen--) status = twsi_send(addr >> (8*alen), MVTWSI_STATUS_DATA_W_ACK); /* begin i2c read to receive eeprom data bytes */ if (status == 0) status = i2c_begin( MVTWSI_STATUS_REPEATED_START, (dev << 1) | 1); /* prepare ACK if at least one byte must be received */ if (length > 0) twsi_control_flags |= MVTWSI_CONTROL_ACK; /* now receive actual bytes */ while ((status == 0) && length--) { /* reset NAK if we if no more to read now */ if (length == 0) twsi_control_flags &= ~MVTWSI_CONTROL_ACK; /* read current byte */ status = twsi_recv(data++); } /* Stop transaction */ status = twsi_stop(status); /* return 0 or status of first failure */ return status; } /* * I2C write called by cmd_i2c when doing 'i2c write' and by cmd_eeprom.c * Begin write, send address byte(s), send data bytes, end. */ int i2c_write(u8 dev, uint addr, int alen, u8 *data, int length) { int status; /* begin i2c write to send the eeprom adress bytes then data bytes */ status = i2c_begin(MVTWSI_STATUS_START, (dev << 1)); /* send addr bytes */ while ((status == 0) && alen--) status = twsi_send(addr >> (8*alen), MVTWSI_STATUS_DATA_W_ACK); /* send data bytes */ while ((status == 0) && (length-- > 0)) status = twsi_send(*(data++), MVTWSI_STATUS_DATA_W_ACK); /* Stop transaction */ status = twsi_stop(status); /* return 0 or status of first failure */ return status; } /* * Bus set routine: we only support bus 0. */ int i2c_set_bus_num(unsigned int bus) { if (bus > 0) { return -1; } return 0; } /* * Bus get routine: hard-return bus 0. */ unsigned int i2c_get_bus_num(void) { return 0; }
1001-study-uboot
drivers/i2c/mvtwsi.c
C
gpl3
12,537
/* * TI DaVinci (TMS320DM644x) I2C driver. * * Copyright (C) 2007 Sergey Kubushyn <ksi@koi8.net> * * -------------------------------------------------------- * * 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 <i2c.h> #include <asm/arch/hardware.h> #include <asm/arch/i2c_defs.h> #define CHECK_NACK() \ do {\ if (tmp & (I2C_TIMEOUT | I2C_STAT_NACK)) {\ REG(I2C_CON) = 0;\ return(1);\ }\ } while (0) static int wait_for_bus(void) { int stat, timeout; REG(I2C_STAT) = 0xffff; for (timeout = 0; timeout < 10; timeout++) { if (!((stat = REG(I2C_STAT)) & I2C_STAT_BB)) { REG(I2C_STAT) = 0xffff; return(0); } REG(I2C_STAT) = stat; udelay(50000); } REG(I2C_STAT) = 0xffff; return(1); } static int poll_i2c_irq(int mask) { int stat, timeout; for (timeout = 0; timeout < 10; timeout++) { udelay(1000); stat = REG(I2C_STAT); if (stat & mask) { return(stat); } } REG(I2C_STAT) = 0xffff; return(stat | I2C_TIMEOUT); } void flush_rx(void) { while (1) { if (!(REG(I2C_STAT) & I2C_STAT_RRDY)) break; REG(I2C_DRR); REG(I2C_STAT) = I2C_STAT_RRDY; udelay(1000); } } void i2c_init(int speed, int slaveadd) { u_int32_t div, psc; if (REG(I2C_CON) & I2C_CON_EN) { REG(I2C_CON) = 0; udelay (50000); } psc = 2; div = (CONFIG_SYS_HZ_CLOCK / ((psc + 1) * speed)) - 10; /* SCLL + SCLH */ REG(I2C_PSC) = psc; /* 27MHz / (2 + 1) = 9MHz */ REG(I2C_SCLL) = (div * 50) / 100; /* 50% Duty */ REG(I2C_SCLH) = div - REG(I2C_SCLL); REG(I2C_OA) = slaveadd; REG(I2C_CNT) = 0; /* Interrupts must be enabled or I2C module won't work */ REG(I2C_IE) = I2C_IE_SCD_IE | I2C_IE_XRDY_IE | I2C_IE_RRDY_IE | I2C_IE_ARDY_IE | I2C_IE_NACK_IE; /* Now enable I2C controller (get it out of reset) */ REG(I2C_CON) = I2C_CON_EN; udelay(1000); } int i2c_set_bus_speed(unsigned int speed) { i2c_init(speed, CONFIG_SYS_I2C_SLAVE); return 0; } int i2c_probe(u_int8_t chip) { int rc = 1; if (chip == REG(I2C_OA)) { return(rc); } REG(I2C_CON) = 0; if (wait_for_bus()) {return(1);} /* try to read one byte from current (or only) address */ REG(I2C_CNT) = 1; REG(I2C_SA) = chip; REG(I2C_CON) = (I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_STP); udelay (50000); if (!(REG(I2C_STAT) & I2C_STAT_NACK)) { rc = 0; flush_rx(); REG(I2C_STAT) = 0xffff; } else { REG(I2C_STAT) = 0xffff; REG(I2C_CON) |= I2C_CON_STP; udelay(20000); if (wait_for_bus()) {return(1);} } flush_rx(); REG(I2C_STAT) = 0xffff; REG(I2C_CNT) = 0; return(rc); } int i2c_read(u_int8_t chip, u_int32_t addr, int alen, u_int8_t *buf, int len) { u_int32_t tmp; int i; if ((alen < 0) || (alen > 2)) { printf("%s(): bogus address length %x\n", __FUNCTION__, alen); return(1); } if (wait_for_bus()) {return(1);} if (alen != 0) { /* Start address phase */ tmp = I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_TRX; REG(I2C_CNT) = alen; REG(I2C_SA) = chip; REG(I2C_CON) = tmp; tmp = poll_i2c_irq(I2C_STAT_XRDY | I2C_STAT_NACK); CHECK_NACK(); switch (alen) { case 2: /* Send address MSByte */ if (tmp & I2C_STAT_XRDY) { REG(I2C_DXR) = (addr >> 8) & 0xff; } else { REG(I2C_CON) = 0; return(1); } tmp = poll_i2c_irq(I2C_STAT_XRDY | I2C_STAT_NACK); CHECK_NACK(); /* No break, fall through */ case 1: /* Send address LSByte */ if (tmp & I2C_STAT_XRDY) { REG(I2C_DXR) = addr & 0xff; } else { REG(I2C_CON) = 0; return(1); } tmp = poll_i2c_irq(I2C_STAT_XRDY | I2C_STAT_NACK | I2C_STAT_ARDY); CHECK_NACK(); if (!(tmp & I2C_STAT_ARDY)) { REG(I2C_CON) = 0; return(1); } } } /* Address phase is over, now read 'len' bytes and stop */ tmp = I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_STP; REG(I2C_CNT) = len & 0xffff; REG(I2C_SA) = chip; REG(I2C_CON) = tmp; for (i = 0; i < len; i++) { tmp = poll_i2c_irq(I2C_STAT_RRDY | I2C_STAT_NACK | I2C_STAT_ROVR); CHECK_NACK(); if (tmp & I2C_STAT_RRDY) { buf[i] = REG(I2C_DRR); } else { REG(I2C_CON) = 0; return(1); } } tmp = poll_i2c_irq(I2C_STAT_SCD | I2C_STAT_NACK); CHECK_NACK(); if (!(tmp & I2C_STAT_SCD)) { REG(I2C_CON) = 0; return(1); } flush_rx(); REG(I2C_STAT) = 0xffff; REG(I2C_CNT) = 0; REG(I2C_CON) = 0; return(0); } int i2c_write(u_int8_t chip, u_int32_t addr, int alen, u_int8_t *buf, int len) { u_int32_t tmp; int i; if ((alen < 0) || (alen > 2)) { printf("%s(): bogus address length %x\n", __FUNCTION__, alen); return(1); } if (len < 0) { printf("%s(): bogus length %x\n", __FUNCTION__, len); return(1); } if (wait_for_bus()) {return(1);} /* Start address phase */ tmp = I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_TRX | I2C_CON_STP; REG(I2C_CNT) = (alen == 0) ? len & 0xffff : (len & 0xffff) + alen; REG(I2C_SA) = chip; REG(I2C_CON) = tmp; switch (alen) { case 2: /* Send address MSByte */ tmp = poll_i2c_irq(I2C_STAT_XRDY | I2C_STAT_NACK); CHECK_NACK(); if (tmp & I2C_STAT_XRDY) { REG(I2C_DXR) = (addr >> 8) & 0xff; } else { REG(I2C_CON) = 0; return(1); } /* No break, fall through */ case 1: /* Send address LSByte */ tmp = poll_i2c_irq(I2C_STAT_XRDY | I2C_STAT_NACK); CHECK_NACK(); if (tmp & I2C_STAT_XRDY) { REG(I2C_DXR) = addr & 0xff; } else { REG(I2C_CON) = 0; return(1); } } for (i = 0; i < len; i++) { tmp = poll_i2c_irq(I2C_STAT_XRDY | I2C_STAT_NACK); CHECK_NACK(); if (tmp & I2C_STAT_XRDY) { REG(I2C_DXR) = buf[i]; } else { return(1); } } tmp = poll_i2c_irq(I2C_STAT_SCD | I2C_STAT_NACK); CHECK_NACK(); if (!(tmp & I2C_STAT_SCD)) { REG(I2C_CON) = 0; return(1); } flush_rx(); REG(I2C_STAT) = 0xffff; REG(I2C_CNT) = 0; REG(I2C_CON) = 0; return(0); }
1001-study-uboot
drivers/i2c/davinci_i2c.c
C
gpl3
6,575
/* * (C) Copyright 2011 * Marvell Inc, <www.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 */ #ifndef _MV_I2C_H_ #define _MV_I2C_H_ extern void i2c_clk_enable(void); /* Shall the current transfer have a start/stop condition? */ #define I2C_COND_NORMAL 0 #define I2C_COND_START 1 #define I2C_COND_STOP 2 /* Shall the current transfer be ack/nacked or being waited for it? */ #define I2C_ACKNAK_WAITACK 1 #define I2C_ACKNAK_SENDACK 2 #define I2C_ACKNAK_SENDNAK 4 /* Specify who shall transfer the data (master or slave) */ #define I2C_READ 0 #define I2C_WRITE 1 #if (CONFIG_SYS_I2C_SPEED == 400000) #define I2C_ICR_INIT (ICR_FM | ICR_BEIE | ICR_IRFIE | ICR_ITEIE | ICR_GCD \ | ICR_SCLE) #else #define I2C_ICR_INIT (ICR_BEIE | ICR_IRFIE | ICR_ITEIE | ICR_GCD | ICR_SCLE) #endif #define I2C_ISR_INIT 0x7FF /* ----- Control register bits ---------------------------------------- */ #define ICR_START 0x1 /* start bit */ #define ICR_STOP 0x2 /* stop bit */ #define ICR_ACKNAK 0x4 /* send ACK(0) or NAK(1) */ #define ICR_TB 0x8 /* transfer byte bit */ #define ICR_MA 0x10 /* master abort */ #define ICR_SCLE 0x20 /* master clock enable, mona SCLEA */ #define ICR_IUE 0x40 /* unit enable */ #define ICR_GCD 0x80 /* general call disable */ #define ICR_ITEIE 0x100 /* enable tx interrupts */ #define ICR_IRFIE 0x200 /* enable rx interrupts, mona: DRFIE */ #define ICR_BEIE 0x400 /* enable bus error ints */ #define ICR_SSDIE 0x800 /* slave STOP detected int enable */ #define ICR_ALDIE 0x1000 /* enable arbitration interrupt */ #define ICR_SADIE 0x2000 /* slave address detected int enable */ #define ICR_UR 0x4000 /* unit reset */ #define ICR_FM 0x8000 /* Fast Mode */ /* ----- Status register bits ----------------------------------------- */ #define ISR_RWM 0x1 /* read/write mode */ #define ISR_ACKNAK 0x2 /* ack/nak status */ #define ISR_UB 0x4 /* unit busy */ #define ISR_IBB 0x8 /* bus busy */ #define ISR_SSD 0x10 /* slave stop detected */ #define ISR_ALD 0x20 /* arbitration loss detected */ #define ISR_ITE 0x40 /* tx buffer empty */ #define ISR_IRF 0x80 /* rx buffer full */ #define ISR_GCAD 0x100 /* general call address detected */ #define ISR_SAD 0x200 /* slave address detected */ #define ISR_BED 0x400 /* bus error no ACK/NAK */ #endif
1001-study-uboot
drivers/i2c/mv_i2c.h
C
gpl3
3,066
/* * Copyright (C) ST-Ericsson SA 2010 * * Basic U-Boot I2C interface for STn8500/DB8500 * Author: Michael Brandt <Michael.Brandt@stericsson.com> for ST-Ericsson * * 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. */ /* * Only 7-bit I2C device addresses are supported. */ #include <common.h> #include <i2c.h> #include "u8500_i2c.h" #include <asm/io.h> #include <asm/arch/clock.h> #define U8500_I2C_ENDAD_COUNTER (CONFIG_SYS_HZ/100) /* I2C bus timeout */ #define U8500_I2C_FIFO_FLUSH_COUNTER 500000 /* flush "timeout" */ #define U8500_I2C_SCL_FREQ 100000 /* I2C bus clock freq */ #define U8500_I2C_INPUT_FREQ 48000000 /* Input clock freq */ #define TX_FIFO_THRESHOLD 0x4 #define RX_FIFO_THRESHOLD 0x4 #define SLAVE_SETUP_TIME 14 /* Slave data setup time, 250ns for 48MHz i2c_clk */ #define WRITE_FIELD(var, mask, shift, value) \ (var = ((var & ~(mask)) | ((value) << (shift)))) static unsigned int bus_initialized[CONFIG_SYS_U8500_I2C_BUS_MAX]; static unsigned int i2c_bus_num; static unsigned int i2c_bus_speed[] = { CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SPEED }; static struct u8500_i2c_regs *i2c_dev[] = { (struct u8500_i2c_regs *)CONFIG_SYS_U8500_I2C0_BASE, (struct u8500_i2c_regs *)CONFIG_SYS_U8500_I2C1_BASE, (struct u8500_i2c_regs *)CONFIG_SYS_U8500_I2C2_BASE, (struct u8500_i2c_regs *)CONFIG_SYS_U8500_I2C3_BASE, }; static struct { int periph; int pcken; int kcken; } i2c_clock_bits[] = { {3, 3, 3}, /* I2C0 */ {1, 2, 2}, /* I2C1 */ {1, 6, 6}, /* I2C2 */ {2, 0, 0}, /* I2C3 */ }; static void i2c_set_bit(void *reg, u32 mask) { writel(readl(reg) | mask, reg); } static void i2c_clr_bit(void *reg, u32 mask) { writel(readl(reg) & ~mask, reg); } static void i2c_write_field(void *reg, u32 mask, uint shift, u32 value) { writel((readl(reg) & ~mask) | (value << shift), reg); } static int __i2c_set_bus_speed(unsigned int speed) { u32 value; struct u8500_i2c_regs *i2c_regs; i2c_regs = i2c_dev[i2c_bus_num]; /* Select standard (100 kbps) speed mode */ i2c_write_field(&i2c_regs->cr, U8500_I2C_CR_SM, U8500_I2C_CR_SHIFT_SM, 0x0); /* * Set the Baud Rate Counter 2 value * Baud rate (standard) = fi2cclk / ( (BRCNT2 x 2) + Foncycle ) * Foncycle = 0 (no digital filtering) */ value = (u32) (U8500_I2C_INPUT_FREQ / (speed * 2)); i2c_write_field(&i2c_regs->brcr, U8500_I2C_BRCR_BRCNT2, U8500_I2C_BRCR_SHIFT_BRCNT2, value); /* ensure that BRCNT value is zero */ i2c_write_field(&i2c_regs->brcr, U8500_I2C_BRCR_BRCNT1, U8500_I2C_BRCR_SHIFT_BRCNT1, 0); return U8500_I2C_INPUT_FREQ/(value * 2); } /* * i2c_init - initialize the i2c bus * * speed: bus speed (in HZ) * slaveaddr: address of device in slave mode * * Slave mode is not implemented. */ void i2c_init(int speed, int slaveaddr) { struct u8500_i2c_regs *i2c_regs; debug("i2c_init bus %d, speed %d\n", i2c_bus_num, speed); u8500_clock_enable(i2c_clock_bits[i2c_bus_num].periph, i2c_clock_bits[i2c_bus_num].pcken, i2c_clock_bits[i2c_bus_num].kcken); i2c_regs = i2c_dev[i2c_bus_num]; /* Disable the controller */ i2c_clr_bit(&i2c_regs->cr, U8500_I2C_CR_PE); /* Clear registers */ writel(0, &i2c_regs->cr); writel(0, &i2c_regs->scr); writel(0, &i2c_regs->hsmcr); writel(0, &i2c_regs->tftr); writel(0, &i2c_regs->rftr); writel(0, &i2c_regs->dmar); i2c_bus_speed[i2c_bus_num] = __i2c_set_bus_speed(speed); /* * Set our own address. * Set slave address mode to 7 bit addressing mode */ i2c_clr_bit(&i2c_regs->cr, U8500_I2C_CR_SAM); i2c_write_field(&i2c_regs->scr, U8500_I2C_SCR_ADDR, U8500_I2C_SCR_SHIFT_ADDR, slaveaddr); /* Slave Data Set up Time */ i2c_write_field(&i2c_regs->scr, U8500_I2C_SCR_DATA_SETUP_TIME, U8500_I2C_SCR_SHIFT_DATA_SETUP_TIME, SLAVE_SETUP_TIME); /* Disable the DMA sync logic */ i2c_write_field(&i2c_regs->cr, U8500_I2C_CR_DMA_SLE, U8500_I2C_CR_SHIFT_DMA_SLE, 0); /* Disable interrupts */ writel(0, &i2c_regs->imscr); /* Configure bus master mode */ i2c_write_field(&i2c_regs->cr, U8500_I2C_CR_OM, U8500_I2C_CR_SHIFT_OM, U8500_I2C_BUS_MASTER_MODE); /* Set FIFO threshold values */ writel(TX_FIFO_THRESHOLD, &i2c_regs->tftr); writel(RX_FIFO_THRESHOLD, &i2c_regs->rftr); /* Enable the I2C Controller */ i2c_set_bit(&i2c_regs->cr, U8500_I2C_CR_PE); bus_initialized[i2c_bus_num] = 1; } /* * loop_till_bit_clear - polls on a bit till it clears * ioreg: register where you want to check status * mask: bit mask for the bit you wish to check * timeout: timeout in ticks/s */ static int loop_till_bit_clear(void *io_reg, u32 mask, unsigned long timeout) { unsigned long timebase = get_timer(0); do { if ((readl(io_reg) & mask) == 0x0UL) return 0; } while (get_timer(timebase) < timeout); debug("loop_till_bit_clear timed out\n"); return -1; } /* * loop_till_bit_set - polls on a bit till it is set. * ioreg: register where you want to check status * mask: bit mask for the bit you wish to check * timeout: timeout in ticks/s */ static int loop_till_bit_set(void *io_reg, u32 mask, unsigned long timeout) { unsigned long timebase = get_timer(0); do { if ((readl(io_reg) & mask) != 0x0UL) return 0; } while (get_timer(timebase) < timeout); debug("loop_till_bit_set timed out\n"); return -1; } /* * flush_fifo - flush the I2C TX and RX FIFOs */ static void flush_fifo(struct u8500_i2c_regs *i2c_regs) { int counter = U8500_I2C_FIFO_FLUSH_COUNTER; /* Flush Tx FIFO */ i2c_set_bit(&i2c_regs->cr, U8500_I2C_CR_FTX); /* Flush Rx FIFO */ i2c_set_bit(&i2c_regs->cr, U8500_I2C_CR_FRX); while (counter--) { if (!(readl(&i2c_regs->cr) & (U8500_I2C_CR_FTX | U8500_I2C_CR_FRX))) break; } return; } #ifdef DEBUG static void print_abort_reason(struct u8500_i2c_regs *i2c_regs) { int cause; printf("abort: risr %08x, sr %08x\n", i2c_regs->risr, i2c_regs->sr); cause = (readl(&i2c_regs->sr) & U8500_I2C_SR_CAUSE) >> U8500_I2C_SR_SHIFT_CAUSE; switch (cause) { case U8500_I2C_NACK_ADDR: printf("No Ack received after Slave Address xmission\n"); break; case U8500_I2C_NACK_DATA: printf("Valid for MASTER_WRITE: No Ack received " "during data phase\n"); break; case U8500_I2C_ACK_MCODE: printf("Master recv ack after xmission of master code" "in hs mode\n"); break; case U8500_I2C_ARB_LOST: printf("Master Lost arbitration\n"); break; case U8500_I2C_BERR_START: printf("Slave restarts\n"); break; case U8500_I2C_BERR_STOP: printf("Slave reset\n"); break; case U8500_I2C_OVFL: printf("Overflow\n"); break; default: printf("Unknown error type\n"); } } #endif /* * i2c_abort - called when a I2C transaction failed */ static void i2c_abort(struct u8500_i2c_regs *i2c_regs) { #ifdef DEBUG print_abort_reason(i2c_regs); #endif /* flush RX and TX fifos */ flush_fifo(i2c_regs); /* Acknowledge the Master Transaction Done */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTD); /* Acknowledge the Master Transaction Done Without Stop */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTDWS); i2c_init(i2c_bus_speed[i2c_bus_num], CONFIG_SYS_I2C_SLAVE); } /* * write addr, alias index, to I2C bus. */ static int i2c_write_addr(struct u8500_i2c_regs *i2c_regs, uint addr, int alen) { while (alen--) { /* Wait until the Tx Fifo is not full */ if (loop_till_bit_clear((void *)&i2c_regs->risr, U8500_I2C_INT_TXFF, U8500_I2C_ENDAD_COUNTER)) { i2c_abort(i2c_regs); return -1; } /* MSB first */ writeb((addr >> (alen * 8)) & 0xff, &i2c_regs->tfr); } return 0; } /* * Internal simplified read function: * i2c_regs: Pointer to I2C registers for current bus * chip: I2C chip address, range 0..127 * addr: Memory (register) address within the chip * alen: Number of bytes to use for addr (typically 1, 2 for larger * memories, 0 for register type devices with only one register) * value: Where to put the data * * Returns: 0 on success, not 0 on failure */ static int i2c_read_byte(struct u8500_i2c_regs *i2c_regs, uchar chip, uint addr, int alen, uchar *value) { u32 mcr = 0; /* Set the address mode to 7 bit */ WRITE_FIELD(mcr, U8500_I2C_MCR_AM, U8500_I2C_MCR_SHIFT_AM, 1); /* Store the slave address in the master control register */ WRITE_FIELD(mcr, U8500_I2C_MCR_A7, U8500_I2C_MCR_SHIFT_A7, chip); if (alen != 0) { /* Master write operation */ mcr &= ~(U8500_I2C_MCR_OP); /* Configure the Frame length to one byte */ WRITE_FIELD(mcr, U8500_I2C_MCR_LENGTH, U8500_I2C_MCR_SHIFT_LENGTH, 1); /* Repeated start, no stop */ mcr &= ~(U8500_I2C_MCR_STOP); /* Write Master Control Register */ writel(mcr, &i2c_regs->mcr); /* send addr/index */ if (i2c_write_addr(i2c_regs, addr, alen) != 0) return -1; /* Check for the Master Transaction Done Without Stop */ if (loop_till_bit_set((void *)&i2c_regs->risr, U8500_I2C_INT_MTDWS, U8500_I2C_ENDAD_COUNTER)) { return -1; } /* Acknowledge the Master Transaction Done Without Stop */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTDWS); } /* Master control configuration for read operation */ mcr |= U8500_I2C_MCR_OP; /* Configure the STOP condition, we read only one byte */ mcr |= U8500_I2C_MCR_STOP; /* Set the frame length to one byte, we support only 1 byte reads */ WRITE_FIELD(mcr, U8500_I2C_MCR_LENGTH, U8500_I2C_MCR_SHIFT_LENGTH, 1); i2c_write_field(&i2c_regs->mcr, U8500_I2C_MCR_LENGTH_STOP_OP, U8500_I2C_MCR_SHIFT_LENGTH_STOP_OP, mcr); /* * receive_data_polling */ /* Wait until the Rx FIFO is not empty */ if (loop_till_bit_clear((void *)&i2c_regs->risr, U8500_I2C_INT_RXFE, U8500_I2C_ENDAD_COUNTER)) return -1; /* Read the data byte from Rx FIFO */ *value = readb(&i2c_regs->rfr); /* Wait until the work is done */ if (loop_till_bit_set((void *)&i2c_regs->risr, U8500_I2C_INT_MTD, U8500_I2C_ENDAD_COUNTER)) return -1; /* Acknowledge the Master Transaction Done */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTD); /* If MTD is set, Master Transaction Done Without Stop is set too */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTDWS); return 0; } /* * Internal simplified write function: * i2c_regs: Pointer to I2C registers for current bus * chip: I2C chip address, range 0..127 * addr: Memory (register) address within the chip * alen: Number of bytes to use for addr (typically 1, 2 for larger * memories, 0 for register type devices with only one register) * data: Where to read the data * len: How many bytes to write * * Returns: 0 on success, not 0 on failure */ static int __i2c_write(struct u8500_i2c_regs *i2c_regs, u8 chip, uint addr, int alen, u8 *data, int len) { int i; u32 mcr = 0; /* Set the address mode to 7 bit */ WRITE_FIELD(mcr, U8500_I2C_MCR_AM, U8500_I2C_MCR_SHIFT_AM, 1); /* Store the slave address in the master control register */ WRITE_FIELD(mcr, U8500_I2C_MCR_A7, U8500_I2C_MCR_SHIFT_A7, chip); /* Write operation */ mcr &= ~(U8500_I2C_MCR_OP); /* Current transaction is terminated by STOP condition */ mcr |= U8500_I2C_MCR_STOP; /* Frame length: addr byte + len */ WRITE_FIELD(mcr, U8500_I2C_MCR_LENGTH, U8500_I2C_MCR_SHIFT_LENGTH, (alen + len)); /* Write MCR register */ writel(mcr, &i2c_regs->mcr); if (i2c_write_addr(i2c_regs, addr, alen) != 0) return -1; for (i = 0; i < len; i++) { /* Wait until the Tx FIFO is not full */ if (loop_till_bit_clear((void *)&i2c_regs->risr, U8500_I2C_INT_TXFF, U8500_I2C_ENDAD_COUNTER)) return -1; /* it is a 32 bit register with upper 24 reserved R/O */ writeb(data[i], &i2c_regs->tfr); } /* Check for Master Transaction Done */ if (loop_till_bit_set((void *)&i2c_regs->risr, U8500_I2C_INT_MTD, U8500_I2C_ENDAD_COUNTER)) { printf("i2c_write_byte error2: risr %08x\n", i2c_regs->risr); return -1; } /* Acknowledge Master Transaction Done */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTD); /* Acknowledge Master Transaction Done Without Stop */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTDWS); return 0; } /* * Probe the given I2C chip address. Returns 0 if a chip responded, * not 0 on failure. */ int i2c_probe(uchar chip) { u32 mcr = 0; struct u8500_i2c_regs *i2c_regs; if (chip == CONFIG_SYS_I2C_SLAVE) return 1; i2c_regs = i2c_dev[i2c_bus_num]; /* Set the address mode to 7 bit */ WRITE_FIELD(mcr, U8500_I2C_MCR_AM, U8500_I2C_MCR_SHIFT_AM, 1); /* Store the slave address in the master control register */ WRITE_FIELD(mcr, U8500_I2C_MCR_A10, U8500_I2C_MCR_SHIFT_A7, chip); /* Read operation */ mcr |= U8500_I2C_MCR_OP; /* Set the frame length to one byte */ WRITE_FIELD(mcr, U8500_I2C_MCR_LENGTH, U8500_I2C_MCR_SHIFT_LENGTH, 1); /* Current transaction is terminated by STOP condition */ mcr |= U8500_I2C_MCR_STOP; /* Write MCR register */ writel(mcr, &i2c_regs->mcr); /* Wait until the Rx Fifo is not empty */ if (loop_till_bit_clear((void *)&i2c_regs->risr, U8500_I2C_INT_RXFE, U8500_I2C_ENDAD_COUNTER)) { i2c_abort(i2c_regs); return -1; } flush_fifo(i2c_regs); /* Acknowledge the Master Transaction Done */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTD); /* Acknowledge the Master Transaction Done Without Stop */ i2c_set_bit(&i2c_regs->icr, U8500_I2C_INT_MTDWS); return 0; } /* * Read/Write interface: * chip: I2C chip address, range 0..127 * addr: Memory (register) address within the chip * alen: Number of bytes to use for addr (typically 1, 2 for larger * memories, 0 for register type devices with only one * register) * buffer: Where to read/write the data * len: How many bytes to read/write * * Returns: 0 on success, not 0 on failure */ int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { int i; int rc; struct u8500_i2c_regs *i2c_regs; if (alen > 2) { debug("I2C read: addr len %d not supported\n", alen); return 1; } i2c_regs = i2c_dev[i2c_bus_num]; for (i = 0; i < len; i++) { rc = i2c_read_byte(i2c_regs, chip, addr + i, alen, &buffer[i]); if (rc != 0) { debug("I2C read: I/O error: %d\n", rc); i2c_abort(i2c_regs); return rc; } } return 0; } int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { int rc; struct u8500_i2c_regs *i2c_regs; i2c_regs = i2c_dev[i2c_bus_num]; rc = __i2c_write(i2c_regs, chip, addr, alen, buffer, len); if (rc != 0) { debug("I2C write: I/O error\n"); i2c_abort(i2c_regs); return rc; } return 0; } int i2c_set_bus_num(unsigned int bus) { if (bus > ARRAY_SIZE(i2c_dev) - 1) { debug("i2c_set_bus_num: only up to bus %d supported\n", ARRAY_SIZE(i2c_dev)-1); return -1; } i2c_bus_num = bus; if (!bus_initialized[i2c_bus_num]) i2c_init(CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE); return 0; } int i2c_set_bus_speed(unsigned int speed) { if (speed > U8500_I2C_MAX_STANDARD_SCL) { debug("i2c_set_bus_speed: only up to %d supported\n", U8500_I2C_MAX_STANDARD_SCL); return -1; } /* sets as side effect i2c_bus_speed[i2c_bus_num] */ i2c_init(speed, CONFIG_SYS_I2C_SLAVE); return 0; } unsigned int i2c_get_bus_num(void) { return i2c_bus_num; } unsigned int i2c_get_bus_speed(void) { return i2c_bus_speed[i2c_bus_num]; }
1001-study-uboot
drivers/i2c/u8500_i2c.c
C
gpl3
15,893
/* * Basic I2C functions * * Copyright (c) 2003 Texas Instruments * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Author: Jian Zhang jzhang@ti.com, Texas Instruments * * Copyright (c) 2003 Wolfgang Denk, wd@denx.de * Rewritten to fit into the current U-Boot framework * */ #include <common.h> static void wait_for_bb (void); static u16 wait_for_pin (void); void i2c_init (int speed, int slaveadd) { u16 scl; if (inw (I2C_CON) & I2C_CON_EN) { outw (0, I2C_CON); udelay (5000); } /* 12MHz I2C module clock */ outw (0, I2C_PSC); outw (I2C_CON_EN, I2C_CON); outw (0, I2C_SYSTEST); /* have to enable intrrupts or OMAP i2c module doesn't work */ outw (I2C_IE_XRDY_IE | I2C_IE_RRDY_IE | I2C_IE_ARDY_IE | I2C_IE_NACK_IE | I2C_IE_AL_IE, I2C_IE); scl = (12000000 / 2) / speed - 6; outw (scl, I2C_SCLL); outw (scl, I2C_SCLH); /* own address */ outw (slaveadd, I2C_OA); outw (0, I2C_CNT); udelay (1000); } static int i2c_read_byte (u8 devaddr, u8 regoffset, u8 * value) { int i2c_error = 0; u16 status; /* wait until bus not busy */ wait_for_bb (); /* one byte only */ outw (1, I2C_CNT); /* set slave address */ outw (devaddr, I2C_SA); /* no stop bit needed here */ outw (I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_TRX, I2C_CON); status = wait_for_pin (); if (status & I2C_STAT_XRDY) { /* Important: have to use byte access */ *(volatile u8 *) (I2C_DATA) = regoffset; udelay (20000); if (inw (I2C_STAT) & I2C_STAT_NACK) { i2c_error = 1; } } else { i2c_error = 1; } if (!i2c_error) { /* free bus, otherwise we can't use a combined transction */ outw (0, I2C_CON); while (inw (I2C_STAT) || (inw (I2C_CON) & I2C_CON_MST)) { udelay (10000); /* Have to clear pending interrupt to clear I2C_STAT */ inw (I2C_IV); } wait_for_bb (); /* set slave address */ outw (devaddr, I2C_SA); /* read one byte from slave */ outw (1, I2C_CNT); /* need stop bit here */ outw (I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_STP, I2C_CON); status = wait_for_pin (); if (status & I2C_STAT_RRDY) { *value = inw (I2C_DATA); udelay (20000); } else { i2c_error = 1; } if (!i2c_error) { outw (I2C_CON_EN, I2C_CON); while (inw (I2C_STAT) || (inw (I2C_CON) & I2C_CON_MST)) { udelay (10000); inw (I2C_IV); } } } return i2c_error; } static int i2c_write_byte (u8 devaddr, u8 regoffset, u8 value) { int i2c_error = 0; u16 status; /* wait until bus not busy */ wait_for_bb (); /* two bytes */ outw (2, I2C_CNT); /* set slave address */ outw (devaddr, I2C_SA); /* stop bit needed here */ outw (I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_TRX | I2C_CON_STP, I2C_CON); /* wait until state change */ status = wait_for_pin (); if (status & I2C_STAT_XRDY) { /* send out two bytes */ outw ((value << 8) + regoffset, I2C_DATA); /* must have enough delay to allow BB bit to go low */ udelay (30000); if (inw (I2C_STAT) & I2C_STAT_NACK) { i2c_error = 1; } } else { i2c_error = 1; } if (!i2c_error) { outw (I2C_CON_EN, I2C_CON); while (inw (I2C_STAT) || (inw (I2C_CON) & I2C_CON_MST)) { udelay (1000); /* have to read to clear intrrupt */ inw (I2C_IV); } } return i2c_error; } int i2c_probe (uchar chip) { int res = 1; if (chip == inw (I2C_OA)) { return res; } /* wait until bus not busy */ wait_for_bb (); /* try to read one byte */ outw (1, I2C_CNT); /* set slave address */ outw (chip, I2C_SA); /* stop bit needed here */ outw (I2C_CON_EN | I2C_CON_MST | I2C_CON_STT | I2C_CON_STP, I2C_CON); /* enough delay for the NACK bit set */ udelay (2000); if (!(inw (I2C_STAT) & I2C_STAT_NACK)) { res = 0; } else { outw (inw (I2C_CON) | I2C_CON_STP, I2C_CON); udelay (20); wait_for_bb (); } return res; } int i2c_read (uchar chip, uint addr, int alen, uchar * buffer, int len) { int i; if (alen > 1) { printf ("I2C read: addr len %d not supported\n", alen); return 1; } if (addr + len > 256) { printf ("I2C read: address out of range\n"); return 1; } for (i = 0; i < len; i++) { if (i2c_read_byte (chip, addr + i, &buffer[i])) { printf ("I2C read: I/O error\n"); i2c_init (CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE); return 1; } } return 0; } int i2c_write (uchar chip, uint addr, int alen, uchar * buffer, int len) { int i; if (alen > 1) { printf ("I2C read: addr len %d not supported\n", alen); return 1; } if (addr + len > 256) { printf ("I2C read: address out of range\n"); return 1; } for (i = 0; i < len; i++) { if (i2c_write_byte (chip, addr + i, buffer[i])) { printf ("I2C read: I/O error\n"); i2c_init (CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE); return 1; } } return 0; } static void wait_for_bb (void) { int timeout = 10; while ((inw (I2C_STAT) & I2C_STAT_BB) && timeout--) { inw (I2C_IV); udelay (1000); } if (timeout <= 0) { printf ("timed out in wait_for_bb: I2C_STAT=%x\n", inw (I2C_STAT)); } } static u16 wait_for_pin (void) { u16 status, iv; int timeout = 10; do { udelay (1000); status = inw (I2C_STAT); iv = inw (I2C_IV); } while (!iv && !(status & (I2C_STAT_ROVR | I2C_STAT_XUDF | I2C_STAT_XRDY | I2C_STAT_RRDY | I2C_STAT_ARDY | I2C_STAT_NACK | I2C_STAT_AL)) && timeout--); if (timeout <= 0) { printf ("timed out in wait_for_pin: I2C_STAT=%x\n", inw (I2C_STAT)); } return status; }
1001-study-uboot
drivers/i2c/omap1510_i2c.c
C
gpl3
5,795
/* * (C) Copyright 2009 * Vipin Kumar, ST Micoelectronics, vipin.kumar@st.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 <common.h> #include <asm/io.h> #include <asm/arch/hardware.h> #include <asm/arch/spr_i2c.h> static struct i2c_regs *const i2c_regs_p = (struct i2c_regs *)CONFIG_SYS_I2C_BASE; /* * set_speed - Set the i2c speed mode (standard, high, fast) * @i2c_spd: required i2c speed mode * * Set the i2c speed mode (standard, high, fast) */ static void set_speed(int i2c_spd) { unsigned int cntl; unsigned int hcnt, lcnt; unsigned int high, low; cntl = (readl(&i2c_regs_p->ic_con) & (~IC_CON_SPD_MSK)); switch (i2c_spd) { case IC_SPEED_MODE_MAX: cntl |= IC_CON_SPD_HS; high = MIN_HS_SCL_HIGHTIME; low = MIN_HS_SCL_LOWTIME; break; case IC_SPEED_MODE_STANDARD: cntl |= IC_CON_SPD_SS; high = MIN_SS_SCL_HIGHTIME; low = MIN_SS_SCL_LOWTIME; break; case IC_SPEED_MODE_FAST: default: cntl |= IC_CON_SPD_FS; high = MIN_FS_SCL_HIGHTIME; low = MIN_FS_SCL_LOWTIME; break; } writel(cntl, &i2c_regs_p->ic_con); hcnt = (IC_CLK * high) / NANO_TO_MICRO; writel(hcnt, &i2c_regs_p->ic_fs_scl_hcnt); lcnt = (IC_CLK * low) / NANO_TO_MICRO; writel(lcnt, &i2c_regs_p->ic_fs_scl_lcnt); } /* * i2c_set_bus_speed - Set the i2c speed * @speed: required i2c speed * * Set the i2c speed. */ void i2c_set_bus_speed(int speed) { if (speed >= I2C_MAX_SPEED) set_speed(IC_SPEED_MODE_MAX); else if (speed >= I2C_FAST_SPEED) set_speed(IC_SPEED_MODE_FAST); else set_speed(IC_SPEED_MODE_STANDARD); } /* * i2c_get_bus_speed - Gets the i2c speed * * Gets the i2c speed. */ int i2c_get_bus_speed(void) { u32 cntl; cntl = (readl(&i2c_regs_p->ic_con) & IC_CON_SPD_MSK); if (cntl == IC_CON_SPD_HS) return I2C_MAX_SPEED; else if (cntl == IC_CON_SPD_FS) return I2C_FAST_SPEED; else if (cntl == IC_CON_SPD_SS) return I2C_STANDARD_SPEED; return 0; } /* * i2c_init - Init function * @speed: required i2c speed * @slaveadd: slave address for the spear device * * Initialization function. */ void i2c_init(int speed, int slaveadd) { unsigned int enbl; /* Disable i2c */ enbl = readl(&i2c_regs_p->ic_enable); enbl &= ~IC_ENABLE_0B; writel(enbl, &i2c_regs_p->ic_enable); writel((IC_CON_SD | IC_CON_SPD_FS | IC_CON_MM), &i2c_regs_p->ic_con); writel(IC_RX_TL, &i2c_regs_p->ic_rx_tl); writel(IC_TX_TL, &i2c_regs_p->ic_tx_tl); i2c_set_bus_speed(speed); writel(IC_STOP_DET, &i2c_regs_p->ic_intr_mask); writel(slaveadd, &i2c_regs_p->ic_sar); /* Enable i2c */ enbl = readl(&i2c_regs_p->ic_enable); enbl |= IC_ENABLE_0B; writel(enbl, &i2c_regs_p->ic_enable); } /* * i2c_setaddress - Sets the target slave address * @i2c_addr: target i2c address * * Sets the target slave address. */ static void i2c_setaddress(unsigned int i2c_addr) { writel(i2c_addr, &i2c_regs_p->ic_tar); } /* * i2c_flush_rxfifo - Flushes the i2c RX FIFO * * Flushes the i2c RX FIFO */ static void i2c_flush_rxfifo(void) { while (readl(&i2c_regs_p->ic_status) & IC_STATUS_RFNE) readl(&i2c_regs_p->ic_cmd_data); } /* * i2c_wait_for_bb - Waits for bus busy * * Waits for bus busy */ static int i2c_wait_for_bb(void) { unsigned long start_time_bb = get_timer(0); while ((readl(&i2c_regs_p->ic_status) & IC_STATUS_MA) || !(readl(&i2c_regs_p->ic_status) & IC_STATUS_TFE)) { /* Evaluate timeout */ if (get_timer(start_time_bb) > (unsigned long)(I2C_BYTE_TO_BB)) return 1; } return 0; } /* check parameters for i2c_read and i2c_write */ static int check_params(uint addr, int alen, uchar *buffer, int len) { if (buffer == NULL) { printf("Buffer is invalid\n"); return 1; } if (alen > 1) { printf("addr len %d not supported\n", alen); return 1; } if (addr + len > 256) { printf("address out of range\n"); return 1; } return 0; } static int i2c_xfer_init(uchar chip, uint addr) { if (i2c_wait_for_bb()) { printf("Timed out waiting for bus\n"); return 1; } i2c_setaddress(chip); writel(addr, &i2c_regs_p->ic_cmd_data); return 0; } static int i2c_xfer_finish(void) { ulong start_stop_det = get_timer(0); while (1) { if ((readl(&i2c_regs_p->ic_raw_intr_stat) & IC_STOP_DET)) { readl(&i2c_regs_p->ic_clr_stop_det); break; } else if (get_timer(start_stop_det) > I2C_STOPDET_TO) { break; } } if (i2c_wait_for_bb()) { printf("Timed out waiting for bus\n"); return 1; } i2c_flush_rxfifo(); /* Wait for read/write operation to complete on actual memory */ udelay(10000); return 0; } /* * i2c_read - Read from i2c memory * @chip: target i2c address * @addr: address to read from * @alen: * @buffer: buffer for read data * @len: no of bytes to be read * * Read from i2c memory. */ int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { unsigned long start_time_rx; if (check_params(addr, alen, buffer, len)) return 1; if (i2c_xfer_init(chip, addr)) return 1; start_time_rx = get_timer(0); while (len) { writel(IC_CMD, &i2c_regs_p->ic_cmd_data); if (readl(&i2c_regs_p->ic_status) & IC_STATUS_RFNE) { *buffer++ = (uchar)readl(&i2c_regs_p->ic_cmd_data); len--; start_time_rx = get_timer(0); } else if (get_timer(start_time_rx) > I2C_BYTE_TO) { printf("Timed out. i2c read Failed\n"); return 1; } } return i2c_xfer_finish(); } /* * i2c_write - Write to i2c memory * @chip: target i2c address * @addr: address to read from * @alen: * @buffer: buffer for read data * @len: no of bytes to be read * * Write to i2c memory. */ int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { int nb = len; unsigned long start_time_tx; if (check_params(addr, alen, buffer, len)) return 1; if (i2c_xfer_init(chip, addr)) return 1; start_time_tx = get_timer(0); while (len) { if (readl(&i2c_regs_p->ic_status) & IC_STATUS_TFNF) { writel(*buffer, &i2c_regs_p->ic_cmd_data); buffer++; len--; start_time_tx = get_timer(0); } else if (get_timer(start_time_tx) > (nb * I2C_BYTE_TO)) { printf("Timed out. i2c write Failed\n"); return 1; } } return i2c_xfer_finish(); } /* * i2c_probe - Probe the i2c chip */ int i2c_probe(uchar chip) { u32 tmp; /* * Try to read the first location of the chip. */ return i2c_read(chip, 0, 1, (uchar *)&tmp, 1); }
1001-study-uboot
drivers/i2c/spr_i2c.c
C
gpl3
7,063
/* * i2c driver for Freescale i.MX series * * (c) 2007 Pengutronix, Sascha Hauer <s.hauer@pengutronix.de> * (c) 2011 Marek Vasut <marek.vasut@gmail.com> * * Based on i2c-imx.c from linux kernel: * Copyright (C) 2005 Torsten Koschorrek <koschorrek at synertronixx.de> * Copyright (C) 2005 Matthias Blaschke <blaschke at synertronixx.de> * Copyright (C) 2007 RightHand Technologies, Inc. * Copyright (C) 2008 Darius Augulis <darius.augulis at teltonika.lt> * * * 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 <asm/io.h> #if defined(CONFIG_HARD_I2C) #include <asm/arch/clock.h> #include <asm/arch/imx-regs.h> #include <i2c.h> struct mxc_i2c_regs { uint32_t iadr; uint32_t ifdr; uint32_t i2cr; uint32_t i2sr; uint32_t i2dr; }; #define I2CR_IEN (1 << 7) #define I2CR_IIEN (1 << 6) #define I2CR_MSTA (1 << 5) #define I2CR_MTX (1 << 4) #define I2CR_TX_NO_AK (1 << 3) #define I2CR_RSTA (1 << 2) #define I2SR_ICF (1 << 7) #define I2SR_IBB (1 << 5) #define I2SR_IIF (1 << 1) #define I2SR_RX_NO_AK (1 << 0) #if defined(CONFIG_SYS_I2C_MX31_PORT1) #define I2C_BASE 0x43f80000 #define I2C_CLK_OFFSET 26 #elif defined (CONFIG_SYS_I2C_MX31_PORT2) #define I2C_BASE 0x43f98000 #define I2C_CLK_OFFSET 28 #elif defined (CONFIG_SYS_I2C_MX31_PORT3) #define I2C_BASE 0x43f84000 #define I2C_CLK_OFFSET 30 #elif defined(CONFIG_SYS_I2C_MX53_PORT1) #define I2C_BASE I2C1_BASE_ADDR #elif defined(CONFIG_SYS_I2C_MX53_PORT2) #define I2C_BASE I2C2_BASE_ADDR #elif defined(CONFIG_SYS_I2C_MX35_PORT1) #define I2C_BASE I2C_BASE_ADDR #elif defined(CONFIG_SYS_I2C_MX35_PORT2) #define I2C_BASE I2C2_BASE_ADDR #elif defined(CONFIG_SYS_I2C_MX35_PORT3) #define I2C_BASE I2C3_BASE_ADDR #else #error "define CONFIG_SYS_I2C_MX<Processor>_PORTx to use the mx I2C driver" #endif #define I2C_MAX_TIMEOUT 10000 static u16 i2c_clk_div[50][2] = { { 22, 0x20 }, { 24, 0x21 }, { 26, 0x22 }, { 28, 0x23 }, { 30, 0x00 }, { 32, 0x24 }, { 36, 0x25 }, { 40, 0x26 }, { 42, 0x03 }, { 44, 0x27 }, { 48, 0x28 }, { 52, 0x05 }, { 56, 0x29 }, { 60, 0x06 }, { 64, 0x2A }, { 72, 0x2B }, { 80, 0x2C }, { 88, 0x09 }, { 96, 0x2D }, { 104, 0x0A }, { 112, 0x2E }, { 128, 0x2F }, { 144, 0x0C }, { 160, 0x30 }, { 192, 0x31 }, { 224, 0x32 }, { 240, 0x0F }, { 256, 0x33 }, { 288, 0x10 }, { 320, 0x34 }, { 384, 0x35 }, { 448, 0x36 }, { 480, 0x13 }, { 512, 0x37 }, { 576, 0x14 }, { 640, 0x38 }, { 768, 0x39 }, { 896, 0x3A }, { 960, 0x17 }, { 1024, 0x3B }, { 1152, 0x18 }, { 1280, 0x3C }, { 1536, 0x3D }, { 1792, 0x3E }, { 1920, 0x1B }, { 2048, 0x3F }, { 2304, 0x1C }, { 2560, 0x1D }, { 3072, 0x1E }, { 3840, 0x1F } }; /* * Calculate and set proper clock divider */ static uint8_t i2c_imx_get_clk(unsigned int rate) { unsigned int i2c_clk_rate; unsigned int div; u8 clk_div; #if defined(CONFIG_MX31) struct clock_control_regs *sc_regs = (struct clock_control_regs *)CCM_BASE; /* start the required I2C clock */ writel(readl(&sc_regs->cgr0) | (3 << I2C_CLK_OFFSET), &sc_regs->cgr0); #endif /* Divider value calculation */ i2c_clk_rate = mxc_get_clock(MXC_IPG_PERCLK); div = (i2c_clk_rate + rate - 1) / rate; if (div < i2c_clk_div[0][0]) clk_div = 0; else if (div > i2c_clk_div[ARRAY_SIZE(i2c_clk_div) - 1][0]) clk_div = ARRAY_SIZE(i2c_clk_div) - 1; else for (clk_div = 0; i2c_clk_div[clk_div][0] < div; clk_div++) ; /* Store divider value */ return clk_div; } /* * Reset I2C Controller */ void i2c_reset(void) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; writeb(0, &i2c_regs->i2cr); /* Reset module */ writeb(0, &i2c_regs->i2sr); } /* * Init I2C Bus */ void i2c_init(int speed, int unused) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; u8 clk_idx = i2c_imx_get_clk(speed); u8 idx = i2c_clk_div[clk_idx][1]; /* Store divider value */ writeb(idx, &i2c_regs->ifdr); i2c_reset(); } /* * Set I2C Speed */ int i2c_set_bus_speed(unsigned int speed) { i2c_init(speed, 0); return 0; } /* * Get I2C Speed */ unsigned int i2c_get_bus_speed(void) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; u8 clk_idx = readb(&i2c_regs->ifdr); u8 clk_div; for (clk_div = 0; i2c_clk_div[clk_div][1] != clk_idx; clk_div++) ; return mxc_get_clock(MXC_IPG_PERCLK) / i2c_clk_div[clk_div][0]; } /* * Wait for bus to be busy (or free if for_busy = 0) * * for_busy = 1: Wait for IBB to be asserted * for_busy = 0: Wait for IBB to be de-asserted */ int i2c_imx_bus_busy(int for_busy) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; unsigned int temp; int timeout = I2C_MAX_TIMEOUT; while (timeout--) { temp = readb(&i2c_regs->i2sr); if (for_busy && (temp & I2SR_IBB)) return 0; if (!for_busy && !(temp & I2SR_IBB)) return 0; udelay(1); } return 1; } /* * Wait for transaction to complete */ int i2c_imx_trx_complete(void) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; int timeout = I2C_MAX_TIMEOUT; while (timeout--) { if (readb(&i2c_regs->i2sr) & I2SR_IIF) { writeb(0, &i2c_regs->i2sr); return 0; } udelay(1); } return 1; } /* * Check if the transaction was ACKed */ int i2c_imx_acked(void) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; return readb(&i2c_regs->i2sr) & I2SR_RX_NO_AK; } /* * Start the controller */ int i2c_imx_start(void) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; unsigned int temp = 0; int result; int speed = i2c_get_bus_speed(); u8 clk_idx = i2c_imx_get_clk(speed); u8 idx = i2c_clk_div[clk_idx][1]; /* Store divider value */ writeb(idx, &i2c_regs->ifdr); /* Enable I2C controller */ writeb(0, &i2c_regs->i2sr); writeb(I2CR_IEN, &i2c_regs->i2cr); /* Wait controller to be stable */ udelay(50); /* Start I2C transaction */ temp = readb(&i2c_regs->i2cr); temp |= I2CR_MSTA; writeb(temp, &i2c_regs->i2cr); result = i2c_imx_bus_busy(1); if (result) return result; temp |= I2CR_MTX | I2CR_TX_NO_AK; writeb(temp, &i2c_regs->i2cr); return 0; } /* * Stop the controller */ void i2c_imx_stop(void) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; unsigned int temp = 0; /* Stop I2C transaction */ temp = readb(&i2c_regs->i2cr); temp |= ~(I2CR_MSTA | I2CR_MTX); writeb(temp, &i2c_regs->i2cr); i2c_imx_bus_busy(0); /* Disable I2C controller */ writeb(0, &i2c_regs->i2cr); } /* * Set chip address and access mode * * read = 1: READ access * read = 0: WRITE access */ int i2c_imx_set_chip_addr(uchar chip, int read) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; int ret; writeb((chip << 1) | read, &i2c_regs->i2dr); ret = i2c_imx_trx_complete(); if (ret) return ret; ret = i2c_imx_acked(); if (ret) return ret; return ret; } /* * Write register address */ int i2c_imx_set_reg_addr(uint addr, int alen) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; int ret = 0; while (alen--) { writeb((addr >> (alen * 8)) & 0xff, &i2c_regs->i2dr); ret = i2c_imx_trx_complete(); if (ret) break; ret = i2c_imx_acked(); if (ret) break; } return ret; } /* * Try if a chip add given address responds (probe the chip) */ int i2c_probe(uchar chip) { int ret; ret = i2c_imx_start(); if (ret) return ret; ret = i2c_imx_set_chip_addr(chip, 0); if (ret) return ret; i2c_imx_stop(); return ret; } /* * Read data from I2C device */ int i2c_read(uchar chip, uint addr, int alen, uchar *buf, int len) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; int ret; unsigned int temp; int i; ret = i2c_imx_start(); if (ret) return ret; /* write slave address */ ret = i2c_imx_set_chip_addr(chip, 0); if (ret) return ret; ret = i2c_imx_set_reg_addr(addr, alen); if (ret) return ret; temp = readb(&i2c_regs->i2cr); temp |= I2CR_RSTA; writeb(temp, &i2c_regs->i2cr); ret = i2c_imx_set_chip_addr(chip, 1); if (ret) return ret; /* setup bus to read data */ temp = readb(&i2c_regs->i2cr); temp &= ~(I2CR_MTX | I2CR_TX_NO_AK); if (len == 1) temp |= I2CR_TX_NO_AK; writeb(temp, &i2c_regs->i2cr); readb(&i2c_regs->i2dr); /* read data */ for (i = 0; i < len; i++) { ret = i2c_imx_trx_complete(); if (ret) return ret; /* * It must generate STOP before read I2DR to prevent * controller from generating another clock cycle */ if (i == (len - 1)) { temp = readb(&i2c_regs->i2cr); temp &= ~(I2CR_MSTA | I2CR_MTX); writeb(temp, &i2c_regs->i2cr); i2c_imx_bus_busy(0); } else if (i == (len - 2)) { temp = readb(&i2c_regs->i2cr); temp |= I2CR_TX_NO_AK; writeb(temp, &i2c_regs->i2cr); } buf[i] = readb(&i2c_regs->i2dr); } i2c_imx_stop(); return ret; } /* * Write data to I2C device */ int i2c_write(uchar chip, uint addr, int alen, uchar *buf, int len) { struct mxc_i2c_regs *i2c_regs = (struct mxc_i2c_regs *)I2C_BASE; int ret; int i; ret = i2c_imx_start(); if (ret) return ret; /* write slave address */ ret = i2c_imx_set_chip_addr(chip, 0); if (ret) return ret; ret = i2c_imx_set_reg_addr(addr, alen); if (ret) return ret; for (i = 0; i < len; i++) { writeb(buf[i], &i2c_regs->i2dr); ret = i2c_imx_trx_complete(); if (ret) return ret; ret = i2c_imx_acked(); if (ret) return ret; } i2c_imx_stop(); return ret; } #endif /* CONFIG_HARD_I2C */
1001-study-uboot
drivers/i2c/mxc_i2c.c
C
gpl3
10,134
/* * File: drivers/i2c/pca9564.c * Based on: drivers/i2c/s3c44b0_i2c.c * Author: * * Created: 2009-06-23 * Description: PCA9564 i2c bridge driver * * Modified: * Copyright 2009 CJSC "NII STT", http://www.niistt.ru/ * * Bugs: * * 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, see the file COPYING, or write * to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <common.h> #include <i2c.h> #include <pca9564.h> #include <asm/io.h> #define PCA_STA (CONFIG_PCA9564_BASE + 0) #define PCA_TO (CONFIG_PCA9564_BASE + 0) #define PCA_DAT (CONFIG_PCA9564_BASE + (1 << 2)) #define PCA_ADR (CONFIG_PCA9564_BASE + (2 << 2)) #define PCA_CON (CONFIG_PCA9564_BASE + (3 << 2)) static unsigned char pca_read_reg(unsigned int reg) { return readb((void *)reg); } static void pca_write_reg(unsigned int reg, unsigned char value) { writeb(value, (void *)reg); } static int pca_wait_busy(void) { unsigned int timeout = 10000; while (!(pca_read_reg(PCA_CON) & PCA_CON_SI) && --timeout) udelay(1); if (timeout == 0) debug("I2C timeout!\n"); debug("CON = 0x%02x, STA = 0x%02x\n", pca_read_reg(PCA_CON), pca_read_reg(PCA_STA)); return timeout ? 0 : 1; } /*=====================================================================*/ /* Public Functions */ /*=====================================================================*/ /*----------------------------------------------------------------------- * Initialization */ void i2c_init(int speed, int slaveaddr) { pca_write_reg(PCA_CON, PCA_CON_ENSIO | speed); } /* * Probe the given I2C chip address. Returns 0 if a chip responded, * not 0 on failure. */ int i2c_probe(uchar chip) { unsigned char res; pca_write_reg(PCA_CON, PCA_CON_STA | PCA_CON_ENSIO); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_STA | PCA_CON_ENSIO); pca_write_reg(PCA_DAT, (chip << 1) | 1); res = pca_wait_busy(); if ((res == 0) && (pca_read_reg(PCA_STA) == 0x48)) res = 1; pca_write_reg(PCA_CON, PCA_CON_STO | PCA_CON_ENSIO); return res; } /* * Read/Write interface: * chip: I2C chip address, range 0..127 * addr: Memory (register) address within the chip * alen: Number of bytes to use for addr (typically 1, 2 for larger * memories, 0 for register type devices with only one * register) * buffer: Where to read/write the data * len: How many bytes to read/write * * Returns: 0 on success, not 0 on failure */ int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { int i; pca_write_reg(PCA_CON, PCA_CON_ENSIO | PCA_CON_STA); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_ENSIO); pca_write_reg(PCA_DAT, (chip << 1)); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_ENSIO); if (alen > 0) { pca_write_reg(PCA_DAT, addr); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_ENSIO); } pca_write_reg(PCA_CON, PCA_CON_ENSIO | PCA_CON_STO); udelay(500); pca_write_reg(PCA_CON, PCA_CON_ENSIO | PCA_CON_STA); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_ENSIO); pca_write_reg(PCA_DAT, (chip << 1) | 1); pca_wait_busy(); for (i = 0; i < len; ++i) { if (i == len - 1) pca_write_reg(PCA_CON, PCA_CON_ENSIO); else pca_write_reg(PCA_CON, PCA_CON_ENSIO | PCA_CON_AA); pca_wait_busy(); buffer[i] = pca_read_reg(PCA_DAT); } pca_write_reg(PCA_CON, PCA_CON_ENSIO | PCA_CON_STO); return 0; } int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { int i; pca_write_reg(PCA_CON, PCA_CON_ENSIO | PCA_CON_STA); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_ENSIO); pca_write_reg(PCA_DAT, chip << 1); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_ENSIO); if (alen > 0) { pca_write_reg(PCA_DAT, addr); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_ENSIO); } for (i = 0; i < len; ++i) { pca_write_reg(PCA_DAT, buffer[i]); pca_wait_busy(); pca_write_reg(PCA_CON, PCA_CON_ENSIO); } pca_write_reg(PCA_CON, PCA_CON_STO | PCA_CON_ENSIO); return 0; }
1001-study-uboot
drivers/i2c/pca9564_i2c.c
C
gpl3
4,688
/* * i2c.c - driver for Blackfin on-chip TWI/I2C * * Copyright (c) 2006-2010 Analog Devices Inc. * * Licensed under the GPL-2 or later. */ #include <common.h> #include <i2c.h> #include <asm/blackfin.h> #include <asm/mach-common/bits/twi.h> /* Every register is 32bit aligned, but only 16bits in size */ #define ureg(name) u16 name; u16 __pad_##name; struct twi_regs { ureg(clkdiv); ureg(control); ureg(slave_ctl); ureg(slave_stat); ureg(slave_addr); ureg(master_ctl); ureg(master_stat); ureg(master_addr); ureg(int_stat); ureg(int_mask); ureg(fifo_ctl); ureg(fifo_stat); char __pad[0x50]; ureg(xmt_data8); ureg(xmt_data16); ureg(rcv_data8); ureg(rcv_data16); }; #undef ureg /* U-Boot I2C framework allows only one active device at a time. */ #ifdef TWI_CLKDIV #define TWI0_CLKDIV TWI_CLKDIV #endif static volatile struct twi_regs *twi = (void *)TWI0_CLKDIV; #ifdef DEBUG # define dmemset(s, c, n) memset(s, c, n) #else # define dmemset(s, c, n) #endif #define debugi(fmt, args...) \ debug( \ "MSTAT:0x%03x FSTAT:0x%x ISTAT:0x%02x\t%-20s:%-3i: " fmt "\n", \ twi->master_stat, twi->fifo_stat, twi->int_stat, \ __func__, __LINE__, ## args) #ifdef CONFIG_TWICLK_KHZ # error do not define CONFIG_TWICLK_KHZ ... use CONFIG_SYS_I2C_SPEED #endif /* * The way speed is changed into duty often results in integer truncation * with 50% duty, so we'll force rounding up to the next duty by adding 1 * to the max. In practice this will get us a speed of something like * 385 KHz. The other limit is easy to handle as it is only 8 bits. */ #define I2C_SPEED_MAX 400000 #define I2C_SPEED_TO_DUTY(speed) (5000000 / (speed)) #define I2C_DUTY_MAX (I2C_SPEED_TO_DUTY(I2C_SPEED_MAX) + 1) #define I2C_DUTY_MIN 0xff /* 8 bit limited */ #define SYS_I2C_DUTY I2C_SPEED_TO_DUTY(CONFIG_SYS_I2C_SPEED) /* Note: duty is inverse of speed, so the comparisons below are correct */ #if SYS_I2C_DUTY < I2C_DUTY_MAX || SYS_I2C_DUTY > I2C_DUTY_MIN # error "The Blackfin I2C hardware can only operate 20KHz - 400KHz" #endif /* All transfers are described by this data structure */ struct i2c_msg { u8 flags; #define I2C_M_COMBO 0x4 #define I2C_M_STOP 0x2 #define I2C_M_READ 0x1 int len; /* msg length */ u8 *buf; /* pointer to msg data */ int alen; /* addr length */ u8 *abuf; /* addr buffer */ }; /* Allow msec timeout per ~byte transfer */ #define I2C_TIMEOUT 10 /** * wait_for_completion - manage the actual i2c transfer * @msg: the i2c msg */ static int wait_for_completion(struct i2c_msg *msg) { uint16_t int_stat; ulong timebase = get_timer(0); do { int_stat = twi->int_stat; if (int_stat & XMTSERV) { debugi("processing XMTSERV"); twi->int_stat = XMTSERV; SSYNC(); if (msg->alen) { twi->xmt_data8 = *(msg->abuf++); --msg->alen; } else if (!(msg->flags & I2C_M_COMBO) && msg->len) { twi->xmt_data8 = *(msg->buf++); --msg->len; } else { twi->master_ctl |= (msg->flags & I2C_M_COMBO) ? RSTART | MDIR : STOP; SSYNC(); } } if (int_stat & RCVSERV) { debugi("processing RCVSERV"); twi->int_stat = RCVSERV; SSYNC(); if (msg->len) { *(msg->buf++) = twi->rcv_data8; --msg->len; } else if (msg->flags & I2C_M_STOP) { twi->master_ctl |= STOP; SSYNC(); } } if (int_stat & MERR) { debugi("processing MERR"); twi->int_stat = MERR; SSYNC(); return msg->len; } if (int_stat & MCOMP) { debugi("processing MCOMP"); twi->int_stat = MCOMP; SSYNC(); if (msg->flags & I2C_M_COMBO && msg->len) { twi->master_ctl = (twi->master_ctl & ~RSTART) | (min(msg->len, 0xff) << 6) | MEN | MDIR; SSYNC(); } else break; } /* If we were able to do something, reset timeout */ if (int_stat) timebase = get_timer(0); } while (get_timer(timebase) < I2C_TIMEOUT); return msg->len; } /** * i2c_transfer - setup an i2c transfer * @return: 0 if things worked, non-0 if things failed * * Here we just get the i2c stuff all prepped and ready, and then tail off * into wait_for_completion() for all the bits to go. */ static int i2c_transfer(uchar chip, uint addr, int alen, uchar *buffer, int len, u8 flags) { uchar addr_buffer[] = { (addr >> 0), (addr >> 8), (addr >> 16), }; struct i2c_msg msg = { .flags = flags | (len >= 0xff ? I2C_M_STOP : 0), .buf = buffer, .len = len, .abuf = addr_buffer, .alen = alen, }; int ret; dmemset(buffer, 0xff, len); debugi("chip=0x%x addr=0x%02x alen=%i buf[0]=0x%02x len=%i flags=0x%02x[%s] ", chip, addr, alen, buffer[0], len, flags, (flags & I2C_M_READ ? "rd" : "wr")); /* wait for things to settle */ while (twi->master_stat & BUSBUSY) if (ctrlc()) return 1; /* Set Transmit device address */ twi->master_addr = chip; /* Clear the FIFO before starting things */ twi->fifo_ctl = XMTFLUSH | RCVFLUSH; SSYNC(); twi->fifo_ctl = 0; SSYNC(); /* prime the pump */ if (msg.alen) { len = (msg.flags & I2C_M_COMBO) ? msg.alen : msg.alen + len; debugi("first byte=0x%02x", *msg.abuf); twi->xmt_data8 = *(msg.abuf++); --msg.alen; } else if (!(msg.flags & I2C_M_READ) && msg.len) { debugi("first byte=0x%02x", *msg.buf); twi->xmt_data8 = *(msg.buf++); --msg.len; } /* clear int stat */ twi->master_stat = -1; twi->int_stat = -1; twi->int_mask = 0; SSYNC(); /* Master enable */ twi->master_ctl = (twi->master_ctl & FAST) | (min(len, 0xff) << 6) | MEN | ((msg.flags & I2C_M_READ) ? MDIR : 0); SSYNC(); debugi("CTL=0x%04x", twi->master_ctl); /* process the rest */ ret = wait_for_completion(&msg); debugi("ret=%d", ret); if (ret) { twi->master_ctl &= ~MEN; twi->control &= ~TWI_ENA; SSYNC(); twi->control |= TWI_ENA; SSYNC(); } return ret; } /** * i2c_set_bus_speed - set i2c bus speed * @speed: bus speed (in HZ) */ int i2c_set_bus_speed(unsigned int speed) { u16 clkdiv = I2C_SPEED_TO_DUTY(speed); /* Set TWI interface clock */ if (clkdiv < I2C_DUTY_MAX || clkdiv > I2C_DUTY_MIN) return -1; twi->clkdiv = (clkdiv << 8) | (clkdiv & 0xff); /* Don't turn it on */ twi->master_ctl = (speed > 100000 ? FAST : 0); return 0; } /** * i2c_get_bus_speed - get i2c bus speed * @speed: bus speed (in HZ) */ unsigned int i2c_get_bus_speed(void) { /* 10 MHz / (2 * CLKDIV) -> 5 MHz / CLKDIV */ return 5000000 / (twi->clkdiv & 0xff); } /** * i2c_init - initialize the i2c bus * @speed: bus speed (in HZ) * @slaveaddr: address of device in slave mode (0 - not slave) * * Slave mode isn't actually implemented. It'll stay that way until * we get a real request for it. */ void i2c_init(int speed, int slaveaddr) { uint8_t prescale = ((get_sclk() / 1024 / 1024 + 5) / 10) & 0x7F; /* Set TWI internal clock as 10MHz */ twi->control = prescale; /* Set TWI interface clock as specified */ i2c_set_bus_speed(speed); /* Enable it */ twi->control = TWI_ENA | prescale; SSYNC(); debugi("CONTROL:0x%04x CLKDIV:0x%04x", twi->control, twi->clkdiv); #if CONFIG_SYS_I2C_SLAVE # error I2C slave support not tested/supported /* If they want us as a slave, do it */ if (slaveaddr) { twi->slave_addr = slaveaddr; twi->slave_ctl = SEN; } #endif } /** * i2c_probe - test if a chip exists at a given i2c address * @chip: i2c chip addr to search for * @return: 0 if found, non-0 if not found */ int i2c_probe(uchar chip) { u8 byte; return i2c_read(chip, 0, 0, &byte, 1); } /** * i2c_read - read data from an i2c device * @chip: i2c chip addr * @addr: memory (register) address in the chip * @alen: byte size of address * @buffer: buffer to store data read from chip * @len: how many bytes to read * @return: 0 on success, non-0 on failure */ int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { return i2c_transfer(chip, addr, alen, buffer, len, (alen ? I2C_M_COMBO : I2C_M_READ)); } /** * i2c_write - write data to an i2c device * @chip: i2c chip addr * @addr: memory (register) address in the chip * @alen: byte size of address * @buffer: buffer holding data to write to chip * @len: how many bytes to write * @return: 0 on success, non-0 on failure */ int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { return i2c_transfer(chip, addr, alen, buffer, len, 0); } /** * i2c_set_bus_num - change active I2C bus * @bus: bus index, zero based * @returns: 0 on success, non-0 on failure */ int i2c_set_bus_num(unsigned int bus) { switch (bus) { #if CONFIG_SYS_MAX_I2C_BUS > 0 case 0: twi = (void *)TWI0_CLKDIV; return 0; #endif #if CONFIG_SYS_MAX_I2C_BUS > 1 case 1: twi = (void *)TWI1_CLKDIV; return 0; #endif #if CONFIG_SYS_MAX_I2C_BUS > 2 case 2: twi = (void *)TWI2_CLKDIV; return 0; #endif default: return -1; } } /** * i2c_get_bus_num - returns index of active I2C bus */ unsigned int i2c_get_bus_num(void) { switch ((unsigned long)twi) { #if CONFIG_SYS_MAX_I2C_BUS > 0 case TWI0_CLKDIV: return 0; #endif #if CONFIG_SYS_MAX_I2C_BUS > 1 case TWI1_CLKDIV: return 1; #endif #if CONFIG_SYS_MAX_I2C_BUS > 2 case TWI2_CLKDIV: return 2; #endif default: return -1; } }
1001-study-uboot
drivers/i2c/bfin-twi_i2c.c
C
gpl3
9,110
/* * (C) Copyright 2004 * DAVE Srl * http://www.dave-tech.it * http://www.wawnet.biz * mailto:info@wawnet.biz * * 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 <asm/hardware.h> /* * Initialization, must be called once on start up, may be called * repeatedly to change the speed and slave addresses. */ void i2c_init(int speed, int slaveaddr) { /* setting up I2C support */ unsigned int save_F,save_PF,rIICCON,rPCONA,rPDATA,rPCONF,rPUPF; save_F = PCONF; save_PF = PUPF; rPCONF = ((save_F & ~(0xF))| 0xa); rPUPF = (save_PF | 0x3); PCONF = rPCONF; /*PF0:IICSCL, PF1:IICSDA*/ PUPF = rPUPF; /* Disable pull-up */ /* Configuring pin for WC pin of EEprom */ rPCONA = PCONA; rPCONA &= ~(1<<9); PCONA = rPCONA; rPDATA = PDATA; rPDATA &= ~(1<<9); PDATA = rPDATA; /* Enable ACK, IICCLK=MCLK/16, enable interrupt 75MHz/16/(12+1) = 390625 Hz */ rIICCON=(1<<7)|(0<<6)|(1<<5)|(0xC); IICCON = rIICCON; IICADD = slaveaddr; } /* * Probe the given I2C chip address. Returns 0 if a chip responded, * not 0 on failure. */ int i2c_probe(uchar chip) { /* not implemented */ printf("i2c_probe chip %d\n", (int) chip); return -1; } /* * Read/Write interface: * chip: I2C chip address, range 0..127 * addr: Memory (register) address within the chip * alen: Number of bytes to use for addr (typically 1, 2 for larger * memories, 0 for register type devices with only one * register) * buffer: Where to read/write the data * len: How many bytes to read/write * * Returns: 0 on success, not 0 on failure */ #define S3C44B0X_rIIC_INTPEND (1<<4) #define S3C44B0X_rIIC_LAST_RECEIV_BIT (1<<0) #define S3C44B0X_rIIC_INTERRUPT_ENABLE (1<<5) #define S3C44B0_IIC_TIMEOUT 100 int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { int k, j, temp; u32 rIICSTAT; /* send the device offset */ rIICSTAT = 0xD0; IICSTAT = rIICSTAT; IICDS = chip; /* this is a write operation... */ rIICSTAT |= (1<<5); IICSTAT = rIICSTAT; for(k=0; k<S3C44B0_IIC_TIMEOUT; k++) { temp = IICCON; if( (temp & S3C44B0X_rIIC_INTPEND) == S3C44B0X_rIIC_INTPEND) break; udelay(2000); } if (k==S3C44B0_IIC_TIMEOUT) return -1; /* wait and check ACK */ temp = IICSTAT; if ((temp & S3C44B0X_rIIC_LAST_RECEIV_BIT) == S3C44B0X_rIIC_LAST_RECEIV_BIT ) return -1; IICDS = addr; IICCON = IICCON & ~(S3C44B0X_rIIC_INTPEND); /* wait and check ACK */ for(k=0; k<S3C44B0_IIC_TIMEOUT; k++) { temp = IICCON; if( (temp & S3C44B0X_rIIC_INTPEND) == S3C44B0X_rIIC_INTPEND) break; udelay(2000); } if (k==S3C44B0_IIC_TIMEOUT) return -1; temp = IICSTAT; if ((temp & S3C44B0X_rIIC_LAST_RECEIV_BIT) == S3C44B0X_rIIC_LAST_RECEIV_BIT ) return -1; /* now we can start with the read operation... */ IICDS = chip | 0x01; /* this is a read operation... */ rIICSTAT = 0x90; /*master recv*/ rIICSTAT |= (1<<5); IICSTAT = rIICSTAT; IICCON = IICCON & ~(S3C44B0X_rIIC_INTPEND); /* wait and check ACK */ for(k=0; k<S3C44B0_IIC_TIMEOUT; k++) { temp = IICCON; if( (temp & S3C44B0X_rIIC_INTPEND) == S3C44B0X_rIIC_INTPEND) break; udelay(2000); } if (k==S3C44B0_IIC_TIMEOUT) return -1; temp = IICSTAT; if ((temp & S3C44B0X_rIIC_LAST_RECEIV_BIT) == S3C44B0X_rIIC_LAST_RECEIV_BIT ) return -1; for (j=0; j<len-1; j++) { /*clear pending bit to resume */ temp = IICCON & ~(S3C44B0X_rIIC_INTPEND); IICCON = temp; /* wait and check ACK */ for(k=0; k<S3C44B0_IIC_TIMEOUT; k++) { temp = IICCON; if( (temp & S3C44B0X_rIIC_INTPEND) == S3C44B0X_rIIC_INTPEND) break; udelay(2000); } if (k==S3C44B0_IIC_TIMEOUT) return -1; buffer[j] = IICDS; /*save readed data*/ } /*end for(j)*/ /* reading the last data unset ACK generation */ temp = IICCON & ~(S3C44B0X_rIIC_INTPEND | (1<<7)); IICCON = temp; /* wait but NOT check ACK */ for(k=0; k<S3C44B0_IIC_TIMEOUT; k++) { temp = IICCON; if( (temp & S3C44B0X_rIIC_INTPEND) == S3C44B0X_rIIC_INTPEND) break; udelay(2000); } if (k==S3C44B0_IIC_TIMEOUT) return -1; buffer[j] = IICDS; /*save readed data*/ rIICSTAT = 0x90; /*master recv*/ /* Write operation Terminate sending STOP */ IICSTAT = rIICSTAT; /*Clear Int Pending Bit to RESUME*/ temp = IICCON; IICCON = temp & (~S3C44B0X_rIIC_INTPEND); IICCON = IICCON | (1<<7); /*restore ACK generation*/ return 0; } int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { int j, k; u32 rIICSTAT, temp; /* send the device offset */ rIICSTAT = 0xD0; IICSTAT = rIICSTAT; IICDS = chip; /* this is a write operation... */ rIICSTAT |= (1<<5); IICSTAT = rIICSTAT; IICCON = IICCON & ~(S3C44B0X_rIIC_INTPEND); /* wait and check ACK */ for(k=0; k<S3C44B0_IIC_TIMEOUT; k++) { temp = IICCON; if( (temp & S3C44B0X_rIIC_INTPEND) == S3C44B0X_rIIC_INTPEND) break; udelay(2000); } if (k==S3C44B0_IIC_TIMEOUT) return -1; temp = IICSTAT; if ((temp & S3C44B0X_rIIC_LAST_RECEIV_BIT) == S3C44B0X_rIIC_LAST_RECEIV_BIT ) return -1; IICDS = addr; IICCON = IICCON & ~(S3C44B0X_rIIC_INTPEND); /* wait and check ACK */ for(k=0; k<S3C44B0_IIC_TIMEOUT; k++) { temp = IICCON; if( (temp & S3C44B0X_rIIC_INTPEND) == S3C44B0X_rIIC_INTPEND) break; udelay(2000); } if (k==S3C44B0_IIC_TIMEOUT) return -1; temp = IICSTAT; if ((temp & S3C44B0X_rIIC_LAST_RECEIV_BIT) == S3C44B0X_rIIC_LAST_RECEIV_BIT ) return -1; /* now we can start with the read write operation */ for (j=0; j<len; j++) { IICDS = buffer[j]; /*prerare data to write*/ /*clear pending bit to resume*/ temp = IICCON & ~(S3C44B0X_rIIC_INTPEND); IICCON = temp; /* wait but NOT check ACK */ for(k=0; k<S3C44B0_IIC_TIMEOUT; k++) { temp = IICCON; if( (temp & S3C44B0X_rIIC_INTPEND) == S3C44B0X_rIIC_INTPEND) break; udelay(2000); } if (k==S3C44B0_IIC_TIMEOUT) return -1; } /* end for(j) */ /* sending stop to terminate */ rIICSTAT = 0xD0; /*master send*/ IICSTAT = rIICSTAT; /*Clear Int Pending Bit to RESUME*/ temp = IICCON; IICCON = temp & (~S3C44B0X_rIIC_INTPEND); return 0; }
1001-study-uboot
drivers/i2c/s3c44b0_i2c.c
C
gpl3
6,912
/* * (C) Copyright 2000 * Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it * * (C) Copyright 2000 Sysgo Real-Time Solutions, GmbH <www.elinos.com> * Marius Groeger <mgroeger@sysgo.de> * * (C) Copyright 2003 Pengutronix e.K. * Robert Schwebel <r.schwebel@pengutronix.de> * * (C) Copyright 2011 Marvell Inc. * Lei Wen <leiwen@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 * * Back ported to the 8xx platform (from the 8260 platform) by * Murray.Jensen@cmst.csiro.au, 27-Jan-01. */ #include <common.h> #include <asm/io.h> #ifdef CONFIG_HARD_I2C #include <i2c.h> #include "mv_i2c.h" #ifdef DEBUG_I2C #define PRINTD(x) printf x #else #define PRINTD(x) #endif /* All transfers are described by this data structure */ struct i2c_msg { u8 condition; u8 acknack; u8 direction; u8 data; }; struct mv_i2c { u32 ibmr; u32 pad0; u32 idbr; u32 pad1; u32 icr; u32 pad2; u32 isr; u32 pad3; u32 isar; }; static struct mv_i2c *base; static void i2c_board_init(struct mv_i2c *base) { #ifdef CONFIG_SYS_I2C_INIT_BOARD u32 icr; /* * call board specific i2c bus reset routine before accessing the * environment, which might be in a chip on that bus. For details * about this problem see doc/I2C_Edge_Conditions. * * disable I2C controller first, otherwhise it thinks we want to * talk to the slave port... */ icr = readl(&base->icr); writel(readl(&base->icr) & ~(ICR_SCLE | ICR_IUE), &base->icr); i2c_init_board(); writel(icr, &base->icr); #endif } #ifdef CONFIG_I2C_MULTI_BUS static u32 i2c_regs[CONFIG_MV_I2C_NUM] = CONFIG_MV_I2C_REG; static unsigned int bus_initialized[CONFIG_MV_I2C_NUM]; static unsigned int current_bus; int i2c_set_bus_num(unsigned int bus) { if ((bus < 0) || (bus >= CONFIG_MV_I2C_NUM)) { printf("Bad bus: %d\n", bus); return -1; } base = (struct mv_i2c *)i2c_regs[bus]; current_bus = bus; if (!bus_initialized[current_bus]) { i2c_board_init(base); bus_initialized[current_bus] = 1; } return 0; } unsigned int i2c_get_bus_num(void) { return current_bus; } #endif /* * i2c_reset: - reset the host controller * */ static void i2c_reset(void) { writel(readl(&base->icr) & ~ICR_IUE, &base->icr); /* disable unit */ writel(readl(&base->icr) | ICR_UR, &base->icr); /* reset the unit */ udelay(100); writel(readl(&base->icr) & ~ICR_IUE, &base->icr); /* disable unit */ i2c_clk_enable(); writel(CONFIG_SYS_I2C_SLAVE, &base->isar); /* set our slave address */ writel(I2C_ICR_INIT, &base->icr); /* set control reg values */ writel(I2C_ISR_INIT, &base->isr); /* set clear interrupt bits */ writel(readl(&base->icr) | ICR_IUE, &base->icr); /* enable unit */ udelay(100); } /* * i2c_isr_set_cleared: - wait until certain bits of the I2C status register * are set and cleared * * @return: 1 in case of success, 0 means timeout (no match within 10 ms). */ static int i2c_isr_set_cleared(unsigned long set_mask, unsigned long cleared_mask) { int timeout = 1000, isr; do { isr = readl(&base->isr); udelay(10); if (timeout-- < 0) return 0; } while (((isr & set_mask) != set_mask) || ((isr & cleared_mask) != 0)); return 1; } /* * i2c_transfer: - Transfer one byte over the i2c bus * * This function can tranfer a byte over the i2c bus in both directions. * It is used by the public API functions. * * @return: 0: transfer successful * -1: message is empty * -2: transmit timeout * -3: ACK missing * -4: receive timeout * -5: illegal parameters * -6: bus is busy and couldn't be aquired */ int i2c_transfer(struct i2c_msg *msg) { int ret; if (!msg) goto transfer_error_msg_empty; switch (msg->direction) { case I2C_WRITE: /* check if bus is not busy */ if (!i2c_isr_set_cleared(0, ISR_IBB)) goto transfer_error_bus_busy; /* start transmission */ writel(readl(&base->icr) & ~ICR_START, &base->icr); writel(readl(&base->icr) & ~ICR_STOP, &base->icr); writel(msg->data, &base->idbr); if (msg->condition == I2C_COND_START) writel(readl(&base->icr) | ICR_START, &base->icr); if (msg->condition == I2C_COND_STOP) writel(readl(&base->icr) | ICR_STOP, &base->icr); if (msg->acknack == I2C_ACKNAK_SENDNAK) writel(readl(&base->icr) | ICR_ACKNAK, &base->icr); if (msg->acknack == I2C_ACKNAK_SENDACK) writel(readl(&base->icr) & ~ICR_ACKNAK, &base->icr); writel(readl(&base->icr) & ~ICR_ALDIE, &base->icr); writel(readl(&base->icr) | ICR_TB, &base->icr); /* transmit register empty? */ if (!i2c_isr_set_cleared(ISR_ITE, 0)) goto transfer_error_transmit_timeout; /* clear 'transmit empty' state */ writel(readl(&base->isr) | ISR_ITE, &base->isr); /* wait for ACK from slave */ if (msg->acknack == I2C_ACKNAK_WAITACK) if (!i2c_isr_set_cleared(0, ISR_ACKNAK)) goto transfer_error_ack_missing; break; case I2C_READ: /* check if bus is not busy */ if (!i2c_isr_set_cleared(0, ISR_IBB)) goto transfer_error_bus_busy; /* start receive */ writel(readl(&base->icr) & ~ICR_START, &base->icr); writel(readl(&base->icr) & ~ICR_STOP, &base->icr); if (msg->condition == I2C_COND_START) writel(readl(&base->icr) | ICR_START, &base->icr); if (msg->condition == I2C_COND_STOP) writel(readl(&base->icr) | ICR_STOP, &base->icr); if (msg->acknack == I2C_ACKNAK_SENDNAK) writel(readl(&base->icr) | ICR_ACKNAK, &base->icr); if (msg->acknack == I2C_ACKNAK_SENDACK) writel(readl(&base->icr) & ~ICR_ACKNAK, &base->icr); writel(readl(&base->icr) & ~ICR_ALDIE, &base->icr); writel(readl(&base->icr) | ICR_TB, &base->icr); /* receive register full? */ if (!i2c_isr_set_cleared(ISR_IRF, 0)) goto transfer_error_receive_timeout; msg->data = readl(&base->idbr); /* clear 'receive empty' state */ writel(readl(&base->isr) | ISR_IRF, &base->isr); break; default: goto transfer_error_illegal_param; } return 0; transfer_error_msg_empty: PRINTD(("i2c_transfer: error: 'msg' is empty\n")); ret = -1; goto i2c_transfer_finish; transfer_error_transmit_timeout: PRINTD(("i2c_transfer: error: transmit timeout\n")); ret = -2; goto i2c_transfer_finish; transfer_error_ack_missing: PRINTD(("i2c_transfer: error: ACK missing\n")); ret = -3; goto i2c_transfer_finish; transfer_error_receive_timeout: PRINTD(("i2c_transfer: error: receive timeout\n")); ret = -4; goto i2c_transfer_finish; transfer_error_illegal_param: PRINTD(("i2c_transfer: error: illegal parameters\n")); ret = -5; goto i2c_transfer_finish; transfer_error_bus_busy: PRINTD(("i2c_transfer: error: bus is busy\n")); ret = -6; goto i2c_transfer_finish; i2c_transfer_finish: PRINTD(("i2c_transfer: ISR: 0x%04x\n", readl(&base->isr))); i2c_reset(); return ret; } /* ------------------------------------------------------------------------ */ /* API Functions */ /* ------------------------------------------------------------------------ */ void i2c_init(int speed, int slaveaddr) { #ifdef CONFIG_I2C_MULTI_BUS current_bus = 0; base = (struct mv_i2c *)i2c_regs[current_bus]; #else base = (struct mv_i2c *)CONFIG_MV_I2C_REG; #endif i2c_board_init(base); } /* * i2c_probe: - Test if a chip answers for a given i2c address * * @chip: address of the chip which is searched for * @return: 0 if a chip was found, -1 otherwhise */ int i2c_probe(uchar chip) { struct i2c_msg msg; i2c_reset(); msg.condition = I2C_COND_START; msg.acknack = I2C_ACKNAK_WAITACK; msg.direction = I2C_WRITE; msg.data = (chip << 1) + 1; if (i2c_transfer(&msg)) return -1; msg.condition = I2C_COND_STOP; msg.acknack = I2C_ACKNAK_SENDNAK; msg.direction = I2C_READ; msg.data = 0x00; if (i2c_transfer(&msg)) return -1; return 0; } /* * i2c_read: - Read multiple bytes from an i2c device * * The higher level routines take into account that this function is only * called with len < page length of the device (see configuration file) * * @chip: address of the chip which is to be read * @addr: i2c data address within the chip * @alen: length of the i2c data address (1..2 bytes) * @buffer: where to write the data * @len: how much byte do we want to read * @return: 0 in case of success */ int i2c_read(uchar chip, uint addr, int alen, uchar *buffer, int len) { struct i2c_msg msg; u8 addr_bytes[3]; /* lowest...highest byte of data address */ PRINTD(("i2c_read(chip=0x%02x, addr=0x%02x, alen=0x%02x, " "len=0x%02x)\n", chip, addr, alen, len)); i2c_reset(); /* dummy chip address write */ PRINTD(("i2c_read: dummy chip address write\n")); msg.condition = I2C_COND_START; msg.acknack = I2C_ACKNAK_WAITACK; msg.direction = I2C_WRITE; msg.data = (chip << 1); msg.data &= 0xFE; if (i2c_transfer(&msg)) return -1; /* * send memory address bytes; * alen defines how much bytes we have to send. */ /*addr &= ((1 << CONFIG_SYS_EEPROM_PAGE_WRITE_BITS)-1); */ addr_bytes[0] = (u8)((addr >> 0) & 0x000000FF); addr_bytes[1] = (u8)((addr >> 8) & 0x000000FF); addr_bytes[2] = (u8)((addr >> 16) & 0x000000FF); while (--alen >= 0) { PRINTD(("i2c_read: send memory word address byte %1d\n", alen)); msg.condition = I2C_COND_NORMAL; msg.acknack = I2C_ACKNAK_WAITACK; msg.direction = I2C_WRITE; msg.data = addr_bytes[alen]; if (i2c_transfer(&msg)) return -1; } /* start read sequence */ PRINTD(("i2c_read: start read sequence\n")); msg.condition = I2C_COND_START; msg.acknack = I2C_ACKNAK_WAITACK; msg.direction = I2C_WRITE; msg.data = (chip << 1); msg.data |= 0x01; if (i2c_transfer(&msg)) return -1; /* read bytes; send NACK at last byte */ while (len--) { if (len == 0) { msg.condition = I2C_COND_STOP; msg.acknack = I2C_ACKNAK_SENDNAK; } else { msg.condition = I2C_COND_NORMAL; msg.acknack = I2C_ACKNAK_SENDACK; } msg.direction = I2C_READ; msg.data = 0x00; if (i2c_transfer(&msg)) return -1; *buffer = msg.data; PRINTD(("i2c_read: reading byte (0x%08x)=0x%02x\n", (unsigned int)buffer, *buffer)); buffer++; } i2c_reset(); return 0; } /* * i2c_write: - Write multiple bytes to an i2c device * * The higher level routines take into account that this function is only * called with len < page length of the device (see configuration file) * * @chip: address of the chip which is to be written * @addr: i2c data address within the chip * @alen: length of the i2c data address (1..2 bytes) * @buffer: where to find the data to be written * @len: how much byte do we want to read * @return: 0 in case of success */ int i2c_write(uchar chip, uint addr, int alen, uchar *buffer, int len) { struct i2c_msg msg; u8 addr_bytes[3]; /* lowest...highest byte of data address */ PRINTD(("i2c_write(chip=0x%02x, addr=0x%02x, alen=0x%02x, " "len=0x%02x)\n", chip, addr, alen, len)); i2c_reset(); /* chip address write */ PRINTD(("i2c_write: chip address write\n")); msg.condition = I2C_COND_START; msg.acknack = I2C_ACKNAK_WAITACK; msg.direction = I2C_WRITE; msg.data = (chip << 1); msg.data &= 0xFE; if (i2c_transfer(&msg)) return -1; /* * send memory address bytes; * alen defines how much bytes we have to send. */ addr_bytes[0] = (u8)((addr >> 0) & 0x000000FF); addr_bytes[1] = (u8)((addr >> 8) & 0x000000FF); addr_bytes[2] = (u8)((addr >> 16) & 0x000000FF); while (--alen >= 0) { PRINTD(("i2c_write: send memory word address\n")); msg.condition = I2C_COND_NORMAL; msg.acknack = I2C_ACKNAK_WAITACK; msg.direction = I2C_WRITE; msg.data = addr_bytes[alen]; if (i2c_transfer(&msg)) return -1; } /* write bytes; send NACK at last byte */ while (len--) { PRINTD(("i2c_write: writing byte (0x%08x)=0x%02x\n", (unsigned int)buffer, *buffer)); if (len == 0) msg.condition = I2C_COND_STOP; else msg.condition = I2C_COND_NORMAL; msg.acknack = I2C_ACKNAK_WAITACK; msg.direction = I2C_WRITE; msg.data = *(buffer++); if (i2c_transfer(&msg)) return -1; } i2c_reset(); return 0; } #endif /* CONFIG_HARD_I2C */
1001-study-uboot
drivers/i2c/mv_i2c.c
C
gpl3
12,867
/* * Copyright (C) ST-Ericsson SA 2009 * * 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 _U8500_I2C_H_ #define _U8500_I2C_H_ #include <asm/types.h> #include <asm/io.h> #include <asm/errno.h> #include <asm/arch/u8500.h> struct u8500_i2c_regs { u32 cr; /* Control Register 0x00 */ u32 scr; /* Slave Address Register 0x04 */ u32 hsmcr; /* HS Master code Register 0x08 */ u32 mcr; /* Master Control Register 0x0C */ u32 tfr; /* Transmit Fifo Register 0x10 */ u32 sr; /* Status Register 0x14 */ u32 rfr; /* Receiver Fifo Register 0x18 */ u32 tftr; /* Transmit Fifo Threshold Register 0x1C */ u32 rftr; /* Receiver Fifo Threshold Register 0x20 */ u32 dmar; /* DMA register 0x24 */ u32 brcr; /* Baud Rate Counter Register 0x28 */ u32 imscr; /* Interrupt Mask Set and Clear Register 0x2C */ u32 risr; /* Raw interrupt status register 0x30 */ u32 misr; /* Masked interrupt status register 0x34 */ u32 icr; /* Interrupt Set and Clear Register 0x38 */ u32 reserved_1[(0xFE0 - 0x3c) >> 2]; /* Reserved 0x03C to 0xFE0 */ u32 periph_id_0; /* peripheral ID 0 0xFE0 */ u32 periph_id_1; /* peripheral ID 1 0xFE4 */ u32 periph_id_2; /* peripheral ID 2 0xFE8 */ u32 periph_id_3; /* peripheral ID 3 0xFEC */ u32 cell_id_0; /* I2C cell ID 0 0xFF0 */ u32 cell_id_1; /* I2C cell ID 1 0xFF4 */ u32 cell_id_2; /* I2C cell ID 2 0xFF8 */ u32 cell_id_3; /* I2C cell ID 3 0xFFC */ }; /* Control Register */ /* Mask values for control register mask */ #define U8500_I2C_CR_PE 0x0001 /* Peripheral enable */ #define U8500_I2C_CR_OM 0x0006 /* Operation mode */ #define U8500_I2C_CR_SAM 0x0008 /* Slave Addressing mode */ #define U8500_I2C_CR_SM 0x0030 /* Speed mode */ #define U8500_I2C_CR_SGCM 0x0040 /* Slave General call mode */ #define U8500_I2C_CR_FTX 0x0080 /* Flush Transmit */ #define U8500_I2C_CR_FRX 0x0100 /* Flush Receive */ #define U8500_I2C_CR_DMA_TX_EN 0x0200 /* DMA TX Enable */ #define U8500_I2C_CR_DMA_RX_EN 0x0400 /* DMA Rx Enable */ #define U8500_I2C_CR_DMA_SLE 0x0800 /* DMA Synchronization Logic enable */ #define U8500_I2C_CR_LM 0x1000 /* Loop back mode */ #define U8500_I2C_CR_FON 0x6000 /* Filtering On */ /* shift valus for control register bit fields */ #define U8500_I2C_CR_SHIFT_PE 0 /* Peripheral enable */ #define U8500_I2C_CR_SHIFT_OM 1 /* Operation mode */ #define U8500_I2C_CR_SHIFT_SAM 3 /* Slave Addressing mode */ #define U8500_I2C_CR_SHIFT_SM 4 /* Speed mode */ #define U8500_I2C_CR_SHIFT_SGCM 6 /* Slave General call mode */ #define U8500_I2C_CR_SHIFT_FTX 7 /* Flush Transmit */ #define U8500_I2C_CR_SHIFT_FRX 8 /* Flush Receive */ #define U8500_I2C_CR_SHIFT_DMA_TX_EN 9 /* DMA TX Enable */ #define U8500_I2C_CR_SHIFT_DMA_RX_EN 10 /* DMA Rx Enable */ #define U8500_I2C_CR_SHIFT_DMA_SLE 11 /* DMA Synch Logic enable */ #define U8500_I2C_CR_SHIFT_LM 12 /* Loop back mode */ #define U8500_I2C_CR_SHIFT_FON 13 /* Filtering On */ /* bus operation modes */ #define U8500_I2C_BUS_SLAVE_MODE 0 #define U8500_I2C_BUS_MASTER_MODE 1 #define U8500_I2C_BUS_MASTER_SLAVE_MODE 2 /* Slave control register*/ /* Mask values slave control register */ #define U8500_I2C_SCR_ADDR 0x3FF #define U8500_I2C_SCR_DATA_SETUP_TIME 0xFFFF0000 /* Shift values for Slave control register */ #define U8500_I2C_SCR_SHIFT_ADDR 0 #define U8500_I2C_SCR_SHIFT_DATA_SETUP_TIME 16 /* Master Control Register */ /* Mask values for Master control register */ #define U8500_I2C_MCR_OP 0x00000001 /* Operation */ #define U8500_I2C_MCR_A7 0x000000FE /* LSB bits of Address */ #define U8500_I2C_MCR_EA10 0x00000700 /* Extended Address */ #define U8500_I2C_MCR_SB 0x00000800 /* Start byte procedure */ #define U8500_I2C_MCR_AM 0x00003000 /* Address type */ #define U8500_I2C_MCR_STOP 0x00004000 /* stop condition */ #define U8500_I2C_MCR_LENGTH 0x03FF8000 /* Frame length */ #define U8500_I2C_MCR_A10 0x000007FE /* Enable 10 bit address */ /* mask for length field,stop and operation */ #define U8500_I2C_MCR_LENGTH_STOP_OP 0x3FFC001 /* Shift values for Master control values */ #define U8500_I2C_MCR_SHIFT_OP 0 /* Operation */ #define U8500_I2C_MCR_SHIFT_A7 1 /* LSB bits of Address */ #define U8500_I2C_MCR_SHIFT_EA10 8 /* Extended Address */ #define U8500_I2C_MCR_SHIFT_SB 11 /* Start byte procedure */ #define U8500_I2C_MCR_SHIFT_AM 12 /* Address type */ #define U8500_I2C_MCR_SHIFT_STOP 14 /* stop condition */ #define U8500_I2C_MCR_SHIFT_LENGTH 15 /* Frame length */ #define U8500_I2C_MCR_SHIFT_A10 1 /* Enable 10 bit address */ #define U8500_I2C_MCR_SHIFT_LENGTH_STOP_OP 0 /* Status Register */ /* Mask values for Status register */ #define U8500_I2C_SR_OP 0x00000003 /* Operation */ #define U8500_I2C_SR_STATUS 0x0000000C /* Controller Status */ #define U8500_I2C_SR_CAUSE 0x00000070 /* Abort Cause */ #define U8500_I2C_SR_TYPE 0x00000180 /* Receive Type */ #define U8500_I2C_SR_LENGTH 0x000FF700 /* Transfer length */ /* Shift values for Status register */ #define U8500_I2C_SR_SHIFT_OP 0 /* Operation */ #define U8500_I2C_SR_SHIFT_STATUS 2 /* Controller Status */ #define U8500_I2C_SR_SHIFT_CAUSE 4 /* Abort Cause */ #define U8500_I2C_SR_SHIFT_TYPE 7 /* Receive Type */ #define U8500_I2C_SR_SHIFT_LENGTH 9 /* Transfer length */ /* abort cause */ #define U8500_I2C_NACK_ADDR 0 #define U8500_I2C_NACK_DATA 1 #define U8500_I2C_ACK_MCODE 2 #define U8500_I2C_ARB_LOST 3 #define U8500_I2C_BERR_START 4 #define U8500_I2C_BERR_STOP 5 #define U8500_I2C_OVFL 6 /* Baud rate counter registers */ /* Mask values for Baud rate counter register */ #define U8500_I2C_BRCR_BRCNT2 0xFFFF /* Baud Rate Cntr BRCR for HS */ #define U8500_I2C_BRCR_BRCNT1 0xFFFF0000 /* BRCR for Standard and Fast */ /* Shift values for the Baud rate counter register */ #define U8500_I2C_BRCR_SHIFT_BRCNT2 0 #define U8500_I2C_BRCR_SHIFT_BRCNT1 16 /* Interrupt Register */ /* Mask values for Interrupt registers */ #define U8500_I2C_INT_TXFE 0x00000001 /* Tx fifo empty */ #define U8500_I2C_INT_TXFNE 0x00000002 /* Tx Fifo nearly empty */ #define U8500_I2C_INT_TXFF 0x00000004 /* Tx Fifo Full */ #define U8500_I2C_INT_TXFOVR 0x00000008 /* Tx Fifo over run */ #define U8500_I2C_INT_RXFE 0x00000010 /* Rx Fifo Empty */ #define U8500_I2C_INT_RXFNF 0x00000020 /* Rx Fifo nearly empty */ #define U8500_I2C_INT_RXFF 0x00000040 /* Rx Fifo Full */ #define U8500_I2C_INT_RFSR 0x00010000 /* Read From slave request */ #define U8500_I2C_INT_RFSE 0x00020000 /* Read from slave empty */ #define U8500_I2C_INT_WTSR 0x00040000 /* Write to Slave request */ #define U8500_I2C_INT_MTD 0x00080000 /* Master Transcation Done*/ #define U8500_I2C_INT_STD 0x00100000 /* Slave Transaction Done */ #define U8500_I2C_INT_MAL 0x01000000 /* Master Arbitation Lost */ #define U8500_I2C_INT_BERR 0x02000000 /* Bus Error */ #define U8500_I2C_INT_MTDWS 0x10000000 /* Master Tran Done wo/ Stop */ /* Max clocks (Hz) */ #define U8500_I2C_MAX_STANDARD_SCL 100000 #define U8500_I2C_MAX_FAST_SCL 400000 #define U8500_I2C_MAX_HIGH_SPEED_SCL 3400000 #endif /* _U8500_I2C_H_ */
1001-study-uboot
drivers/i2c/u8500_i2c.h
C
gpl3
8,056
/* * Copyright 2006,2009 Freescale Semiconductor, Inc. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #ifdef CONFIG_HARD_I2C #include <command.h> #include <i2c.h> /* Functional interface */ #include <asm/io.h> #include <asm/fsl_i2c.h> /* HW definitions */ /* The maximum number of microseconds we will wait until another master has * released the bus. If not defined in the board header file, then use a * generic value. */ #ifndef CONFIG_I2C_MBB_TIMEOUT #define CONFIG_I2C_MBB_TIMEOUT 100000 #endif /* The maximum number of microseconds we will wait for a read or write * operation to complete. If not defined in the board header file, then use a * generic value. */ #ifndef CONFIG_I2C_TIMEOUT #define CONFIG_I2C_TIMEOUT 10000 #endif #define I2C_READ_BIT 1 #define I2C_WRITE_BIT 0 DECLARE_GLOBAL_DATA_PTR; /* Initialize the bus pointer to whatever one the SPD EEPROM is on. * Default is bus 0. This is necessary because the DDR initialization * runs from ROM, and we can't switch buses because we can't modify * the global variables. */ #ifndef CONFIG_SYS_SPD_BUS_NUM #define CONFIG_SYS_SPD_BUS_NUM 0 #endif static unsigned int i2c_bus_num __attribute__ ((section (".data"))) = CONFIG_SYS_SPD_BUS_NUM; #if defined(CONFIG_I2C_MUX) static unsigned int i2c_bus_num_mux __attribute__ ((section ("data"))) = 0; #endif static unsigned int i2c_bus_speed[2] = {CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SPEED}; static const struct fsl_i2c *i2c_dev[2] = { (struct fsl_i2c *) (CONFIG_SYS_IMMR + CONFIG_SYS_I2C_OFFSET), #ifdef CONFIG_SYS_I2C2_OFFSET (struct fsl_i2c *) (CONFIG_SYS_IMMR + CONFIG_SYS_I2C2_OFFSET) #endif }; /* I2C speed map for a DFSR value of 1 */ /* * Map I2C frequency dividers to FDR and DFSR values * * This structure is used to define the elements of a table that maps I2C * frequency divider (I2C clock rate divided by I2C bus speed) to a value to be * programmed into the Frequency Divider Ratio (FDR) and Digital Filter * Sampling Rate (DFSR) registers. * * The actual table should be defined in the board file, and it must be called * fsl_i2c_speed_map[]. * * The last entry of the table must have a value of {-1, X}, where X is same * FDR/DFSR values as the second-to-last entry. This guarantees that any * search through the array will always find a match. * * The values of the divider must be in increasing numerical order, i.e. * fsl_i2c_speed_map[x+1].divider > fsl_i2c_speed_map[x].divider. * * For this table, the values are based on a value of 1 for the DFSR * register. See the application note AN2919 "Determining the I2C Frequency * Divider Ratio for SCL" * * ColdFire I2C frequency dividers for FDR values are different from * PowerPC. The protocol to use the I2C module is still the same. * A different table is defined and are based on MCF5xxx user manual. * */ static const struct { unsigned short divider; u8 fdr; } fsl_i2c_speed_map[] = { #ifdef __M68K__ {20, 32}, {22, 33}, {24, 34}, {26, 35}, {28, 0}, {28, 36}, {30, 1}, {32, 37}, {34, 2}, {36, 38}, {40, 3}, {40, 39}, {44, 4}, {48, 5}, {48, 40}, {56, 6}, {56, 41}, {64, 42}, {68, 7}, {72, 43}, {80, 8}, {80, 44}, {88, 9}, {96, 41}, {104, 10}, {112, 42}, {128, 11}, {128, 43}, {144, 12}, {160, 13}, {160, 48}, {192, 14}, {192, 49}, {224, 50}, {240, 15}, {256, 51}, {288, 16}, {320, 17}, {320, 52}, {384, 18}, {384, 53}, {448, 54}, {480, 19}, {512, 55}, {576, 20}, {640, 21}, {640, 56}, {768, 22}, {768, 57}, {960, 23}, {896, 58}, {1024, 59}, {1152, 24}, {1280, 25}, {1280, 60}, {1536, 26}, {1536, 61}, {1792, 62}, {1920, 27}, {2048, 63}, {2304, 28}, {2560, 29}, {3072, 30}, {3840, 31}, {-1, 31} #endif }; /** * Set the I2C bus speed for a given I2C device * * @param dev: the I2C device * @i2c_clk: I2C bus clock frequency * @speed: the desired speed of the bus * * The I2C device must be stopped before calling this function. * * The return value is the actual bus speed that is set. */ static unsigned int set_i2c_bus_speed(const struct fsl_i2c *dev, unsigned int i2c_clk, unsigned int speed) { unsigned short divider = min(i2c_clk / speed, (unsigned short) -1); /* * We want to choose an FDR/DFSR that generates an I2C bus speed that * is equal to or lower than the requested speed. That means that we * want the first divider that is equal to or greater than the * calculated divider. */ #ifdef __PPC__ u8 dfsr, fdr = 0x31; /* Default if no FDR found */ /* a, b and dfsr matches identifiers A,B and C respectively in AN2919 */ unsigned short a, b, ga, gb; unsigned long c_div, est_div; #ifdef CONFIG_FSL_I2C_CUSTOM_DFSR dfsr = CONFIG_FSL_I2C_CUSTOM_DFSR; #else /* Condition 1: dfsr <= 50/T */ dfsr = (5 * (i2c_clk / 1000)) / 100000; #endif #ifdef CONFIG_FSL_I2C_CUSTOM_FDR fdr = CONFIG_FSL_I2C_CUSTOM_FDR; speed = i2c_clk / divider; /* Fake something */ #else debug("Requested speed:%d, i2c_clk:%d\n", speed, i2c_clk); if (!dfsr) dfsr = 1; est_div = ~0; for (ga = 0x4, a = 10; a <= 30; ga++, a += 2) { for (gb = 0; gb < 8; gb++) { b = 16 << gb; c_div = b * (a + ((3*dfsr)/b)*2); if ((c_div > divider) && (c_div < est_div)) { unsigned short bin_gb, bin_ga; est_div = c_div; bin_gb = gb << 2; bin_ga = (ga & 0x3) | ((ga & 0x4) << 3); fdr = bin_gb | bin_ga; speed = i2c_clk / est_div; debug("FDR:0x%.2x, div:%ld, ga:0x%x, gb:0x%x, " "a:%d, b:%d, speed:%d\n", fdr, est_div, ga, gb, a, b, speed); /* Condition 2 not accounted for */ debug("Tr <= %d ns\n", (b - 3 * dfsr) * 1000000 / (i2c_clk / 1000)); } } if (a == 20) a += 2; if (a == 24) a += 4; } debug("divider:%d, est_div:%ld, DFSR:%d\n", divider, est_div, dfsr); debug("FDR:0x%.2x, speed:%d\n", fdr, speed); #endif writeb(dfsr, &dev->dfsrr); /* set default filter */ writeb(fdr, &dev->fdr); /* set bus speed */ #else unsigned int i; for (i = 0; i < ARRAY_SIZE(fsl_i2c_speed_map); i++) if (fsl_i2c_speed_map[i].divider >= divider) { u8 fdr; fdr = fsl_i2c_speed_map[i].fdr; speed = i2c_clk / fsl_i2c_speed_map[i].divider; writeb(fdr, &dev->fdr); /* set bus speed */ break; } #endif return speed; } unsigned int get_i2c_clock(int bus) { if (bus) return gd->i2c2_clk; /* I2C2 clock */ else return gd->i2c1_clk; /* I2C1 clock */ } void i2c_init(int speed, int slaveadd) { const struct fsl_i2c *dev; unsigned int temp; int bus_num, i; #ifdef CONFIG_SYS_I2C_INIT_BOARD /* Call board specific i2c bus reset routine before accessing the * environment, which might be in a chip on that bus. For details * about this problem see doc/I2C_Edge_Conditions. */ i2c_init_board(); #endif #ifdef CONFIG_SYS_I2C2_OFFSET bus_num = 2; #else bus_num = 1; #endif for (i = 0; i < bus_num; i++) { dev = i2c_dev[i]; writeb(0, &dev->cr); /* stop I2C controller */ udelay(5); /* let it shutdown in peace */ temp = set_i2c_bus_speed(dev, get_i2c_clock(i), speed); if (gd->flags & GD_FLG_RELOC) i2c_bus_speed[i] = temp; writeb(slaveadd << 1, &dev->adr);/* write slave address */ writeb(0x0, &dev->sr); /* clear status register */ writeb(I2C_CR_MEN, &dev->cr); /* start I2C controller */ } #ifdef CONFIG_SYS_I2C_BOARD_LATE_INIT /* Call board specific i2c bus reset routine AFTER the bus has been * initialized. Use either this callpoint or i2c_init_board; * which is called before i2c_init operations. * For details about this problem see doc/I2C_Edge_Conditions. */ i2c_board_late_init(); #endif } static int i2c_wait4bus(void) { unsigned long long timeval = get_ticks(); const unsigned long long timeout = usec2ticks(CONFIG_I2C_MBB_TIMEOUT); while (readb(&i2c_dev[i2c_bus_num]->sr) & I2C_SR_MBB) { if ((get_ticks() - timeval) > timeout) return -1; } return 0; } static __inline__ int i2c_wait(int write) { u32 csr; unsigned long long timeval = get_ticks(); const unsigned long long timeout = usec2ticks(CONFIG_I2C_TIMEOUT); do { csr = readb(&i2c_dev[i2c_bus_num]->sr); if (!(csr & I2C_SR_MIF)) continue; /* Read again to allow register to stabilise */ csr = readb(&i2c_dev[i2c_bus_num]->sr); writeb(0x0, &i2c_dev[i2c_bus_num]->sr); if (csr & I2C_SR_MAL) { debug("i2c_wait: MAL\n"); return -1; } if (!(csr & I2C_SR_MCF)) { debug("i2c_wait: unfinished\n"); return -1; } if (write == I2C_WRITE_BIT && (csr & I2C_SR_RXAK)) { debug("i2c_wait: No RXACK\n"); return -1; } return 0; } while ((get_ticks() - timeval) < timeout); debug("i2c_wait: timed out\n"); return -1; } static __inline__ int i2c_write_addr (u8 dev, u8 dir, int rsta) { writeb(I2C_CR_MEN | I2C_CR_MSTA | I2C_CR_MTX | (rsta ? I2C_CR_RSTA : 0), &i2c_dev[i2c_bus_num]->cr); writeb((dev << 1) | dir, &i2c_dev[i2c_bus_num]->dr); if (i2c_wait(I2C_WRITE_BIT) < 0) return 0; return 1; } static __inline__ int __i2c_write(u8 *data, int length) { int i; for (i = 0; i < length; i++) { writeb(data[i], &i2c_dev[i2c_bus_num]->dr); if (i2c_wait(I2C_WRITE_BIT) < 0) break; } return i; } static __inline__ int __i2c_read(u8 *data, int length) { int i; writeb(I2C_CR_MEN | I2C_CR_MSTA | ((length == 1) ? I2C_CR_TXAK : 0), &i2c_dev[i2c_bus_num]->cr); /* dummy read */ readb(&i2c_dev[i2c_bus_num]->dr); for (i = 0; i < length; i++) { if (i2c_wait(I2C_READ_BIT) < 0) break; /* Generate ack on last next to last byte */ if (i == length - 2) writeb(I2C_CR_MEN | I2C_CR_MSTA | I2C_CR_TXAK, &i2c_dev[i2c_bus_num]->cr); /* Do not generate stop on last byte */ if (i == length - 1) writeb(I2C_CR_MEN | I2C_CR_MSTA | I2C_CR_MTX, &i2c_dev[i2c_bus_num]->cr); data[i] = readb(&i2c_dev[i2c_bus_num]->dr); } return i; } int i2c_read(u8 dev, uint addr, int alen, u8 *data, int length) { int i = -1; /* signal error */ u8 *a = (u8*)&addr; if (i2c_wait4bus() >= 0 && i2c_write_addr(dev, I2C_WRITE_BIT, 0) != 0 && __i2c_write(&a[4 - alen], alen) == alen) i = 0; /* No error so far */ if (length && i2c_write_addr(dev, I2C_READ_BIT, 1) != 0) i = __i2c_read(data, length); writeb(I2C_CR_MEN, &i2c_dev[i2c_bus_num]->cr); if (i2c_wait4bus()) /* Wait until STOP */ debug("i2c_read: wait4bus timed out\n"); if (i == length) return 0; return -1; } int i2c_write(u8 dev, uint addr, int alen, u8 *data, int length) { int i = -1; /* signal error */ u8 *a = (u8*)&addr; if (i2c_wait4bus() >= 0 && i2c_write_addr(dev, I2C_WRITE_BIT, 0) != 0 && __i2c_write(&a[4 - alen], alen) == alen) { i = __i2c_write(data, length); } writeb(I2C_CR_MEN, &i2c_dev[i2c_bus_num]->cr); if (i2c_wait4bus()) /* Wait until STOP */ debug("i2c_write: wait4bus timed out\n"); if (i == length) return 0; return -1; } int i2c_probe(uchar chip) { /* For unknow reason the controller will ACK when * probing for a slave with the same address, so skip * it. */ if (chip == (readb(&i2c_dev[i2c_bus_num]->adr) >> 1)) return -1; return i2c_read(chip, 0, 0, NULL, 0); } int i2c_set_bus_num(unsigned int bus) { #if defined(CONFIG_I2C_MUX) if (bus < CONFIG_SYS_MAX_I2C_BUS) { i2c_bus_num = bus; } else { int ret; ret = i2x_mux_select_mux(bus); if (ret) return ret; i2c_bus_num = 0; } i2c_bus_num_mux = bus; #else #ifdef CONFIG_SYS_I2C2_OFFSET if (bus > 1) { #else if (bus > 0) { #endif return -1; } i2c_bus_num = bus; #endif return 0; } int i2c_set_bus_speed(unsigned int speed) { unsigned int i2c_clk = (i2c_bus_num == 1) ? gd->i2c2_clk : gd->i2c1_clk; writeb(0, &i2c_dev[i2c_bus_num]->cr); /* stop controller */ i2c_bus_speed[i2c_bus_num] = set_i2c_bus_speed(i2c_dev[i2c_bus_num], i2c_clk, speed); writeb(I2C_CR_MEN, &i2c_dev[i2c_bus_num]->cr); /* start controller */ return 0; } unsigned int i2c_get_bus_num(void) { #if defined(CONFIG_I2C_MUX) return i2c_bus_num_mux; #else return i2c_bus_num; #endif } unsigned int i2c_get_bus_speed(void) { return i2c_bus_speed[i2c_bus_num]; } #endif /* CONFIG_HARD_I2C */
1001-study-uboot
drivers/i2c/fsl_i2c.c
C
gpl3
12,645
/* * (C) Copyright 2007-2009 * Stefan Roese, DENX Software Engineering, sr@denx.de. * * based on work by Anne Sophie Harnois <anne-sophie.harnois@nextream.fr> * * (C) Copyright 2001 * Bill Hunter, Wave 7 Optics, williamhunter@mediaone.net * * 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 <asm/ppc4xx.h> #include <asm/ppc4xx-i2c.h> #include <i2c.h> #include <asm/io.h> #ifdef CONFIG_HARD_I2C DECLARE_GLOBAL_DATA_PTR; #if defined(CONFIG_I2C_MULTI_BUS) /* * Initialize the bus pointer to whatever one the SPD EEPROM is on. * Default is bus 0. This is necessary because the DDR initialization * runs from ROM, and we can't switch buses because we can't modify * the global variables. */ #ifndef CONFIG_SYS_SPD_BUS_NUM #define CONFIG_SYS_SPD_BUS_NUM 0 #endif static unsigned int i2c_bus_num __attribute__ ((section (".data"))) = CONFIG_SYS_SPD_BUS_NUM; #endif /* CONFIG_I2C_MULTI_BUS */ static void _i2c_bus_reset(void) { struct ppc4xx_i2c *i2c = (struct ppc4xx_i2c *)I2C_BASE_ADDR; int i; u8 dc; /* Reset status register */ /* write 1 in SCMP and IRQA to clear these fields */ out_8(&i2c->sts, 0x0A); /* write 1 in IRQP IRQD LA ICT XFRA to clear these fields */ out_8(&i2c->extsts, 0x8F); /* Place chip in the reset state */ out_8(&i2c->xtcntlss, IIC_XTCNTLSS_SRST); /* Check if bus is free */ dc = in_8(&i2c->directcntl); if (!DIRCTNL_FREE(dc)){ /* Try to set bus free state */ out_8(&i2c->directcntl, IIC_DIRCNTL_SDAC | IIC_DIRCNTL_SCC); /* Wait until we regain bus control */ for (i = 0; i < 100; ++i) { dc = in_8(&i2c->directcntl); if (DIRCTNL_FREE(dc)) break; /* Toggle SCL line */ dc ^= IIC_DIRCNTL_SCC; out_8(&i2c->directcntl, dc); udelay(10); dc ^= IIC_DIRCNTL_SCC; out_8(&i2c->directcntl, dc); } } /* Remove reset */ out_8(&i2c->xtcntlss, 0); } void i2c_init(int speed, int slaveaddr) { struct ppc4xx_i2c *i2c; int val, divisor; int bus; #ifdef CONFIG_SYS_I2C_INIT_BOARD /* * Call board specific i2c bus reset routine before accessing the * environment, which might be in a chip on that bus. For details * about this problem see doc/I2C_Edge_Conditions. */ i2c_init_board(); #endif for (bus = 0; bus < CONFIG_SYS_MAX_I2C_BUS; bus++) { I2C_SET_BUS(bus); /* Set i2c pointer after calling I2C_SET_BUS() */ i2c = (struct ppc4xx_i2c *)I2C_BASE_ADDR; /* Handle possible failed I2C state */ /* FIXME: put this into i2c_init_board()? */ _i2c_bus_reset(); /* clear lo master address */ out_8(&i2c->lmadr, 0); /* clear hi master address */ out_8(&i2c->hmadr, 0); /* clear lo slave address */ out_8(&i2c->lsadr, 0); /* clear hi slave address */ out_8(&i2c->hsadr, 0); /* Clock divide Register */ /* set divisor according to freq_opb */ divisor = (get_OPB_freq() - 1) / 10000000; if (divisor == 0) divisor = 1; out_8(&i2c->clkdiv, divisor); /* no interrupts */ out_8(&i2c->intrmsk, 0); /* clear transfer count */ out_8(&i2c->xfrcnt, 0); /* clear extended control & stat */ /* write 1 in SRC SRS SWC SWS to clear these fields */ out_8(&i2c->xtcntlss, 0xF0); /* Mode Control Register Flush Slave/Master data buffer */ out_8(&i2c->mdcntl, IIC_MDCNTL_FSDB | IIC_MDCNTL_FMDB); val = in_8(&i2c->mdcntl); /* Ignore General Call, slave transfers are ignored, * disable interrupts, exit unknown bus state, enable hold * SCL 100kHz normaly or FastMode for 400kHz and above */ val |= IIC_MDCNTL_EUBS | IIC_MDCNTL_HSCL; if (speed >= 400000) val |= IIC_MDCNTL_FSM; out_8(&i2c->mdcntl, val); /* clear control reg */ out_8(&i2c->cntl, 0x00); } /* set to SPD bus as default bus upon powerup */ I2C_SET_BUS(CONFIG_SYS_SPD_BUS_NUM); } /* * This code tries to use the features of the 405GP i2c * controller. It will transfer up to 4 bytes in one pass * on the loop. It only does out_8((u8 *)lbz) to the buffer when it * is possible to do out16(lhz) transfers. * * cmd_type is 0 for write 1 for read. * * addr_len can take any value from 0-255, it is only limited * by the char, we could make it larger if needed. If it is * 0 we skip the address write cycle. * * Typical case is a Write of an addr followd by a Read. The * IBM FAQ does not cover this. On the last byte of the write * we don't set the creg CHT bit, and on the first bytes of the * read we set the RPST bit. * * It does not support address only transfers, there must be * a data part. If you want to write the address yourself, put * it in the data pointer. * * It does not support transfer to/from address 0. * * It does not check XFRCNT. */ static int i2c_transfer(unsigned char cmd_type, unsigned char chip, unsigned char addr[], unsigned char addr_len, unsigned char data[], unsigned short data_len) { struct ppc4xx_i2c *i2c = (struct ppc4xx_i2c *)I2C_BASE_ADDR; u8 *ptr; int reading; int tran, cnt; int result; int status; int i; u8 creg; if (data == 0 || data_len == 0) { /* Don't support data transfer of no length or to address 0 */ printf( "i2c_transfer: bad call\n" ); return IIC_NOK; } if (addr && addr_len) { ptr = addr; cnt = addr_len; reading = 0; } else { ptr = data; cnt = data_len; reading = cmd_type; } /* Clear Stop Complete Bit */ out_8(&i2c->sts, IIC_STS_SCMP); /* Check init */ i = 10; do { /* Get status */ status = in_8(&i2c->sts); i--; } while ((status & IIC_STS_PT) && (i > 0)); if (status & IIC_STS_PT) { result = IIC_NOK_TOUT; return(result); } /* flush the Master/Slave Databuffers */ out_8(&i2c->mdcntl, in_8(&i2c->mdcntl) | IIC_MDCNTL_FMDB | IIC_MDCNTL_FSDB); /* need to wait 4 OPB clocks? code below should take that long */ /* 7-bit adressing */ out_8(&i2c->hmadr, 0); out_8(&i2c->lmadr, chip); tran = 0; result = IIC_OK; creg = 0; while (tran != cnt && (result == IIC_OK)) { int bc,j; /* * Control register = * Normal transfer, 7-bits adressing, Transfer up to * bc bytes, Normal start, Transfer is a sequence of transfers */ creg |= IIC_CNTL_PT; bc = (cnt - tran) > 4 ? 4 : cnt - tran; creg |= (bc - 1) << 4; /* if the real cmd type is write continue trans */ if ((!cmd_type && (ptr == addr)) || ((tran + bc) != cnt)) creg |= IIC_CNTL_CHT; if (reading) { creg |= IIC_CNTL_READ; } else { for(j = 0; j < bc; j++) { /* Set buffer */ out_8(&i2c->mdbuf, ptr[tran + j]); } } out_8(&i2c->cntl, creg); /* * Transfer is in progress * we have to wait for upto 5 bytes of data * 1 byte chip address+r/w bit then bc bytes * of data. * udelay(10) is 1 bit time at 100khz * Doubled for slop. 20 is too small. */ i = 2 * 5 * 8; do { /* Get status */ status = in_8(&i2c->sts); udelay(10); i--; } while ((status & IIC_STS_PT) && !(status & IIC_STS_ERR) && (i > 0)); if (status & IIC_STS_ERR) { result = IIC_NOK; status = in_8(&i2c->extsts); /* Lost arbitration? */ if (status & IIC_EXTSTS_LA) result = IIC_NOK_LA; /* Incomplete transfer? */ if (status & IIC_EXTSTS_ICT) result = IIC_NOK_ICT; /* Transfer aborted? */ if (status & IIC_EXTSTS_XFRA) result = IIC_NOK_XFRA; } else if ( status & IIC_STS_PT) { result = IIC_NOK_TOUT; } /* Command is reading => get buffer */ if ((reading) && (result == IIC_OK)) { /* Are there data in buffer */ if (status & IIC_STS_MDBS) { /* * even if we have data we have to wait 4OPB * clocks for it to hit the front of the FIFO, * after that we can just read. We should check * XFCNT here and if the FIFO is full there is * no need to wait. */ udelay(1); for (j = 0; j < bc; j++) ptr[tran + j] = in_8(&i2c->mdbuf); } else result = IIC_NOK_DATA; } creg = 0; tran += bc; if (ptr == addr && tran == cnt) { ptr = data; cnt = data_len; tran = 0; reading = cmd_type; if (reading) creg = IIC_CNTL_RPST; } } return result; } int i2c_probe(uchar chip) { uchar buf[1]; buf[0] = 0; /* * What is needed is to send the chip address and verify that the * address was <ACK>ed (i.e. there was a chip at that address which * drove the data line low). */ return (i2c_transfer(1, chip << 1, 0, 0, buf, 1) != 0); } static int ppc4xx_i2c_transfer(uchar chip, uint addr, int alen, uchar *buffer, int len, int read) { uchar xaddr[4]; int ret; if (alen > 4) { printf("I2C: addr len %d not supported\n", alen); return 1; } if (alen > 0) { xaddr[0] = (addr >> 24) & 0xFF; xaddr[1] = (addr >> 16) & 0xFF; xaddr[2] = (addr >> 8) & 0xFF; xaddr[3] = addr & 0xFF; } #ifdef CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW /* * EEPROM chips that implement "address overflow" are ones * like Catalyst 24WC04/08/16 which has 9/10/11 bits of * address and the extra bits end up in the "chip address" * bit slots. This makes a 24WC08 (1Kbyte) chip look like * four 256 byte chips. * * Note that we consider the length of the address field to * still be one byte because the extra address bits are * hidden in the chip address. */ if (alen > 0) chip |= ((addr >> (alen * 8)) & CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW); #endif if ((ret = i2c_transfer(read, chip << 1, &xaddr[4 - alen], alen, buffer, len)) != 0) { printf("I2C %s: failed %d\n", read ? "read" : "write", ret); return 1; } return 0; } int i2c_read(uchar chip, uint addr, int alen, uchar * buffer, int len) { return ppc4xx_i2c_transfer(chip, addr, alen, buffer, len, 1); } int i2c_write(uchar chip, uint addr, int alen, uchar * buffer, int len) { return ppc4xx_i2c_transfer(chip, addr, alen, buffer, len, 0); } #if defined(CONFIG_I2C_MULTI_BUS) /* * Functions for multiple I2C bus handling */ unsigned int i2c_get_bus_num(void) { return i2c_bus_num; } int i2c_set_bus_num(unsigned int bus) { if (bus >= CONFIG_SYS_MAX_I2C_BUS) return -1; i2c_bus_num = bus; return 0; } #endif /* CONFIG_I2C_MULTI_BUS */ #endif /* CONFIG_HARD_I2C */
1001-study-uboot
drivers/i2c/ppc4xx_i2c.c
C
gpl3
10,779
/* * (C) Copyright 2004-2010 * Texas Instruments, <www.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 */ #ifndef _OMAP2PLUS_I2C_H_ #define _OMAP2PLUS_I2C_H_ /* I2C masks */ /* I2C Interrupt Enable Register (I2C_IE): */ #define I2C_IE_GC_IE (1 << 5) #define I2C_IE_XRDY_IE (1 << 4) /* Transmit data ready interrupt enable */ #define I2C_IE_RRDY_IE (1 << 3) /* Receive data ready interrupt enable */ #define I2C_IE_ARDY_IE (1 << 2) /* Register access ready interrupt enable */ #define I2C_IE_NACK_IE (1 << 1) /* No acknowledgment interrupt enable */ #define I2C_IE_AL_IE (1 << 0) /* Arbitration lost interrupt enable */ /* I2C Status Register (I2C_STAT): */ #define I2C_STAT_SBD (1 << 15) /* Single byte data */ #define I2C_STAT_BB (1 << 12) /* Bus busy */ #define I2C_STAT_ROVR (1 << 11) /* Receive overrun */ #define I2C_STAT_XUDF (1 << 10) /* Transmit underflow */ #define I2C_STAT_AAS (1 << 9) /* Address as slave */ #define I2C_STAT_GC (1 << 5) #define I2C_STAT_XRDY (1 << 4) /* Transmit data ready */ #define I2C_STAT_RRDY (1 << 3) /* Receive data ready */ #define I2C_STAT_ARDY (1 << 2) /* Register access ready */ #define I2C_STAT_NACK (1 << 1) /* No acknowledgment interrupt enable */ #define I2C_STAT_AL (1 << 0) /* Arbitration lost interrupt enable */ /* I2C Interrupt Code Register (I2C_INTCODE): */ #define I2C_INTCODE_MASK 7 #define I2C_INTCODE_NONE 0 #define I2C_INTCODE_AL 1 /* Arbitration lost */ #define I2C_INTCODE_NAK 2 /* No acknowledgement/general call */ #define I2C_INTCODE_ARDY 3 /* Register access ready */ #define I2C_INTCODE_RRDY 4 /* Rcv data ready */ #define I2C_INTCODE_XRDY 5 /* Xmit data ready */ /* I2C Buffer Configuration Register (I2C_BUF): */ #define I2C_BUF_RDMA_EN (1 << 15) /* Receive DMA channel enable */ #define I2C_BUF_XDMA_EN (1 << 7) /* Transmit DMA channel enable */ /* I2C Configuration Register (I2C_CON): */ #define I2C_CON_EN (1 << 15) /* I2C module enable */ #define I2C_CON_BE (1 << 14) /* Big endian mode */ #define I2C_CON_STB (1 << 11) /* Start byte mode (master mode only) */ #define I2C_CON_MST (1 << 10) /* Master/slave mode */ #define I2C_CON_TRX (1 << 9) /* Transmitter/receiver mode */ /* (master mode only) */ #define I2C_CON_XA (1 << 8) /* Expand address */ #define I2C_CON_STP (1 << 1) /* Stop condition (master mode only) */ #define I2C_CON_STT (1 << 0) /* Start condition (master mode only) */ /* I2C System Test Register (I2C_SYSTEST): */ #define I2C_SYSTEST_ST_EN (1 << 15) /* System test enable */ #define I2C_SYSTEST_FREE (1 << 14) /* Free running mode, on brkpoint) */ #define I2C_SYSTEST_TMODE_MASK (3 << 12) /* Test mode select */ #define I2C_SYSTEST_TMODE_SHIFT (12) /* Test mode select */ #define I2C_SYSTEST_SCL_I (1 << 3) /* SCL line sense input value */ #define I2C_SYSTEST_SCL_O (1 << 2) /* SCL line drive output value */ #define I2C_SYSTEST_SDA_I (1 << 1) /* SDA line sense input value */ #define I2C_SYSTEST_SDA_O (1 << 0) /* SDA line drive output value */ /* I2C System Status Register (I2C_SYSS): */ #define I2C_SYSS_RDONE (1 << 0) /* Internel reset monitoring */ #define I2C_SCLL_SCLL 0 #define I2C_SCLL_SCLL_M 0xFF #define I2C_SCLL_HSSCLL 8 #define I2C_SCLH_HSSCLL_M 0xFF #define I2C_SCLH_SCLH 0 #define I2C_SCLH_SCLH_M 0xFF #define I2C_SCLH_HSSCLH 8 #define I2C_SCLH_HSSCLH_M 0xFF #define OMAP_I2C_STANDARD 100000 #define OMAP_I2C_FAST_MODE 400000 #define OMAP_I2C_HIGH_SPEED 3400000 #define SYSTEM_CLOCK_12 12000000 #define SYSTEM_CLOCK_13 13000000 #define SYSTEM_CLOCK_192 19200000 #define SYSTEM_CLOCK_96 96000000 /* Use the reference value of 96MHz if not explicitly set by the board */ #ifndef I2C_IP_CLK #define I2C_IP_CLK SYSTEM_CLOCK_96 #endif /* * The reference minimum clock for high speed is 19.2MHz. * The linux 2.6.30 kernel uses this value. * The reference minimum clock for fast mode is 9.6MHz * The reference minimum clock for standard mode is 4MHz * In TRM, the value of 12MHz is used. */ #ifndef I2C_INTERNAL_SAMPLING_CLK #define I2C_INTERNAL_SAMPLING_CLK 19200000 #endif /* * The equation for the low and high time is * tlow = scll + scll_trim = (sampling clock * tlow_duty) / speed * thigh = sclh + sclh_trim = (sampling clock * (1 - tlow_duty)) / speed * * If the duty cycle is 50% * * tlow = scll + scll_trim = sampling clock / (2 * speed) * thigh = sclh + sclh_trim = sampling clock / (2 * speed) * * In TRM * scll_trim = 7 * sclh_trim = 5 * * The linux 2.6.30 kernel uses * scll_trim = 6 * sclh_trim = 6 * * These are the trim values for standard and fast speed */ #ifndef I2C_FASTSPEED_SCLL_TRIM #define I2C_FASTSPEED_SCLL_TRIM 6 #endif #ifndef I2C_FASTSPEED_SCLH_TRIM #define I2C_FASTSPEED_SCLH_TRIM 6 #endif /* These are the trim values for high speed */ #ifndef I2C_HIGHSPEED_PHASE_ONE_SCLL_TRIM #define I2C_HIGHSPEED_PHASE_ONE_SCLL_TRIM I2C_FASTSPEED_SCLL_TRIM #endif #ifndef I2C_HIGHSPEED_PHASE_ONE_SCLH_TRIM #define I2C_HIGHSPEED_PHASE_ONE_SCLH_TRIM I2C_FASTSPEED_SCLH_TRIM #endif #ifndef I2C_HIGHSPEED_PHASE_TWO_SCLL_TRIM #define I2C_HIGHSPEED_PHASE_TWO_SCLL_TRIM I2C_FASTSPEED_SCLL_TRIM #endif #ifndef I2C_HIGHSPEED_PHASE_TWO_SCLH_TRIM #define I2C_HIGHSPEED_PHASE_TWO_SCLH_TRIM I2C_FASTSPEED_SCLH_TRIM #endif #define I2C_PSC_MAX 0x0f #define I2C_PSC_MIN 0x00 #endif /* _OMAP24XX_I2C_H_ */
1001-study-uboot
drivers/i2c/omap24xx_i2c.h
C
gpl3
6,075
/* * Porting to u-boot: * * (C) Copyright 2010 * Stefano Babic, DENX Software Engineering, sbabic@denx.de * * Linux IPU driver for MX51: * * (C) Copyright 2005-2010 Freescale Semiconductor, Inc. * * 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 */ /* #define DEBUG */ #include <common.h> #include <linux/types.h> #include <linux/err.h> #include <asm/io.h> #include <asm/errno.h> #include <asm/arch/imx-regs.h> #include <asm/arch/crm_regs.h> #include "ipu.h" #include "ipu_regs.h" extern struct mxc_ccm_reg *mxc_ccm; extern u32 *ipu_cpmem_base; struct ipu_ch_param_word { uint32_t data[5]; uint32_t res[3]; }; struct ipu_ch_param { struct ipu_ch_param_word word[2]; }; #define ipu_ch_param_addr(ch) (((struct ipu_ch_param *)ipu_cpmem_base) + (ch)) #define _param_word(base, w) \ (((struct ipu_ch_param *)(base))->word[(w)].data) #define ipu_ch_param_set_field(base, w, bit, size, v) { \ int i = (bit) / 32; \ int off = (bit) % 32; \ _param_word(base, w)[i] |= (v) << off; \ if (((bit) + (size) - 1) / 32 > i) { \ _param_word(base, w)[i + 1] |= (v) >> (off ? (32 - off) : 0); \ } \ } #define ipu_ch_param_mod_field(base, w, bit, size, v) { \ int i = (bit) / 32; \ int off = (bit) % 32; \ u32 mask = (1UL << size) - 1; \ u32 temp = _param_word(base, w)[i]; \ temp &= ~(mask << off); \ _param_word(base, w)[i] = temp | (v) << off; \ if (((bit) + (size) - 1) / 32 > i) { \ temp = _param_word(base, w)[i + 1]; \ temp &= ~(mask >> (32 - off)); \ _param_word(base, w)[i + 1] = \ temp | ((v) >> (off ? (32 - off) : 0)); \ } \ } #define ipu_ch_param_read_field(base, w, bit, size) ({ \ u32 temp2; \ int i = (bit) / 32; \ int off = (bit) % 32; \ u32 mask = (1UL << size) - 1; \ u32 temp1 = _param_word(base, w)[i]; \ temp1 = mask & (temp1 >> off); \ if (((bit)+(size) - 1) / 32 > i) { \ temp2 = _param_word(base, w)[i + 1]; \ temp2 &= mask >> (off ? (32 - off) : 0); \ temp1 |= temp2 << (off ? (32 - off) : 0); \ } \ temp1; \ }) void clk_enable(struct clk *clk) { if (clk) { if (clk->usecount++ == 0) { clk->enable(clk); } } } void clk_disable(struct clk *clk) { if (clk) { if (!(--clk->usecount)) { if (clk->disable) clk->disable(clk); } } } int clk_get_usecount(struct clk *clk) { if (clk == NULL) return 0; return clk->usecount; } u32 clk_get_rate(struct clk *clk) { if (!clk) return 0; return clk->rate; } struct clk *clk_get_parent(struct clk *clk) { if (!clk) return 0; return clk->parent; } int clk_set_rate(struct clk *clk, unsigned long rate) { if (clk && clk->set_rate) clk->set_rate(clk, rate); return clk->rate; } long clk_round_rate(struct clk *clk, unsigned long rate) { if (clk == NULL || !clk->round_rate) return 0; return clk->round_rate(clk, rate); } int clk_set_parent(struct clk *clk, struct clk *parent) { clk->parent = parent; if (clk->set_parent) return clk->set_parent(clk, parent); return 0; } static int clk_ipu_enable(struct clk *clk) { u32 reg; reg = __raw_readl(clk->enable_reg); reg |= MXC_CCM_CCGR_CG_MASK << clk->enable_shift; __raw_writel(reg, clk->enable_reg); /* Handshake with IPU when certain clock rates are changed. */ reg = __raw_readl(&mxc_ccm->ccdr); reg &= ~MXC_CCM_CCDR_IPU_HS_MASK; __raw_writel(reg, &mxc_ccm->ccdr); /* Handshake with IPU when LPM is entered as its enabled. */ reg = __raw_readl(&mxc_ccm->clpcr); reg &= ~MXC_CCM_CLPCR_BYPASS_IPU_LPM_HS; __raw_writel(reg, &mxc_ccm->clpcr); return 0; } static void clk_ipu_disable(struct clk *clk) { u32 reg; reg = __raw_readl(clk->enable_reg); reg &= ~(MXC_CCM_CCGR_CG_MASK << clk->enable_shift); __raw_writel(reg, clk->enable_reg); /* * No handshake with IPU whe dividers are changed * as its not enabled. */ reg = __raw_readl(&mxc_ccm->ccdr); reg |= MXC_CCM_CCDR_IPU_HS_MASK; __raw_writel(reg, &mxc_ccm->ccdr); /* No handshake with IPU when LPM is entered as its not enabled. */ reg = __raw_readl(&mxc_ccm->clpcr); reg |= MXC_CCM_CLPCR_BYPASS_IPU_LPM_HS; __raw_writel(reg, &mxc_ccm->clpcr); } static struct clk ipu_clk = { .name = "ipu_clk", .rate = 133000000, .enable_reg = (u32 *)(MXC_CCM_BASE + offsetof(struct mxc_ccm_reg, CCGR5)), .enable_shift = MXC_CCM_CCGR5_CG5_OFFSET, .enable = clk_ipu_enable, .disable = clk_ipu_disable, .usecount = 0, }; /* Globals */ struct clk *g_ipu_clk; unsigned char g_ipu_clk_enabled; struct clk *g_di_clk[2]; struct clk *g_pixel_clk[2]; unsigned char g_dc_di_assignment[10]; uint32_t g_channel_init_mask; uint32_t g_channel_enable_mask; static int ipu_dc_use_count; static int ipu_dp_use_count; static int ipu_dmfc_use_count; static int ipu_di_use_count[2]; u32 *ipu_cpmem_base; u32 *ipu_dc_tmpl_reg; /* Static functions */ static inline void ipu_ch_param_set_high_priority(uint32_t ch) { ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 93, 2, 1); }; static inline uint32_t channel_2_dma(ipu_channel_t ch, ipu_buffer_t type) { return ((uint32_t) ch >> (6 * type)) & 0x3F; }; /* Either DP BG or DP FG can be graphic window */ static inline int ipu_is_dp_graphic_chan(uint32_t dma_chan) { return (dma_chan == 23 || dma_chan == 27); } static inline int ipu_is_dmfc_chan(uint32_t dma_chan) { return ((dma_chan >= 23) && (dma_chan <= 29)); } static inline void ipu_ch_param_set_buffer(uint32_t ch, int bufNum, dma_addr_t phyaddr) { ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 29 * bufNum, 29, phyaddr / 8); }; #define idma_is_valid(ch) (ch != NO_DMA) #define idma_mask(ch) (idma_is_valid(ch) ? (1UL << (ch & 0x1F)) : 0) #define idma_is_set(reg, dma) (__raw_readl(reg(dma)) & idma_mask(dma)) static void ipu_pixel_clk_recalc(struct clk *clk) { u32 div = __raw_readl(DI_BS_CLKGEN0(clk->id)); if (div == 0) clk->rate = 0; else clk->rate = (clk->parent->rate * 16) / div; } static unsigned long ipu_pixel_clk_round_rate(struct clk *clk, unsigned long rate) { u32 div, div1; u32 tmp; /* * Calculate divider * Fractional part is 4 bits, * so simply multiply by 2^4 to get fractional part. */ tmp = (clk->parent->rate * 16); div = tmp / rate; if (div < 0x10) /* Min DI disp clock divider is 1 */ div = 0x10; if (div & ~0xFEF) div &= 0xFF8; else { div1 = div & 0xFE0; if ((tmp/div1 - tmp/div) < rate / 4) div = div1; else div &= 0xFF8; } return (clk->parent->rate * 16) / div; } static int ipu_pixel_clk_set_rate(struct clk *clk, unsigned long rate) { u32 div = (clk->parent->rate * 16) / rate; __raw_writel(div, DI_BS_CLKGEN0(clk->id)); /* Setup pixel clock timing */ __raw_writel((div / 16) << 16, DI_BS_CLKGEN1(clk->id)); clk->rate = (clk->parent->rate * 16) / div; return 0; } static int ipu_pixel_clk_enable(struct clk *clk) { u32 disp_gen = __raw_readl(IPU_DISP_GEN); disp_gen |= clk->id ? DI1_COUNTER_RELEASE : DI0_COUNTER_RELEASE; __raw_writel(disp_gen, IPU_DISP_GEN); return 0; } static void ipu_pixel_clk_disable(struct clk *clk) { u32 disp_gen = __raw_readl(IPU_DISP_GEN); disp_gen &= clk->id ? ~DI1_COUNTER_RELEASE : ~DI0_COUNTER_RELEASE; __raw_writel(disp_gen, IPU_DISP_GEN); } static int ipu_pixel_clk_set_parent(struct clk *clk, struct clk *parent) { u32 di_gen = __raw_readl(DI_GENERAL(clk->id)); if (parent == g_ipu_clk) di_gen &= ~DI_GEN_DI_CLK_EXT; else if (!IS_ERR(g_di_clk[clk->id]) && parent == g_di_clk[clk->id]) di_gen |= DI_GEN_DI_CLK_EXT; else return -EINVAL; __raw_writel(di_gen, DI_GENERAL(clk->id)); ipu_pixel_clk_recalc(clk); return 0; } static struct clk pixel_clk[] = { { .name = "pixel_clk", .id = 0, .recalc = ipu_pixel_clk_recalc, .set_rate = ipu_pixel_clk_set_rate, .round_rate = ipu_pixel_clk_round_rate, .set_parent = ipu_pixel_clk_set_parent, .enable = ipu_pixel_clk_enable, .disable = ipu_pixel_clk_disable, .usecount = 0, }, { .name = "pixel_clk", .id = 1, .recalc = ipu_pixel_clk_recalc, .set_rate = ipu_pixel_clk_set_rate, .round_rate = ipu_pixel_clk_round_rate, .set_parent = ipu_pixel_clk_set_parent, .enable = ipu_pixel_clk_enable, .disable = ipu_pixel_clk_disable, .usecount = 0, }, }; /* * This function resets IPU */ void ipu_reset(void) { u32 *reg; u32 value; reg = (u32 *)SRC_BASE_ADDR; value = __raw_readl(reg); value = value | SW_IPU_RST; __raw_writel(value, reg); } /* * This function is called by the driver framework to initialize the IPU * hardware. * * @param dev The device structure for the IPU passed in by the * driver framework. * * @return Returns 0 on success or negative error code on error */ int ipu_probe(void) { unsigned long ipu_base; u32 temp; u32 *reg_hsc_mcd = (u32 *)MIPI_HSC_BASE_ADDR; u32 *reg_hsc_mxt_conf = (u32 *)(MIPI_HSC_BASE_ADDR + 0x800); __raw_writel(0xF00, reg_hsc_mcd); /* CSI mode reserved*/ temp = __raw_readl(reg_hsc_mxt_conf); __raw_writel(temp | 0x0FF, reg_hsc_mxt_conf); temp = __raw_readl(reg_hsc_mxt_conf); __raw_writel(temp | 0x10000, reg_hsc_mxt_conf); ipu_base = IPU_CTRL_BASE_ADDR; ipu_cpmem_base = (u32 *)(ipu_base + IPU_CPMEM_REG_BASE); ipu_dc_tmpl_reg = (u32 *)(ipu_base + IPU_DC_TMPL_REG_BASE); g_pixel_clk[0] = &pixel_clk[0]; g_pixel_clk[1] = &pixel_clk[1]; g_ipu_clk = &ipu_clk; debug("ipu_clk = %u\n", clk_get_rate(g_ipu_clk)); ipu_reset(); clk_set_parent(g_pixel_clk[0], g_ipu_clk); clk_set_parent(g_pixel_clk[1], g_ipu_clk); clk_enable(g_ipu_clk); g_di_clk[0] = NULL; g_di_clk[1] = NULL; __raw_writel(0x807FFFFF, IPU_MEM_RST); while (__raw_readl(IPU_MEM_RST) & 0x80000000) ; ipu_init_dc_mappings(); __raw_writel(0, IPU_INT_CTRL(5)); __raw_writel(0, IPU_INT_CTRL(6)); __raw_writel(0, IPU_INT_CTRL(9)); __raw_writel(0, IPU_INT_CTRL(10)); /* DMFC Init */ ipu_dmfc_init(DMFC_NORMAL, 1); /* Set sync refresh channels as high priority */ __raw_writel(0x18800000L, IDMAC_CHA_PRI(0)); /* Set MCU_T to divide MCU access window into 2 */ __raw_writel(0x00400000L | (IPU_MCU_T_DEFAULT << 18), IPU_DISP_GEN); clk_disable(g_ipu_clk); return 0; } void ipu_dump_registers(void) { debug("IPU_CONF = \t0x%08X\n", __raw_readl(IPU_CONF)); debug("IDMAC_CONF = \t0x%08X\n", __raw_readl(IDMAC_CONF)); debug("IDMAC_CHA_EN1 = \t0x%08X\n", __raw_readl(IDMAC_CHA_EN(0))); debug("IDMAC_CHA_EN2 = \t0x%08X\n", __raw_readl(IDMAC_CHA_EN(32))); debug("IDMAC_CHA_PRI1 = \t0x%08X\n", __raw_readl(IDMAC_CHA_PRI(0))); debug("IDMAC_CHA_PRI2 = \t0x%08X\n", __raw_readl(IDMAC_CHA_PRI(32))); debug("IPU_CHA_DB_MODE_SEL0 = \t0x%08X\n", __raw_readl(IPU_CHA_DB_MODE_SEL(0))); debug("IPU_CHA_DB_MODE_SEL1 = \t0x%08X\n", __raw_readl(IPU_CHA_DB_MODE_SEL(32))); debug("DMFC_WR_CHAN = \t0x%08X\n", __raw_readl(DMFC_WR_CHAN)); debug("DMFC_WR_CHAN_DEF = \t0x%08X\n", __raw_readl(DMFC_WR_CHAN_DEF)); debug("DMFC_DP_CHAN = \t0x%08X\n", __raw_readl(DMFC_DP_CHAN)); debug("DMFC_DP_CHAN_DEF = \t0x%08X\n", __raw_readl(DMFC_DP_CHAN_DEF)); debug("DMFC_IC_CTRL = \t0x%08X\n", __raw_readl(DMFC_IC_CTRL)); debug("IPU_FS_PROC_FLOW1 = \t0x%08X\n", __raw_readl(IPU_FS_PROC_FLOW1)); debug("IPU_FS_PROC_FLOW2 = \t0x%08X\n", __raw_readl(IPU_FS_PROC_FLOW2)); debug("IPU_FS_PROC_FLOW3 = \t0x%08X\n", __raw_readl(IPU_FS_PROC_FLOW3)); debug("IPU_FS_DISP_FLOW1 = \t0x%08X\n", __raw_readl(IPU_FS_DISP_FLOW1)); } /* * This function is called to initialize a logical IPU channel. * * @param channel Input parameter for the logical channel ID to init. * * @param params Input parameter containing union of channel * initialization parameters. * * @return Returns 0 on success or negative error code on fail */ int32_t ipu_init_channel(ipu_channel_t channel, ipu_channel_params_t *params) { int ret = 0; uint32_t ipu_conf; debug("init channel = %d\n", IPU_CHAN_ID(channel)); if (g_ipu_clk_enabled == 0) { g_ipu_clk_enabled = 1; clk_enable(g_ipu_clk); } if (g_channel_init_mask & (1L << IPU_CHAN_ID(channel))) { printf("Warning: channel already initialized %d\n", IPU_CHAN_ID(channel)); } ipu_conf = __raw_readl(IPU_CONF); switch (channel) { case MEM_DC_SYNC: if (params->mem_dc_sync.di > 1) { ret = -EINVAL; goto err; } g_dc_di_assignment[1] = params->mem_dc_sync.di; ipu_dc_init(1, params->mem_dc_sync.di, params->mem_dc_sync.interlaced); ipu_di_use_count[params->mem_dc_sync.di]++; ipu_dc_use_count++; ipu_dmfc_use_count++; break; case MEM_BG_SYNC: if (params->mem_dp_bg_sync.di > 1) { ret = -EINVAL; goto err; } g_dc_di_assignment[5] = params->mem_dp_bg_sync.di; ipu_dp_init(channel, params->mem_dp_bg_sync.in_pixel_fmt, params->mem_dp_bg_sync.out_pixel_fmt); ipu_dc_init(5, params->mem_dp_bg_sync.di, params->mem_dp_bg_sync.interlaced); ipu_di_use_count[params->mem_dp_bg_sync.di]++; ipu_dc_use_count++; ipu_dp_use_count++; ipu_dmfc_use_count++; break; case MEM_FG_SYNC: ipu_dp_init(channel, params->mem_dp_fg_sync.in_pixel_fmt, params->mem_dp_fg_sync.out_pixel_fmt); ipu_dc_use_count++; ipu_dp_use_count++; ipu_dmfc_use_count++; break; default: printf("Missing channel initialization\n"); break; } /* Enable IPU sub module */ g_channel_init_mask |= 1L << IPU_CHAN_ID(channel); if (ipu_dc_use_count == 1) ipu_conf |= IPU_CONF_DC_EN; if (ipu_dp_use_count == 1) ipu_conf |= IPU_CONF_DP_EN; if (ipu_dmfc_use_count == 1) ipu_conf |= IPU_CONF_DMFC_EN; if (ipu_di_use_count[0] == 1) { ipu_conf |= IPU_CONF_DI0_EN; } if (ipu_di_use_count[1] == 1) { ipu_conf |= IPU_CONF_DI1_EN; } __raw_writel(ipu_conf, IPU_CONF); err: return ret; } /* * This function is called to uninitialize a logical IPU channel. * * @param channel Input parameter for the logical channel ID to uninit. */ void ipu_uninit_channel(ipu_channel_t channel) { uint32_t reg; uint32_t in_dma, out_dma = 0; uint32_t ipu_conf; if ((g_channel_init_mask & (1L << IPU_CHAN_ID(channel))) == 0) { debug("Channel already uninitialized %d\n", IPU_CHAN_ID(channel)); return; } /* * Make sure channel is disabled * Get input and output dma channels */ in_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); out_dma = channel_2_dma(channel, IPU_VIDEO_IN_BUFFER); if (idma_is_set(IDMAC_CHA_EN, in_dma) || idma_is_set(IDMAC_CHA_EN, out_dma)) { printf( "Channel %d is not disabled, disable first\n", IPU_CHAN_ID(channel)); return; } ipu_conf = __raw_readl(IPU_CONF); /* Reset the double buffer */ reg = __raw_readl(IPU_CHA_DB_MODE_SEL(in_dma)); __raw_writel(reg & ~idma_mask(in_dma), IPU_CHA_DB_MODE_SEL(in_dma)); reg = __raw_readl(IPU_CHA_DB_MODE_SEL(out_dma)); __raw_writel(reg & ~idma_mask(out_dma), IPU_CHA_DB_MODE_SEL(out_dma)); switch (channel) { case MEM_DC_SYNC: ipu_dc_uninit(1); ipu_di_use_count[g_dc_di_assignment[1]]--; ipu_dc_use_count--; ipu_dmfc_use_count--; break; case MEM_BG_SYNC: ipu_dp_uninit(channel); ipu_dc_uninit(5); ipu_di_use_count[g_dc_di_assignment[5]]--; ipu_dc_use_count--; ipu_dp_use_count--; ipu_dmfc_use_count--; break; case MEM_FG_SYNC: ipu_dp_uninit(channel); ipu_dc_use_count--; ipu_dp_use_count--; ipu_dmfc_use_count--; break; default: break; } g_channel_init_mask &= ~(1L << IPU_CHAN_ID(channel)); if (ipu_dc_use_count == 0) ipu_conf &= ~IPU_CONF_DC_EN; if (ipu_dp_use_count == 0) ipu_conf &= ~IPU_CONF_DP_EN; if (ipu_dmfc_use_count == 0) ipu_conf &= ~IPU_CONF_DMFC_EN; if (ipu_di_use_count[0] == 0) { ipu_conf &= ~IPU_CONF_DI0_EN; } if (ipu_di_use_count[1] == 0) { ipu_conf &= ~IPU_CONF_DI1_EN; } __raw_writel(ipu_conf, IPU_CONF); if (ipu_conf == 0) { clk_disable(g_ipu_clk); g_ipu_clk_enabled = 0; } } static inline void ipu_ch_param_dump(int ch) { #ifdef DEBUG struct ipu_ch_param *p = ipu_ch_param_addr(ch); debug("ch %d word 0 - %08X %08X %08X %08X %08X\n", ch, p->word[0].data[0], p->word[0].data[1], p->word[0].data[2], p->word[0].data[3], p->word[0].data[4]); debug("ch %d word 1 - %08X %08X %08X %08X %08X\n", ch, p->word[1].data[0], p->word[1].data[1], p->word[1].data[2], p->word[1].data[3], p->word[1].data[4]); debug("PFS 0x%x, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 85, 4)); debug("BPP 0x%x, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 0, 107, 3)); debug("NPB 0x%x\n", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 78, 7)); debug("FW %d, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 0, 125, 13)); debug("FH %d, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 0, 138, 12)); debug("Stride %d\n", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 102, 14)); debug("Width0 %d+1, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 116, 3)); debug("Width1 %d+1, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 119, 3)); debug("Width2 %d+1, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 122, 3)); debug("Width3 %d+1, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 125, 3)); debug("Offset0 %d, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 128, 5)); debug("Offset1 %d, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 133, 5)); debug("Offset2 %d, ", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 138, 5)); debug("Offset3 %d\n", ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 143, 5)); #endif } static inline void ipu_ch_params_set_packing(struct ipu_ch_param *p, int red_width, int red_offset, int green_width, int green_offset, int blue_width, int blue_offset, int alpha_width, int alpha_offset) { /* Setup red width and offset */ ipu_ch_param_set_field(p, 1, 116, 3, red_width - 1); ipu_ch_param_set_field(p, 1, 128, 5, red_offset); /* Setup green width and offset */ ipu_ch_param_set_field(p, 1, 119, 3, green_width - 1); ipu_ch_param_set_field(p, 1, 133, 5, green_offset); /* Setup blue width and offset */ ipu_ch_param_set_field(p, 1, 122, 3, blue_width - 1); ipu_ch_param_set_field(p, 1, 138, 5, blue_offset); /* Setup alpha width and offset */ ipu_ch_param_set_field(p, 1, 125, 3, alpha_width - 1); ipu_ch_param_set_field(p, 1, 143, 5, alpha_offset); } static void ipu_ch_param_init(int ch, uint32_t pixel_fmt, uint32_t width, uint32_t height, uint32_t stride, uint32_t u, uint32_t v, uint32_t uv_stride, dma_addr_t addr0, dma_addr_t addr1) { uint32_t u_offset = 0; uint32_t v_offset = 0; struct ipu_ch_param params; memset(&params, 0, sizeof(params)); ipu_ch_param_set_field(&params, 0, 125, 13, width - 1); if ((ch == 8) || (ch == 9) || (ch == 10)) { ipu_ch_param_set_field(&params, 0, 138, 12, (height / 2) - 1); ipu_ch_param_set_field(&params, 1, 102, 14, (stride * 2) - 1); } else { ipu_ch_param_set_field(&params, 0, 138, 12, height - 1); ipu_ch_param_set_field(&params, 1, 102, 14, stride - 1); } ipu_ch_param_set_field(&params, 1, 0, 29, addr0 >> 3); ipu_ch_param_set_field(&params, 1, 29, 29, addr1 >> 3); switch (pixel_fmt) { case IPU_PIX_FMT_GENERIC: /*Represents 8-bit Generic data */ ipu_ch_param_set_field(&params, 0, 107, 3, 5); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 6); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 63); /* burst size */ break; case IPU_PIX_FMT_GENERIC_32: /*Represents 32-bit Generic data */ break; case IPU_PIX_FMT_RGB565: ipu_ch_param_set_field(&params, 0, 107, 3, 3); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 7); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 15); /* burst size */ ipu_ch_params_set_packing(&params, 5, 0, 6, 5, 5, 11, 8, 16); break; case IPU_PIX_FMT_BGR24: ipu_ch_param_set_field(&params, 0, 107, 3, 1); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 7); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 19); /* burst size */ ipu_ch_params_set_packing(&params, 8, 0, 8, 8, 8, 16, 8, 24); break; case IPU_PIX_FMT_RGB24: case IPU_PIX_FMT_YUV444: ipu_ch_param_set_field(&params, 0, 107, 3, 1); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 7); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 19); /* burst size */ ipu_ch_params_set_packing(&params, 8, 16, 8, 8, 8, 0, 8, 24); break; case IPU_PIX_FMT_BGRA32: case IPU_PIX_FMT_BGR32: ipu_ch_param_set_field(&params, 0, 107, 3, 0); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 7); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 15); /* burst size */ ipu_ch_params_set_packing(&params, 8, 8, 8, 16, 8, 24, 8, 0); break; case IPU_PIX_FMT_RGBA32: case IPU_PIX_FMT_RGB32: ipu_ch_param_set_field(&params, 0, 107, 3, 0); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 7); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 15); /* burst size */ ipu_ch_params_set_packing(&params, 8, 24, 8, 16, 8, 8, 8, 0); break; case IPU_PIX_FMT_ABGR32: ipu_ch_param_set_field(&params, 0, 107, 3, 0); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 7); /* pix format */ ipu_ch_params_set_packing(&params, 8, 0, 8, 8, 8, 16, 8, 24); break; case IPU_PIX_FMT_UYVY: ipu_ch_param_set_field(&params, 0, 107, 3, 3); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 0xA); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 15); /* burst size */ break; case IPU_PIX_FMT_YUYV: ipu_ch_param_set_field(&params, 0, 107, 3, 3); /* bits/pixel */ ipu_ch_param_set_field(&params, 1, 85, 4, 0x8); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 31); /* burst size */ break; case IPU_PIX_FMT_YUV420P2: case IPU_PIX_FMT_YUV420P: ipu_ch_param_set_field(&params, 1, 85, 4, 2); /* pix format */ if (uv_stride < stride / 2) uv_stride = stride / 2; u_offset = stride * height; v_offset = u_offset + (uv_stride * height / 2); /* burst size */ if ((ch == 8) || (ch == 9) || (ch == 10)) { ipu_ch_param_set_field(&params, 1, 78, 7, 15); uv_stride = uv_stride*2; } else { ipu_ch_param_set_field(&params, 1, 78, 7, 31); } break; case IPU_PIX_FMT_YVU422P: /* BPP & pixel format */ ipu_ch_param_set_field(&params, 1, 85, 4, 1); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 31); /* burst size */ if (uv_stride < stride / 2) uv_stride = stride / 2; v_offset = (v == 0) ? stride * height : v; u_offset = (u == 0) ? v_offset + v_offset / 2 : u; break; case IPU_PIX_FMT_YUV422P: /* BPP & pixel format */ ipu_ch_param_set_field(&params, 1, 85, 4, 1); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 31); /* burst size */ if (uv_stride < stride / 2) uv_stride = stride / 2; u_offset = (u == 0) ? stride * height : u; v_offset = (v == 0) ? u_offset + u_offset / 2 : v; break; case IPU_PIX_FMT_NV12: /* BPP & pixel format */ ipu_ch_param_set_field(&params, 1, 85, 4, 4); /* pix format */ ipu_ch_param_set_field(&params, 1, 78, 7, 31); /* burst size */ uv_stride = stride; u_offset = (u == 0) ? stride * height : u; break; default: puts("mxc ipu: unimplemented pixel format\n"); break; } if (uv_stride) ipu_ch_param_set_field(&params, 1, 128, 14, uv_stride - 1); /* Get the uv offset from user when need cropping */ if (u || v) { u_offset = u; v_offset = v; } /* UBO and VBO are 22-bit */ if (u_offset/8 > 0x3fffff) puts("The value of U offset exceeds IPU limitation\n"); if (v_offset/8 > 0x3fffff) puts("The value of V offset exceeds IPU limitation\n"); ipu_ch_param_set_field(&params, 0, 46, 22, u_offset / 8); ipu_ch_param_set_field(&params, 0, 68, 22, v_offset / 8); debug("initializing idma ch %d @ %p\n", ch, ipu_ch_param_addr(ch)); memcpy(ipu_ch_param_addr(ch), &params, sizeof(params)); }; /* * This function is called to initialize a buffer for logical IPU channel. * * @param channel Input parameter for the logical channel ID. * * @param type Input parameter which buffer to initialize. * * @param pixel_fmt Input parameter for pixel format of buffer. * Pixel format is a FOURCC ASCII code. * * @param width Input parameter for width of buffer in pixels. * * @param height Input parameter for height of buffer in pixels. * * @param stride Input parameter for stride length of buffer * in pixels. * * @param phyaddr_0 Input parameter buffer 0 physical address. * * @param phyaddr_1 Input parameter buffer 1 physical address. * Setting this to a value other than NULL enables * double buffering mode. * * @param u private u offset for additional cropping, * zero if not used. * * @param v private v offset for additional cropping, * zero if not used. * * @return Returns 0 on success or negative error code on fail */ int32_t ipu_init_channel_buffer(ipu_channel_t channel, ipu_buffer_t type, uint32_t pixel_fmt, uint16_t width, uint16_t height, uint32_t stride, dma_addr_t phyaddr_0, dma_addr_t phyaddr_1, uint32_t u, uint32_t v) { uint32_t reg; uint32_t dma_chan; dma_chan = channel_2_dma(channel, type); if (!idma_is_valid(dma_chan)) return -EINVAL; if (stride < width * bytes_per_pixel(pixel_fmt)) stride = width * bytes_per_pixel(pixel_fmt); if (stride % 4) { printf( "Stride not 32-bit aligned, stride = %d\n", stride); return -EINVAL; } /* Build parameter memory data for DMA channel */ ipu_ch_param_init(dma_chan, pixel_fmt, width, height, stride, u, v, 0, phyaddr_0, phyaddr_1); if (ipu_is_dmfc_chan(dma_chan)) { ipu_dmfc_set_wait4eot(dma_chan, width); } if (idma_is_set(IDMAC_CHA_PRI, dma_chan)) ipu_ch_param_set_high_priority(dma_chan); ipu_ch_param_dump(dma_chan); reg = __raw_readl(IPU_CHA_DB_MODE_SEL(dma_chan)); if (phyaddr_1) reg |= idma_mask(dma_chan); else reg &= ~idma_mask(dma_chan); __raw_writel(reg, IPU_CHA_DB_MODE_SEL(dma_chan)); /* Reset to buffer 0 */ __raw_writel(idma_mask(dma_chan), IPU_CHA_CUR_BUF(dma_chan)); return 0; } /* * This function enables a logical channel. * * @param channel Input parameter for the logical channel ID. * * @return This function returns 0 on success or negative error code on * fail. */ int32_t ipu_enable_channel(ipu_channel_t channel) { uint32_t reg; uint32_t in_dma; uint32_t out_dma; if (g_channel_enable_mask & (1L << IPU_CHAN_ID(channel))) { printf("Warning: channel already enabled %d\n", IPU_CHAN_ID(channel)); } /* Get input and output dma channels */ out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); in_dma = channel_2_dma(channel, IPU_VIDEO_IN_BUFFER); if (idma_is_valid(in_dma)) { reg = __raw_readl(IDMAC_CHA_EN(in_dma)); __raw_writel(reg | idma_mask(in_dma), IDMAC_CHA_EN(in_dma)); } if (idma_is_valid(out_dma)) { reg = __raw_readl(IDMAC_CHA_EN(out_dma)); __raw_writel(reg | idma_mask(out_dma), IDMAC_CHA_EN(out_dma)); } if ((channel == MEM_DC_SYNC) || (channel == MEM_BG_SYNC) || (channel == MEM_FG_SYNC)) ipu_dp_dc_enable(channel); g_channel_enable_mask |= 1L << IPU_CHAN_ID(channel); return 0; } /* * This function clear buffer ready for a logical channel. * * @param channel Input parameter for the logical channel ID. * * @param type Input parameter which buffer to clear. * * @param bufNum Input parameter for which buffer number clear * ready state. * */ void ipu_clear_buffer_ready(ipu_channel_t channel, ipu_buffer_t type, uint32_t bufNum) { uint32_t dma_ch = channel_2_dma(channel, type); if (!idma_is_valid(dma_ch)) return; __raw_writel(0xF0000000, IPU_GPR); /* write one to clear */ if (bufNum == 0) { if (idma_is_set(IPU_CHA_BUF0_RDY, dma_ch)) { __raw_writel(idma_mask(dma_ch), IPU_CHA_BUF0_RDY(dma_ch)); } } else { if (idma_is_set(IPU_CHA_BUF1_RDY, dma_ch)) { __raw_writel(idma_mask(dma_ch), IPU_CHA_BUF1_RDY(dma_ch)); } } __raw_writel(0x0, IPU_GPR); /* write one to set */ } /* * This function disables a logical channel. * * @param channel Input parameter for the logical channel ID. * * @param wait_for_stop Flag to set whether to wait for channel end * of frame or return immediately. * * @return This function returns 0 on success or negative error code on * fail. */ int32_t ipu_disable_channel(ipu_channel_t channel) { uint32_t reg; uint32_t in_dma; uint32_t out_dma; if ((g_channel_enable_mask & (1L << IPU_CHAN_ID(channel))) == 0) { debug("Channel already disabled %d\n", IPU_CHAN_ID(channel)); return 0; } /* Get input and output dma channels */ out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); in_dma = channel_2_dma(channel, IPU_VIDEO_IN_BUFFER); if ((idma_is_valid(in_dma) && !idma_is_set(IDMAC_CHA_EN, in_dma)) && (idma_is_valid(out_dma) && !idma_is_set(IDMAC_CHA_EN, out_dma))) return -EINVAL; if ((channel == MEM_BG_SYNC) || (channel == MEM_FG_SYNC) || (channel == MEM_DC_SYNC)) { ipu_dp_dc_disable(channel, 0); } /* Disable DMA channel(s) */ if (idma_is_valid(in_dma)) { reg = __raw_readl(IDMAC_CHA_EN(in_dma)); __raw_writel(reg & ~idma_mask(in_dma), IDMAC_CHA_EN(in_dma)); __raw_writel(idma_mask(in_dma), IPU_CHA_CUR_BUF(in_dma)); } if (idma_is_valid(out_dma)) { reg = __raw_readl(IDMAC_CHA_EN(out_dma)); __raw_writel(reg & ~idma_mask(out_dma), IDMAC_CHA_EN(out_dma)); __raw_writel(idma_mask(out_dma), IPU_CHA_CUR_BUF(out_dma)); } g_channel_enable_mask &= ~(1L << IPU_CHAN_ID(channel)); /* Set channel buffers NOT to be ready */ if (idma_is_valid(in_dma)) { ipu_clear_buffer_ready(channel, IPU_VIDEO_IN_BUFFER, 0); ipu_clear_buffer_ready(channel, IPU_VIDEO_IN_BUFFER, 1); } if (idma_is_valid(out_dma)) { ipu_clear_buffer_ready(channel, IPU_OUTPUT_BUFFER, 0); ipu_clear_buffer_ready(channel, IPU_OUTPUT_BUFFER, 1); } return 0; } uint32_t bytes_per_pixel(uint32_t fmt) { switch (fmt) { case IPU_PIX_FMT_GENERIC: /*generic data */ case IPU_PIX_FMT_RGB332: case IPU_PIX_FMT_YUV420P: case IPU_PIX_FMT_YUV422P: return 1; break; case IPU_PIX_FMT_RGB565: case IPU_PIX_FMT_YUYV: case IPU_PIX_FMT_UYVY: return 2; break; case IPU_PIX_FMT_BGR24: case IPU_PIX_FMT_RGB24: return 3; break; case IPU_PIX_FMT_GENERIC_32: /*generic data */ case IPU_PIX_FMT_BGR32: case IPU_PIX_FMT_BGRA32: case IPU_PIX_FMT_RGB32: case IPU_PIX_FMT_RGBA32: case IPU_PIX_FMT_ABGR32: return 4; break; default: return 1; break; } return 0; } ipu_color_space_t format_to_colorspace(uint32_t fmt) { switch (fmt) { case IPU_PIX_FMT_RGB666: case IPU_PIX_FMT_RGB565: case IPU_PIX_FMT_BGR24: case IPU_PIX_FMT_RGB24: case IPU_PIX_FMT_BGR32: case IPU_PIX_FMT_BGRA32: case IPU_PIX_FMT_RGB32: case IPU_PIX_FMT_RGBA32: case IPU_PIX_FMT_ABGR32: case IPU_PIX_FMT_LVDS666: case IPU_PIX_FMT_LVDS888: return RGB; break; default: return YCbCr; break; } return RGB; }
1001-study-uboot
drivers/video/ipu_common.c
C
gpl3
31,906
/* * Porting to u-boot: * * (C) Copyright 2010 * Stefano Babic, DENX Software Engineering, sbabic@denx.de * * MX51 Linux framebuffer: * * (C) Copyright 2004-2010 Freescale Semiconductor, Inc. * * 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 <asm/errno.h> #include <linux/string.h> #include <linux/list.h> #include <linux/fb.h> #include <asm/io.h> #include <malloc.h> #include <video_fb.h> #include "videomodes.h" #include "ipu.h" #include "mxcfb.h" static int mxcfb_map_video_memory(struct fb_info *fbi); static int mxcfb_unmap_video_memory(struct fb_info *fbi); /* graphics setup */ static GraphicDevice panel; static struct fb_videomode *gmode; static uint8_t gdisp; static uint32_t gpixfmt; void fb_videomode_to_var(struct fb_var_screeninfo *var, const struct fb_videomode *mode) { var->xres = mode->xres; var->yres = mode->yres; var->xres_virtual = mode->xres; var->yres_virtual = mode->yres; var->xoffset = 0; var->yoffset = 0; var->pixclock = mode->pixclock; var->left_margin = mode->left_margin; var->right_margin = mode->right_margin; var->upper_margin = mode->upper_margin; var->lower_margin = mode->lower_margin; var->hsync_len = mode->hsync_len; var->vsync_len = mode->vsync_len; var->sync = mode->sync; var->vmode = mode->vmode & FB_VMODE_MASK; } /* * Structure containing the MXC specific framebuffer information. */ struct mxcfb_info { int blank; ipu_channel_t ipu_ch; int ipu_di; u32 ipu_di_pix_fmt; unsigned char overlay; unsigned char alpha_chan_en; dma_addr_t alpha_phy_addr0; dma_addr_t alpha_phy_addr1; void *alpha_virt_addr0; void *alpha_virt_addr1; uint32_t alpha_mem_len; uint32_t cur_ipu_buf; uint32_t cur_ipu_alpha_buf; u32 pseudo_palette[16]; }; enum { BOTH_ON, SRC_ON, TGT_ON, BOTH_OFF }; static unsigned long default_bpp = 16; static unsigned char g_dp_in_use; static struct fb_info *mxcfb_info[3]; static int ext_clk_used; static uint32_t bpp_to_pixfmt(struct fb_info *fbi) { uint32_t pixfmt = 0; debug("bpp_to_pixfmt: %d\n", fbi->var.bits_per_pixel); if (fbi->var.nonstd) return fbi->var.nonstd; switch (fbi->var.bits_per_pixel) { case 24: pixfmt = IPU_PIX_FMT_BGR24; break; case 32: pixfmt = IPU_PIX_FMT_BGR32; break; case 16: pixfmt = IPU_PIX_FMT_RGB565; break; } return pixfmt; } /* * Set fixed framebuffer parameters based on variable settings. * * @param info framebuffer information pointer */ static int mxcfb_set_fix(struct fb_info *info) { struct fb_fix_screeninfo *fix = &info->fix; struct fb_var_screeninfo *var = &info->var; fix->line_length = var->xres_virtual * var->bits_per_pixel / 8; fix->type = FB_TYPE_PACKED_PIXELS; fix->accel = FB_ACCEL_NONE; fix->visual = FB_VISUAL_TRUECOLOR; fix->xpanstep = 1; fix->ypanstep = 1; return 0; } static int setup_disp_channel1(struct fb_info *fbi) { ipu_channel_params_t params; struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; memset(&params, 0, sizeof(params)); params.mem_dp_bg_sync.di = mxc_fbi->ipu_di; debug("%s called\n", __func__); /* * Assuming interlaced means yuv output, below setting also * valid for mem_dc_sync. FG should have the same vmode as BG. */ if (fbi->var.vmode & FB_VMODE_INTERLACED) { params.mem_dp_bg_sync.interlaced = 1; params.mem_dp_bg_sync.out_pixel_fmt = IPU_PIX_FMT_YUV444; } else { if (mxc_fbi->ipu_di_pix_fmt) { params.mem_dp_bg_sync.out_pixel_fmt = mxc_fbi->ipu_di_pix_fmt; } else { params.mem_dp_bg_sync.out_pixel_fmt = IPU_PIX_FMT_RGB666; } } params.mem_dp_bg_sync.in_pixel_fmt = bpp_to_pixfmt(fbi); if (mxc_fbi->alpha_chan_en) params.mem_dp_bg_sync.alpha_chan_en = 1; ipu_init_channel(mxc_fbi->ipu_ch, &params); return 0; } static int setup_disp_channel2(struct fb_info *fbi) { int retval = 0; struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; mxc_fbi->cur_ipu_buf = 1; if (mxc_fbi->alpha_chan_en) mxc_fbi->cur_ipu_alpha_buf = 1; fbi->var.xoffset = fbi->var.yoffset = 0; debug("%s: %x %d %d %d %lx %lx\n", __func__, mxc_fbi->ipu_ch, fbi->var.xres, fbi->var.yres, fbi->fix.line_length, fbi->fix.smem_start, fbi->fix.smem_start + (fbi->fix.line_length * fbi->var.yres)); retval = ipu_init_channel_buffer(mxc_fbi->ipu_ch, IPU_INPUT_BUFFER, bpp_to_pixfmt(fbi), fbi->var.xres, fbi->var.yres, fbi->fix.line_length, fbi->fix.smem_start + (fbi->fix.line_length * fbi->var.yres), fbi->fix.smem_start, 0, 0); if (retval) printf("ipu_init_channel_buffer error %d\n", retval); return retval; } /* * Set framebuffer parameters and change the operating mode. * * @param info framebuffer information pointer */ static int mxcfb_set_par(struct fb_info *fbi) { int retval = 0; u32 mem_len; ipu_di_signal_cfg_t sig_cfg; struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; uint32_t out_pixel_fmt; ipu_disable_channel(mxc_fbi->ipu_ch); ipu_uninit_channel(mxc_fbi->ipu_ch); mxcfb_set_fix(fbi); mem_len = fbi->var.yres_virtual * fbi->fix.line_length; if (!fbi->fix.smem_start || (mem_len > fbi->fix.smem_len)) { if (fbi->fix.smem_start) mxcfb_unmap_video_memory(fbi); if (mxcfb_map_video_memory(fbi) < 0) return -ENOMEM; } setup_disp_channel1(fbi); memset(&sig_cfg, 0, sizeof(sig_cfg)); if (fbi->var.vmode & FB_VMODE_INTERLACED) { sig_cfg.interlaced = 1; out_pixel_fmt = IPU_PIX_FMT_YUV444; } else { if (mxc_fbi->ipu_di_pix_fmt) out_pixel_fmt = mxc_fbi->ipu_di_pix_fmt; else out_pixel_fmt = IPU_PIX_FMT_RGB666; } if (fbi->var.vmode & FB_VMODE_ODD_FLD_FIRST) /* PAL */ sig_cfg.odd_field_first = 1; if ((fbi->var.sync & FB_SYNC_EXT) || ext_clk_used) sig_cfg.ext_clk = 1; if (fbi->var.sync & FB_SYNC_HOR_HIGH_ACT) sig_cfg.Hsync_pol = 1; if (fbi->var.sync & FB_SYNC_VERT_HIGH_ACT) sig_cfg.Vsync_pol = 1; if (!(fbi->var.sync & FB_SYNC_CLK_LAT_FALL)) sig_cfg.clk_pol = 1; if (fbi->var.sync & FB_SYNC_DATA_INVERT) sig_cfg.data_pol = 1; if (!(fbi->var.sync & FB_SYNC_OE_LOW_ACT)) sig_cfg.enable_pol = 1; if (fbi->var.sync & FB_SYNC_CLK_IDLE_EN) sig_cfg.clkidle_en = 1; debug("pixclock = %ul Hz\n", (u32) (PICOS2KHZ(fbi->var.pixclock) * 1000UL)); if (ipu_init_sync_panel(mxc_fbi->ipu_di, (PICOS2KHZ(fbi->var.pixclock)) * 1000UL, fbi->var.xres, fbi->var.yres, out_pixel_fmt, fbi->var.left_margin, fbi->var.hsync_len, fbi->var.right_margin, fbi->var.upper_margin, fbi->var.vsync_len, fbi->var.lower_margin, 0, sig_cfg) != 0) { puts("mxcfb: Error initializing panel.\n"); return -EINVAL; } retval = setup_disp_channel2(fbi); if (retval) return retval; if (mxc_fbi->blank == FB_BLANK_UNBLANK) ipu_enable_channel(mxc_fbi->ipu_ch); return retval; } /* * Check framebuffer variable parameters and adjust to valid values. * * @param var framebuffer variable parameters * * @param info framebuffer information pointer */ static int mxcfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { u32 vtotal; u32 htotal; if (var->xres_virtual < var->xres) var->xres_virtual = var->xres; if (var->yres_virtual < var->yres) var->yres_virtual = var->yres; if ((var->bits_per_pixel != 32) && (var->bits_per_pixel != 24) && (var->bits_per_pixel != 16) && (var->bits_per_pixel != 8)) var->bits_per_pixel = default_bpp; switch (var->bits_per_pixel) { case 8: var->red.length = 3; var->red.offset = 5; var->red.msb_right = 0; var->green.length = 3; var->green.offset = 2; var->green.msb_right = 0; var->blue.length = 2; var->blue.offset = 0; var->blue.msb_right = 0; var->transp.length = 0; var->transp.offset = 0; var->transp.msb_right = 0; break; case 16: var->red.length = 5; var->red.offset = 11; var->red.msb_right = 0; var->green.length = 6; var->green.offset = 5; var->green.msb_right = 0; var->blue.length = 5; var->blue.offset = 0; var->blue.msb_right = 0; var->transp.length = 0; var->transp.offset = 0; var->transp.msb_right = 0; break; case 24: var->red.length = 8; var->red.offset = 16; var->red.msb_right = 0; var->green.length = 8; var->green.offset = 8; var->green.msb_right = 0; var->blue.length = 8; var->blue.offset = 0; var->blue.msb_right = 0; var->transp.length = 0; var->transp.offset = 0; var->transp.msb_right = 0; break; case 32: var->red.length = 8; var->red.offset = 16; var->red.msb_right = 0; var->green.length = 8; var->green.offset = 8; var->green.msb_right = 0; var->blue.length = 8; var->blue.offset = 0; var->blue.msb_right = 0; var->transp.length = 8; var->transp.offset = 24; var->transp.msb_right = 0; break; } if (var->pixclock < 1000) { htotal = var->xres + var->right_margin + var->hsync_len + var->left_margin; vtotal = var->yres + var->lower_margin + var->vsync_len + var->upper_margin; var->pixclock = (vtotal * htotal * 6UL) / 100UL; var->pixclock = KHZ2PICOS(var->pixclock); printf("pixclock set for 60Hz refresh = %u ps\n", var->pixclock); } var->height = -1; var->width = -1; var->grayscale = 0; return 0; } static int mxcfb_map_video_memory(struct fb_info *fbi) { if (fbi->fix.smem_len < fbi->var.yres_virtual * fbi->fix.line_length) { fbi->fix.smem_len = fbi->var.yres_virtual * fbi->fix.line_length; } fbi->screen_base = (char *)malloc(fbi->fix.smem_len); fbi->fix.smem_start = (unsigned long)fbi->screen_base; if (fbi->screen_base == 0) { puts("Unable to allocate framebuffer memory\n"); fbi->fix.smem_len = 0; fbi->fix.smem_start = 0; return -EBUSY; } debug("allocated fb @ paddr=0x%08X, size=%d.\n", (uint32_t) fbi->fix.smem_start, fbi->fix.smem_len); fbi->screen_size = fbi->fix.smem_len; /* Clear the screen */ memset((char *)fbi->screen_base, 0, fbi->fix.smem_len); return 0; } static int mxcfb_unmap_video_memory(struct fb_info *fbi) { fbi->screen_base = 0; fbi->fix.smem_start = 0; fbi->fix.smem_len = 0; return 0; } /* * Initializes the framebuffer information pointer. After allocating * sufficient memory for the framebuffer structure, the fields are * filled with custom information passed in from the configurable * structures. This includes information such as bits per pixel, * color maps, screen width/height and RGBA offsets. * * @return Framebuffer structure initialized with our information */ static struct fb_info *mxcfb_init_fbinfo(void) { #define BYTES_PER_LONG 4 #define PADDING (BYTES_PER_LONG - (sizeof(struct fb_info) % BYTES_PER_LONG)) struct fb_info *fbi; struct mxcfb_info *mxcfbi; char *p; int size = sizeof(struct mxcfb_info) + PADDING + sizeof(struct fb_info); debug("%s: %d %d %d %d\n", __func__, PADDING, size, sizeof(struct mxcfb_info), sizeof(struct fb_info)); /* * Allocate sufficient memory for the fb structure */ p = malloc(size); if (!p) return NULL; memset(p, 0, size); fbi = (struct fb_info *)p; fbi->par = p + sizeof(struct fb_info) + PADDING; mxcfbi = (struct mxcfb_info *)fbi->par; debug("Framebuffer structures at: fbi=0x%x mxcfbi=0x%x\n", (unsigned int)fbi, (unsigned int)mxcfbi); fbi->var.activate = FB_ACTIVATE_NOW; fbi->flags = FBINFO_FLAG_DEFAULT; fbi->pseudo_palette = mxcfbi->pseudo_palette; return fbi; } /* * Probe routine for the framebuffer driver. It is called during the * driver binding process. The following functions are performed in * this routine: Framebuffer initialization, Memory allocation and * mapping, Framebuffer registration, IPU initialization. * * @return Appropriate error code to the kernel common code */ static int mxcfb_probe(u32 interface_pix_fmt, uint8_t disp, struct fb_videomode *mode) { struct fb_info *fbi; struct mxcfb_info *mxcfbi; int ret = 0; /* * Initialize FB structures */ fbi = mxcfb_init_fbinfo(); if (!fbi) { ret = -ENOMEM; goto err0; } mxcfbi = (struct mxcfb_info *)fbi->par; if (!g_dp_in_use) { mxcfbi->ipu_ch = MEM_BG_SYNC; mxcfbi->blank = FB_BLANK_UNBLANK; } else { mxcfbi->ipu_ch = MEM_DC_SYNC; mxcfbi->blank = FB_BLANK_POWERDOWN; } mxcfbi->ipu_di = disp; ipu_disp_set_global_alpha(mxcfbi->ipu_ch, 1, 0x80); ipu_disp_set_color_key(mxcfbi->ipu_ch, 0, 0); strcpy(fbi->fix.id, "DISP3 BG"); g_dp_in_use = 1; mxcfb_info[mxcfbi->ipu_di] = fbi; /* Need dummy values until real panel is configured */ mxcfbi->ipu_di_pix_fmt = interface_pix_fmt; fb_videomode_to_var(&fbi->var, mode); fbi->var.bits_per_pixel = 16; fbi->fix.line_length = fbi->var.xres * (fbi->var.bits_per_pixel / 8); fbi->fix.smem_len = fbi->var.yres_virtual * fbi->fix.line_length; mxcfb_check_var(&fbi->var, fbi); /* Default Y virtual size is 2x panel size */ fbi->var.yres_virtual = fbi->var.yres * 2; mxcfb_set_fix(fbi); /* alocate fb first */ if (mxcfb_map_video_memory(fbi) < 0) return -ENOMEM; mxcfb_set_par(fbi); panel.winSizeX = mode->xres; panel.winSizeY = mode->yres; panel.plnSizeX = mode->xres; panel.plnSizeY = mode->yres; panel.frameAdrs = (u32)fbi->screen_base; panel.memSize = fbi->screen_size; panel.gdfBytesPP = 2; panel.gdfIndex = GDF_16BIT_565RGB; ipu_dump_registers(); return 0; err0: return ret; } void *video_hw_init(void) { int ret; ret = ipu_probe(); if (ret) puts("Error initializing IPU\n"); ret = mxcfb_probe(gpixfmt, gdisp, gmode); debug("Framebuffer at 0x%x\n", (unsigned int)panel.frameAdrs); return (void *)&panel; } void video_set_lut(unsigned int index, /* color number */ unsigned char r, /* red */ unsigned char g, /* green */ unsigned char b /* blue */ ) { return; } int mx51_fb_init(struct fb_videomode *mode, uint8_t disp, uint32_t pixfmt) { gmode = mode; gdisp = disp; gpixfmt = pixfmt; return 0; }
1001-study-uboot
drivers/video/mxc_ipuv3_fb.c
C
gpl3
14,572