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
|
|---|---|---|---|---|---|
/*
* Header file for UBI support for U-Boot
*
* Adaptation from kernel to U-Boot
*
* Copyright (C) 2005-2007 Samsung Electronics
* Kyungmin Park <kyungmin.park@samsung.com>
*
* 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.
*/
#ifndef __UBOOT_UBI_H
#define __UBOOT_UBI_H
#include <common.h>
#include <compiler.h>
#include <malloc.h>
#include <div64.h>
#include <linux/crc32.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/rbtree.h>
#include <linux/string.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/ubi.h>
#ifdef CONFIG_CMD_ONENAND
#include <onenand_uboot.h>
#endif
#include <asm/errno.h>
#define DPRINTK(format, args...) \
do { \
printf("%s[%d]: " format "\n", __func__, __LINE__, ##args); \
} while (0)
/* configurable */
#define CONFIG_MTD_UBI_WL_THRESHOLD 4096
#define CONFIG_MTD_UBI_BEB_RESERVE 1
#define UBI_IO_DEBUG 0
/* debug options (Linux: drivers/mtd/ubi/Kconfig.debug) */
#undef CONFIG_MTD_UBI_DEBUG
#undef CONFIG_MTD_UBI_DEBUG_PARANOID
#undef CONFIG_MTD_UBI_DEBUG_MSG
#undef CONFIG_MTD_UBI_DEBUG_MSG_EBA
#undef CONFIG_MTD_UBI_DEBUG_MSG_WL
#undef CONFIG_MTD_UBI_DEBUG_MSG_IO
#undef CONFIG_MTD_UBI_DEBUG_MSG_BLD
#define CONFIG_MTD_UBI_DEBUG_DISABLE_BGT
/* build.c */
#define get_device(...)
#define put_device(...)
#define ubi_sysfs_init(...) 0
#define ubi_sysfs_close(...) do { } while (0)
static inline int is_power_of_2(unsigned long n)
{
return (n != 0 && ((n & (n - 1)) == 0));
}
/* FIXME */
#define MKDEV(...) 0
#define MAJOR(dev) 0
#define MINOR(dev) 0
#define alloc_chrdev_region(...) 0
#define unregister_chrdev_region(...)
#define class_create(...) __builtin_return_address(0)
#define class_create_file(...) 0
#define class_remove_file(...)
#define class_destroy(...)
#define misc_register(...) 0
#define misc_deregister(...)
/* vmt.c */
#define device_register(...) 0
#define volume_sysfs_init(...) 0
#define volume_sysfs_close(...) do { } while (0)
/* kapi.c */
/* eba.c */
/* io.c */
#define init_waitqueue_head(...) do { } while (0)
#define wait_event_interruptible(...) 0
#define wake_up_interruptible(...) do { } while (0)
#define print_hex_dump(...) do { } while (0)
#define dump_stack(...) do { } while (0)
/* wl.c */
#define task_pid_nr(x) 0
#define set_freezable(...) do { } while (0)
#define try_to_freeze(...) 0
#define set_current_state(...) do { } while (0)
#define kthread_should_stop(...) 0
#define schedule() do { } while (0)
/* upd.c */
static inline unsigned long copy_from_user(void *dest, const void *src,
unsigned long count)
{
memcpy((void *)dest, (void *)src, count);
return 0;
}
/* common */
typedef int spinlock_t;
typedef int wait_queue_head_t;
#define spin_lock_init(...)
#define spin_lock(...)
#define spin_unlock(...)
#define mutex_init(...)
#define mutex_lock(...)
#define mutex_unlock(...)
#define init_rwsem(...) do { } while (0)
#define down_read(...) do { } while (0)
#define down_write(...) do { } while (0)
#define down_write_trylock(...) 1
#define up_read(...) do { } while (0)
#define up_write(...) do { } while (0)
struct kmem_cache { int i; };
#define kmem_cache_create(...) 1
#define kmem_cache_alloc(obj, gfp) malloc(sizeof(struct ubi_wl_entry))
#define kmem_cache_free(obj, size) free(size)
#define kmem_cache_destroy(...)
#define cond_resched() do { } while (0)
#define yield() do { } while (0)
#define KERN_WARNING
#define KERN_ERR
#define KERN_NOTICE
#define KERN_DEBUG
#define GFP_KERNEL 0
#define GFP_NOFS 1
#define __user
#define __init
#define __exit
#define kthread_create(...) __builtin_return_address(0)
#define kthread_stop(...) do { } while (0)
#define wake_up_process(...) do { } while (0)
#define BUS_ID_SIZE 20
struct rw_semaphore { int i; };
struct device {
struct device *parent;
struct class *class;
char bus_id[BUS_ID_SIZE]; /* position on parent bus */
dev_t devt; /* dev_t, creates the sysfs "dev" */
void (*release)(struct device *dev);
};
struct mutex { int i; };
struct kernel_param { int i; };
struct cdev {
int owner;
dev_t dev;
};
#define cdev_init(...) do { } while (0)
#define cdev_add(...) 0
#define cdev_del(...) do { } while (0)
#define MAX_ERRNO 4095
#define IS_ERR_VALUE(x) ((x) >= (unsigned long)-MAX_ERRNO)
static inline void *ERR_PTR(long error)
{
return (void *) error;
}
static inline long PTR_ERR(const void *ptr)
{
return (long) ptr;
}
static inline long IS_ERR(const void *ptr)
{
return IS_ERR_VALUE((unsigned long)ptr);
}
/* module */
#define THIS_MODULE 0
#define try_module_get(...) 1
#define module_put(...) do { } while (0)
#define module_init(...)
#define module_exit(...)
#define EXPORT_SYMBOL(...)
#define EXPORT_SYMBOL_GPL(...)
#define module_param_call(...)
#define MODULE_PARM_DESC(...)
#define MODULE_VERSION(...)
#define MODULE_DESCRIPTION(...)
#define MODULE_AUTHOR(...)
#define MODULE_LICENSE(...)
#ifndef __UBIFS_H__
#include "../drivers/mtd/ubi/ubi.h"
#endif
/* functions */
extern int ubi_mtd_param_parse(const char *val, struct kernel_param *kp);
extern int ubi_init(void);
extern void ubi_exit(void);
extern struct ubi_device *ubi_devices[];
#endif
|
1001-study-uboot
|
include/ubi_uboot.h
|
C
|
gpl3
| 5,281
|
/*
* Interface to SPI flash
*
* Copyright (C) 2008 Atmel Corporation
*
* 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
* 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
*/
#ifndef _SPI_FLASH_H_
#define _SPI_FLASH_H_
#include <spi.h>
#include <linux/types.h>
struct spi_flash {
struct spi_slave *spi;
const char *name;
/* Total flash size */
u32 size;
/* Write (page) size */
u32 page_size;
/* Erase (sector) size */
u32 sector_size;
int (*read)(struct spi_flash *flash, u32 offset,
size_t len, void *buf);
int (*write)(struct spi_flash *flash, u32 offset,
size_t len, const void *buf);
int (*erase)(struct spi_flash *flash, u32 offset,
size_t len);
};
struct spi_flash *spi_flash_probe(unsigned int bus, unsigned int cs,
unsigned int max_hz, unsigned int spi_mode);
void spi_flash_free(struct spi_flash *flash);
static inline int spi_flash_read(struct spi_flash *flash, u32 offset,
size_t len, void *buf)
{
return flash->read(flash, offset, len, buf);
}
static inline int spi_flash_write(struct spi_flash *flash, u32 offset,
size_t len, const void *buf)
{
return flash->write(flash, offset, len, buf);
}
static inline int spi_flash_erase(struct spi_flash *flash, u32 offset,
size_t len)
{
return flash->erase(flash, offset, len);
}
#endif /* _SPI_FLASH_H_ */
|
1001-study-uboot
|
include/spi_flash.h
|
C
|
gpl3
| 1,943
|
/*
* (C) Copyright 2000-2004
* 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
*/
#ifndef _PCMCIA_H
#define _PCMCIA_H
#include <common.h>
#include <config.h>
/*
* Allow configuration to select PCMCIA slot,
* or try to generate a useful default
*/
#if defined(CONFIG_CMD_PCMCIA) || \
(defined(CONFIG_CMD_IDE) && \
(defined(CONFIG_IDE_8xx_PCCARD) || defined(CONFIG_IDE_8xx_DIRECT) ) )
#if !defined(CONFIG_PCMCIA_SLOT_A) && !defined(CONFIG_PCMCIA_SLOT_B)
/* The RPX series use SLOT_B */
#if defined(CONFIG_RPXCLASSIC) || defined(CONFIG_RPXLITE)
# define CONFIG_PCMCIA_SLOT_B
#elif defined(CONFIG_ADS) /* The ADS board uses SLOT_A */
# define CONFIG_PCMCIA_SLOT_A
#elif defined(CONFIG_FADS) /* The FADS series are a mess */
# if defined(CONFIG_MPC86x) || defined(CONFIG_MPC821)
# define CONFIG_PCMCIA_SLOT_A
# else
# define CONFIG_PCMCIA_SLOT_B
# endif
#elif defined(CONFIG_TQM8xxL) || defined(CONFIG_SVM_SC8xx)
# define CONFIG_PCMCIA_SLOT_B /* The TQM8xxL use SLOT_B */
#elif defined(CONFIG_SPD823TS) /* The SPD8xx use SLOT_B */
# define CONFIG_PCMCIA_SLOT_B
#elif defined(CONFIG_IVMS8) || defined(CONFIG_IVML24) /* The IVM* use SLOT_A */
# define CONFIG_PCMCIA_SLOT_A
#elif defined(CONFIG_LWMON) /* The LWMON use SLOT_B */
# define CONFIG_PCMCIA_SLOT_B
#elif defined(CONFIG_ICU862) /* The ICU862 use SLOT_B */
# define CONFIG_PCMCIA_SLOT_B
#elif defined(CONFIG_C2MON) /* The C2MON use SLOT_B */
# define CONFIG_PCMCIA_SLOT_B
#elif defined(CONFIG_R360MPI) /* The R360MPI use SLOT_B */
# define CONFIG_PCMCIA_SLOT_B
#elif defined(CONFIG_ATC) /* The ATC use SLOT_A */
# define CONFIG_PCMCIA_SLOT_A
#elif defined(CONFIG_NETTA)
# define CONFIG_PCMCIA_SLOT_A
#elif defined(CONFIG_UC100) /* The UC100 use SLOT_B */
# define CONFIG_PCMCIA_SLOT_B
#else
# error "PCMCIA Slot not configured"
#endif
#endif /* !defined(CONFIG_PCMCIA_SLOT_A) && !defined(CONFIG_PCMCIA_SLOT_B) */
/* Make sure exactly one slot is defined - we support only one for now */
#if !defined(CONFIG_PCMCIA_SLOT_A) && !defined(CONFIG_PCMCIA_SLOT_B)
#error Neither CONFIG_PCMCIA_SLOT_A nor CONFIG_PCMCIA_SLOT_B configured
#endif
#if defined(CONFIG_PCMCIA_SLOT_A) && defined(CONFIG_PCMCIA_SLOT_B)
#error Both CONFIG_PCMCIA_SLOT_A and CONFIG_PCMCIA_SLOT_B configured
#endif
#ifndef PCMCIA_SOCKETS_NO
#define PCMCIA_SOCKETS_NO 1
#endif
#ifndef PCMCIA_MEM_WIN_NO
#define PCMCIA_MEM_WIN_NO 4
#endif
#define PCMCIA_IO_WIN_NO 2
/* define _slot_ to be able to optimize macros */
#ifdef CONFIG_PCMCIA_SLOT_A
# define _slot_ 0
# define PCMCIA_SLOT_MSG "slot A"
# define PCMCIA_SLOT_x PCMCIA_PSLOT_A
#else
# define _slot_ 1
# define PCMCIA_SLOT_MSG "slot B"
# define PCMCIA_SLOT_x PCMCIA_PSLOT_B
#endif
/*
* The TQM850L hardware has two pins swapped! Grrrrgh!
*/
#ifdef CONFIG_TQM850L
#define __MY_PCMCIA_GCRX_CXRESET PCMCIA_GCRX_CXOE
#define __MY_PCMCIA_GCRX_CXOE PCMCIA_GCRX_CXRESET
#else
#define __MY_PCMCIA_GCRX_CXRESET PCMCIA_GCRX_CXRESET
#define __MY_PCMCIA_GCRX_CXOE PCMCIA_GCRX_CXOE
#endif
/*
* This structure is used to address each window in the PCMCIA controller.
*
* Keep in mind that we assume that pcmcia_win_t[n+1] is mapped directly
* after pcmcia_win_t[n]...
*/
typedef struct {
ulong br;
ulong or;
} pcmcia_win_t;
/*
* Definitions for PCMCIA control registers to operate in IDE mode
*
* All timing related setup (PCMCIA_SHT, PCMCIA_SST, PCMCIA_SL)
* to be done later (depending on CPU clock)
*/
/* Window 0:
* Base: 0xFE100000 CS1
* Port Size: 2 Bytes
* Port Size: 16 Bit
* Common Memory Space
*/
#define CONFIG_SYS_PCMCIA_PBR0 0xFE100000
#define CONFIG_SYS_PCMCIA_POR0 ( PCMCIA_BSIZE_2 \
| PCMCIA_PPS_16 \
| PCMCIA_PRS_MEM \
| PCMCIA_SLOT_x \
| PCMCIA_PV \
)
/* Window 1:
* Base: 0xFE100080 CS1
* Port Size: 8 Bytes
* Port Size: 8 Bit
* Common Memory Space
*/
#define CONFIG_SYS_PCMCIA_PBR1 0xFE100080
#define CONFIG_SYS_PCMCIA_POR1 ( PCMCIA_BSIZE_8 \
| PCMCIA_PPS_8 \
| PCMCIA_PRS_MEM \
| PCMCIA_SLOT_x \
| PCMCIA_PV \
)
/* Window 2:
* Base: 0xFE100100 CS2
* Port Size: 8 Bytes
* Port Size: 8 Bit
* Common Memory Space
*/
#define CONFIG_SYS_PCMCIA_PBR2 0xFE100100
#define CONFIG_SYS_PCMCIA_POR2 ( PCMCIA_BSIZE_8 \
| PCMCIA_PPS_8 \
| PCMCIA_PRS_MEM \
| PCMCIA_SLOT_x \
| PCMCIA_PV \
)
/* Window 3:
* not used
*/
#define CONFIG_SYS_PCMCIA_PBR3 0
#define CONFIG_SYS_PCMCIA_POR3 0
/* Window 4:
* Base: 0xFE100C00 CS1
* Port Size: 2 Bytes
* Port Size: 16 Bit
* Common Memory Space
*/
#define CONFIG_SYS_PCMCIA_PBR4 0xFE100C00
#define CONFIG_SYS_PCMCIA_POR4 ( PCMCIA_BSIZE_2 \
| PCMCIA_PPS_16 \
| PCMCIA_PRS_MEM \
| PCMCIA_SLOT_x \
| PCMCIA_PV \
)
/* Window 5:
* Base: 0xFE100C80 CS1
* Port Size: 8 Bytes
* Port Size: 8 Bit
* Common Memory Space
*/
#define CONFIG_SYS_PCMCIA_PBR5 0xFE100C80
#define CONFIG_SYS_PCMCIA_POR5 ( PCMCIA_BSIZE_8 \
| PCMCIA_PPS_8 \
| PCMCIA_PRS_MEM \
| PCMCIA_SLOT_x \
| PCMCIA_PV \
)
/* Window 6:
* Base: 0xFE100D00 CS2
* Port Size: 8 Bytes
* Port Size: 8 Bit
* Common Memory Space
*/
#define CONFIG_SYS_PCMCIA_PBR6 0xFE100D00
#define CONFIG_SYS_PCMCIA_POR6 ( PCMCIA_BSIZE_8 \
| PCMCIA_PPS_8 \
| PCMCIA_PRS_MEM \
| PCMCIA_SLOT_x \
| PCMCIA_PV \
)
/* Window 7:
* not used
*/
#define CONFIG_SYS_PCMCIA_PBR7 0
#define CONFIG_SYS_PCMCIA_POR7 0
/**********************************************************************/
/*
* CIS Tupel codes
*/
#define CISTPL_NULL 0x00
#define CISTPL_DEVICE 0x01
#define CISTPL_LONGLINK_CB 0x02
#define CISTPL_INDIRECT 0x03
#define CISTPL_CONFIG_CB 0x04
#define CISTPL_CFTABLE_ENTRY_CB 0x05
#define CISTPL_LONGLINK_MFC 0x06
#define CISTPL_BAR 0x07
#define CISTPL_PWR_MGMNT 0x08
#define CISTPL_EXTDEVICE 0x09
#define CISTPL_CHECKSUM 0x10
#define CISTPL_LONGLINK_A 0x11
#define CISTPL_LONGLINK_C 0x12
#define CISTPL_LINKTARGET 0x13
#define CISTPL_NO_LINK 0x14
#define CISTPL_VERS_1 0x15
#define CISTPL_ALTSTR 0x16
#define CISTPL_DEVICE_A 0x17
#define CISTPL_JEDEC_C 0x18
#define CISTPL_JEDEC_A 0x19
#define CISTPL_CONFIG 0x1a
#define CISTPL_CFTABLE_ENTRY 0x1b
#define CISTPL_DEVICE_OC 0x1c
#define CISTPL_DEVICE_OA 0x1d
#define CISTPL_DEVICE_GEO 0x1e
#define CISTPL_DEVICE_GEO_A 0x1f
#define CISTPL_MANFID 0x20
#define CISTPL_FUNCID 0x21
#define CISTPL_FUNCE 0x22
#define CISTPL_SWIL 0x23
#define CISTPL_END 0xff
/*
* CIS Function ID codes
*/
#define CISTPL_FUNCID_MULTI 0x00
#define CISTPL_FUNCID_MEMORY 0x01
#define CISTPL_FUNCID_SERIAL 0x02
#define CISTPL_FUNCID_PARALLEL 0x03
#define CISTPL_FUNCID_FIXED 0x04
#define CISTPL_FUNCID_VIDEO 0x05
#define CISTPL_FUNCID_NETWORK 0x06
#define CISTPL_FUNCID_AIMS 0x07
#define CISTPL_FUNCID_SCSI 0x08
/*
* Fixed Disk FUNCE codes
*/
#define CISTPL_IDE_INTERFACE 0x01
#define CISTPL_FUNCE_IDE_IFACE 0x01
#define CISTPL_FUNCE_IDE_MASTER 0x02
#define CISTPL_FUNCE_IDE_SLAVE 0x03
/* First feature byte */
#define CISTPL_IDE_SILICON 0x04
#define CISTPL_IDE_UNIQUE 0x08
#define CISTPL_IDE_DUAL 0x10
/* Second feature byte */
#define CISTPL_IDE_HAS_SLEEP 0x01
#define CISTPL_IDE_HAS_STANDBY 0x02
#define CISTPL_IDE_HAS_IDLE 0x04
#define CISTPL_IDE_LOW_POWER 0x08
#define CISTPL_IDE_REG_INHIBIT 0x10
#define CISTPL_IDE_HAS_INDEX 0x20
#define CISTPL_IDE_IOIS16 0x40
#endif
#ifdef CONFIG_8xx
extern u_int *pcmcia_pgcrx[];
#define PCMCIA_PGCRX(slot) (*pcmcia_pgcrx[slot])
#endif
#if defined(CONFIG_CMD_IDE) && defined(CONFIG_IDE_8xx_PCCARD) \
|| defined(CONFIG_PXA_PCMCIA)
extern int check_ide_device(int slot);
#endif
#endif /* _PCMCIA_H */
|
1001-study-uboot
|
include/pcmcia.h
|
C
|
gpl3
| 8,534
|
/*
* (C) Copyright 2007
* Eran Liberty, Extricom, eran.liberty@gmail.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 _STRATIXII_H_
#define _STRATIXII_H_
extern int StratixII_load (Altera_desc * desc, void *image, size_t size);
extern int StratixII_dump (Altera_desc * desc, void *buf, size_t bsize);
extern int StratixII_info (Altera_desc * desc);
#endif /* _STRATIXII_H_ */
|
1001-study-uboot
|
include/stratixII.h
|
C
|
gpl3
| 1,148
|
/*
* (C) Copyright 2000
* Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#ifndef _VIDEO_AD7177_H_
#define _VIDEO_AD7177_H_
/* #define VIDEO_DEBUG_DISABLE_COLORS 0 */
#define VIDEO_ENCODER_NAME "Analog Devices AD7177"
#define VIDEO_ENCODER_I2C_RATE 100000 /* Max rate is 100 kHz */
#define VIDEO_ENCODER_CB_Y_CR_Y /* Use CB Y CR Y format... */
#define VIDEO_MODE_YUYV /* The only mode supported by this encoder */
#undef VIDEO_MODE_RGB
#define VIDEO_MODE_BPP 16
#ifdef VIDEO_MODE_PAL
#define VIDEO_ACTIVE_COLS 720
#define VIDEO_ACTIVE_ROWS 576
#define VIDEO_VISIBLE_COLS 640
#define VIDEO_VISIBLE_ROWS 480
#endif
#ifdef VIDEO_MODE_NTSC
#define VIDEO_ACTIVE_COLS 720
#define VIDEO_ACTIVE_ROWS 525
#define VIDEO_VISIBLE_COLS 640
#define VIDEO_VISIBLE_ROWS 400
#endif
static unsigned char
video_encoder_data[] = {
#ifdef VIDEO_MODE_NTSC
0x04, /* Mode Register 0 */
#ifdef VIDEO_DEBUG_COLORBARS
0xc2,
#else
0x42, /* Mode Register 1 */
#endif /* VIDEO_DEBUG_COLORBARS */
0x16, /* Subcarrier Freq 0 */
0x7c, /* Subcarrier Freq 1 */
0xf0, /* Subcarrier Freq 2 */
0x21, /* Subcarrier Freq 3 */
0x00, /* Subcarrier phase */
0x02, /* Timing Register 0 */
0x00, /* Extended Captioning 0 */
0x00, /* Extended Captioning 1 */
0x00, /* Closed Captioning 0 */
0x00, /* Closed Captioning 1 */
0x00, /* Timing Register 1 */
0x08, /* Mode Register 2 */
0x00, /* Pedestal Register 0 */
0x00, /* Pedestal Register 1 */
0x00, /* Pedestal Register 2 */
0x00, /* Pedestal Register 3 */
0x08, /* Mode Register 3 */
#endif /* VIDEO_MODE_NTSC */
#ifdef VIDEO_MODE_PAL
#ifdef VIDEO_MODE_RGB_OUT
0x69, /* Mode Register 0 */
#ifdef VIDEO_DEBUG_COLORBARS
0xc0, /* Mode Register 1 (c0) */
#else
0x40, /* Mode Register 1 (c0) */
#endif /* VIDEO_DEBUG_COLORBARS */
0xcb, /* Subcarrier Freq 0 */
0x8a, /* Subcarrier Freq 1 */
0x09, /* Subcarrier Freq 2 */
0x2a, /* Subcarrier Freq 3 */
0x00, /* Subcarrier phase */
0x02, /* Timing Register 0 */
0x00, /* Extended Captioning 0 */
0x00, /* Extended Captioning 1 */
0x00, /* Closed Captioning 0 */
0x00, /* Closed Captioning 1 */
0x00, /* Timing Register 1 */
0x28, /* Mode Register 2 */
0x00, /* Pedestal Register 0 */
0x00, /* Pedestal Register 1 */
0x00, /* Pedestal Register 2 */
0x00, /* Pedestal Register 3 */
0x08, /* Mode Register 3 */
#else /* ! VIDEO_MODE_RGB_OUT */
0x09, /* Mode Register 0 (was 01) */
#ifdef VIDEO_DEBUG_COLORBARS
0xd8, /* */
#else
0x59, /* Mode Register 1 (was 58) */
#endif /* VIDEO_DEBUG_COLORBARS */
0xcb, /* Subcarrier Freq 0 */
0x8a, /* Subcarrier Freq 1 */
0x09, /* Subcarrier Freq 2 */
0x2a, /* Subcarrier Freq 3 */
0x00, /* Subcarrier phase */
0x02, /* Timing Register 0 (was a) */
0x00, /* Extended Captioning 0 */
0x00, /* Extended Captioning 1 */
0x00, /* Closed Captioning 0 */
0x00, /* Closed Captioning 1 */
0x00, /* Timing Register 1 */
#ifdef VIDEO_DEBUG_LOWPOWER
#ifdef VIDEO_DEBUG_DISABLE_COLORS
0x98, /* Mode Register 2 */
#else
0x88, /* Mode Register 2 */
#endif /* VIDEO_DEBUG_DISABLE_COLORS */
#else /* ! VIDEO_DEBUG_LOWPOWER */
#ifdef VIDEO_DEBUG_DISABLE_COLORS
0x18, /* Mode Register 2 */
#else
0x08, /* Mode Register 2 */
#endif /* VIDEO_DEBUG_DISABLE_COLORS */
#endif /* VIDEO_DEBUG_LOWPOWER */
0x00, /* Pedestal Register 0 */
0x00, /* Pedestal Register 1 */
0x00, /* Pedestal Register 2 */
0x00, /* Pedestal Register 3 */
0x08 /* Mode Register 3 */
#endif /* VIDEO_MODE_RGB_OUT */
#endif /* VIDEO_MODE_PAL */
} ;
#endif /* _VIDEO_AD7177_H_ */
|
1001-study-uboot
|
include/video_ad7177.h
|
C
|
gpl3
| 4,577
|
/*
* (C) Copyright 2002
* Daniel Engström, Omicron Ceti AB <daniel@omicron.se>.
*
* 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 __ASM_IC_ALI512X_H_
#define __ASM_IC_ALI512X_H_
# define ALI_INDEX 0x3f0
# define ALI_DATA 0x3f1
# define ALI_ENABLED 1
# define ALI_DISABLED 0
# define ALI_UART1 0
# define ALI_UART2 1
/* setup functions */
void ali512x_init(void);
void ali512x_set_fdc(int enabled, u16 io, u8 irq, u8 dma_channel);
void ali512x_set_pp(int enabled, u16 io, u8 irq, u8 dma_channel);
void ali512x_set_uart(int enabled, int index, u16 io, u8 irq);
void ali512x_set_rtc(int enabled, u16 io, u8 irq);
void ali512x_set_kbc(int enabled, u8 kbc_irq, u8 mouse_irq);
void ali512x_set_cio(int enabled);
/* common I/O functions */
void ali512x_cio_function(int pin, int special, int inv, int input);
void ali512x_cio_out(int pin, int value);
int ali512x_cio_in(int pin);
/* misc features */
void ali512x_set_uart2_irda(int enabled);
#endif
|
1001-study-uboot
|
include/ali512x.h
|
C
|
gpl3
| 1,725
|
/*
* An inteface for configuring a hardware via u-boot environment.
*
* Copyright (c) 2009 MontaVista Software, Inc.
* Copyright 2011 Freescale Semiconductor, Inc.
*
* Author: Anton Vorontsov <avorontsov@ru.mvista.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.
*/
#ifndef _HWCONFIG_H
#define _HWCONFIG_H
#include <linux/types.h>
#include <asm/errno.h>
#ifdef CONFIG_HWCONFIG
extern int hwconfig_f(const char *opt, char *buf);
extern const char *hwconfig_arg_f(const char *opt, size_t *arglen, char *buf);
extern int hwconfig_arg_cmp_f(const char *opt, const char *arg, char *buf);
extern int hwconfig_sub_f(const char *opt, const char *subopt, char *buf);
extern const char *hwconfig_subarg_f(const char *opt, const char *subopt,
size_t *subarglen, char *buf);
extern int hwconfig_subarg_cmp_f(const char *opt, const char *subopt,
const char *subarg, char *buf);
#else
static inline int hwconfig_f(const char *opt, char *buf)
{
return -ENOSYS;
}
static inline const char *hwconfig_arg_f(const char *opt, size_t *arglen,
char *buf)
{
*arglen = 0;
return "";
}
static inline int hwconfig_arg_cmp_f(const char *opt, const char *arg,
char *buf)
{
return -ENOSYS;
}
static inline int hwconfig_sub_f(const char *opt, const char *subopt, char *buf)
{
return -ENOSYS;
}
static inline const char *hwconfig_subarg_f(const char *opt, const char *subopt,
size_t *subarglen, char *buf)
{
*subarglen = 0;
return "";
}
static inline int hwconfig_subarg_cmp_f(const char *opt, const char *subopt,
const char *subarg, char *buf)
{
return -ENOSYS;
}
#endif /* CONFIG_HWCONFIG */
static inline int hwconfig(const char *opt)
{
return hwconfig_f(opt, NULL);
}
static inline const char *hwconfig_arg(const char *opt, size_t *arglen)
{
return hwconfig_arg_f(opt, arglen, NULL);
}
static inline int hwconfig_arg_cmp(const char *opt, const char *arg)
{
return hwconfig_arg_cmp_f(opt, arg, NULL);
}
static inline int hwconfig_sub(const char *opt, const char *subopt)
{
return hwconfig_sub_f(opt, subopt, NULL);
}
static inline const char *hwconfig_subarg(const char *opt, const char *subopt,
size_t *subarglen)
{
return hwconfig_subarg_f(opt, subopt, subarglen, NULL);
}
static inline int hwconfig_subarg_cmp(const char *opt, const char *subopt,
const char *subarg)
{
return hwconfig_subarg_cmp_f(opt, subopt, subarg, NULL);
}
#endif /* _HWCONFIG_H */
|
1001-study-uboot
|
include/hwconfig.h
|
C
|
gpl3
| 2,639
|
/*
* header file for pwm driver.
*
* Copyright (c) 2011 samsung electronics
* Donghwa Lee <dh09.lee@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
*/
#ifndef _pwm_h_
#define _pwm_h_
int pwm_init (int pwm_id, int div, int invert);
int pwm_config (int pwm_id, int duty_ns, int period_ns);
int pwm_enable (int pwm_id);
void pwm_disable (int pwm_id);
#endif /* _pwm_h_ */
|
1001-study-uboot
|
include/pwm.h
|
C
|
gpl3
| 1,063
|
/*
* MPC823 LCD and Video Controller
* Copyright (c) 1999 Dan Malek (dmalek@jlc.net)
*/
#ifndef __LCDVIDEO_H__
#define __LCDVIDEO_H__
/* LCD Controller Configuration Register.
*/
#define LCCR_BNUM ((uint)0xfffe0000)
#define LCCR_EIEN ((uint)0x00010000)
#define LCCR_IEN ((uint)0x00008000)
#define LCCR_IRQL ((uint)0x00007000)
#define LCCR_CLKP ((uint)0x00000800)
#define LCCR_OEP ((uint)0x00000400)
#define LCCR_HSP ((uint)0x00000200)
#define LCCR_VSP ((uint)0x00000100)
#define LCCR_DP ((uint)0x00000080)
#define LCCR_BPIX ((uint)0x00000060)
#define LCCR_LBW ((uint)0x00000010)
#define LCCR_SPLT ((uint)0x00000008)
#define LCCR_CLOR ((uint)0x00000004)
#define LCCR_TFT ((uint)0x00000002)
#define LCCR_PON ((uint)0x00000001)
/* Define the bit shifts to load values into the register.
*/
#define LCDBIT(BIT, VAL) ((VAL) << (31 - BIT))
#define LCCR_BNUM_BIT ((uint)14)
#define LCCR_EIEN_BIT ((uint)15)
#define LCCR_IEN_BIT ((uint)16)
#define LCCR_IROL_BIT ((uint)19)
#define LCCR_CLKP_BIT ((uint)20)
#define LCCR_OEP_BIT ((uint)21)
#define LCCR_HSP_BIT ((uint)22)
#define LCCR_VSP_BIT ((uint)23)
#define LCCR_DP_BIT ((uint)24)
#define LCCR_BPIX_BIT ((uint)26)
#define LCCR_LBW_BIT ((uint)27)
#define LCCR_SPLT_BIT ((uint)28)
#define LCCR_CLOR_BIT ((uint)29)
#define LCCR_TFT_BIT ((uint)30)
#define LCCR_PON_BIT ((uint)31)
/* LCD Horizontal control register.
*/
#define LCHCR_BO ((uint)0x01000000)
#define LCHCR_AT ((uint)0x00e00000)
#define LCHCR_HPC ((uint)0x001ffc00)
#define LCHCR_WBL ((uint)0x000003ff)
#define LCHCR_AT_BIT ((uint)10)
#define LCHCR_HPC_BIT ((uint)21)
#define LCHCR_WBL_BIT ((uint)31)
/* LCD Vertical control register.
*/
#define LCVCR_VPW ((uint)0xf0000000)
#define LCVCR_LCD_AC ((uint)0x01e00000)
#define LCVCR_VPC ((uint)0x001ff800)
#define LCVCR_WBF ((uint)0x000003ff)
#define LCVCR_VPW_BIT ((uint)3)
#define LCVCR_LCD_AC_BIT ((uint)10)
#define LCVCR_VPC_BIT ((uint)20)
#endif /* __LCDVIDEO_H__ */
|
1001-study-uboot
|
include/lcdvideo.h
|
C
|
gpl3
| 1,933
|
/*
* (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
*/
/* Video support for Epson SED13806 chipset */
#ifndef _SED13806_H_
#define _SED13806_H_
/* General definitions */
#define FRAME_BUFFER_OFFSET 0x200000 /* Frame buffer offset */
#define TOTAL_SPACE_SIZE 0x400000
#define DEFAULT_VIDEO_MEMORY_SIZE 0x140000 /* Video Memory Size */
#define HWCURSORSIZE 1024 /* Size of memory reserved
for HW cursor*/
/* Offset of chipset registers */
#define BLT_CTRL0 (0x0100)
#define BLT_CTRL1 (0x0101)
#define BLT_ROP (0x0102)
#define BLT_OP (0x0103)
#define BLT_SRC_ADDR0 (0x0104)
#define BLT_SRC_ADDR1 (0x0105)
#define BLT_SRC_ADDR2 (0x0106)
#define BLT_DST_ADDR0 (0x0108)
#define BLT_DST_ADDR1 (0x0109)
#define BLT_DST_ADDR2 (0x010A)
#define BLT_MEM_OFF0 (0x010C)
#define BLT_MEM_OFF1 (0x010D)
#define BLT_WIDTH0 (0x0110)
#define BLT_WIDTH1 (0x0111)
#define BLT_HEIGHT0 (0x0112)
#define BLT_HEIGHT1 (0x0113)
#define BLT_BGCOLOR0 (0x0114)
#define BLT_BGCOLOR1 (0x0115)
#define BLT_FGCOLOR0 (0x0118)
#define BLT_FGCOLOR1 (0x0119)
#define BLT_REG (0x100000)
/* Lookup table registers */
#define REG_LUT_ADDR 0x1e2
#define REG_LUT_DATA 0x1e4
/* Cursor/Ink registers */
#define LCD_CURSOR_CNTL (0x0070)
#define LCD_CURSOR_START (0x0071)
#define LCD_CURSOR_XL (0x0072)
#define LCD_CURSOR_XM (0x0073)
#define LCD_CURSOR_YL (0x0074)
#define LCD_CURSOR_YM (0x0075)
#define LCD_CURSOR_COL0_B (0x0076)
#define LCD_CURSOR_COL0_G (0x0077)
#define LCD_CURSOR_COL0_R (0x0078)
#define LCD_CURSOR_COL1_B (0x007A)
#define LCD_CURSOR_COL1_G (0x007B)
#define LCD_CURSOR_COL1_R (0x007C)
#define LCD_CURSOR_FIFO (0x007E)
typedef struct
{
unsigned short Index;
unsigned char Value;
} S1D_REGS;
/* Board specific functions */
unsigned int board_video_init (void);
void board_validate_screen (unsigned int base);
const S1D_REGS *board_get_regs (void);
int board_get_width (void);
int board_get_height (void);
#endif /* _SED13806_H_ */
|
1001-study-uboot
|
include/sed13806.h
|
C
|
gpl3
| 3,222
|
/*
* Copyright (C) 2011 Samsung Electronics
* Lukasz Majewski <l.majewski@samsung.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 __CORE_PMIC_H_
#define __CORE_PMIC_H_
enum { PMIC_I2C, PMIC_SPI, };
enum { I2C_PMIC, I2C_NUM, };
enum { PMIC_READ, PMIC_WRITE, };
struct p_i2c {
unsigned char addr;
unsigned char *buf;
unsigned char tx_num;
};
struct p_spi {
unsigned int cs;
unsigned int mode;
unsigned int bitlen;
unsigned int clk;
unsigned int flags;
u32 (*prepare_tx)(u32 reg, u32 *val, u32 write);
};
struct pmic {
const char *name;
unsigned char bus;
unsigned char interface;
unsigned char number_of_regs;
union hw {
struct p_i2c i2c;
struct p_spi spi;
} hw;
};
int pmic_init(void);
int check_reg(u32 reg);
struct pmic *get_pmic(void);
int pmic_probe(struct pmic *p);
int pmic_reg_read(struct pmic *p, u32 reg, u32 *val);
int pmic_reg_write(struct pmic *p, u32 reg, u32 val);
int pmic_set_output(struct pmic *p, u32 reg, int ldo, int on);
#define pmic_i2c_addr (p->hw.i2c.addr)
#define pmic_i2c_tx_num (p->hw.i2c.tx_num)
#define pmic_spi_bitlen (p->hw.spi.bitlen)
#define pmic_spi_flags (p->hw.spi.flags)
#endif /* __CORE_PMIC_H_ */
|
1001-study-uboot
|
include/pmic.h
|
C
|
gpl3
| 1,930
|
/*
* 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 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 file contains convenience functions for decoding useful and
* enlightening information from FDTs. It is intended to be used by device
* drivers and board-specific code within U-Boot. It aims to reduce the
* amount of FDT munging required within U-Boot itself, so that driver code
* changes to support FDT are minimized.
*/
#include <libfdt.h>
/*
* A typedef for a physical address. Note that fdt data is always big
* endian even on a litle endian machine.
*/
#ifdef CONFIG_PHYS_64BIT
typedef u64 fdt_addr_t;
#define FDT_ADDR_T_NONE (-1ULL)
#define fdt_addr_to_cpu(reg) be64_to_cpu(reg)
#else
typedef u32 fdt_addr_t;
#define FDT_ADDR_T_NONE (-1U)
#define fdt_addr_to_cpu(reg) be32_to_cpu(reg)
#endif
/* Information obtained about memory from the FDT */
struct fdt_memory {
fdt_addr_t start;
fdt_addr_t end;
};
/**
* Compat types that we know about and for which we might have drivers.
* Each is named COMPAT_<dir>_<filename> where <dir> is the directory
* within drivers.
*/
enum fdt_compat_id {
COMPAT_UNKNOWN,
COMPAT_COUNT,
};
/**
* Find the next numbered alias for a peripheral. This is used to enumerate
* all the peripherals of a certain type.
*
* Do the first call with *upto = 0. Assuming /aliases/<name>0 exists then
* this function will return a pointer to the node the alias points to, and
* then update *upto to 1. Next time you call this function, the next node
* will be returned.
*
* All nodes returned will match the compatible ID, as it is assumed that
* all peripherals use the same driver.
*
* @param blob FDT blob to use
* @param name Root name of alias to search for
* @param id Compatible ID to look for
* @return offset of next compatible node, or -FDT_ERR_NOTFOUND if no more
*/
int fdtdec_next_alias(const void *blob, const char *name,
enum fdt_compat_id id, int *upto);
/**
* Look up an address property in a node and return it as an address.
* The property must hold either one address with no trailing data or
* one address with a length. This is only tested on 32-bit machines.
*
* @param blob FDT blob
* @param node node to examine
* @param prop_name name of property to find
* @return address, if found, or FDT_ADDR_T_NONE if not
*/
fdt_addr_t fdtdec_get_addr(const void *blob, int node,
const char *prop_name);
/**
* Look up a 32-bit integer property in a node and return it. The property
* must have at least 4 bytes of data. The value of the first cell is
* returned.
*
* @param blob FDT blob
* @param node node to examine
* @param prop_name name of property to find
* @param default_val default value to return if the property is not found
* @return integer value, if found, or default_val if not
*/
s32 fdtdec_get_int(const void *blob, int node, const char *prop_name,
s32 default_val);
/**
* Checks whether a node is enabled.
* This looks for a 'status' property. If this exists, then returns 1 if
* the status is 'ok' and 0 otherwise. If there is no status property,
* it returns the default value.
*
* @param blob FDT blob
* @param node node to examine
* @param default_val default value to return if no 'status' property exists
* @return integer value 0/1, if found, or default_val if not
*/
int fdtdec_get_is_enabled(const void *blob, int node, int default_val);
/**
* Checks whether we have a valid fdt available to control U-Boot, and panic
* if not.
*/
int fdtdec_check_fdt(void);
|
1001-study-uboot
|
include/fdtdec.h
|
C
|
gpl3
| 4,265
|
/*
* (C) Copyright 2002 ELTEC Elektronik AG
* Frank Gottschling <fgottschling@eltec.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
*/
/* i8042.h - Intel 8042 keyboard driver header */
#ifndef _I8042_H_
#define _I8042_H_
#ifdef __I386__
#include <common.h>
#include <asm/io.h>
#define in8(p) inb(p)
#define out8(p,v) outb(v,p)
#endif
/* defines */
#define I8042_DATA_REG (CONFIG_SYS_ISA_IO + 0x0060) /* keyboard i/o buffer */
#define I8042_STATUS_REG (CONFIG_SYS_ISA_IO + 0x0064) /* keyboard status read */
#define I8042_COMMAND_REG (CONFIG_SYS_ISA_IO + 0x0064) /* keyboard ctrl write */
#define KBD_US 0 /* default US layout */
#define KBD_GER 1 /* german layout */
#define KBD_TIMEOUT 1000 /* 1 sec */
#define KBD_RESET_TRIES 3
#define AS 0 /* normal character index */
#define SH 1 /* shift index */
#define CN 2 /* control index */
#define NM 3 /* numeric lock index */
#define AK 4 /* right alt key */
#define CP 5 /* capslock index */
#define ST 6 /* stop output index */
#define EX 7 /* extended code index */
#define ES 8 /* escape and extended code index */
#define NORMAL 0x0000 /* normal key */
#define STP 0x0001 /* scroll lock stop output*/
#define NUM 0x0002 /* numeric lock */
#define CAPS 0x0004 /* capslock */
#define SHIFT 0x0008 /* shift */
#define CTRL 0x0010 /* control*/
#define EXT 0x0020 /* extended scan code 0xe0 */
#define ESC 0x0040 /* escape key press */
#define E1 0x0080 /* extended scan code 0xe1 */
#define BRK 0x0100 /* make break flag for keyboard */
#define ALT 0x0200 /* right alt */
/* exports */
int i8042_kbd_init(void);
int i8042_tstc(void);
int i8042_getc(void);
#endif /* _I8042_H_ */
|
1001-study-uboot
|
include/i8042.h
|
C
|
gpl3
| 2,887
|
/*
* Copyright (C) 2004-2007 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
*/
/* This file is autogenerated. Do not change */
#define CURRBD 4
#define DCOUNT 6
#define DESTPTR 5
#define SRCPTR 7
|
1001-study-uboot
|
include/MCD_progCheck.h
|
C
|
gpl3
| 982
|
/*
* (C) Copyright 2003
* Data Flash Atmel Description File
* Author : Hamid Ikdoumi (Atmel)
*
* 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
*/
/* File Name : dataflash.h */
/* Object : Data Flash Atmel Description File */
/* Translator : */
/* */
/* 1.0 03/04/01 HI : Creation */
/* 1.2 20/10/02 FB : Adapatation Service and Lib v3 */
/*----------------------------------------------------------------------*/
#ifndef _DataFlash_h
#define _DataFlash_h
#include "config.h"
/*number of protected area*/
#define NB_DATAFLASH_AREA 5
#ifdef CONFIG_SYS_NO_FLASH
/*-----------------------------------------------------------------------
* return codes from flash_write():
*/
# define ERR_OK 0
# define ERR_TIMOUT 1
# define ERR_NOT_ERASED 2
# define ERR_PROTECTED 4
# define ERR_INVAL 8
# define ERR_ALIGN 16
# define ERR_UNKNOWN_FLASH_VENDOR 32
# define ERR_UNKNOWN_FLASH_TYPE 64
# define ERR_PROG_ERROR 128
/*-----------------------------------------------------------------------
* Protection Flags for flash_protect():
*/
# define FLAG_PROTECT_SET 0x01
# define FLAG_PROTECT_CLEAR 0x02
# define FLAG_PROTECT_INVALID 0x03
/*-----------------------------------------------------------------------
* Set Environment according to label:
*/
# define FLAG_SETENV 0x80
#endif /* CONFIG_SYS_NO_FLASH */
/*define the area structure*/
typedef struct {
unsigned long start;
unsigned long end;
unsigned char protected;
unsigned char setenv;
unsigned char label[20];
} dataflash_protect_t;
typedef unsigned int AT91S_DataFlashStatus;
/*----------------------------------------------------------------------*/
/* DataFlash Structures */
/*----------------------------------------------------------------------*/
/*---------------------------------------------*/
/* DataFlash Descriptor Structure Definition */
/*---------------------------------------------*/
typedef struct _AT91S_DataflashDesc {
unsigned char *tx_cmd_pt;
unsigned int tx_cmd_size;
unsigned char *rx_cmd_pt;
unsigned int rx_cmd_size;
unsigned char *tx_data_pt;
unsigned int tx_data_size;
unsigned char *rx_data_pt;
unsigned int rx_data_size;
volatile unsigned char state;
volatile unsigned char DataFlash_state;
unsigned char command[8];
} AT91S_DataflashDesc, *AT91PS_DataflashDesc;
/*---------------------------------------------*/
/* DataFlash device definition structure */
/*---------------------------------------------*/
typedef struct _AT91S_Dataflash {
int pages_number; /* dataflash page number */
int pages_size; /* dataflash page size */
int page_offset; /* page offset in command */
int byte_mask; /* byte mask in command */
int cs;
dataflash_protect_t area_list[NB_DATAFLASH_AREA]; /* area protection status */
} AT91S_DataflashFeatures, *AT91PS_DataflashFeatures;
/*---------------------------------------------*/
/* DataFlash Structure Definition */
/*---------------------------------------------*/
typedef struct _AT91S_DataFlash {
AT91PS_DataflashDesc pDataFlashDesc; /* dataflash descriptor */
AT91PS_DataflashFeatures pDevice; /* Pointer on a dataflash features array */
} AT91S_DataFlash, *AT91PS_DataFlash;
typedef struct _AT91S_DATAFLASH_INFO {
AT91S_DataflashDesc Desc;
AT91S_DataflashFeatures Device; /* Pointer on a dataflash features array */
unsigned long logical_address;
unsigned long end_address;
unsigned int id; /* device id */
} AT91S_DATAFLASH_INFO, *AT91PS_DATAFLASH_INFO;
struct dataflash_addr {
unsigned long addr;
int cs;
};
/*-------------------------------------------------------------------------------------------------*/
#define AT45DB161 0x2c
#define AT45DB021 0x14
#define AT45DB081 0x24
#define AT45DB321 0x34
#define AT45DB642 0x3c
#define AT45DB128 0x10
#define PAGES_PER_BLOCK 8
#define AT91C_DATAFLASH_TIMEOUT 10000 /* For AT91F_DataFlashWaitReady */
/* DataFlash return value */
#define DATAFLASH_BUSY 0x00
#define DATAFLASH_OK 0x01
#define DATAFLASH_ERROR 0x02
#define DATAFLASH_MEMORY_OVERFLOW 0x03
#define DATAFLASH_BAD_COMMAND 0x04
#define DATAFLASH_BAD_ADDRESS 0x05
/* Driver State */
#define IDLE 0x0
#define BUSY 0x1
#define ERROR 0x2
/* DataFlash Driver State */
#define GET_STATUS 0x0F
/*-------------------------------------------------------------------------------------------------*/
/* Command Definition */
/*-------------------------------------------------------------------------------------------------*/
/* READ COMMANDS */
#define DB_CONTINUOUS_ARRAY_READ 0xE8 /* Continuous array read */
#define DB_BURST_ARRAY_READ 0xE8 /* Burst array read */
#define DB_PAGE_READ 0xD2 /* Main memory page read */
#define DB_BUF1_READ 0xD4 /* Buffer 1 read */
#define DB_BUF2_READ 0xD6 /* Buffer 2 read */
#define DB_STATUS 0xD7 /* Status Register */
/* PROGRAM and ERASE COMMANDS */
#define DB_BUF1_WRITE 0x84 /* Buffer 1 write */
#define DB_BUF2_WRITE 0x87 /* Buffer 2 write */
#define DB_BUF1_PAGE_ERASE_PGM 0x83 /* Buffer 1 to main memory page program with built-In erase */
#define DB_BUF1_PAGE_ERASE_FASTPGM 0x93 /* Buffer 1 to main memory page program with built-In erase, Fast program */
#define DB_BUF2_PAGE_ERASE_PGM 0x86 /* Buffer 2 to main memory page program with built-In erase */
#define DB_BUF2_PAGE_ERASE_FASTPGM 0x96 /* Buffer 1 to main memory page program with built-In erase, Fast program */
#define DB_BUF1_PAGE_PGM 0x88 /* Buffer 1 to main memory page program without built-In erase */
#define DB_BUF1_PAGE_FASTPGM 0x98 /* Buffer 1 to main memory page program without built-In erase, Fast program */
#define DB_BUF2_PAGE_PGM 0x89 /* Buffer 2 to main memory page program without built-In erase */
#define DB_BUF2_PAGE_FASTPGM 0x99 /* Buffer 1 to main memory page program without built-In erase, Fast program */
#define DB_PAGE_ERASE 0x81 /* Page Erase */
#define DB_BLOCK_ERASE 0x50 /* Block Erase */
#define DB_PAGE_PGM_BUF1 0x82 /* Main memory page through buffer 1 */
#define DB_PAGE_FASTPGM_BUF1 0x92 /* Main memory page through buffer 1, Fast program */
#define DB_PAGE_PGM_BUF2 0x85 /* Main memory page through buffer 2 */
#define DB_PAGE_FastPGM_BUF2 0x95 /* Main memory page through buffer 2, Fast program */
/* ADDITIONAL COMMANDS */
#define DB_PAGE_2_BUF1_TRF 0x53 /* Main memory page to buffer 1 transfert */
#define DB_PAGE_2_BUF2_TRF 0x55 /* Main memory page to buffer 2 transfert */
#define DB_PAGE_2_BUF1_CMP 0x60 /* Main memory page to buffer 1 compare */
#define DB_PAGE_2_BUF2_CMP 0x61 /* Main memory page to buffer 2 compare */
#define DB_AUTO_PAGE_PGM_BUF1 0x58 /* Auto page rewrite throught buffer 1 */
#define DB_AUTO_PAGE_PGM_BUF2 0x59 /* Auto page rewrite throught buffer 2 */
/*-------------------------------------------------------------------------------------------------*/
extern int size_dataflash (AT91PS_DataFlash pdataFlash, unsigned long addr, unsigned long size);
extern int prot_dataflash (AT91PS_DataFlash pdataFlash, unsigned long addr);
extern int addr2ram(ulong addr);
extern int dataflash_real_protect (int flag, unsigned long start_addr, unsigned long end_addr);
extern int addr_dataflash (unsigned long addr);
extern int read_dataflash (unsigned long addr, unsigned long size, char *result);
extern int write_dataflash(unsigned long addr_dest, unsigned long addr_src,
unsigned long size);
extern int AT91F_DataflashInit(void);
extern void dataflash_print_info (void);
extern void dataflash_perror (int err);
extern void AT91F_DataflashSetEnv (void);
extern struct dataflash_addr cs[CONFIG_SYS_MAX_DATAFLASH_BANKS];
extern dataflash_protect_t area_list[NB_DATAFLASH_AREA];
extern AT91S_DATAFLASH_INFO dataflash_info[];
#endif
|
1001-study-uboot
|
include/dataflash.h
|
C
|
gpl3
| 8,462
|
#ifndef __KGDB_H__
#define __KGDB_H__
#include <asm/ptrace.h>
#define KGDBERR_BADPARAMS 1
#define KGDBERR_NOTHEXDIG 2
#define KGDBERR_MEMFAULT 3
#define KGDBERR_NOSPACE 4
#define KGDBERR_ALIGNFAULT 5
#define KGDBDATA_MAXREGS 8
#define KGDBDATA_MAXPRIV 8
#define KGDBEXIT_TYPEMASK 0xff
#define KGDBEXIT_KILL 0
#define KGDBEXIT_CONTINUE 1
#define KGDBEXIT_SINGLE 2
#define KGDBEXIT_WITHADDR 0x100
typedef
struct {
int num;
unsigned long val;
}
kgdb_reg;
typedef
struct {
int sigval;
int extype;
unsigned long exaddr;
int nregs;
kgdb_reg regs[KGDBDATA_MAXREGS];
unsigned long private[KGDBDATA_MAXPRIV];
}
kgdb_data;
/* these functions are provided by the generic kgdb support */
extern void kgdb_init(void);
extern void kgdb_error(int);
extern int kgdb_output_string(const char *, unsigned int);
extern void breakpoint(void);
/* these functions are provided by the platform specific kgdb support */
extern void kgdb_flush_cache_range(void *, void *);
extern void kgdb_flush_cache_all(void);
extern int kgdb_setjmp(long *);
extern void kgdb_longjmp(long *, int);
extern void kgdb_enter(struct pt_regs *, kgdb_data *);
extern void kgdb_exit(struct pt_regs *, kgdb_data *);
extern int kgdb_getregs(struct pt_regs *, char *, int);
extern void kgdb_putreg(struct pt_regs *, int, char *, int);
extern void kgdb_putregs(struct pt_regs *, char *, int);
extern int kgdb_trap(struct pt_regs *);
extern void kgdb_breakpoint(int argc, char * const argv[]);
/* these functions are provided by the platform serial driver */
extern void kgdb_serial_init(void);
extern int getDebugChar(void);
extern void putDebugChar(int);
extern void putDebugStr(const char *);
extern void kgdb_interruptible(int);
/* this is referenced in the trap handler for the platform */
extern int (*debugger_exception_handler)(struct pt_regs *);
#endif /* __KGDB_H__ */
|
1001-study-uboot
|
include/kgdb.h
|
C
|
gpl3
| 1,863
|
/*
* 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
*/
/*
* lh7a400 SoC interface
*/
#ifndef __LH7A400_H__
#define __LH7A400_H__
#include "lh7a40x.h"
/* Interrupt Controller (userguide 8.2.1) */
typedef struct {
volatile u32 intsr;
volatile u32 intrsr;
volatile u32 intens;
volatile u32 intenc;
volatile u32 rsvd1;
volatile u32 rsvd2;
volatile u32 rsvd3;
} /*__attribute__((__packed__))*/ lh7a400_interrupt_t;
#define LH7A400_INTERRUPT_BASE (0x80000500)
#define LH7A400_INTERRUPT_PTR ((lh7a400_interrupt_t*) LH7A400_INTERRUPT_BASE)
/* (DMA) Direct Memory Access Controller (userguide 9.2.1) */
typedef struct {
lh7a40x_dmachan_t chan[15];
volatile u32 glblint;
volatile u32 rsvd1;
volatile u32 rsvd2;
volatile u32 rsvd3;
} /*__attribute__((__packed__))*/ lh7a400_dma_t;
#define LH7A400_DMA_BASE (0x80002800)
#define DMA_USBTX_OFFSET (0x000)
#define DMA_USBRX_OFFSET (0x040)
#define DMA_MMCTX_OFFSET (0x080)
#define DMA_MMCRX_OFFSET (0x0C0)
#define DMA_AC97_BASE (0x80002A00)
#define LH7A400_DMA_PTR ((lh7a400_dma_t*) LH7A400_DMA_BASE)
#define LH7A400_DMA_USBTX \
((lh7a400_dmachan_t*) (LH7A400_DMA_BASE + DMA_USBTX_OFFSET))
#define LH7A400_DMA_USBRX \
((lh7a400_dmachan_t*) (LH7A400_DMA_BASE + DMA_USBRX_OFFSET))
#define LH7A400_DMA_MMCTX \
((lh7a400_dmachan_t*) (LH7A400_DMA_BASE + DMA_MMCTX_OFFSET))
#define LH7A400_DMA_MMCRX \
((lh7a400_dmachan_t*) (LH7A400_DMA_BASE + DMA_MMCRX_OFFSET))
#define LH7A400_AC97RX(n) \
((lh7a400_dmachan_t*) (LH7A400_AC97_BASE + \
((2*n) * sizeof(lh7a400_dmachan_t))))
#define LH7A400_AC97TX(n) \
((lh7a400_dmachan_t*) (LH7A400_AC97_BASE + \
(((2*n)+1) * sizeof(lh7a400_dmachan_t))))
#endif /* __LH7A400_H__ */
|
1001-study-uboot
|
include/lh7a400.h
|
C
|
gpl3
| 2,494
|
/*
* Copyright 2008 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.
*/
#ifndef _DDR_SPD_H_
#define _DDR_SPD_H_
/*
* Format from "JEDEC Standard No. 21-C,
* Appendix D: Rev 1.0: SPD's for DDR SDRAM
*/
typedef struct ddr1_spd_eeprom_s {
unsigned char info_size; /* 0 # bytes written into serial memory */
unsigned char chip_size; /* 1 Total # bytes of SPD memory device */
unsigned char mem_type; /* 2 Fundamental memory type */
unsigned char nrow_addr; /* 3 # of Row Addresses on this assembly */
unsigned char ncol_addr; /* 4 # of Column Addrs on this assembly */
unsigned char nrows; /* 5 Number of DIMM Banks */
unsigned char dataw_lsb; /* 6 Data Width of this assembly */
unsigned char dataw_msb; /* 7 ... Data Width continuation */
unsigned char voltage; /* 8 Voltage intf std of this assembly */
unsigned char clk_cycle; /* 9 SDRAM Cycle time @ CL=X */
unsigned char clk_access; /* 10 SDRAM Access from Clk @ CL=X (tAC) */
unsigned char config; /* 11 DIMM Configuration type */
unsigned char refresh; /* 12 Refresh Rate/Type */
unsigned char primw; /* 13 Primary SDRAM Width */
unsigned char ecw; /* 14 Error Checking SDRAM width */
unsigned char min_delay; /* 15 for Back to Back Random Address */
unsigned char burstl; /* 16 Burst Lengths Supported */
unsigned char nbanks; /* 17 # of Banks on SDRAM Device */
unsigned char cas_lat; /* 18 CAS# Latencies Supported */
unsigned char cs_lat; /* 19 CS# Latency */
unsigned char write_lat; /* 20 Write Latency (aka Write Recovery) */
unsigned char mod_attr; /* 21 SDRAM Module Attributes */
unsigned char dev_attr; /* 22 SDRAM Device Attributes */
unsigned char clk_cycle2; /* 23 Min SDRAM Cycle time @ CL=X-0.5 */
unsigned char clk_access2; /* 24 SDRAM Access from
Clk @ CL=X-0.5 (tAC) */
unsigned char clk_cycle3; /* 25 Min SDRAM Cycle time @ CL=X-1 */
unsigned char clk_access3; /* 26 Max Access from Clk @ CL=X-1 (tAC) */
unsigned char trp; /* 27 Min Row Precharge Time (tRP)*/
unsigned char trrd; /* 28 Min Row Active to Row Active (tRRD) */
unsigned char trcd; /* 29 Min RAS to CAS Delay (tRCD) */
unsigned char tras; /* 30 Minimum RAS Pulse Width (tRAS) */
unsigned char bank_dens; /* 31 Density of each bank on module */
unsigned char ca_setup; /* 32 Addr + Cmd Setup Time Before Clk */
unsigned char ca_hold; /* 33 Addr + Cmd Hold Time After Clk */
unsigned char data_setup; /* 34 Data Input Setup Time Before Strobe */
unsigned char data_hold; /* 35 Data Input Hold Time After Strobe */
unsigned char res_36_40[5];/* 36-40 reserved for VCSDRAM */
unsigned char trc; /* 41 Min Active to Auto refresh time tRC */
unsigned char trfc; /* 42 Min Auto to Active period tRFC */
unsigned char tckmax; /* 43 Max device cycle time tCKmax */
unsigned char tdqsq; /* 44 Max DQS to DQ skew (tDQSQ max) */
unsigned char tqhs; /* 45 Max Read DataHold skew (tQHS) */
unsigned char res_46; /* 46 Reserved */
unsigned char dimm_height; /* 47 DDR SDRAM DIMM Height */
unsigned char res_48_61[14]; /* 48-61 Reserved */
unsigned char spd_rev; /* 62 SPD Data Revision Code */
unsigned char cksum; /* 63 Checksum for bytes 0-62 */
unsigned char mid[8]; /* 64-71 Mfr's JEDEC ID code per JEP-106 */
unsigned char mloc; /* 72 Manufacturing Location */
unsigned char mpart[18]; /* 73 Manufacturer's Part Number */
unsigned char rev[2]; /* 91 Revision Code */
unsigned char mdate[2]; /* 93 Manufacturing Date */
unsigned char sernum[4]; /* 95 Assembly Serial Number */
unsigned char mspec[27]; /* 99-127 Manufacturer Specific Data */
} ddr1_spd_eeprom_t;
/*
* Format from "JEDEC Appendix X: Serial Presence Detects for DDR2 SDRAM",
* SPD Revision 1.2
*/
typedef struct ddr2_spd_eeprom_s {
unsigned char info_size; /* 0 # bytes written into serial memory */
unsigned char chip_size; /* 1 Total # bytes of SPD memory device */
unsigned char mem_type; /* 2 Fundamental memory type */
unsigned char nrow_addr; /* 3 # of Row Addresses on this assembly */
unsigned char ncol_addr; /* 4 # of Column Addrs on this assembly */
unsigned char mod_ranks; /* 5 Number of DIMM Ranks */
unsigned char dataw; /* 6 Module Data Width */
unsigned char res_7; /* 7 Reserved */
unsigned char voltage; /* 8 Voltage intf std of this assembly */
unsigned char clk_cycle; /* 9 SDRAM Cycle time @ CL=X */
unsigned char clk_access; /* 10 SDRAM Access from Clk @ CL=X (tAC) */
unsigned char config; /* 11 DIMM Configuration type */
unsigned char refresh; /* 12 Refresh Rate/Type */
unsigned char primw; /* 13 Primary SDRAM Width */
unsigned char ecw; /* 14 Error Checking SDRAM width */
unsigned char res_15; /* 15 Reserved */
unsigned char burstl; /* 16 Burst Lengths Supported */
unsigned char nbanks; /* 17 # of Banks on Each SDRAM Device */
unsigned char cas_lat; /* 18 CAS# Latencies Supported */
unsigned char mech_char; /* 19 DIMM Mechanical Characteristics */
unsigned char dimm_type; /* 20 DIMM type information */
unsigned char mod_attr; /* 21 SDRAM Module Attributes */
unsigned char dev_attr; /* 22 SDRAM Device Attributes */
unsigned char clk_cycle2; /* 23 Min SDRAM Cycle time @ CL=X-1 */
unsigned char clk_access2; /* 24 SDRAM Access from Clk @ CL=X-1 (tAC) */
unsigned char clk_cycle3; /* 25 Min SDRAM Cycle time @ CL=X-2 */
unsigned char clk_access3; /* 26 Max Access from Clk @ CL=X-2 (tAC) */
unsigned char trp; /* 27 Min Row Precharge Time (tRP)*/
unsigned char trrd; /* 28 Min Row Active to Row Active (tRRD) */
unsigned char trcd; /* 29 Min RAS to CAS Delay (tRCD) */
unsigned char tras; /* 30 Minimum RAS Pulse Width (tRAS) */
unsigned char rank_dens; /* 31 Density of each rank on module */
unsigned char ca_setup; /* 32 Addr+Cmd Setup Time Before Clk (tIS) */
unsigned char ca_hold; /* 33 Addr+Cmd Hold Time After Clk (tIH) */
unsigned char data_setup; /* 34 Data Input Setup Time
Before Strobe (tDS) */
unsigned char data_hold; /* 35 Data Input Hold Time
After Strobe (tDH) */
unsigned char twr; /* 36 Write Recovery time tWR */
unsigned char twtr; /* 37 Int write to read delay tWTR */
unsigned char trtp; /* 38 Int read to precharge delay tRTP */
unsigned char mem_probe; /* 39 Mem analysis probe characteristics */
unsigned char trctrfc_ext; /* 40 Extensions to trc and trfc */
unsigned char trc; /* 41 Min Active to Auto refresh time tRC */
unsigned char trfc; /* 42 Min Auto to Active period tRFC */
unsigned char tckmax; /* 43 Max device cycle time tCKmax */
unsigned char tdqsq; /* 44 Max DQS to DQ skew (tDQSQ max) */
unsigned char tqhs; /* 45 Max Read DataHold skew (tQHS) */
unsigned char pll_relock; /* 46 PLL Relock time */
unsigned char Tcasemax; /* 47 Tcasemax */
unsigned char psiTAdram; /* 48 Thermal Resistance of DRAM Package from
Top (Case) to Ambient (Psi T-A DRAM) */
unsigned char dt0_mode; /* 49 DRAM Case Temperature Rise from Ambient
due to Activate-Precharge/Mode Bits
(DT0/Mode Bits) */
unsigned char dt2n_dt2q; /* 50 DRAM Case Temperature Rise from Ambient
due to Precharge/Quiet Standby
(DT2N/DT2Q) */
unsigned char dt2p; /* 51 DRAM Case Temperature Rise from Ambient
due to Precharge Power-Down (DT2P) */
unsigned char dt3n; /* 52 DRAM Case Temperature Rise from Ambient
due to Active Standby (DT3N) */
unsigned char dt3pfast; /* 53 DRAM Case Temperature Rise from Ambient
due to Active Power-Down with
Fast PDN Exit (DT3Pfast) */
unsigned char dt3pslow; /* 54 DRAM Case Temperature Rise from Ambient
due to Active Power-Down with Slow
PDN Exit (DT3Pslow) */
unsigned char dt4r_dt4r4w; /* 55 DRAM Case Temperature Rise from Ambient
due to Page Open Burst Read/DT4R4W
Mode Bit (DT4R/DT4R4W Mode Bit) */
unsigned char dt5b; /* 56 DRAM Case Temperature Rise from Ambient
due to Burst Refresh (DT5B) */
unsigned char dt7; /* 57 DRAM Case Temperature Rise from Ambient
due to Bank Interleave Reads with
Auto-Precharge (DT7) */
unsigned char psiTApll; /* 58 Thermal Resistance of PLL Package form
Top (Case) to Ambient (Psi T-A PLL) */
unsigned char psiTAreg; /* 59 Thermal Reisitance of Register Package
from Top (Case) to Ambient
(Psi T-A Register) */
unsigned char dtpllactive; /* 60 PLL Case Temperature Rise from Ambient
due to PLL Active (DT PLL Active) */
unsigned char dtregact; /* 61 Register Case Temperature Rise from
Ambient due to Register Active/Mode Bit
(DT Register Active/Mode Bit) */
unsigned char spd_rev; /* 62 SPD Data Revision Code */
unsigned char cksum; /* 63 Checksum for bytes 0-62 */
unsigned char mid[8]; /* 64 Mfr's JEDEC ID code per JEP-106 */
unsigned char mloc; /* 72 Manufacturing Location */
unsigned char mpart[18]; /* 73 Manufacturer's Part Number */
unsigned char rev[2]; /* 91 Revision Code */
unsigned char mdate[2]; /* 93 Manufacturing Date */
unsigned char sernum[4]; /* 95 Assembly Serial Number */
unsigned char mspec[27]; /* 99-127 Manufacturer Specific Data */
} ddr2_spd_eeprom_t;
typedef struct ddr3_spd_eeprom_s {
/* General Section: Bytes 0-59 */
unsigned char info_size_crc; /* 0 # bytes written into serial memory,
CRC coverage */
unsigned char spd_rev; /* 1 Total # bytes of SPD mem device */
unsigned char mem_type; /* 2 Key Byte / Fundamental mem type */
unsigned char module_type; /* 3 Key Byte / Module Type */
unsigned char density_banks; /* 4 SDRAM Density and Banks */
unsigned char addressing; /* 5 SDRAM Addressing */
unsigned char module_vdd; /* 6 Module nominal voltage, VDD */
unsigned char organization; /* 7 Module Organization */
unsigned char bus_width; /* 8 Module Memory Bus Width */
unsigned char ftb_div; /* 9 Fine Timebase (FTB)
Dividend / Divisor */
unsigned char mtb_dividend; /* 10 Medium Timebase (MTB) Dividend */
unsigned char mtb_divisor; /* 11 Medium Timebase (MTB) Divisor */
unsigned char tCK_min; /* 12 SDRAM Minimum Cycle Time */
unsigned char res_13; /* 13 Reserved */
unsigned char caslat_lsb; /* 14 CAS Latencies Supported,
Least Significant Byte */
unsigned char caslat_msb; /* 15 CAS Latencies Supported,
Most Significant Byte */
unsigned char tAA_min; /* 16 Min CAS Latency Time */
unsigned char tWR_min; /* 17 Min Write REcovery Time */
unsigned char tRCD_min; /* 18 Min RAS# to CAS# Delay Time */
unsigned char tRRD_min; /* 19 Min Row Active to
Row Active Delay Time */
unsigned char tRP_min; /* 20 Min Row Precharge Delay Time */
unsigned char tRAS_tRC_ext; /* 21 Upper Nibbles for tRAS and tRC */
unsigned char tRAS_min_lsb; /* 22 Min Active to Precharge
Delay Time */
unsigned char tRC_min_lsb; /* 23 Min Active to Active/Refresh
Delay Time, LSB */
unsigned char tRFC_min_lsb; /* 24 Min Refresh Recovery Delay Time */
unsigned char tRFC_min_msb; /* 25 Min Refresh Recovery Delay Time */
unsigned char tWTR_min; /* 26 Min Internal Write to
Read Command Delay Time */
unsigned char tRTP_min; /* 27 Min Internal Read to Precharge
Command Delay Time */
unsigned char tFAW_msb; /* 28 Upper Nibble for tFAW */
unsigned char tFAW_min; /* 29 Min Four Activate Window
Delay Time*/
unsigned char opt_features; /* 30 SDRAM Optional Features */
unsigned char therm_ref_opt; /* 31 SDRAM Thermal and Refresh Opts */
unsigned char therm_sensor; /* 32 Module Thermal Sensor */
unsigned char device_type; /* 33 SDRAM device type */
unsigned char res_34_59[26]; /* 34-59 Reserved, General Section */
/* Module-Specific Section: Bytes 60-116 */
union {
struct {
/* 60 (Unbuffered) Module Nominal Height */
unsigned char mod_height;
/* 61 (Unbuffered) Module Maximum Thickness */
unsigned char mod_thickness;
/* 62 (Unbuffered) Reference Raw Card Used */
unsigned char ref_raw_card;
/* 63 (Unbuffered) Address Mapping from
Edge Connector to DRAM */
unsigned char addr_mapping;
/* 64-116 (Unbuffered) Reserved */
unsigned char res_64_116[53];
} unbuffered;
struct {
/* 60 (Registered) Module Nominal Height */
unsigned char mod_height;
/* 61 (Registered) Module Maximum Thickness */
unsigned char mod_thickness;
/* 62 (Registered) Reference Raw Card Used */
unsigned char ref_raw_card;
/* 63 DIMM Module Attributes */
unsigned char modu_attr;
/* 64 RDIMM Thermal Heat Spreader Solution */
unsigned char thermal;
/* 65 Register Manufacturer ID Code, Least Significant Byte */
unsigned char reg_id_lo;
/* 66 Register Manufacturer ID Code, Most Significant Byte */
unsigned char reg_id_hi;
/* 67 Register Revision Number */
unsigned char reg_rev;
/* 68 Register Type */
unsigned char reg_type;
/* 69-76 RC1,3,5...15 (MS Nibble) / RC0,2,4...14 (LS Nibble) */
unsigned char rcw[8];
} registered;
unsigned char uc[57]; /* 60-116 Module-Specific Section */
} mod_section;
/* Unique Module ID: Bytes 117-125 */
unsigned char mmid_lsb; /* 117 Module MfgID Code LSB - JEP-106 */
unsigned char mmid_msb; /* 118 Module MfgID Code MSB - JEP-106 */
unsigned char mloc; /* 119 Mfg Location */
unsigned char mdate[2]; /* 120-121 Mfg Date */
unsigned char sernum[4]; /* 122-125 Module Serial Number */
/* CRC: Bytes 126-127 */
unsigned char crc[2]; /* 126-127 SPD CRC */
/* Other Manufacturer Fields and User Space: Bytes 128-255 */
unsigned char mpart[18]; /* 128-145 Mfg's Module Part Number */
unsigned char mrev[2]; /* 146-147 Module Revision Code */
unsigned char dmid_lsb; /* 148 DRAM MfgID Code LSB - JEP-106 */
unsigned char dmid_msb; /* 149 DRAM MfgID Code MSB - JEP-106 */
unsigned char msd[26]; /* 150-175 Mfg's Specific Data */
unsigned char cust[80]; /* 176-255 Open for Customer Use */
} ddr3_spd_eeprom_t;
extern unsigned int ddr1_spd_check(const ddr1_spd_eeprom_t *spd);
extern void ddr1_spd_dump(const ddr1_spd_eeprom_t *spd);
extern unsigned int ddr2_spd_check(const ddr2_spd_eeprom_t *spd);
extern void ddr2_spd_dump(const ddr2_spd_eeprom_t *spd);
extern unsigned int ddr3_spd_check(const ddr3_spd_eeprom_t *spd);
/*
* Byte 2 Fundamental Memory Types.
*/
#define SPD_MEMTYPE_FPM (0x01)
#define SPD_MEMTYPE_EDO (0x02)
#define SPD_MEMTYPE_PIPE_NIBBLE (0x03)
#define SPD_MEMTYPE_SDRAM (0x04)
#define SPD_MEMTYPE_ROM (0x05)
#define SPD_MEMTYPE_SGRAM (0x06)
#define SPD_MEMTYPE_DDR (0x07)
#define SPD_MEMTYPE_DDR2 (0x08)
#define SPD_MEMTYPE_DDR2_FBDIMM (0x09)
#define SPD_MEMTYPE_DDR2_FBDIMM_PROBE (0x0A)
#define SPD_MEMTYPE_DDR3 (0x0B)
/* DIMM Type for DDR2 SPD (according to v1.3) */
#define DDR2_SPD_DIMMTYPE_UNDEFINED (0x00)
#define DDR2_SPD_DIMMTYPE_RDIMM (0x01)
#define DDR2_SPD_DIMMTYPE_UDIMM (0x02)
#define DDR2_SPD_DIMMTYPE_SO_DIMM (0x04)
#define DDR2_SPD_DIMMTYPE_72B_SO_CDIMM (0x06)
#define DDR2_SPD_DIMMTYPE_72B_SO_RDIMM (0x07)
#define DDR2_SPD_DIMMTYPE_MICRO_DIMM (0x08)
#define DDR2_SPD_DIMMTYPE_MINI_RDIMM (0x10)
#define DDR2_SPD_DIMMTYPE_MINI_UDIMM (0x20)
/* Byte 3 Key Byte / Module Type for DDR3 SPD */
#define DDR3_SPD_MODULETYPE_MASK (0x0f)
#define DDR3_SPD_MODULETYPE_RDIMM (0x01)
#define DDR3_SPD_MODULETYPE_UDIMM (0x02)
#define DDR3_SPD_MODULETYPE_SO_DIMM (0x03)
#define DDR3_SPD_MODULETYPE_MICRO_DIMM (0x04)
#define DDR3_SPD_MODULETYPE_MINI_RDIMM (0x05)
#define DDR3_SPD_MODULETYPE_MINI_UDIMM (0x06)
#define DDR3_SPD_MODULETYPE_MINI_CDIMM (0x07)
#define DDR3_SPD_MODULETYPE_72B_SO_UDIMM (0x08)
#define DDR3_SPD_MODULETYPE_72B_SO_RDIMM (0x09)
#define DDR3_SPD_MODULETYPE_72B_SO_CDIMM (0x0A)
#define DDR3_SPD_MODULETYPE_LRDIMM (0x0B)
#define DDR3_SPD_MODULETYPE_16B_SO_DIMM (0x0C)
#define DDR3_SPD_MODULETYPE_32B_SO_DIMM (0x0D)
#endif /* _DDR_SPD_H_ */
|
1001-study-uboot
|
include/ddr_spd.h
|
C
|
gpl3
| 16,638
|
/*
* (C) Copyright 2001
* Denis Peter, MPL AG Switzerland
*
* 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
*
*
* Most of these definitions are derived from
* linux/drivers/scsi/sym53c8xx_defs.h
*
*/
#ifndef _SYM53C8XX_DEFS_H
#define _SYM53C8XX_DEFS_H
#define SCNTL0 0x00 /* full arb., ena parity, par->ATN */
#define SCNTL1 0x01 /* no reset */
#define ISCON 0x10 /* connected to scsi */
#define CRST 0x08 /* force reset */
#define IARB 0x02 /* immediate arbitration */
#define SCNTL2 0x02 /* no disconnect expected */
#define SDU 0x80 /* cmd: disconnect will raise error */
#define CHM 0x40 /* sta: chained mode */
#define WSS 0x08 /* sta: wide scsi send [W]*/
#define WSR 0x01 /* sta: wide scsi received [W]*/
#define SCNTL3 0x03 /* cnf system clock dependent */
#define EWS 0x08 /* cmd: enable wide scsi [W]*/
#define ULTRA 0x80 /* cmd: ULTRA enable */
/* bits 0-2, 7 rsvd for C1010 */
#define SCID 0x04 /* cnf host adapter scsi address */
#define RRE 0x40 /* r/w:e enable response to resel. */
#define SRE 0x20 /* r/w:e enable response to select */
#define SXFER 0x05 /* ### Sync speed and count */
/* bits 6-7 rsvd for C1010 */
#define SDID 0x06 /* ### Destination-ID */
#define GPREG 0x07 /* ??? IO-Pins */
#define SFBR 0x08 /* ### First byte in phase */
#define SOCL 0x09
#define CREQ 0x80 /* r/w: SCSI-REQ */
#define CACK 0x40 /* r/w: SCSI-ACK */
#define CBSY 0x20 /* r/w: SCSI-BSY */
#define CSEL 0x10 /* r/w: SCSI-SEL */
#define CATN 0x08 /* r/w: SCSI-ATN */
#define CMSG 0x04 /* r/w: SCSI-MSG */
#define CC_D 0x02 /* r/w: SCSI-C_D */
#define CI_O 0x01 /* r/w: SCSI-I_O */
#define SSID 0x0a
#define SBCL 0x0b
#define DSTAT 0x0c
#define DFE 0x80 /* sta: dma fifo empty */
#define MDPE 0x40 /* int: master data parity error */
#define BF 0x20 /* int: script: bus fault */
#define ABRT 0x10 /* int: script: command aborted */
#define SSI 0x08 /* int: script: single step */
#define SIR 0x04 /* int: script: interrupt instruct. */
#define IID 0x01 /* int: script: illegal instruct. */
#define SSTAT0 0x0d
#define ILF 0x80 /* sta: data in SIDL register lsb */
#define ORF 0x40 /* sta: data in SODR register lsb */
#define OLF 0x20 /* sta: data in SODL register lsb */
#define AIP 0x10 /* sta: arbitration in progress */
#define LOA 0x08 /* sta: arbitration lost */
#define WOA 0x04 /* sta: arbitration won */
#define IRST 0x02 /* sta: scsi reset signal */
#define SDP 0x01 /* sta: scsi parity signal */
#define SSTAT1 0x0e
#define FF3210 0xf0 /* sta: bytes in the scsi fifo */
#define SSTAT2 0x0f
#define ILF1 0x80 /* sta: data in SIDL register msb[W]*/
#define ORF1 0x40 /* sta: data in SODR register msb[W]*/
#define OLF1 0x20 /* sta: data in SODL register msb[W]*/
#define DM 0x04 /* sta: DIFFSENS mismatch (895/6 only) */
#define LDSC 0x02 /* sta: disconnect & reconnect */
#define DSA 0x10 /* --> Base page */
#define DSA1 0x11
#define DSA2 0x12
#define DSA3 0x13
#define ISTAT 0x14 /* --> Main Command and status */
#define CABRT 0x80 /* cmd: abort current operation */
#define SRST 0x40 /* mod: reset chip */
#define SIGP 0x20 /* r/w: message from host to ncr */
#define SEM 0x10 /* r/w: message between host + ncr */
#define CON 0x08 /* sta: connected to scsi */
#define INTF 0x04 /* sta: int on the fly (reset by wr)*/
#define SIP 0x02 /* sta: scsi-interrupt */
#define DIP 0x01 /* sta: host/script interrupt */
#define CTEST0 0x18
#define CTEST1 0x19
#define CTEST2 0x1a
#define CSIGP 0x40
/* bits 0-2,7 rsvd for C1010 */
#define CTEST3 0x1b
#define FLF 0x08 /* cmd: flush dma fifo */
#define CLF 0x04 /* cmd: clear dma fifo */
#define FM 0x02 /* mod: fetch pin mode */
#define WRIE 0x01 /* mod: write and invalidate enable */
/* bits 4-7 rsvd for C1010 */
#define DFIFO 0x20
#define CTEST4 0x21
#define BDIS 0x80 /* mod: burst disable */
#define MPEE 0x08 /* mod: master parity error enable */
#define CTEST5 0x22
#define DFS 0x20 /* mod: dma fifo size */
/* bits 0-1, 3-7 rsvd for C1010 */
#define CTEST6 0x23
#define DBC 0x24 /* ### Byte count and command */
#define DNAD 0x28 /* ### Next command register */
#define DSP 0x2c /* --> Script Pointer */
#define DSPS 0x30 /* --> Script pointer save/opcode#2 */
#define SCRATCHA 0x34 /* Temporary register a */
#define SCRATCHA1 0x35
#define SCRATCHA2 0x36
#define SCRATCHA3 0x37
#define DMODE 0x38
#define BL_2 0x80 /* mod: burst length shift value +2 */
#define BL_1 0x40 /* mod: burst length shift value +1 */
#define ERL 0x08 /* mod: enable read line */
#define ERMP 0x04 /* mod: enable read multiple */
#define BOF 0x02 /* mod: burst op code fetch */
#define MAN 0x01 /* mod: manual start */
#define DIEN 0x39
#define SBR 0x3a
#define DCNTL 0x3b /* --> Script execution control */
#define CLSE 0x80 /* mod: cache line size enable */
#define PFF 0x40 /* cmd: pre-fetch flush */
#define PFEN 0x20 /* mod: pre-fetch enable */
#define SSM 0x10 /* mod: single step mode */
#define IRQM 0x08 /* mod: irq mode (1 = totem pole !) */
#define STD 0x04 /* cmd: start dma mode */
#define IRQD 0x02 /* mod: irq disable */
#define NOCOM 0x01 /* cmd: protect sfbr while reselect */
/* bits 0-1 rsvd for C1010 */
#define ADDER 0x3c
#define SIEN 0x40 /* -->: interrupt enable */
#define SIST 0x42 /* <--: interrupt status */
#define SBMC 0x1000/* sta: SCSI Bus Mode Change (895/6 only) */
#define STO 0x0400/* sta: timeout (select) */
#define GEN 0x0200/* sta: timeout (general) */
#define HTH 0x0100/* sta: timeout (handshake) */
#define MA 0x80 /* sta: phase mismatch */
#define CMP 0x40 /* sta: arbitration complete */
#define SEL 0x20 /* sta: selected by another device */
#define RSL 0x10 /* sta: reselected by another device*/
#define SGE 0x08 /* sta: gross error (over/underflow)*/
#define UDC 0x04 /* sta: unexpected disconnect */
#define RST 0x02 /* sta: scsi bus reset detected */
#define PAR 0x01 /* sta: scsi parity error */
#define SLPAR 0x44
#define SWIDE 0x45
#define MACNTL 0x46
#define GPCNTL 0x47
#define STIME0 0x48 /* cmd: timeout for select&handshake*/
#define STIME1 0x49 /* cmd: timeout user defined */
#define RESPID 0x4a /* sta: Reselect-IDs */
#define STEST0 0x4c
#define STEST1 0x4d
#define SCLK 0x80 /* Use the PCI clock as SCSI clock */
#define DBLEN 0x08 /* clock doubler running */
#define DBLSEL 0x04 /* clock doubler selected */
#define STEST2 0x4e
#define ROF 0x40 /* reset scsi offset (after gross error!) */
#define EXT 0x02 /* extended filtering */
#define STEST3 0x4f
#define TE 0x80 /* c: tolerAnt enable */
#define HSC 0x20 /* c: Halt SCSI Clock */
#define CSF 0x02 /* c: clear scsi fifo */
#define SIDL 0x50 /* Lowlevel: latched from scsi data */
#define STEST4 0x52
#define SMODE 0xc0 /* SCSI bus mode (895/6 only) */
#define SMODE_HVD 0x40 /* High Voltage Differential */
#define SMODE_SE 0x80 /* Single Ended */
#define SMODE_LVD 0xc0 /* Low Voltage Differential */
#define LCKFRQ 0x20 /* Frequency Lock (895/6 only) */
/* bits 0-5 rsvd for C1010 */
#define SODL 0x54 /* Lowlevel: data out to scsi data */
#define SBDL 0x58 /* Lowlevel: data from scsi data */
/*-----------------------------------------------------------
**
** Utility macros for the script.
**
**-----------------------------------------------------------
*/
#define REG(r) (r)
/*-----------------------------------------------------------
**
** SCSI phases
**
** DT phases illegal for ncr driver.
**
**-----------------------------------------------------------
*/
#define SCR_DATA_OUT 0x00000000
#define SCR_DATA_IN 0x01000000
#define SCR_COMMAND 0x02000000
#define SCR_STATUS 0x03000000
#define SCR_DT_DATA_OUT 0x04000000
#define SCR_DT_DATA_IN 0x05000000
#define SCR_MSG_OUT 0x06000000
#define SCR_MSG_IN 0x07000000
#define SCR_ILG_OUT 0x04000000
#define SCR_ILG_IN 0x05000000
/*-----------------------------------------------------------
**
** Data transfer via SCSI.
**
**-----------------------------------------------------------
**
** MOVE_ABS (LEN)
** <<start address>>
**
** MOVE_IND (LEN)
** <<dnad_offset>>
**
** MOVE_TBL
** <<dnad_offset>>
**
**-----------------------------------------------------------
*/
#define OPC_MOVE 0x08000000
#define SCR_MOVE_ABS(l) ((0x00000000 | OPC_MOVE) | (l))
#define SCR_MOVE_IND(l) ((0x20000000 | OPC_MOVE) | (l))
#define SCR_MOVE_TBL (0x10000000 | OPC_MOVE)
#define SCR_CHMOV_ABS(l) ((0x00000000) | (l))
#define SCR_CHMOV_IND(l) ((0x20000000) | (l))
#define SCR_CHMOV_TBL (0x10000000)
/*-----------------------------------------------------------
**
** Selection
**
**-----------------------------------------------------------
**
** SEL_ABS | SCR_ID (0..15) [ | REL_JMP]
** <<alternate_address>>
**
** SEL_TBL | << dnad_offset>> [ | REL_JMP]
** <<alternate_address>>
**
**-----------------------------------------------------------
*/
#define SCR_SEL_ABS 0x40000000
#define SCR_SEL_ABS_ATN 0x41000000
#define SCR_SEL_TBL 0x42000000
#define SCR_SEL_TBL_ATN 0x43000000
#define SCR_JMP_REL 0x04000000
#define SCR_ID(id) (((unsigned long)(id)) << 16)
/*-----------------------------------------------------------
**
** Waiting for Disconnect or Reselect
**
**-----------------------------------------------------------
**
** WAIT_DISC
** dummy: <<alternate_address>>
**
** WAIT_RESEL
** <<alternate_address>>
**
**-----------------------------------------------------------
*/
#define SCR_WAIT_DISC 0x48000000
#define SCR_WAIT_RESEL 0x50000000
/*-----------------------------------------------------------
**
** Bit Set / Reset
**
**-----------------------------------------------------------
**
** SET (flags {|.. })
**
** CLR (flags {|.. })
**
**-----------------------------------------------------------
*/
#define SCR_SET(f) (0x58000000 | (f))
#define SCR_CLR(f) (0x60000000 | (f))
#define SCR_CARRY 0x00000400
#define SCR_TRG 0x00000200
#define SCR_ACK 0x00000040
#define SCR_ATN 0x00000008
/*-----------------------------------------------------------
**
** Memory to memory move
**
**-----------------------------------------------------------
**
** COPY (bytecount)
** << source_address >>
** << destination_address >>
**
** SCR_COPY sets the NO FLUSH option by default.
** SCR_COPY_F does not set this option.
**
** For chips which do not support this option,
** ncr_copy_and_bind() will remove this bit.
**-----------------------------------------------------------
*/
#define SCR_NO_FLUSH 0x01000000
#define SCR_COPY(n) (0xc0000000 | SCR_NO_FLUSH | (n))
#define SCR_COPY_F(n) (0xc0000000 | (n))
/*-----------------------------------------------------------
**
** Register move and binary operations
**
**-----------------------------------------------------------
**
** SFBR_REG (reg, op, data) reg = SFBR op data
** << 0 >>
**
** REG_SFBR (reg, op, data) SFBR = reg op data
** << 0 >>
**
** REG_REG (reg, op, data) reg = reg op data
** << 0 >>
**
**-----------------------------------------------------------
** On 810A, 860, 825A, 875, 895 and 896 chips the content
** of SFBR register can be used as data (SCR_SFBR_DATA).
** The 896 has additionnal IO registers starting at
** offset 0x80. Bit 7 of register offset is stored in
** bit 7 of the SCRIPTS instruction first DWORD.
**-----------------------------------------------------------
*/
#define SCR_REG_OFS(ofs) ((((ofs) & 0x7f) << 16ul)) /* + ((ofs) & 0x80)) */
#define SCR_SFBR_REG(reg,op,data) \
(0x68000000 | (SCR_REG_OFS(REG(reg))) | (op) | (((data)&0xff)<<8ul))
#define SCR_REG_SFBR(reg,op,data) \
(0x70000000 | (SCR_REG_OFS(REG(reg))) | (op) | (((data)&0xff)<<8ul))
#define SCR_REG_REG(reg,op,data) \
(0x78000000 | (SCR_REG_OFS(REG(reg))) | (op) | (((data)&0xff)<<8ul))
#define SCR_LOAD 0x00000000
#define SCR_SHL 0x01000000
#define SCR_OR 0x02000000
#define SCR_XOR 0x03000000
#define SCR_AND 0x04000000
#define SCR_SHR 0x05000000
#define SCR_ADD 0x06000000
#define SCR_ADDC 0x07000000
#define SCR_SFBR_DATA (0x00800000>>8ul) /* Use SFBR as data */
/*-----------------------------------------------------------
**
** FROM_REG (reg) SFBR = reg
** << 0 >>
**
** TO_REG (reg) reg = SFBR
** << 0 >>
**
** LOAD_REG (reg, data) reg = <data>
** << 0 >>
**
** LOAD_SFBR(data) SFBR = <data>
** << 0 >>
**
**-----------------------------------------------------------
*/
#define SCR_FROM_REG(reg) \
SCR_REG_SFBR(reg,SCR_OR,0)
#define SCR_TO_REG(reg) \
SCR_SFBR_REG(reg,SCR_OR,0)
#define SCR_LOAD_REG(reg,data) \
SCR_REG_REG(reg,SCR_LOAD,data)
#define SCR_LOAD_SFBR(data) \
(SCR_REG_SFBR (gpreg, SCR_LOAD, data))
/*-----------------------------------------------------------
**
** LOAD from memory to register.
** STORE from register to memory.
**
** Only supported by 810A, 860, 825A, 875, 895 and 896.
**
**-----------------------------------------------------------
**
** LOAD_ABS (LEN)
** <<start address>>
**
** LOAD_REL (LEN) (DSA relative)
** <<dsa_offset>>
**
**-----------------------------------------------------------
*/
#define SCR_REG_OFS2(ofs) (((ofs) & 0xff) << 16ul)
#define SCR_NO_FLUSH2 0x02000000
#define SCR_DSA_REL2 0x10000000
#define SCR_LOAD_R(reg, how, n) \
(0xe1000000 | how | (SCR_REG_OFS2(REG(reg))) | (n))
#define SCR_STORE_R(reg, how, n) \
(0xe0000000 | how | (SCR_REG_OFS2(REG(reg))) | (n))
#define SCR_LOAD_ABS(reg, n) SCR_LOAD_R(reg, SCR_NO_FLUSH2, n)
#define SCR_LOAD_REL(reg, n) SCR_LOAD_R(reg, SCR_NO_FLUSH2|SCR_DSA_REL2, n)
#define SCR_LOAD_ABS_F(reg, n) SCR_LOAD_R(reg, 0, n)
#define SCR_LOAD_REL_F(reg, n) SCR_LOAD_R(reg, SCR_DSA_REL2, n)
#define SCR_STORE_ABS(reg, n) SCR_STORE_R(reg, SCR_NO_FLUSH2, n)
#define SCR_STORE_REL(reg, n) SCR_STORE_R(reg, SCR_NO_FLUSH2|SCR_DSA_REL2,n)
#define SCR_STORE_ABS_F(reg, n) SCR_STORE_R(reg, 0, n)
#define SCR_STORE_REL_F(reg, n) SCR_STORE_R(reg, SCR_DSA_REL2, n)
/*-----------------------------------------------------------
**
** Waiting for Disconnect or Reselect
**
**-----------------------------------------------------------
**
** JUMP [ | IFTRUE/IFFALSE ( ... ) ]
** <<address>>
**
** JUMPR [ | IFTRUE/IFFALSE ( ... ) ]
** <<distance>>
**
** CALL [ | IFTRUE/IFFALSE ( ... ) ]
** <<address>>
**
** CALLR [ | IFTRUE/IFFALSE ( ... ) ]
** <<distance>>
**
** RETURN [ | IFTRUE/IFFALSE ( ... ) ]
** <<dummy>>
**
** INT [ | IFTRUE/IFFALSE ( ... ) ]
** <<ident>>
**
** INT_FLY [ | IFTRUE/IFFALSE ( ... ) ]
** <<ident>>
**
** Conditions:
** WHEN (phase)
** IF (phase)
** CARRYSET
** DATA (data, mask)
**
**-----------------------------------------------------------
*/
#define SCR_NO_OP 0x80000000
#define SCR_JUMP 0x80080000
#define SCR_JUMP64 0x80480000
#define SCR_JUMPR 0x80880000
#define SCR_CALL 0x88080000
#define SCR_CALLR 0x88880000
#define SCR_RETURN 0x90080000
#define SCR_INT 0x98080000
#define SCR_INT_FLY 0x98180000
#define IFFALSE(arg) (0x00080000 | (arg))
#define IFTRUE(arg) (0x00000000 | (arg))
#define WHEN(phase) (0x00030000 | (phase))
#define IF(phase) (0x00020000 | (phase))
#define DATA(D) (0x00040000 | ((D) & 0xff))
#define MASK(D,M) (0x00040000 | (((M ^ 0xff) & 0xff) << 8ul)|((D) & 0xff))
#define CARRYSET (0x00200000)
#define SIR_COMPLETE 0x10000000
/* script errors */
#define SIR_SEL_ATN_NO_MSG_OUT 0x00000001
#define SIR_CMD_OUT_ILL_PH 0x00000002
#define SIR_STATUS_ILL_PH 0x00000003
#define SIR_MSG_RECEIVED 0x00000004
#define SIR_DATA_IN_ERR 0x00000005
#define SIR_DATA_OUT_ERR 0x00000006
#define SIR_SCRIPT_ERROR 0x00000007
#define SIR_MSG_OUT_NO_CMD 0x00000008
#define SIR_MSG_OVER7 0x00000009
/* Fly interrupt */
#define INT_ON_FY 0x00000080
/* Hardware errors are defined in scsi.h */
#define SCSI_IDENTIFY 0xC0
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#endif
|
1001-study-uboot
|
include/sym53c8xx.h
|
C
|
gpl3
| 18,435
|
/*
* Register definitions for the AMBA CLCD logic cell.
*
* derived from David A Rusling, although rearranged as a C structure
* linux/include/asm-arm/hardware/amba_clcd.h -- Integrator LCD panel.
*
* Copyright (C) 2001 ARM Limited
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
/*
* CLCD Controller Internal Register addresses
*/
struct clcd_registers {
u32 tim0; /* 0x00 */
u32 tim1;
u32 tim2;
u32 tim3;
u32 ubas; /* 0x10 */
u32 lbas;
#if !defined(CONFIG_ARCH_VERSATILE) && !defined(CONFIG_ARCH_REALVIEW)
u32 ienb;
u32 cntl;
#else /* Someone rearranged these two registers on the Versatile */
u32 cntl;
u32 ienb;
#endif
u32 stat; /* 0x20 */
u32 intr;
u32 ucur;
u32 lcur;
u32 unused[0x74]; /* 0x030..0x1ff */
u32 palette[0x80]; /* 0x200..0x3ff */
};
/* Bit definition for TIM2 */
#define TIM2_CLKSEL (1 << 5)
#define TIM2_IVS (1 << 11)
#define TIM2_IHS (1 << 12)
#define TIM2_IPC (1 << 13)
#define TIM2_IOE (1 << 14)
#define TIM2_BCD (1 << 26)
/* Bit definitions for control register */
#define CNTL_LCDEN (1 << 0)
#define CNTL_LCDBPP1 (0 << 1)
#define CNTL_LCDBPP2 (1 << 1)
#define CNTL_LCDBPP4 (2 << 1)
#define CNTL_LCDBPP8 (3 << 1)
#define CNTL_LCDBPP16 (4 << 1)
#define CNTL_LCDBPP16_565 (6 << 1)
#define CNTL_LCDBPP24 (5 << 1)
#define CNTL_LCDBW (1 << 4)
#define CNTL_LCDTFT (1 << 5)
#define CNTL_LCDMONO8 (1 << 6)
#define CNTL_LCDDUAL (1 << 7)
#define CNTL_BGR (1 << 8)
#define CNTL_BEBO (1 << 9)
#define CNTL_BEPO (1 << 10)
#define CNTL_LCDPWR (1 << 11)
#define CNTL_LCDVCOMP(x) ((x) << 12)
#define CNTL_LDMAFIFOTIME (1 << 15)
#define CNTL_WATERMARK (1 << 16)
/* u-boot specific: information passed by the board file */
struct clcd_config {
struct clcd_registers *address;
u32 tim0;
u32 tim1;
u32 tim2;
u32 tim3;
u32 cntl;
unsigned long pixclock;
};
|
1001-study-uboot
|
include/amba_clcd.h
|
C
|
gpl3
| 1,961
|
/*
* definitions for MPC8260 I/O Ports
*
* (in addition to those provided in <asm/immap_8260.h>)
*
* Murray.Jensen@cmst.csiro.au, 20-Oct-00
*/
/*
* this structure mirrors the layout of the five port registers in
* the internal memory map - see iop8260_t in <asm/immap_8260.h>
*/
typedef struct {
unsigned int pdir; /* Port Data Direction Register (35-3) */
unsigned int ppar; /* Port Pin Assignment Register (35-4) */
unsigned int psor; /* Port Special Options Register (35-5) */
unsigned int podr; /* Port Open Drain Register (35-2) */
unsigned int pdat; /* Port Data Register (35-3) */
} ioport_t;
/*
* this macro calculates the address within the internal
* memory map (im) of the set of registers for a port (idx)
*
* the internal memory map aligns the above structure on
* a 0x20 byte boundary
*/
#ifdef CONFIG_MPC85xx
#define ioport_addr(im, idx) (ioport_t *)((uint)&(im->im_cpm_iop) + ((idx)*0x20))
#else
#define ioport_addr(im, idx) (ioport_t *)((uint)&(im)->im_ioport + ((idx)*0x20))
#endif
/*
* this structure provides configuration
* information for one port pin
*/
typedef struct {
unsigned char conf:1; /* if 1, configure this port */
unsigned char ppar:1; /* Port Pin Assignment Register (35-4) */
unsigned char psor:1; /* Port Special Options Register (35-2) */
unsigned char pdir:1; /* Port Data Direction Register (35-3) */
unsigned char podr:1; /* Port Open Drain Register (35-2) */
unsigned char pdat:1; /* Port Data Register (35-2) */
} iop_conf_t;
/*
* a table that contains configuration information for all 32 pins
* of all four MPC8260 I/O ports.
*
* NOTE: in the second dimension of this table, index 0 refers to pin 31
* and index 31 refers to pin 0. this made the code in the table look more
* like the table in the 8260UM (and in the hymod manuals).
*/
extern const iop_conf_t iop_conf_tab[4][32];
typedef struct {
unsigned char port;
unsigned char pin;
int dir;
int open_drain;
int assign;
} qe_iop_conf_t;
#define QE_IOP_TAB_END (-1)
|
1001-study-uboot
|
include/ioports.h
|
C
|
gpl3
| 2,052
|
/*
* (C) Copyright 2002
* Rich Ireland, Enterasys Networks, rireland@enterasys.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 <linux/types.h> /* for ulong typedef */
#ifndef _FPGA_H_
#define _FPGA_H_
#ifndef CONFIG_MAX_FPGA_DEVICES
#define CONFIG_MAX_FPGA_DEVICES 5
#endif
/* these probably belong somewhere else */
#ifndef FALSE
#define FALSE (0)
#endif
#ifndef TRUE
#define TRUE (!FALSE)
#endif
/* CONFIG_FPGA bit assignments */
#define CONFIG_SYS_FPGA_MAN(x) (x)
#define CONFIG_SYS_FPGA_DEV(x) ((x) << 8 )
#define CONFIG_SYS_FPGA_IF(x) ((x) << 16 )
/* FPGA Manufacturer bits in CONFIG_FPGA */
#define CONFIG_SYS_FPGA_XILINX CONFIG_SYS_FPGA_MAN( 0x1 )
#define CONFIG_SYS_FPGA_ALTERA CONFIG_SYS_FPGA_MAN( 0x2 )
/* fpga_xxxx function return value definitions */
#define FPGA_SUCCESS 0
#define FPGA_FAIL -1
/* device numbers must be non-negative */
#define FPGA_INVALID_DEVICE -1
/* root data type defintions */
typedef enum { /* typedef fpga_type */
fpga_min_type, /* range check value */
fpga_xilinx, /* Xilinx Family) */
fpga_altera, /* unimplemented */
fpga_lattice, /* Lattice family */
fpga_undefined /* invalid range check value */
} fpga_type; /* end, typedef fpga_type */
typedef struct { /* typedef fpga_desc */
fpga_type devtype; /* switch value to select sub-functions */
void *devdesc; /* real device descriptor */
} fpga_desc; /* end, typedef fpga_desc */
/* root function definitions */
extern void fpga_init(void);
extern int fpga_add(fpga_type devtype, void *desc);
extern int fpga_count(void);
extern int fpga_load(int devnum, const void *buf, size_t bsize);
extern int fpga_dump(int devnum, const void *buf, size_t bsize);
extern int fpga_info(int devnum);
#endif /* _FPGA_H_ */
|
1001-study-uboot
|
include/fpga.h
|
C
|
gpl3
| 2,521
|
/*
* (C) Copyright 2005
* ARM Ltd.
* Peter Pearse, <Peter.Pearse@arm.com>
* Configuration for ARM Core Modules.
* No standalonw port yet available
* - this file is included by both integratorap.h & integratorcp.h
*
* 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 __ARMCOREMODULE_H
#define __ARMCOREMODULE_H
#define CM_BASE 0x10000000
/* CM registers common to all CMs */
/* Note that observed values after reboot into the ARM Boot Monitor
have been used as defaults, rather than the POR values */
#define OS_CTRL 0x0000000C
#define CMMASK_REMAP 0x00000005 /* set remap & led */
#define CMMASK_RESET 0x00000008
#define OS_LOCK 0x00000014
#define CMVAL_LOCK1 0x0000A000 /* locking value */
#define CMVAL_LOCK2 0x0000005F /* locking value */
#define CMVAL_UNLOCK 0x00000000 /* any value != CM_LOCKVAL */
#define OS_SDRAM 0x00000020
#define OS_INIT 0x00000024
#define CMMASK_MAP_SIMPLE 0xFFFDFFFF /* simple mapping */
#define CMMASK_TCRAM_DISABLE 0xFFFEFFFF /* TCRAM disabled */
#define CMMASK_LOWVEC 0x00000000 /* vectors @ 0x00000000 */
#define CMMASK_LE 0xFFFFFFF7 /* little endian */
#define CMMASK_CMxx6_COMMON 0x00000013 /* Common value for CMxx6 */
/* - observed reset value of */
/* CM926EJ-S */
/* CM1136-EJ-S */
#if defined (CONFIG_CM10200E) || defined (CONFIG_CM10220E)
#define CMMASK_INIT_102 0x00000300 /* see CM102xx ref manual */
/* - PLL test clock bypassed */
/* - bus clock ratio 2 */
/* - little endian */
/* - vectors at zero */
#endif /* CM1022xx */
/* Determine CM characteristics */
#undef CONFIG_CM_MULTIPLE_SSRAM
#undef CONFIG_CM_SPD_DETECT
#undef CONFIG_CM_REMAP
#undef CONFIG_CM_INIT
#undef CONFIG_CM_TCRAM
#if defined (CONFIG_CM946E_S) || defined (CONFIG_CM966E_S)
#define CONFIG_CM_MULTIPLE_SSRAM /* CM has multiple SSRAM mapping */
#endif
/* Excalibur core module has reduced functionality */
#ifndef CONFIG_CM922T_XA10
#define CONFIG_CM_SPD_DETECT /* CM supports SPD query */
#define OS_SPD 0x00000100 /* Address of SPD data */
#define CONFIG_CM_REMAP /* CM supports remapping */
#define CONFIG_CM_INIT /* CM has initialization reg */
#endif /* NOT EXCALIBUR */
#if defined(CONFIG_CM926EJ_S) || defined (CONFIG_CM946E_S) || \
defined(CONFIG_CM966E_S) || defined (CONFIG_CM1026EJ_S) || \
defined(CONFIG_CM1136JF_S)
#define CONFIG_CM_TCRAM /* CM has TCRAM */
#endif
#ifdef CONFIG_CM_SPD_DETECT
#define OS_SPD 0x00000100 /* The SDRAM SPD data is copied here */
#endif
#endif /* __ARMCOREMODULE_H */
|
1001-study-uboot
|
include/armcoremodule.h
|
C
|
gpl3
| 3,350
|
/*
* Copyright (C) 2009 Marc Kleine-Budde <mkl@pengutronix.de>
*
* Copyright 2004-2009 Freescale Semiconductor, Inc. All Rights Reserved.
*
* 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 __ASM_ARCH_MC9SDZ60_H
#define __ASM_ARCH_MC9SDZ60_H
/**
* Register addresses for the MC9SDZ60
*
* @note: these match those in the kernel drivers/mxc/mcu_pmic/mc9s08dz60.h
* but not include/linux/mfd/mc9s08dz60/pmic.h
*
*/
enum mc9sdz60_reg {
MC9SDZ60_REG_VERSION = 0x00,
/* reserved 0x01 */
MC9SDZ60_REG_SECS = 0x02,
MC9SDZ60_REG_MINS = 0x03,
MC9SDZ60_REG_HRS = 0x04,
MC9SDZ60_REG_DAY = 0x05,
MC9SDZ60_REG_DATE = 0x06,
MC9SDZ60_REG_MONTH = 0x07,
MC9SDZ60_REG_YEAR = 0x08,
MC9SDZ60_REG_ALARM_SECS = 0x09,
MC9SDZ60_REG_ALARM_MINS = 0x0a,
MC9SDZ60_REG_ALARM_HRS = 0x0b,
/* reserved 0x0c */
/* reserved 0x0d */
MC9SDZ60_REG_TS_CONTROL = 0x0e,
MC9SDZ60_REG_X_LOW = 0x0f,
MC9SDZ60_REG_Y_LOW = 0x10,
MC9SDZ60_REG_XY_HIGH = 0x11,
MC9SDZ60_REG_X_LEFT_LOW = 0x12,
MC9SDZ60_REG_X_LEFT_HIGH = 0x13,
MC9SDZ60_REG_X_RIGHT = 0x14,
MC9SDZ60_REG_Y_TOP_LOW = 0x15,
MC9SDZ60_REG_Y_TOP_HIGH = 0x16,
MC9SDZ60_REG_Y_BOTTOM = 0x17,
/* reserved 0x18 */
/* reserved 0x19 */
MC9SDZ60_REG_RESET_1 = 0x1a,
MC9SDZ60_REG_RESET_2 = 0x1b,
MC9SDZ60_REG_POWER_CTL = 0x1c,
MC9SDZ60_REG_DELAY_CONFIG = 0x1d,
/* reserved 0x1e */
/* reserved 0x1f */
MC9SDZ60_REG_GPIO_1 = 0x20,
MC9SDZ60_REG_GPIO_2 = 0x21,
MC9SDZ60_REG_KPD_1 = 0x22,
MC9SDZ60_REG_KPD_2 = 0x23,
MC9SDZ60_REG_KPD_CONTROL = 0x24,
MC9SDZ60_REG_INT_ENABLE_1 = 0x25,
MC9SDZ60_REG_INT_ENABLE_2 = 0x26,
MC9SDZ60_REG_INT_FLAG_1 = 0x27,
MC9SDZ60_REG_INT_FLAG_2 = 0x28,
MC9SDZ60_REG_DES_FLAG = 0x29,
};
extern u8 mc9sdz60_reg_read(enum mc9sdz60_reg reg);
extern void mc9sdz60_reg_write(enum mc9sdz60_reg reg, u8 val);
#endif /* __ASM_ARCH_MC9SDZ60_H */
|
1001-study-uboot
|
include/mc9sdz60.h
|
C
|
gpl3
| 2,757
|
/*
* (C) Copyright 2003
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* This file is based on code
* (C) Copyright Motorola, Inc., 2000
*
* odin smartdma header file
*/
#ifndef __MPC5XXX_SDMA_H
#define __MPC5XXX_SDMA_H
#include <common.h>
#include <mpc5xxx.h>
/* Task number assignment */
#define FEC_RECV_TASK_NO 0
#define FEC_XMIT_TASK_NO 1
/*---------------------------------------------------------------------*/
/* Stuff for Ethernet Tx/Rx tasks */
/*---------------------------------------------------------------------*/
/* Layout of Ethernet controller Parameter SRAM area:
----------------------------------------------------------------
0x00: TBD_BASE, base address of TX BD ring
0x04: TBD_NEXT, address of next TX BD to be processed
0x08: RBD_BASE, base address of RX BD ring
0x0C: RBD_NEXT, address of next RX BD to be processed
---------------------------------------------------------------
ALL PARAMETERS ARE ALL LONGWORDS (FOUR BYTES EACH).
*/
/* base address of SRAM area to store parameters used by Ethernet tasks */
#define FEC_PARAM_BASE (MPC5XXX_SRAM + 0x0800)
/* base address of SRAM area for buffer descriptors */
#define FEC_BD_BASE (MPC5XXX_SRAM + 0x0820)
/*---------------------------------------------------------------------*/
/* common shortcuts used by driver C code */
/*---------------------------------------------------------------------*/
/* Disable SmartDMA task */
#define SDMA_TASK_DISABLE(tasknum) \
{ \
volatile ushort *tcr = (ushort *)(MPC5XXX_SDMA + 0x0000001c + 2 * tasknum); \
*tcr = (*tcr) & (~0x8000); \
}
/* Enable SmartDMA task */
#define SDMA_TASK_ENABLE(tasknum) \
{ \
volatile ushort *tcr = (ushort *) (MPC5XXX_SDMA + 0x0000001c + 2 * tasknum); \
*tcr = (*tcr) | 0x8000; \
}
/* Enable interrupt */
#define SDMA_INT_ENABLE(tasknum) \
{ \
struct mpc5xxx_sdma *sdma = (struct mpc5xxx_sdma *)MPC5XXX_SDMA; \
sdma->IntMask &= ~(1 << tasknum); \
}
/* Disable interrupt */
#define SDMA_INT_DISABLE(tasknum) \
{ \
struct mpc5xxx_sdma *sdma = (struct mpc5xxx_sdma *)MPC5XXX_SDMA; \
sdma->IntMask |= (1 << tasknum); \
}
/* Clear interrupt pending bits */
#define SDMA_CLEAR_IEVENT(tasknum) \
{ \
struct mpc5xxx_sdma *sdma = (struct mpc5xxx_sdma *)MPC5XXX_SDMA; \
sdma->IntPend = (1 << tasknum); \
}
/* get interrupt pending bit of a task */
#define SDMA_GET_PENDINGBIT(tasknum) \
((*(vu_long *)(MPC5XXX_SDMA + 0x14)) & (1<<(tasknum)))
/* get interrupt mask bit of a task */
#define SDMA_GET_MASKBIT(tasknum) \
((*(vu_long *)(MPC5XXX_SDMA + 0x18)) & (1<<(tasknum)))
#endif /* __MPC5XXX_SDMA_H */
|
1001-study-uboot
|
include/mpc5xxx_sdma.h
|
C
|
gpl3
| 3,184
|
/*
* Memory Setup stuff - taken from blob memsetup.S
*
* Copyright (C) 1999 2000 2001 Erik Mouw (J.A.K.Mouw@its.tudelft.nl) and
* Jan-Derk Bakker (J.D.Bakker@its.tudelft.nl)
*
* Modified for the friendly-arm mini2440 by
* wang_xi@anyka.com
* (C) Copyright 2012
* 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
*/
#include <config.h>
#include <version.h>
/* some parameters for the board */
/*
*
* Taken from linux/arch/arm/boot/compressed/head-s3c2410.S
*
* Copyright (C) 2002 Samsung Electronics SW.LEE <hitchcar@sec.samsung.com>
*
*/
/*wx: memery bank controler base address*/
#define BWSCON 0x48000000
/* BWSCON wx: data bus width(chipwidth)*/
#define DW8 (0x0)
#define DW16 (0x1)
#define DW32 (0x2)
#define WAIT (0x1<<2)
#define UBLB (0x1<<3)
#define B1_BWSCON (DW32)
#define B2_BWSCON (DW16)
#define B3_BWSCON (DW16 + WAIT + UBLB)
#define B4_BWSCON (DW16)
#define B5_BWSCON (DW16)
/*wx:mini2440 SDRAM use 2 piece K4S561632N(16bit) run parallely = 32*/
#define B6_BWSCON (DW32)
#define B7_BWSCON (DW32)
/* BANK0CON */
#define B0_Tacs 0x0 /* 0clk */
#define B0_Tcos 0x0 /* 0clk */
#define B0_Tacc 0x7 /* 14clk */
#define B0_Tcoh 0x0 /* 0clk */
#define B0_Tah 0x0 /* 0clk */
#define B0_Tacp 0x0
#define B0_PMC 0x0 /* normal */
/* BANK1CON */
#define B1_Tacs 0x0 /* 0clk */
#define B1_Tcos 0x0 /* 0clk */
#define B1_Tacc 0x7 /* 14clk */
#define B1_Tcoh 0x0 /* 0clk */
#define B1_Tah 0x0 /* 0clk */
#define B1_Tacp 0x0
#define B1_PMC 0x0
#define B2_Tacs 0x0
#define B2_Tcos 0x0
#define B2_Tacc 0x7
#define B2_Tcoh 0x0
#define B2_Tah 0x0
#define B2_Tacp 0x0
#define B2_PMC 0x0
#define B3_Tacs 0x0 /* 0clk */
#define B3_Tcos 0x3 /* 4clk */
#define B3_Tacc 0x7 /* 14clk */
#define B3_Tcoh 0x1 /* 1clk */
#define B3_Tah 0x0 /* 0clk */
#define B3_Tacp 0x3 /* 6clk */
#define B3_PMC 0x0 /* normal */
/*wx:For LAN*/
#define B4_Tacs 0x1
#define B4_Tcos 0x1
#define B4_Tacc 0x6
#define B4_Tcoh 0x1
#define B4_Tah 0x1
#define B4_Tacp 0x0
#define B4_PMC 0x0 /* normal */
#define B5_Tacs 0x0 /* 0clk */
#define B5_Tcos 0x0 /* 0clk */
#define B5_Tacc 0x7 /* 14clk */
#define B5_Tcoh 0x0 /* 0clk */
#define B5_Tah 0x0 /* 0clk */
#define B5_Tacp 0x0
#define B5_PMC 0x0 /* normal */
/*wx:For SDRAM K4S561632N*/
#define B6_MT 0x3 /*SDRAM => 0x3 ()[00(rom:sram)/11(sdram)/other(reserved)]*/
#define B6_Trcd 0x1 /*20ns => [00(2clk)/01(3clk)/02(4clk)]*/
#define B6_SCAN 0x1 /*C0-C8 => 9bit [00(8bit)/01(9bit)/10(10bit)]*/
#define B7_MT 0x3 /* SDRAM */
#define B7_Trcd 0x1 /* 3clk */
#define B7_SCAN 0x1 /* 9bit */
/* REFRESH parameter */
#define REFEN 0x1 /* Refresh enable */
#define TREFMD 0x0 /* CBR(CAS before RAS)/Auto refresh */
#define Trp 0x2 /* 20ns =>4clk */
#define Trc 0x3 /* 65~70ns =>7clk */
#define Tchr 0x2 /* 3clk, wx:sdram neednot this item */
#define REFCNT 1113 /* period=15.6us, HCLK=60Mhz, (2048+1-15.6*60) */
/**************************************/
_TEXT_BASE:
.word CONFIG_SYS_TEXT_BASE
.globl lowlevel_init
lowlevel_init:
/* memory control configuration */
/* make r0 relative the current location so that it */
/* reads SMRDATA out of FLASH rather than memory ! */
ldr r0, =SMRDATA /*wx: get symbol link address*/
ldr r1, =lowlevel_init /* get symbol link address*/
sub r0, r0, r1 /*calc the offset between lowlevel_init and SMRDATA */
adr r3, lowlevel_init /*get the pc of lowlevel_init(runtime address)*/
add r0,r0,r3 /*calc the SMRDATA pc addrress(runtime address)*/
ldr r1, =BWSCON /* Bus Width Status Controller */
add r2, r0, #13*4
0:
ldr r3, [r0], #4
str r3, [r1], #4
cmp r2, r0
bne 0b
/* everything is fine now */
mov pc, lr
.ltorg
/* the literal pools origin */
SMRDATA:
/*wx:bank data bus(bank 0 neednot setup, it decide by the OM[1:0] PIN by board config)*/
/* BWSCON */ .word (0+(B1_BWSCON<<4)+(B2_BWSCON<<8)+(B3_BWSCON<<12)+(B4_BWSCON<<16)+(B5_BWSCON<<20)+(B6_BWSCON<<24)+(B7_BWSCON<<28))
/* BANKCON0 */ .word ((B0_Tacs<<13)+(B0_Tcos<<11)+(B0_Tacc<<8)+(B0_Tcoh<<6)+(B0_Tah<<4)+(B0_Tacp<<2)+(B0_PMC))
/* BANKCON1 */ .word ((B1_Tacs<<13)+(B1_Tcos<<11)+(B1_Tacc<<8)+(B1_Tcoh<<6)+(B1_Tah<<4)+(B1_Tacp<<2)+(B1_PMC))
/* BANKCON2 */ .word ((B2_Tacs<<13)+(B2_Tcos<<11)+(B2_Tacc<<8)+(B2_Tcoh<<6)+(B2_Tah<<4)+(B2_Tacp<<2)+(B2_PMC))
/* BANKCON3 */ .word ((B3_Tacs<<13)+(B3_Tcos<<11)+(B3_Tacc<<8)+(B3_Tcoh<<6)+(B3_Tah<<4)+(B3_Tacp<<2)+(B3_PMC))
/* BANKCON4 */ .word ((B4_Tacs<<13)+(B4_Tcos<<11)+(B4_Tacc<<8)+(B4_Tcoh<<6)+(B4_Tah<<4)+(B4_Tacp<<2)+(B4_PMC))
/* BANKCON5 */ .word ((B5_Tacs<<13)+(B5_Tcos<<11)+(B5_Tacc<<8)+(B5_Tcoh<<6)+(B5_Tah<<4)+(B5_Tacp<<2)+(B5_PMC))
/* BANKCON6 */ .word ((B6_MT<<15)+(B6_Trcd<<2)+(B6_SCAN))
/* BANKCON7 */ .word ((B7_MT<<15)+(B7_Trcd<<2)+(B7_SCAN))
/* REFRESH */ .word ((REFEN<<23)+(TREFMD<<22)+(Trp<<20)+(Trc<<18)+(Tchr<<16)+REFCNT)
/*wx: bank6/7 size(mini2440 is 2 piece K4S561632N(32M:[4M x 16Bit x 4Bank]) Share Bank6(All CS Connected to nGCS6))
* therefor The Bank6 mapped to 64M Address, and the BK76MAP bit[2:0] = 001, means 64M byte.
*/
/* BANKSIZE */ .word 0xb1 /* enable burst operation */
/* MRSRB6 */ .word 0x30
/* MRSRB7 */ .word 0x30
|
1001-study-uboot
|
board/samsung/mini2440/lowlevel_init.S
|
Unix Assembly
|
gpl3
| 6,113
|
#
# (C) Copyright 2000-2006
# Wolfgang Denk, DENX Software Engineering, wd@denx.de.
#
# See file CREDITS for list of people who contributed to this
# project.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
#
include $(TOPDIR)/config.mk
LIB = $(obj)lib$(BOARD).o
COBJS := mini2440.o nandboot_load.o
SOBJS := lowlevel_init.o
SRCS := $(SOBJS:.o=.S) $(COBJS:.o=.c)
OBJS := $(addprefix $(obj),$(COBJS))
SOBJS := $(addprefix $(obj),$(SOBJS))
$(LIB): $(obj).depend $(OBJS) $(SOBJS)
$(call cmd_link_o_target, $(OBJS) $(SOBJS))
#########################################################################
# defines $(obj).depend target
include $(SRCTREE)/rules.mk
sinclude $(obj).depend
#########################################################################
|
1001-study-uboot
|
board/samsung/mini2440/Makefile
|
Makefile
|
gpl3
| 1,414
|
/*
* (C) Copyright 2002
* Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Marius Groeger <mgroeger@sysgo.de>
*
* (C) Copyright 2002, 2010
* 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
*/
#include <common.h>
#include <netdev.h>
#include <asm/io.h>
#include <asm/arch/s3c24x0_cpu.h>
DECLARE_GLOBAL_DATA_PTR;
#define FCLK_SPEED 2 //wx:replace 1
#if FCLK_SPEED==0 /* Fout = 203MHz, Fin = 12MHz for Audio */
#define M_MDIV 0xC3
#define M_PDIV 0x4
#define M_SDIV 0x1
#elif FCLK_SPEED==1 /* Fout = 202.8MHz */
#define M_MDIV 0xA1
#define M_PDIV 0x3
#define M_SDIV 0x1
#elif FCLK_SPEED==2 /*wx:add: Fout=405MHz*/
#define M_MDIV 0x7F // ref s3c2440 spec:PLL VALUE SELECTION
#define M_PDIV 0x2
#define M_SDIV 0x1
#endif
#define USB_CLOCK 2 //wx:replace 1
#if USB_CLOCK==0
#define U_M_MDIV 0xA1
#define U_M_PDIV 0x3
#define U_M_SDIV 0x1
#elif USB_CLOCK==1
#define U_M_MDIV 0x48
#define U_M_PDIV 0x3
#define U_M_SDIV 0x2
#elif USB_CLOCK==2 // Fout = 48Mhz
#define U_M_MDIV 0x38
#define U_M_PDIV 0x2
#define U_M_SDIV 0x2
#endif
static inline void pll_delay(unsigned long loops)
{
__asm__ volatile ("1:\n"
"subs %0, %1, #1\n"
"bne 1b":"=r" (loops):"0" (loops));
}
/*
* Miscellaneous platform dependent initialisations
*/
int board_early_init_f(void)
{
struct s3c24x0_clock_power * const clk_power =
s3c24x0_get_base_clock_power();
struct s3c24x0_gpio * const gpio = s3c24x0_get_base_gpio();
/* to reduce PLL lock time, adjust the LOCKTIME register */
writel(0xFFFFFF, &clk_power->locktime);
/* configure MPLL */
writel((M_MDIV << 12) + (M_PDIV << 4) + M_SDIV,
&clk_power->mpllcon);
/* some delay between MPLL and UPLL */
pll_delay(4000);
/* configure UPLL */
writel((U_M_MDIV << 12) + (U_M_PDIV << 4) + U_M_SDIV,
&clk_power->upllcon);
/* some delay between MPLL and UPLL */
pll_delay(8000);
/* set up the I/O ports */
writel(0x007FFFFF, &gpio->gpacon);
/* wx: GPB10 and GPB9 Config as External DMA CON, lookup CON5 PIN13,14
* of Mini2440 shema, GPB0 output 0(Speaker),GPB1 input 1, other output 1)
*/
writel(0x00295551, &gpio->gpbcon);
writel(0x000007FE, &gpio->gpbup);
/* wx: GPC5 set as gpio output , other for lcd control,
* GPC5 output as 0(usb disable, connected to usb D+)
*/
writel(0xAAAAA6AA, &gpio->gpccon);
writel(readl(&gpio->gpcdat)&(~(1<<5)),&gpio->gpcdat);
writel(0x0000FFFF, &gpio->gpcup);
writel(0xAAAAAAAA, &gpio->gpdcon);
writel(0x0000FFFF, &gpio->gpdup);
writel(0xAAAAAAAA, &gpio->gpecon);
writel(0x0000FFFF, &gpio->gpeup);
writel(0x000055AA, &gpio->gpfcon);
writel(0x000000FF, &gpio->gpfup);
writel(0xFF95FFBA, &gpio->gpgcon);
writel(0x0000FFFF, &gpio->gpgup);
writel(0x002AFAAA, &gpio->gphcon);
writel(0x000007FF, &gpio->gphup);
return 0;
}
int board_init(void)
{
/* arch number of mini2440-Board*/
gd->bd->bi_arch_number = MACH_TYPE_MINI2440;//MACH_TYPE_SMDK2410
/* adress of boot parameters */
gd->bd->bi_boot_params = 0x30000100;
icache_enable();
dcache_enable();
return 0;
}
int dram_init(void)
{
/* dram_init must store complete ramsize in gd->ram_size */
//wx: this will be called at initquence table (board.c:init_sequence last item)
gd->ram_size = PHYS_SDRAM_1_SIZE;
return 0;
}
#ifdef CONFIG_CMD_NET
int board_eth_init(bd_t *bis)
{
int rc = 0;
#ifdef CONFIG_CS8900
cs8900_initialize(0, CONFIG_CS8900_BASE);
#endif
#ifdef CONFIG_DRIVER_DM9000
rc = dm9000_initialize(bis);
#endif
return rc;
}
#endif
/*
* Hardcoded flash setup:
* Flash 0 is a non-CFI AMD AM29LV800BB flash.
*/
ulong board_flash_get_legacy(ulong base, int banknum, flash_info_t *info)
{
/*wx:8 x 2(portwidth) (S29AL160J BYTE#(PIN 47) is 1, hense,
we select word(16bit) mode)*/
info->portwidth = FLASH_CFI_16BIT;
/*wx:8 x 2 = 16(chipwidth)(mini2440,OM[1] PIN is 0, OM[0] PIN is 1, hense
we select 16bit mode(bank0 data width mode),*/
info->chipwidth = FLASH_CFI_BY16;
info->interface = FLASH_CFI_X16;
return 1;
}
|
1001-study-uboot
|
board/samsung/mini2440/mini2440.c
|
C
|
gpl3
| 4,770
|
/*
* nand_read.c: Simple NAND read functions for booting from NAND
*
* This is used by cpu/arm920/start.S assembler code,
* and the board-specific linker script must make sure this
* file is linked within the first 4kB of NAND flash.
*
* Taken from GPLv2 licensed vivi bootloader,
* Copyright (C) 2002 MIZI Research, Inc.
*
* Author: Hwang, Chideok <hwang@mizi.com>
* Date : $Date: 2004/02/04 10:37:37 $
*
* u-boot integration and bad-block skipping (C) 2006 by OpenMoko, Inc.
* Author: Harald Welte <laforge@openmoko.org>
*
* sorting code
* Author: chaoswizard <85855632@qq.com>
*/
#include <common.h>
#include <linux/mtd/nand.h>
#include <asm/io.h>
#include <asm/arch/s3c24x0_cpu.h>
#define NANDBOOT_DEBUG
//#define NANDBOOT_LOAD_VERIFY
//#define NANDBOOT_SKIP_BAD
//wx: steppingstone zone maped addr, refrence of S3c2440 spec,C6-6
#define STEPPING_STONE_RAM_BASE 0x00000000
#define STEPPING_STONE_RAM_SIZE (4<<10)
#define NANDBOOT_IMG_LENGTH 0x80000
#if 1
#define __READ_B(c) readb(c)
#define __READ_W(c) readw(c)
#define __READ_L(c) readl(c)
#define __WRITE_B(v, c) writeb(v, c)
#define __WRITE_L(v, c) writel(v, c)
#else
#define __READ_B(c) (*(volatile unsigned char *)(c))
#define __READ_W(c) (*(volatile unsigned short *)(c))
#define __READ_L(c) (*(volatile unsigned int *)(c))
#define __WRITE_B(v, c) (*(volatile unsigned char *)(c) = (v))
#define __WRITE_L(v, c) (*(volatile unsigned int *)(c) = (v))
#endif
/*--------------- NFCONF --------------------------*/
/*wx: NFCONF[13:12]*/
#define NFCONF_TACLS(x) ((x) << 12)
/*wx: NFCONF[10:8]*/
#define NFCONF_TWRPH0(x) ((x) << 8)
/*wx: NFCONF[6:4]*/
#define NFCONF_TWRPH1(x) ((x) << 4)
/*wx: NFCONF[0]*/
#define NFCONF_BUSWIDTH(x) ((x) << 0) //HW Set
/*-------------- NFCONT --------------------------*/
/*wx: initialize ecc decoder/encoder*/
#define NFCONT_RnB_MODE (1 << 8)
#define NFCONT_INITECC_BIT (1 << 4)
/*wx: NandFlash Chip Enable(low)*/
#define NFCONT_nCE_BIT (1 << 1)
/*wx: NandFlash Controller Enable(1)/Disable(0)*/
#define NFCONT_MODE_BIT (1 << 0)
/*--------------- NFSTAT --------------------------*/
/*wx: NFSTAT[2]*/
#define NFSTAT_RnB_BIT (1 << 2)
/*wx: NFSTAT[1]*/
#define NFSTAT_nCE_BIT (1 << 1)
/*wx: NFSTAT[0]*/
#define NFSTAT_BUSY_BIT (1 << 0)
/*-------------------------------------------------*/
#if defined(NANDBOOT_DEBUG)
static void boot_delay_ms(unsigned int t)
{
int j,k;
while(t--)
{
k = 1000*40;
__asm__ __volatile__("": : :"memory");
for (;k>0;k--) {
j = 1000000;
__asm__ __volatile__("": : :"memory");
while(j--);
}
}
}
#define LED_SPK_VAL(a,b,c,d,s) (((a)<<8) | ((b)<<7) | ((c)<<6) | ((d)<<5) | ((s)<<0))
void speaker_play(int times)
{
struct s3c24x0_gpio *gpio = s3c24x0_get_base_gpio();
if (!times)
return;
//gpb 5,6,7,8 => led 1,2,3,4
//gpb 0 =>speaker
__WRITE_L(0x00295551, &gpio->gpbcon);//[10:17]=01010101,set as gpio
__WRITE_L(0x000001FF, &gpio->gpbup);//[5:8]=1110 (1:disable pullup)
while (times--) {
__WRITE_L(LED_SPK_VAL(0,0,0,0,1), &gpio->gpbdat);
boot_delay_ms(200);
__WRITE_L(LED_SPK_VAL(0,0,0,0,0), &gpio->gpbdat);
boot_delay_ms(400);
}
__WRITE_L(LED_SPK_VAL(0,0,0,0,0), &gpio->gpbdat);
boot_delay_ms(1000);
}
#endif
#if defined(CONFIG_NAND_BOOT)
#ifdef NANDBOOT_DEBUG
#define LOAD_STATUS_ERROR(x) show_boot_status(x)
#else
#define LOAD_STATUS_ERROR(x)
#endif
enum {
NFBT_STATUS_UNSUPPORT_ID = 1,
NFBT_STATUS_ALIGN_ERR,
NFBT_STATUS_UNSUPPORT_PAGE_SIZE,
NFBT_STATUS_LOAD_ERR,
NFBT_STATUS_VERIFY_ERR,
NFBT_STATUS_LOAD_END,
};
void show_boot_status(unsigned int flag)
{
switch (flag)
{
case NFBT_STATUS_UNSUPPORT_ID:
case NFBT_STATUS_ALIGN_ERR:
case NFBT_STATUS_UNSUPPORT_PAGE_SIZE:
case NFBT_STATUS_LOAD_ERR:
case NFBT_STATUS_VERIFY_ERR:
do {
speaker_play(flag);
} while(1);
break;
case NFBT_STATUS_LOAD_END:
speaker_play(2);
speaker_play(5);
break;
default:
break;
}
}
static inline void nand_wait_chip_ready(void)
{
struct s3c2440_nand *nand_reg = s3c2440_get_base_nand();
int i;
while (!(__READ_B(&nand_reg->nfstat) & NFSTAT_BUSY_BIT)) {
for (i=0; i<10; i++);
}
}
static inline void nand_clear_chip_busy(void)
{
struct s3c2440_nand *nand_reg = s3c2440_get_base_nand();
__WRITE_B(__READ_B(&nand_reg->nfstat) | NFSTAT_RnB_BIT,
&nand_reg->nfstat);
}
static inline void nand_disable_chip(void)
{
struct s3c2440_nand *nand_reg = s3c2440_get_base_nand();
__WRITE_L(__READ_L(&nand_reg->nfcont) | NFCONT_nCE_BIT, &nand_reg->nfcont);
}
static inline void nand_enable_chip(void)
{
struct s3c2440_nand *nand_reg = s3c2440_get_base_nand();
__WRITE_L(__READ_L(&nand_reg->nfcont) & ~NFCONT_nCE_BIT, &nand_reg->nfcont);
}
/*--------------------------------------------------------------------*/
struct boot_nand_t {
int page_size;
#ifdef NANDBOOT_SKIP_BAD
int block_size;
int bad_block_offset;
#endif
};
#ifdef NANDBOOT_SKIP_BAD
static int is_bad_block(struct boot_nand_t * mtd, unsigned long i)
{
struct s3c2440_nand *nand_reg = s3c2440_get_base_nand();
nand_clear_chip_busy();
if (mtd->page_size == 512) {
__WRITE_B(NAND_CMD_READOOB, /* 0x50 */
&nand_reg->nfcmd);
__WRITE_B(mtd->bad_block_offset & 0xf,
&nand_reg->nfaddr); /*1st cycle*/
__WRITE_B((i >> 9) & 0xff,
&nand_reg->nfaddr); /*2nd cycle*/
__WRITE_B((i >> 17) & 0xff,
&nand_reg->nfaddr); /*3th cycle*/
__WRITE_B((i >> 25) & 0xff,
&nand_reg->nfaddr); /*4th cycle*/
} else if (mtd->page_size == 2048) {
unsigned long page_num;
page_num = i >> 11; /* addr / 2048 */
__WRITE_B(NAND_CMD_READ0,
&nand_reg->nfcmd);
__WRITE_B(mtd->bad_block_offset & 0xff,
&nand_reg->nfaddr); /*1st cycle*/
__WRITE_B((mtd->bad_block_offset >> 8) & 0xff,
&nand_reg->nfaddr); /*2nd cycle*/
__WRITE_B(page_num & 0xff,
&nand_reg->nfaddr); /*3th cycle*/
__WRITE_B((page_num >> 16) & 0xff,
&nand_reg->nfaddr); /*4th cycle*/
__WRITE_B(NAND_CMD_READSTART,
&nand_reg->nfcmd);
} else {
LOAD_STATUS_ERROR(NFBT_STATUS_UNSUPPORT_PAGE_SIZE);
return -1;
}
nand_wait_chip_ready();
if ((__READ_B(&nand_reg->nfdata) & 0xff) != 0xff)
return 1;
return 0;
}
#endif
static int nand_read_page_ll(struct boot_nand_t * mtd, unsigned char *buf, unsigned long addr)
{
struct s3c2440_nand *nand_reg = s3c2440_get_base_nand();
unsigned short *ptr16 = (unsigned short *)buf;
unsigned int i, page_num;
nand_clear_chip_busy();
__WRITE_B(NAND_CMD_READ0, &nand_reg->nfcmd);
if (mtd->page_size == 512) {
/* Write Address */
__WRITE_B(addr & 0xff,
&nand_reg->nfaddr); /*1st cycle*/
__WRITE_B((addr >> 9) & 0xff,
&nand_reg->nfaddr); /*2nd cycle*/
__WRITE_B((addr >> 17) & 0xff,
&nand_reg->nfaddr); /*3th cycle*/
__WRITE_B((addr >> 25) & 0xff,
&nand_reg->nfaddr); /*4th cycle*/
} else if (mtd->page_size == 2048) {
page_num = addr >> 11; /* addr / 2048 */
/* Write Address */
__WRITE_B(0,
&nand_reg->nfaddr); /*1st cycle*/
__WRITE_B(0,
&nand_reg->nfaddr); /*2nd cycle*/
__WRITE_B(page_num & 0xff,
&nand_reg->nfaddr); /*3th cycle*/
__WRITE_B((page_num >> 8) & 0xff,
&nand_reg->nfaddr); /*4th cycle*/
__WRITE_B((page_num >> 16) & 0xff,
&nand_reg->nfaddr); /*5th cycle*/
__WRITE_B(NAND_CMD_READSTART,
&nand_reg->nfcmd);
} else {
LOAD_STATUS_ERROR(NFBT_STATUS_UNSUPPORT_PAGE_SIZE);
return -1;
}
nand_wait_chip_ready();
for (i = 0; i < (mtd->page_size>>1); i++) {
*ptr16 = __READ_W(&nand_reg->nfdata);
ptr16++;
}
return 0;
}
static unsigned short nand_read_id()
{
struct s3c2440_nand *nand_reg = s3c2440_get_base_nand();
unsigned short res = 0;
__WRITE_B(NAND_CMD_READID, &nand_reg->nfcmd);
__WRITE_B(0, &nand_reg->nfaddr); /*1st cycle*/
res = __READ_B(&nand_reg->nfdata);
return ((res << 8) | __READ_B(&nand_reg->nfdata));
}
static int nand_read_init(struct boot_nand_t *mtd)
{
struct s3c2440_nand *nand_reg = s3c2440_get_base_nand();
struct s3c24x0_clock_power *clk_power = s3c24x0_get_base_clock_power();
unsigned short nand_id;
unsigned int cfg;
int i;
/* Enable NAND flash clk */
__WRITE_L(__READ_L(&clk_power->clkcon) | (1 << 4), &clk_power->clkcon);
cfg = NFCONF_TACLS(1) | NFCONF_TWRPH0(2) | NFCONF_TWRPH1(0) | NFCONF_BUSWIDTH(0);
__WRITE_L(cfg, &nand_reg->nfconf);
cfg = NFCONT_MODE_BIT; /* wx:controler enable */
cfg &= ~NFCONT_RnB_MODE;//wx: detect rise edge,
cfg |= NFCONT_INITECC_BIT;//init ecc
cfg &= ~NFCONT_nCE_BIT;//chip enable,
__WRITE_L(cfg, &nand_reg->nfcont);
cfg = NFSTAT_RnB_BIT | NFSTAT_nCE_BIT;
__WRITE_L(cfg, &nand_reg->nfstat); /*wx: clr RnB*/
//------------------------------------------------------------------
__WRITE_B(NAND_CMD_RESET, &nand_reg->nfcmd); /*wx: reset mtd*/
//wx: is NFSTAT_RnB_BIT is hight, means chip is ready
while(!(__READ_B(&nand_reg->nfstat) & NFSTAT_RnB_BIT)) {
for (i=0; i<10; i++);
}
//------------------------------------------------------------------
nand_enable_chip();
nand_clear_chip_busy();
i = 0;
cfg = 0;
nand_id = nand_read_id();
if (nand_id == 0xec76 || /* Samsung K91208 */
nand_id == 0xad76) { /*Hynix HY27US08121A*/
mtd->page_size = 512;
cfg = (16 << 10);
#ifdef NANDBOOT_SKIP_BAD
mtd->block_size = cfg;
mtd->bad_block_offset = 5;
#endif
} else if (nand_id == 0xecf1 || /* Samsung K9F1G08U0B */
nand_id == 0xecda || /* Samsung K9F2G08U0B */
nand_id == 0xecd3 ) { /* Samsung K9K8G08 */
mtd->page_size = (2 << 10);
cfg = (128 << 10);
#ifdef NANDBOOT_SKIP_BAD
mtd->block_size = cfg;
mtd->bad_block_offset = mtd->page_size;
#endif
} else {
i = -1; // hang
LOAD_STATUS_ERROR(NFBT_STATUS_UNSUPPORT_ID);
}
nand_disable_chip();
return i;
}
/* low level nand read function */
static int nand_read_ll(struct boot_nand_t *mtd, unsigned char *buf, unsigned long start_addr, int size)
{
int i, ret;
#ifdef NANDBOOT_SKIP_BAD
if ((start_addr & (mtd->block_size-1)) || (size & ((mtd->block_size-1)))) {
LOAD_STATUS_ERROR(NFBT_STATUS_ALIGN_ERR);
return -1; /* invalid alignment */
}
#endif
/* chip Enable */
nand_enable_chip();
nand_clear_chip_busy();
for (i = 0; i < 10; i++)
;
ret = 0;
for (i=start_addr; i < (start_addr + size);) {
#ifdef NANDBOOT_SKIP_BAD
if (i & (mtd->block_size-1)== 0) {
if (is_bad_block(mtd, i) ||
is_bad_block(mtd, i + mtd->page_size)) {
/* Bad block */
i += mtd->block_size;
size += mtd->block_size;
continue;
}
}
#endif
if (0 == nand_read_page_ll(mtd, buf, i)) {
i += mtd->page_size;
buf += mtd->page_size;
} else {
ret = -1;
break;
}
}
/* chip Disable */
nand_disable_chip();
return ret;
}
#ifdef NANDBOOT_LOAD_VERIFY
static int nandboot_imgcmp(const void * cs,const void * ct,size_t count)
{
const unsigned int *su1, *su2;
count >>= 2;
for(su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
if (*su1 != *su2) {
LOAD_STATUS_ERROR(NFBT_STATUS_VERIFY_ERR);
return -1;
}
return 0;
}
#endif
int nandboot_load_img(unsigned char * destAddr)
{
struct boot_nand_t nand;
// init nand
if (0 != nand_read_init(&nand)) {
return -1;
}
// load..
if (0 != nand_read_ll(&nand, destAddr, 0, NANDBOOT_IMG_LENGTH)) {
return -1;
}
#ifdef NANDBOOT_LOAD_VERIFY
// verify
if (0 != nandboot_imgcmp(destAddr, STEPPING_STONE_RAM_BASE, STEPPING_STONE_RAM_SIZE)) {
return -1;
}
#endif
LOAD_STATUS_ERROR(NFBT_STATUS_LOAD_END);
return 0;
}
#endif
|
1001-study-uboot
|
board/samsung/mini2440/nandboot_load.c
|
C
|
gpl3
| 12,181
|
/*
* (C) Copyright 2001
* Raymond Lo, lo@routefree.com
* 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
*/
/*
* Support for harddisk partitions.
*
* To be compatible with LinuxPPC and Apple we use the standard Apple
* SCSI disk partitioning scheme. For more information see:
* http://developer.apple.com/techpubs/mac/Devices/Devices-126.html#MARKER-14-92
*/
#include <common.h>
#include <command.h>
#include <ide.h>
#include "part_dos.h"
#if defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_MG_DISK) || \
defined(CONFIG_CMD_SATA) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC) || \
defined(CONFIG_SYSTEMACE)
/* Convert char[4] in little endian format to the host format integer
*/
static inline int le32_to_int(unsigned char *le32)
{
return ((le32[3] << 24) +
(le32[2] << 16) +
(le32[1] << 8) +
le32[0]
);
}
static inline int is_extended(int part_type)
{
return (part_type == 0x5 ||
part_type == 0xf ||
part_type == 0x85);
}
static void print_one_part (dos_partition_t *p, int ext_part_sector, int part_num)
{
int lba_start = ext_part_sector + le32_to_int (p->start4);
int lba_size = le32_to_int (p->size4);
printf ("%5d\t\t%10d\t%10d\t%2x%s\n",
part_num, lba_start, lba_size, p->sys_ind,
(is_extended (p->sys_ind) ? " Extd" : ""));
}
static int test_block_type(unsigned char *buffer)
{
if((buffer[DOS_PART_MAGIC_OFFSET + 0] != 0x55) ||
(buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) ) {
return (-1);
} /* no DOS Signature at all */
if (strncmp((char *)&buffer[DOS_PBR_FSTYPE_OFFSET],"FAT",3)==0 ||
strncmp((char *)&buffer[DOS_PBR32_FSTYPE_OFFSET],"FAT32",5)==0) {
return DOS_PBR; /* is PBR */
}
return DOS_MBR; /* Is MBR */
}
int test_part_dos (block_dev_desc_t *dev_desc)
{
unsigned char buffer[dev_desc->blksz];
if ((dev_desc->block_read(dev_desc->dev, 0, 1, (ulong *) buffer) != 1) ||
(buffer[DOS_PART_MAGIC_OFFSET + 0] != 0x55) ||
(buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) ) {
return (-1);
}
return (0);
}
/* Print a partition that is relative to its Extended partition table
*/
static void print_partition_extended (block_dev_desc_t *dev_desc, int ext_part_sector, int relative,
int part_num)
{
unsigned char buffer[dev_desc->blksz];
dos_partition_t *pt;
int i;
if (dev_desc->block_read(dev_desc->dev, ext_part_sector, 1, (ulong *) buffer) != 1) {
printf ("** Can't read partition table on %d:%d **\n",
dev_desc->dev, ext_part_sector);
return;
}
i=test_block_type(buffer);
if(i==-1) {
printf ("bad MBR sector signature 0x%02x%02x\n",
buffer[DOS_PART_MAGIC_OFFSET],
buffer[DOS_PART_MAGIC_OFFSET + 1]);
return;
}
if(i==DOS_PBR) {
printf (" 1\t\t 0\t%10ld\t%2x\n",
dev_desc->lba, buffer[DOS_PBR_MEDIA_TYPE_OFFSET]);
return;
}
/* Print all primary/logical partitions */
pt = (dos_partition_t *) (buffer + DOS_PART_TBL_OFFSET);
for (i = 0; i < 4; i++, pt++) {
/*
* fdisk does not show the extended partitions that
* are not in the MBR
*/
if ((pt->sys_ind != 0) &&
(ext_part_sector == 0 || !is_extended (pt->sys_ind)) ) {
print_one_part (pt, ext_part_sector, part_num);
}
/* Reverse engr the fdisk part# assignment rule! */
if ((ext_part_sector == 0) ||
(pt->sys_ind != 0 && !is_extended (pt->sys_ind)) ) {
part_num++;
}
}
/* Follows the extended partitions */
pt = (dos_partition_t *) (buffer + DOS_PART_TBL_OFFSET);
for (i = 0; i < 4; i++, pt++) {
if (is_extended (pt->sys_ind)) {
int lba_start = le32_to_int (pt->start4) + relative;
print_partition_extended (dev_desc, lba_start,
ext_part_sector == 0 ? lba_start
: relative,
part_num);
}
}
return;
}
/* Print a partition that is relative to its Extended partition table
*/
static int get_partition_info_extended (block_dev_desc_t *dev_desc, int ext_part_sector,
int relative, int part_num,
int which_part, disk_partition_t *info)
{
unsigned char buffer[dev_desc->blksz];
dos_partition_t *pt;
int i;
if (dev_desc->block_read (dev_desc->dev, ext_part_sector, 1, (ulong *) buffer) != 1) {
printf ("** Can't read partition table on %d:%d **\n",
dev_desc->dev, ext_part_sector);
return -1;
}
if (buffer[DOS_PART_MAGIC_OFFSET] != 0x55 ||
buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) {
printf ("bad MBR sector signature 0x%02x%02x\n",
buffer[DOS_PART_MAGIC_OFFSET],
buffer[DOS_PART_MAGIC_OFFSET + 1]);
return -1;
}
/* Print all primary/logical partitions */
pt = (dos_partition_t *) (buffer + DOS_PART_TBL_OFFSET);
for (i = 0; i < 4; i++, pt++) {
/*
* fdisk does not show the extended partitions that
* are not in the MBR
*/
if (((pt->boot_ind & ~0x80) == 0) &&
(pt->sys_ind != 0) &&
(part_num == which_part) &&
(is_extended(pt->sys_ind) == 0)) {
info->blksz = 512;
info->start = ext_part_sector + le32_to_int (pt->start4);
info->size = le32_to_int (pt->size4);
switch(dev_desc->if_type) {
case IF_TYPE_IDE:
case IF_TYPE_SATA:
case IF_TYPE_ATAPI:
sprintf ((char *)info->name, "hd%c%d",
'a' + dev_desc->dev, part_num);
break;
case IF_TYPE_SCSI:
sprintf ((char *)info->name, "sd%c%d",
'a' + dev_desc->dev, part_num);
break;
case IF_TYPE_USB:
sprintf ((char *)info->name, "usbd%c%d",
'a' + dev_desc->dev, part_num);
break;
case IF_TYPE_DOC:
sprintf ((char *)info->name, "docd%c%d",
'a' + dev_desc->dev, part_num);
break;
default:
sprintf ((char *)info->name, "xx%c%d",
'a' + dev_desc->dev, part_num);
break;
}
/* sprintf(info->type, "%d, pt->sys_ind); */
sprintf ((char *)info->type, "U-Boot");
return 0;
}
/* Reverse engr the fdisk part# assignment rule! */
if ((ext_part_sector == 0) ||
(pt->sys_ind != 0 && !is_extended (pt->sys_ind)) ) {
part_num++;
}
}
/* Follows the extended partitions */
pt = (dos_partition_t *) (buffer + DOS_PART_TBL_OFFSET);
for (i = 0; i < 4; i++, pt++) {
if (is_extended (pt->sys_ind)) {
int lba_start = le32_to_int (pt->start4) + relative;
return get_partition_info_extended (dev_desc, lba_start,
ext_part_sector == 0 ? lba_start : relative,
part_num, which_part, info);
}
}
return -1;
}
void print_part_dos (block_dev_desc_t *dev_desc)
{
printf ("Partition Start Sector Num Sectors Type\n");
print_partition_extended (dev_desc, 0, 0, 1);
}
int get_partition_info_dos (block_dev_desc_t *dev_desc, int part, disk_partition_t * info)
{
return get_partition_info_extended (dev_desc, 0, 0, 1, part, info);
}
#endif
|
1001-study-uboot
|
disk/part_dos.c
|
C
|
gpl3
| 7,473
|
/*
* (C) Copyright 2000
* Hans-Joerg Frieden, Hyperion Entertainment
* Hans-JoergF@hyperion-entertainment.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 _DISK_PART_AMIGA_H
#define _DISK_PART_AMIGA_H
#include <common.h>
#ifdef CONFIG_ISO_PARTITION
/* Make the buffers bigger if ISO partition support is enabled -- CD-ROMS
have 2048 byte blocks */
#define DEFAULT_SECTOR_SIZE 2048
#else
#define DEFAULT_SECTOR_SIZE 512
#endif
#define AMIGA_BLOCK_LIMIT 16
/*
* Amiga disks have a very open structure. The head for the partition table information
* is stored somewhere within the first 16 blocks on disk, and is called the
* "RigidDiskBlock".
*/
struct rigid_disk_block
{
u32 id;
u32 summed_longs;
s32 chk_sum;
u32 host_id;
u32 block_bytes;
u32 flags;
u32 bad_block_list;
u32 partition_list;
u32 file_sys_header_list;
u32 drive_init;
u32 bootcode_block;
u32 reserved_1[5];
/* Physical drive geometry */
u32 cylinders;
u32 sectors;
u32 heads;
u32 interleave;
u32 park;
u32 reserved_2[3];
u32 write_pre_comp;
u32 reduced_write;
u32 step_rate;
u32 reserved_3[5];
/* logical drive geometry */
u32 rdb_blocks_lo;
u32 rdb_blocks_hi;
u32 lo_cylinder;
u32 hi_cylinder;
u32 cyl_blocks;
u32 auto_park_seconds;
u32 high_rdsk_block;
u32 reserved_4;
char disk_vendor[8];
char disk_product[16];
char disk_revision[4];
char controller_vendor[8];
char controller_product[16];
char controller_revision[4];
u32 reserved_5[10];
};
/*
* Each partition on this drive is defined by such a block
*/
struct partition_block
{
u32 id;
u32 summed_longs;
s32 chk_sum;
u32 host_id;
u32 next;
u32 flags;
u32 reserved_1[2];
u32 dev_flags;
char drive_name[32];
u32 reserved_2[15];
u32 environment[17];
u32 reserved_3[15];
};
struct bootcode_block
{
u32 id;
u32 summed_longs;
s32 chk_sum;
u32 host_id;
u32 next;
u32 load_data[123];
};
#define AMIGA_ID_RDISK 0x5244534B
#define AMIGA_ID_PART 0x50415254
#define AMIGA_ID_BOOT 0x424f4f54
/*
* The environment array in the partition block
* describes the partition
*/
struct amiga_part_geometry
{
u32 table_size;
u32 size_blocks;
u32 unused1;
u32 surfaces;
u32 sector_per_block;
u32 block_per_track;
u32 reserved;
u32 prealloc;
u32 interleave;
u32 low_cyl;
u32 high_cyl;
u32 num_buffers;
u32 buf_mem_type;
u32 max_transfer;
u32 mask;
s32 boot_priority;
u32 dos_type;
u32 baud;
u32 control;
u32 boot_blocks;
};
#endif /* _DISK_PART_AMIGA_H_ */
|
1001-study-uboot
|
disk/part_amiga.h
|
C
|
gpl3
| 3,524
|
/*
* (C) Copyright 2001
* Hans-Joerg Frieden, Hyperion Entertainment
* Hans-JoergF@hyperion-entertainment.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 <command.h>
#include <ide.h>
#include "part_amiga.h"
#if defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_MG_DISK) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC) || \
defined(CONFIG_SYSTEMACE)
#undef AMIGA_DEBUG
#ifdef AMIGA_DEBUG
#define PRINTF(fmt, args...) printf(fmt ,##args)
#else
#define PRINTF(fmt, args...)
#endif
struct block_header
{
u32 id;
u32 summed_longs;
s32 chk_sum;
};
static unsigned char block_buffer[DEFAULT_SECTOR_SIZE];
static struct rigid_disk_block rdb = {0};
static struct bootcode_block bootcode = {0};
/*
* Copy a bcpl to a c string
*/
static void bcpl_strcpy(char *to, char *from)
{
int len = *from++;
while (len)
{
*to++ = *from++;
len--;
}
*to = 0;
}
/*
* Print a BCPL String. BCPL strings start with a byte with the length
* of the string, and don't contain a terminating nul character
*/
static void bstr_print(char *string)
{
int len = *string++;
char buffer[256];
int i;
i = 0;
while (len)
{
buffer[i++] = *string++;
len--;
}
buffer[i] = 0;
printf("%-10s", buffer);
}
/*
* Sum a block. The checksum of a block must end up at zero
* to be valid. The chk_sum field is selected so that adding
* it yields zero.
*/
int sum_block(struct block_header *header)
{
s32 *block = (s32 *)header;
u32 i;
s32 sum = 0;
for (i = 0; i < header->summed_longs; i++)
sum += *block++;
return (sum != 0);
}
/*
* Print an AmigaOS disk type. Disk types are a four-byte identifier
* describing the file system. They are usually written as a three-letter
* word followed by a backslash and a version number. For example,
* DOS\0 would be the original file system. SFS\0 would be SmartFileSystem.
* DOS\1 is FFS.
*/
static void print_disk_type(u32 disk_type)
{
char buffer[6];
buffer[0] = (disk_type & 0xFF000000)>>24;
buffer[1] = (disk_type & 0x00FF0000)>>16;
buffer[2] = (disk_type & 0x0000FF00)>>8;
buffer[3] = '\\';
buffer[4] = (disk_type & 0x000000FF) + '0';
buffer[5] = 0;
printf("%s", buffer);
}
/*
* Print the info contained within the given partition block
*/
static void print_part_info(struct partition_block *p)
{
struct amiga_part_geometry *g;
g = (struct amiga_part_geometry *)&(p->environment);
bstr_print(p->drive_name);
printf("%6d\t%6d\t",
g->low_cyl * g->block_per_track * g->surfaces ,
(g->high_cyl - g->low_cyl + 1) * g->block_per_track * g->surfaces - 1);
print_disk_type(g->dos_type);
printf("\t%5d\n", g->boot_priority);
}
/*
* Search for the Rigid Disk Block. The rigid disk block is required
* to be within the first 16 blocks of a drive, needs to have
* the ID AMIGA_ID_RDISK ('RDSK') and needs to have a valid
* sum-to-zero checksum
*/
struct rigid_disk_block *get_rdisk(block_dev_desc_t *dev_desc)
{
int i;
int limit;
char *s;
s = getenv("amiga_scanlimit");
if (s)
limit = simple_strtoul(s, NULL, 10);
else
limit = AMIGA_BLOCK_LIMIT;
for (i=0; i<limit; i++)
{
ulong res = dev_desc->block_read(dev_desc->dev, i, 1,
(ulong *)block_buffer);
if (res == 1)
{
struct rigid_disk_block *trdb = (struct rigid_disk_block *)block_buffer;
if (trdb->id == AMIGA_ID_RDISK)
{
PRINTF("Rigid disk block suspect at %d, checking checksum\n",i);
if (sum_block((struct block_header *)block_buffer) == 0)
{
PRINTF("FOUND\n");
memcpy(&rdb, trdb, sizeof(struct rigid_disk_block));
return (struct rigid_disk_block *)&rdb;
}
}
}
}
PRINTF("Done scanning, no RDB found\n");
return NULL;
}
/*
* Search for boot code
* Again, the first boot block must be located somewhere in the first 16 blocks, or rooted in the
* Ridgid disk block
*/
struct bootcode_block *get_bootcode(block_dev_desc_t *dev_desc)
{
int i;
int limit;
char *s;
s = getenv("amiga_scanlimit");
if (s)
limit = simple_strtoul(s, NULL, 10);
else
limit = AMIGA_BLOCK_LIMIT;
PRINTF("Scanning for BOOT from 0 to %d\n", limit);
for (i = 0; i < limit; i++)
{
ulong res = dev_desc->block_read(dev_desc->dev, i, 1, (ulong *)block_buffer);
if (res == 1)
{
struct bootcode_block *boot = (struct bootcode_block *)block_buffer;
if (boot->id == AMIGA_ID_BOOT)
{
PRINTF("BOOT block at %d, checking checksum\n", i);
if (sum_block((struct block_header *)block_buffer) == 0)
{
PRINTF("Found valid bootcode block\n");
memcpy(&bootcode, boot, sizeof(struct bootcode_block));
return &bootcode;
}
}
}
}
PRINTF("No boot code found on disk\n");
return 0;
}
/*
* Test if the given partition has an Amiga partition table/Rigid
* Disk block
*/
int test_part_amiga(block_dev_desc_t *dev_desc)
{
struct rigid_disk_block *rdb;
struct bootcode_block *bootcode;
PRINTF("test_part_amiga: Testing for an Amiga RDB partition\n");
rdb = get_rdisk(dev_desc);
if (rdb)
{
bootcode = get_bootcode(dev_desc);
if (bootcode)
PRINTF("test_part_amiga: bootable Amiga disk\n");
else
PRINTF("test_part_amiga: non-bootable Amiga disk\n");
return 0;
}
else
{
PRINTF("test_part_amiga: no RDB found\n");
return -1;
}
}
/*
* Find partition number partnum on the given drive.
*/
static struct partition_block *find_partition(block_dev_desc_t *dev_desc, int partnum)
{
struct rigid_disk_block *rdb;
struct partition_block *p;
u32 block;
PRINTF("Trying to find partition block %d\n", partnum);
rdb = get_rdisk(dev_desc);
if (!rdb)
{
PRINTF("find_partition: no rdb found\n");
return NULL;
}
PRINTF("find_partition: Scanning partition list\n");
block = rdb->partition_list;
PRINTF("find_partition: partition list at 0x%x\n", block);
while (block != 0xFFFFFFFF)
{
ulong res = dev_desc->block_read(dev_desc->dev, block, 1,
(ulong *)block_buffer);
if (res == 1)
{
p = (struct partition_block *)block_buffer;
if (p->id == AMIGA_ID_PART)
{
PRINTF("PART block suspect at 0x%x, checking checksum\n",block);
if (sum_block((struct block_header *)p) == 0)
{
if (partnum == 0) break;
else
{
partnum--;
block = p->next;
}
}
} else block = 0xFFFFFFFF;
} else block = 0xFFFFFFFF;
}
if (block == 0xFFFFFFFF)
{
PRINTF("PART block not found\n");
return NULL;
}
return (struct partition_block *)block_buffer;
}
/*
* Get info about a partition
*/
int get_partition_info_amiga (block_dev_desc_t *dev_desc, int part, disk_partition_t *info)
{
struct partition_block *p = find_partition(dev_desc, part-1);
struct amiga_part_geometry *g;
u32 disk_type;
if (!p) return -1;
g = (struct amiga_part_geometry *)&(p->environment);
info->start = g->low_cyl * g->block_per_track * g->surfaces;
info->size = (g->high_cyl - g->low_cyl + 1) * g->block_per_track * g->surfaces - 1;
info->blksz = rdb.block_bytes;
bcpl_strcpy(info->name, p->drive_name);
disk_type = g->dos_type;
info->type[0] = (disk_type & 0xFF000000)>>24;
info->type[1] = (disk_type & 0x00FF0000)>>16;
info->type[2] = (disk_type & 0x0000FF00)>>8;
info->type[3] = '\\';
info->type[4] = (disk_type & 0x000000FF) + '0';
info->type[5] = 0;
return 0;
}
void print_part_amiga (block_dev_desc_t *dev_desc)
{
struct rigid_disk_block *rdb;
struct bootcode_block *boot;
struct partition_block *p;
u32 block;
int i = 1;
rdb = get_rdisk(dev_desc);
if (!rdb)
{
PRINTF("print_part_amiga: no rdb found\n");
return;
}
PRINTF("print_part_amiga: Scanning partition list\n");
block = rdb->partition_list;
PRINTF("print_part_amiga: partition list at 0x%x\n", block);
printf("Summary: DiskBlockSize: %d\n"
" Cylinders : %d\n"
" Sectors/Track: %d\n"
" Heads : %d\n\n",
rdb->block_bytes, rdb->cylinders, rdb->sectors,
rdb->heads);
printf(" First Num. \n"
"Nr. Part. Name Block Block Type Boot Priority\n");
while (block != 0xFFFFFFFF)
{
ulong res;
PRINTF("Trying to load block #0x%X\n", block);
res = dev_desc->block_read(dev_desc->dev, block, 1,
(ulong *)block_buffer);
if (res == 1)
{
p = (struct partition_block *)block_buffer;
if (p->id == AMIGA_ID_PART)
{
PRINTF("PART block suspect at 0x%x, checking checksum\n",block);
if (sum_block((struct block_header *)p) == 0)
{
printf("%-4d ", i); i++;
print_part_info(p);
block = p->next;
}
} else block = 0xFFFFFFFF;
} else block = 0xFFFFFFFF;
}
boot = get_bootcode(dev_desc);
if (boot)
{
printf("Disk is bootable\n");
}
}
#endif
|
1001-study-uboot
|
disk/part_amiga.c
|
C
|
gpl3
| 9,756
|
/*
* (C) Copyright 2001
* Denis Peter, MPL AG Switzerland, d.peter@mpl.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
*/
#include <common.h>
#include <command.h>
#include "part_iso.h"
#if defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_MG_DISK) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_SATA) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC) || \
defined(CONFIG_SYSTEMACE)
/* #define ISO_PART_DEBUG */
#ifdef ISO_PART_DEBUG
#define PRINTF(fmt,args...) printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif
/* enable this if CDs are written with the PowerPC Platform ID */
#undef CHECK_FOR_POWERPC_PLATTFORM
#define CD_SECTSIZE 2048
static unsigned char tmpbuf[CD_SECTSIZE];
/* Convert char[4] in little endian format to the host format integer
*/
static inline unsigned long le32_to_int(unsigned char *le32)
{
return ((le32[3] << 24) +
(le32[2] << 16) +
(le32[1] << 8) +
le32[0]
);
}
/* Convert char[2] in little endian format to the host format integer
*/
static inline unsigned short le16_to_int(unsigned char *le16)
{
return ((le16[1] << 8) +
le16[0]
);
}
/* only boot records will be listed as valid partitions */
int get_partition_info_iso_verb(block_dev_desc_t * dev_desc, int part_num, disk_partition_t * info, int verb)
{
int i,offset,entry_num;
unsigned short *chksumbuf;
unsigned short chksum;
unsigned long newblkaddr,blkaddr,lastsect,bootaddr;
iso_boot_rec_t *pbr = (iso_boot_rec_t *)tmpbuf; /* boot record */
iso_pri_rec_t *ppr = (iso_pri_rec_t *)tmpbuf; /* primary desc */
iso_val_entry_t *pve = (iso_val_entry_t *)tmpbuf;
iso_init_def_entry_t *pide;
/* the first sector (sector 0x10) must be a primary volume desc */
blkaddr=PVD_OFFSET;
if (dev_desc->block_read (dev_desc->dev, PVD_OFFSET, 1, (ulong *) tmpbuf) != 1)
return (-1);
if(ppr->desctype!=0x01) {
if(verb)
printf ("** First descriptor is NOT a primary desc on %d:%d **\n",
dev_desc->dev, part_num);
return (-1);
}
if(strncmp((char *)ppr->stand_ident,"CD001",5)!=0) {
if(verb)
printf ("** Wrong ISO Ident: %s on %d:%d **\n",
ppr->stand_ident,dev_desc->dev, part_num);
return (-1);
}
lastsect= ((ppr->firstsek_LEpathtab1_LE & 0x000000ff)<<24) +
((ppr->firstsek_LEpathtab1_LE & 0x0000ff00)<< 8) +
((ppr->firstsek_LEpathtab1_LE & 0x00ff0000)>> 8) +
((ppr->firstsek_LEpathtab1_LE & 0xff000000)>>24) ;
info->blksz=ppr->secsize_BE; /* assuming same block size for all entries */
PRINTF(" Lastsect:%08lx\n",lastsect);
for(i=blkaddr;i<lastsect;i++) {
PRINTF("Reading block %d\n", i);
if (dev_desc->block_read (dev_desc->dev, i, 1, (ulong *) tmpbuf) != 1)
return (-1);
if(ppr->desctype==0x00)
break; /* boot entry found */
if(ppr->desctype==0xff) {
if(verb)
printf ("** No valid boot catalog found on %d:%d **\n",
dev_desc->dev, part_num);
return (-1);
}
}
/* boot entry found */
if(strncmp(pbr->ident_str,"EL TORITO SPECIFICATION",23)!=0) {
if(verb)
printf ("** Wrong El Torito ident: %s on %d:%d **\n",
pbr->ident_str,dev_desc->dev, part_num);
return (-1);
}
bootaddr=le32_to_int(pbr->pointer);
PRINTF(" Boot Entry at: %08lX\n",bootaddr);
if (dev_desc->block_read (dev_desc->dev, bootaddr, 1, (ulong *) tmpbuf) != 1) {
if(verb)
printf ("** Can't read Boot Entry at %lX on %d:%d **\n",
bootaddr,dev_desc->dev, part_num);
return (-1);
}
chksum=0;
chksumbuf = (unsigned short *)tmpbuf;
for(i=0;i<0x10;i++)
chksum+=((chksumbuf[i] &0xff)<<8)+((chksumbuf[i] &0xff00)>>8);
if(chksum!=0) {
if(verb)
printf ("** Checksum Error in booting catalog validation entry on %d:%d **\n",
dev_desc->dev, part_num);
return (-1);
}
if((pve->key[0]!=0x55)||(pve->key[1]!=0xAA)) {
if(verb)
printf ("** Key 0x55 0xAA error on %d:%d **\n",
dev_desc->dev, part_num);
return(-1);
}
#ifdef CHECK_FOR_POWERPC_PLATTFORM
if(pve->platform!=0x01) {
if(verb)
printf ("** No PowerPC platform CD on %d:%d **\n",
dev_desc->dev, part_num);
return(-1);
}
#endif
/* the validation entry seems to be ok, now search the "partition" */
entry_num=0;
offset=0x20;
sprintf ((char *)info->type, "U-Boot");
switch(dev_desc->if_type) {
case IF_TYPE_IDE:
case IF_TYPE_SATA:
case IF_TYPE_ATAPI:
sprintf ((char *)info->name, "hd%c%d",
'a' + dev_desc->dev, part_num);
break;
case IF_TYPE_SCSI:
sprintf ((char *)info->name, "sd%c%d",
'a' + dev_desc->dev, part_num);
break;
case IF_TYPE_USB:
sprintf ((char *)info->name, "usbd%c%d",
'a' + dev_desc->dev, part_num);
break;
case IF_TYPE_DOC:
sprintf ((char *)info->name, "docd%c%d",
'a' + dev_desc->dev, part_num);
break;
default:
sprintf ((char *)info->name, "xx%c%d",
'a' + dev_desc->dev, part_num);
break;
}
/* the bootcatalog (including validation Entry) is limited to 2048Bytes
* (63 boot entries + validation entry) */
while(offset<2048) {
pide=(iso_init_def_entry_t *)&tmpbuf[offset];
if ((pide->boot_ind==0x88) ||
(pide->boot_ind==0x00)) { /* Header Id for default Sections Entries */
if(entry_num==part_num) { /* part found */
goto found;
}
entry_num++; /* count partitions Entries (boot and non bootables */
offset+=0x20;
continue;
}
if ((pide->boot_ind==0x90) || /* Section Header Entry */
(pide->boot_ind==0x91) || /* Section Header Entry (last) */
(pide->boot_ind==0x44)) { /* Extension Indicator */
offset+=0x20; /* skip unused entries */
}
else {
if(verb)
printf ("** Partition %d not found on device %d **\n",
part_num,dev_desc->dev);
return(-1);
}
}
/* if we reach this point entire sector has been
* searched w/o succsess */
if(verb)
printf ("** Partition %d not found on device %d **\n",
part_num,dev_desc->dev);
return(-1);
found:
if(pide->boot_ind!=0x88) {
if(verb)
printf ("** Partition %d is not bootable on device %d **\n",
part_num,dev_desc->dev);
return (-1);
}
switch(pide->boot_media) {
case 0x00: /* no emulation */
info->size=le16_to_int(pide->sec_cnt)>>2;
break;
case 0x01: info->size=2400>>2; break; /* 1.2MByte Floppy */
case 0x02: info->size=2880>>2; break; /* 1.44MByte Floppy */
case 0x03: info->size=5760>>2; break; /* 2.88MByte Floppy */
case 0x04: info->size=2880>>2; break; /* dummy (HD Emulation) */
default: info->size=0; break;
}
newblkaddr=le32_to_int(pide->rel_block_addr);
info->start=newblkaddr;
PRINTF(" part %d found @ %lx size %lx\n",part_num,newblkaddr,info->size);
return 0;
}
int get_partition_info_iso(block_dev_desc_t * dev_desc, int part_num, disk_partition_t * info)
{
return(get_partition_info_iso_verb(dev_desc, part_num, info, 1));
}
void print_part_iso(block_dev_desc_t * dev_desc)
{
disk_partition_t info;
int i;
if(get_partition_info_iso_verb(dev_desc,0,&info,0)==-1) {
printf("** No boot partition found on device %d **\n",dev_desc->dev);
return;
}
printf("Part Start Sect x Size Type\n");
i=0;
do {
printf (" %2d %8ld %8ld %6ld %.32s\n",
i, info.start, info.size, info.blksz, info.type);
i++;
} while (get_partition_info_iso_verb(dev_desc,i,&info,0)!=-1);
}
int test_part_iso (block_dev_desc_t *dev_desc)
{
disk_partition_t info;
return(get_partition_info_iso_verb(dev_desc,0,&info,0));
}
#endif
|
1001-study-uboot
|
disk/part_iso.c
|
C
|
gpl3
| 8,056
|
#
# (C) Copyright 2000-2006
# Wolfgang Denk, DENX Software Engineering, wd@denx.de.
#
# See file CREDITS for list of people who contributed to this
# project.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
#
include $(TOPDIR)/config.mk
#CFLAGS += -DET_DEBUG -DDEBUG
LIB = $(obj)libdisk.o
COBJS-$(CONFIG_PARTITIONS) += part.o
COBJS-$(CONFIG_MAC_PARTITION) += part_mac.o
COBJS-$(CONFIG_DOS_PARTITION) += part_dos.o
COBJS-$(CONFIG_ISO_PARTITION) += part_iso.o
COBJS-$(CONFIG_AMIGA_PARTITION) += part_amiga.o
COBJS-$(CONFIG_EFI_PARTITION) += part_efi.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
|
disk/Makefile
|
Makefile
|
gpl3
| 1,612
|
/*
* Copyright (C) 2008 RuggedCom, Inc.
* Richard Retanubun <RichardRetanubun@RuggedCom.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
*/
/*
* See also linux/fs/partitions/efi.h
*
* EFI GUID Partition Table
* Per Intel EFI Specification v1.02
* http://developer.intel.com/technology/efi/efi.htm
*/
#ifndef _DISK_PART_EFI_H
#define _DISK_PART_EFI_H
#define MSDOS_MBR_SIGNATURE 0xAA55
#define EFI_PMBR_OSTYPE_EFI 0xEF
#define EFI_PMBR_OSTYPE_EFI_GPT 0xEE
#define GPT_BLOCK_SIZE 512
#define GPT_HEADER_SIGNATURE 0x5452415020494645ULL
#define GPT_HEADER_REVISION_V1 0x00010000
#define GPT_PRIMARY_PARTITION_TABLE_LBA 1ULL
#define GPT_ENTRY_NAME "gpt"
#define EFI_GUID(a,b,c,d0,d1,d2,d3,d4,d5,d6,d7) \
((efi_guid_t) \
{{ (a) & 0xff, ((a) >> 8) & 0xff, ((a) >> 16) & 0xff, ((a) >> 24) & 0xff, \
(b) & 0xff, ((b) >> 8) & 0xff, \
(c) & 0xff, ((c) >> 8) & 0xff, \
(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }})
#define PARTITION_SYSTEM_GUID \
EFI_GUID( 0xC12A7328, 0xF81F, 0x11d2, \
0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B)
#define LEGACY_MBR_PARTITION_GUID \
EFI_GUID( 0x024DEE41, 0x33E7, 0x11d3, \
0x9D, 0x69, 0x00, 0x08, 0xC7, 0x81, 0xF3, 0x9F)
#define PARTITION_MSFT_RESERVED_GUID \
EFI_GUID( 0xE3C9E316, 0x0B5C, 0x4DB8, \
0x81, 0x7D, 0xF9, 0x2D, 0xF0, 0x02, 0x15, 0xAE)
#define PARTITION_BASIC_DATA_GUID \
EFI_GUID( 0xEBD0A0A2, 0xB9E5, 0x4433, \
0x87, 0xC0, 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7)
#define PARTITION_LINUX_RAID_GUID \
EFI_GUID( 0xa19d880f, 0x05fc, 0x4d3b, \
0xa0, 0x06, 0x74, 0x3f, 0x0f, 0x84, 0x91, 0x1e)
#define PARTITION_LINUX_SWAP_GUID \
EFI_GUID( 0x0657fd6d, 0xa4ab, 0x43c4, \
0x84, 0xe5, 0x09, 0x33, 0xc8, 0x4b, 0x4f, 0x4f)
#define PARTITION_LINUX_LVM_GUID \
EFI_GUID( 0xe6d6d379, 0xf507, 0x44c2, \
0xa2, 0x3c, 0x23, 0x8f, 0x2a, 0x3d, 0xf9, 0x28)
/* linux/include/efi.h */
typedef unsigned short efi_char16_t;
typedef struct {
unsigned char b[16];
} efi_guid_t;
/* based on linux/include/genhd.h */
struct partition {
unsigned char boot_ind; /* 0x80 - active */
unsigned char head; /* starting head */
unsigned char sector; /* starting sector */
unsigned char cyl; /* starting cylinder */
unsigned char sys_ind; /* What partition type */
unsigned char end_head; /* end head */
unsigned char end_sector; /* end sector */
unsigned char end_cyl; /* end cylinder */
unsigned char start_sect[4]; /* starting sector counting from 0 */
unsigned char nr_sects[4]; /* nr of sectors in partition */
} __attribute__ ((packed));
/* based on linux/fs/partitions/efi.h */
typedef struct _gpt_header {
unsigned char signature[8];
unsigned char revision[4];
unsigned char header_size[4];
unsigned char header_crc32[4];
unsigned char reserved1[4];
unsigned char my_lba[8];
unsigned char alternate_lba[8];
unsigned char first_usable_lba[8];
unsigned char last_usable_lba[8];
efi_guid_t disk_guid;
unsigned char partition_entry_lba[8];
unsigned char num_partition_entries[4];
unsigned char sizeof_partition_entry[4];
unsigned char partition_entry_array_crc32[4];
unsigned char reserved2[GPT_BLOCK_SIZE - 92];
} __attribute__ ((packed)) gpt_header;
typedef struct _gpt_entry_attributes {
unsigned long long required_to_function:1;
unsigned long long reserved:47;
unsigned long long type_guid_specific:16;
} __attribute__ ((packed)) gpt_entry_attributes;
#define PARTNAME_SZ (72 / sizeof(efi_char16_t))
typedef struct _gpt_entry {
efi_guid_t partition_type_guid;
efi_guid_t unique_partition_guid;
unsigned char starting_lba[8];
unsigned char ending_lba[8];
gpt_entry_attributes attributes;
efi_char16_t partition_name[PARTNAME_SZ];
}
__attribute__ ((packed)) gpt_entry;
typedef struct _legacy_mbr {
unsigned char boot_code[440];
unsigned char unique_mbr_signature[4];
unsigned char unknown[2];
struct partition partition_record[4];
unsigned char signature[2];
} __attribute__ ((packed)) legacy_mbr;
#endif /* _DISK_PART_EFI_H */
|
1001-study-uboot
|
disk/part_efi.h
|
C
|
gpl3
| 4,684
|
/*
* Copyright (C) 2008 RuggedCom, Inc.
* Richard Retanubun <RichardRetanubun@RuggedCom.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
*/
/*
* Problems with CONFIG_SYS_64BIT_LBA:
*
* struct disk_partition.start in include/part.h is sized as ulong.
* When CONFIG_SYS_64BIT_LBA is activated, lbaint_t changes from ulong to uint64_t.
* For now, it is cast back to ulong at assignment.
*
* This limits the maximum size of addressable storage to < 2 Terra Bytes
*/
#include <common.h>
#include <command.h>
#include <ide.h>
#include <malloc.h>
#include "part_efi.h"
#include <linux/ctype.h>
#if defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_MG_DISK) || \
defined(CONFIG_CMD_SATA) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC) || \
defined(CONFIG_SYSTEMACE)
/* Convert char[2] in little endian format to the host format integer
*/
static inline unsigned short le16_to_int(unsigned char *le16)
{
return ((le16[1] << 8) + le16[0]);
}
/* Convert char[4] in little endian format to the host format integer
*/
static inline unsigned long le32_to_int(unsigned char *le32)
{
return ((le32[3] << 24) + (le32[2] << 16) + (le32[1] << 8) + le32[0]);
}
/* Convert char[8] in little endian format to the host format integer
*/
static inline unsigned long long le64_to_int(unsigned char *le64)
{
return (((unsigned long long)le64[7] << 56) +
((unsigned long long)le64[6] << 48) +
((unsigned long long)le64[5] << 40) +
((unsigned long long)le64[4] << 32) +
((unsigned long long)le64[3] << 24) +
((unsigned long long)le64[2] << 16) +
((unsigned long long)le64[1] << 8) +
(unsigned long long)le64[0]);
}
/**
* efi_crc32() - EFI version of crc32 function
* @buf: buffer to calculate crc32 of
* @len - length of buf
*
* Description: Returns EFI-style CRC32 value for @buf
*/
static inline unsigned long efi_crc32(const void *buf, unsigned long len)
{
return crc32(0, buf, len);
}
/*
* Private function prototypes
*/
static int pmbr_part_valid(struct partition *part);
static int is_pmbr_valid(legacy_mbr * mbr);
static int is_gpt_valid(block_dev_desc_t * dev_desc, unsigned long long lba,
gpt_header * pgpt_head, gpt_entry ** pgpt_pte);
static gpt_entry *alloc_read_gpt_entries(block_dev_desc_t * dev_desc,
gpt_header * pgpt_head);
static int is_pte_valid(gpt_entry * pte);
static char *print_efiname(gpt_entry *pte)
{
static char name[PARTNAME_SZ + 1];
int i;
for (i = 0; i < PARTNAME_SZ; i++) {
u8 c;
c = pte->partition_name[i] & 0xff;
c = (c && !isprint(c)) ? '.' : c;
name[i] = c;
}
name[PARTNAME_SZ] = 0;
return name;
}
/*
* Public Functions (include/part.h)
*/
void print_part_efi(block_dev_desc_t * dev_desc)
{
ALLOC_CACHE_ALIGN_BUFFER(gpt_header, gpt_head, 1);
gpt_entry *gpt_pte = NULL;
int i = 0;
if (!dev_desc) {
printf("%s: Invalid Argument(s)\n", __func__);
return;
}
/* This function validates AND fills in the GPT header and PTE */
if (is_gpt_valid(dev_desc, GPT_PRIMARY_PARTITION_TABLE_LBA,
gpt_head, &gpt_pte) != 1) {
printf("%s: *** ERROR: Invalid GPT ***\n", __func__);
return;
}
debug("%s: gpt-entry at %p\n", __func__, gpt_pte);
printf("Part\tName\t\t\tStart LBA\tEnd LBA\n");
for (i = 0; i < le32_to_int(gpt_head->num_partition_entries); i++) {
if (is_pte_valid(&gpt_pte[i])) {
printf("%3d\t%-18s\t0x%08llX\t0x%08llX\n", (i + 1),
print_efiname(&gpt_pte[i]),
le64_to_int(gpt_pte[i].starting_lba),
le64_to_int(gpt_pte[i].ending_lba));
} else {
break; /* Stop at the first non valid PTE */
}
}
/* Remember to free pte */
free(gpt_pte);
return;
}
int get_partition_info_efi(block_dev_desc_t * dev_desc, int part,
disk_partition_t * info)
{
ALLOC_CACHE_ALIGN_BUFFER(gpt_header, gpt_head, 1);
gpt_entry *gpt_pte = NULL;
/* "part" argument must be at least 1 */
if (!dev_desc || !info || part < 1) {
printf("%s: Invalid Argument(s)\n", __func__);
return -1;
}
/* This function validates AND fills in the GPT header and PTE */
if (is_gpt_valid(dev_desc, GPT_PRIMARY_PARTITION_TABLE_LBA,
gpt_head, &gpt_pte) != 1) {
printf("%s: *** ERROR: Invalid GPT ***\n", __func__);
return -1;
}
/* The ulong casting limits the maximum disk size to 2 TB */
info->start = (ulong) le64_to_int(gpt_pte[part - 1].starting_lba);
/* The ending LBA is inclusive, to calculate size, add 1 to it */
info->size = ((ulong)le64_to_int(gpt_pte[part - 1].ending_lba) + 1)
- info->start;
info->blksz = GPT_BLOCK_SIZE;
sprintf((char *)info->name, "%s",
print_efiname(&gpt_pte[part - 1]));
sprintf((char *)info->type, "U-Boot");
debug("%s: start 0x%lX, size 0x%lX, name %s", __func__,
info->start, info->size, info->name);
/* Remember to free pte */
free(gpt_pte);
return 0;
}
int test_part_efi(block_dev_desc_t * dev_desc)
{
ALLOC_CACHE_ALIGN_BUFFER(legacy_mbr, legacymbr, 1);
/* Read legacy MBR from block 0 and validate it */
if ((dev_desc->block_read(dev_desc->dev, 0, 1, (ulong *)legacymbr) != 1)
|| (is_pmbr_valid(legacymbr) != 1)) {
return -1;
}
return 0;
}
/*
* Private functions
*/
/*
* pmbr_part_valid(): Check for EFI partition signature
*
* Returns: 1 if EFI GPT partition type is found.
*/
static int pmbr_part_valid(struct partition *part)
{
if (part->sys_ind == EFI_PMBR_OSTYPE_EFI_GPT &&
le32_to_int(part->start_sect) == 1UL) {
return 1;
}
return 0;
}
/*
* is_pmbr_valid(): test Protective MBR for validity
*
* Returns: 1 if PMBR is valid, 0 otherwise.
* Validity depends on two things:
* 1) MSDOS signature is in the last two bytes of the MBR
* 2) One partition of type 0xEE is found, checked by pmbr_part_valid()
*/
static int is_pmbr_valid(legacy_mbr * mbr)
{
int i = 0;
if (!mbr || le16_to_int(mbr->signature) != MSDOS_MBR_SIGNATURE) {
return 0;
}
for (i = 0; i < 4; i++) {
if (pmbr_part_valid(&mbr->partition_record[i])) {
return 1;
}
}
return 0;
}
/**
* is_gpt_valid() - tests one GPT header and PTEs for validity
*
* lba is the logical block address of the GPT header to test
* gpt is a GPT header ptr, filled on return.
* ptes is a PTEs ptr, filled on return.
*
* Description: returns 1 if valid, 0 on error.
* If valid, returns pointers to PTEs.
*/
static int is_gpt_valid(block_dev_desc_t * dev_desc, unsigned long long lba,
gpt_header * pgpt_head, gpt_entry ** pgpt_pte)
{
unsigned char crc32_backup[4] = { 0 };
unsigned long calc_crc32;
unsigned long long lastlba;
if (!dev_desc || !pgpt_head) {
printf("%s: Invalid Argument(s)\n", __func__);
return 0;
}
/* Read GPT Header from device */
if (dev_desc->block_read(dev_desc->dev, lba, 1, pgpt_head) != 1) {
printf("*** ERROR: Can't read GPT header ***\n");
return 0;
}
/* Check the GPT header signature */
if (le64_to_int(pgpt_head->signature) != GPT_HEADER_SIGNATURE) {
printf("GUID Partition Table Header signature is wrong:"
"0x%llX != 0x%llX\n",
(unsigned long long)le64_to_int(pgpt_head->signature),
(unsigned long long)GPT_HEADER_SIGNATURE);
return 0;
}
/* Check the GUID Partition Table CRC */
memcpy(crc32_backup, pgpt_head->header_crc32, sizeof(crc32_backup));
memset(pgpt_head->header_crc32, 0, sizeof(pgpt_head->header_crc32));
calc_crc32 = efi_crc32((const unsigned char *)pgpt_head,
le32_to_int(pgpt_head->header_size));
memcpy(pgpt_head->header_crc32, crc32_backup, sizeof(crc32_backup));
if (calc_crc32 != le32_to_int(crc32_backup)) {
printf("GUID Partition Table Header CRC is wrong:"
"0x%08lX != 0x%08lX\n",
le32_to_int(crc32_backup), calc_crc32);
return 0;
}
/* Check that the my_lba entry points to the LBA that contains the GPT */
if (le64_to_int(pgpt_head->my_lba) != lba) {
printf("GPT: my_lba incorrect: %llX != %llX\n",
(unsigned long long)le64_to_int(pgpt_head->my_lba),
(unsigned long long)lba);
return 0;
}
/* Check the first_usable_lba and last_usable_lba are within the disk. */
lastlba = (unsigned long long)dev_desc->lba;
if (le64_to_int(pgpt_head->first_usable_lba) > lastlba) {
printf("GPT: first_usable_lba incorrect: %llX > %llX\n",
le64_to_int(pgpt_head->first_usable_lba), lastlba);
return 0;
}
if (le64_to_int(pgpt_head->last_usable_lba) > lastlba) {
printf("GPT: last_usable_lba incorrect: %llX > %llX\n",
le64_to_int(pgpt_head->last_usable_lba), lastlba);
return 0;
}
debug("GPT: first_usable_lba: %llX last_usable_lba %llX last lba %llX\n",
le64_to_int(pgpt_head->first_usable_lba),
le64_to_int(pgpt_head->last_usable_lba), lastlba);
/* Read and allocate Partition Table Entries */
*pgpt_pte = alloc_read_gpt_entries(dev_desc, pgpt_head);
if (*pgpt_pte == NULL) {
printf("GPT: Failed to allocate memory for PTE\n");
return 0;
}
/* Check the GUID Partition Table Entry Array CRC */
calc_crc32 = efi_crc32((const unsigned char *)*pgpt_pte,
le32_to_int(pgpt_head->num_partition_entries) *
le32_to_int(pgpt_head->sizeof_partition_entry));
if (calc_crc32 != le32_to_int(pgpt_head->partition_entry_array_crc32)) {
printf("GUID Partition Table Entry Array CRC is wrong:"
"0x%08lX != 0x%08lX\n",
le32_to_int(pgpt_head->partition_entry_array_crc32),
calc_crc32);
free(*pgpt_pte);
return 0;
}
/* We're done, all's well */
return 1;
}
/**
* alloc_read_gpt_entries(): reads partition entries from disk
* @dev_desc
* @gpt - GPT header
*
* Description: Returns ptes on success, NULL on error.
* Allocates space for PTEs based on information found in @gpt.
* Notes: remember to free pte when you're done!
*/
static gpt_entry *alloc_read_gpt_entries(block_dev_desc_t * dev_desc,
gpt_header * pgpt_head)
{
size_t count = 0;
gpt_entry *pte = NULL;
if (!dev_desc || !pgpt_head) {
printf("%s: Invalid Argument(s)\n", __func__);
return NULL;
}
count = le32_to_int(pgpt_head->num_partition_entries) *
le32_to_int(pgpt_head->sizeof_partition_entry);
debug("%s: count = %lu * %lu = %u\n", __func__,
le32_to_int(pgpt_head->num_partition_entries),
le32_to_int(pgpt_head->sizeof_partition_entry), count);
/* Allocate memory for PTE, remember to FREE */
if (count != 0) {
pte = memalign(ARCH_DMA_MINALIGN, count);
}
if (count == 0 || pte == NULL) {
printf("%s: ERROR: Can't allocate 0x%X bytes for GPT Entries\n",
__func__, count);
return NULL;
}
/* Read GPT Entries from device */
if (dev_desc->block_read (dev_desc->dev,
(unsigned long)le64_to_int(pgpt_head->partition_entry_lba),
(lbaint_t) (count / GPT_BLOCK_SIZE), pte)
!= (count / GPT_BLOCK_SIZE)) {
printf("*** ERROR: Can't read GPT Entries ***\n");
free(pte);
return NULL;
}
return pte;
}
/**
* is_pte_valid(): validates a single Partition Table Entry
* @gpt_entry - Pointer to a single Partition Table Entry
*
* Description: returns 1 if valid, 0 on error.
*/
static int is_pte_valid(gpt_entry * pte)
{
efi_guid_t unused_guid;
if (!pte) {
printf("%s: Invalid Argument(s)\n", __func__);
return 0;
}
/* Only one validation for now:
* The GUID Partition Type != Unused Entry (ALL-ZERO)
*/
memset(unused_guid.b, 0, sizeof(unused_guid.b));
if (memcmp(pte->partition_type_guid.b, unused_guid.b,
sizeof(unused_guid.b)) == 0) {
debug("%s: Found an unused PTE GUID at 0x%08X\n", __func__,
(unsigned int)pte);
return 0;
} else {
return 1;
}
}
#endif
|
1001-study-uboot
|
disk/part_efi.c
|
C
|
gpl3
| 12,061
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* See also Linux sources, fs/partitions/mac.h
*
* This file describes structures and values related to the standard
* Apple SCSI disk partitioning scheme. For more information see:
* http://developer.apple.com/techpubs/mac/Devices/Devices-126.html#MARKER-14-92
*/
#ifndef _DISK_PART_MAC_H
#define _DISK_PART_MAC_H
#define MAC_DRIVER_MAGIC 0x4552
/*
* Driver Descriptor Structure, in block 0.
* This block is (and shall remain) 512 bytes long.
* Note that there is an alignment problem for the driver descriptor map!
*/
typedef struct mac_driver_desc {
__u16 signature; /* expected to be MAC_DRIVER_MAGIC */
__u16 blk_size; /* block size of device */
__u32 blk_count; /* number of blocks on device */
__u16 dev_type; /* device type */
__u16 dev_id; /* device id */
__u32 data; /* reserved */
__u16 drvr_cnt; /* number of driver descriptor entries */
__u16 drvr_map[247]; /* driver descriptor map */
} mac_driver_desc_t;
/*
* Device Driver Entry
* (Cannot be included in mac_driver_desc because of alignment problems)
*/
typedef struct mac_driver_entry {
__u32 block; /* block number of starting block */
__u16 size; /* size of driver, in 512 byte blocks */
__u16 type; /* OS Type */
} mac_driver_entry_t;
#define MAC_PARTITION_MAGIC 0x504d
/* type field value for A/UX or other Unix partitions */
#define APPLE_AUX_TYPE "Apple_UNIX_SVR2"
/*
* Each Partition Map entry (in blocks 1 ... N) has this format:
*/
typedef struct mac_partition {
__u16 signature; /* expected to be MAC_PARTITION_MAGIC */
__u16 sig_pad; /* reserved */
__u32 map_count; /* # blocks in partition map */
__u32 start_block; /* abs. starting block # of partition */
__u32 block_count; /* number of blocks in partition */
uchar name[32]; /* partition name */
uchar type[32]; /* string type description */
__u32 data_start; /* rel block # of first data block */
__u32 data_count; /* number of data blocks */
__u32 status; /* partition status bits */
__u32 boot_start; /* first block of boot code */
__u32 boot_size; /* size of boot code, in bytes */
__u32 boot_load; /* boot code load address */
__u32 boot_load2; /* reserved */
__u32 boot_entry; /* boot code entry point */
__u32 boot_entry2; /* reserved */
__u32 boot_cksum; /* boot code checksum */
uchar processor[16]; /* Type of Processor */
__u16 part_pad[188]; /* reserved */
#ifdef CONFIG_ISO_PARTITION
uchar iso_dummy[2048];/* Reservere enough room for an ISO partition block to fit */
#endif
} mac_partition_t;
#define MAC_STATUS_BOOTABLE 8 /* partition is bootable */
#endif /* _DISK_PART_MAC_H */
|
1001-study-uboot
|
disk/part_mac.h
|
C
|
gpl3
| 3,517
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* Support for harddisk partitions.
*
* To be compatible with LinuxPPC and Apple we use the standard Apple
* SCSI disk partitioning scheme. For more information see:
* http://developer.apple.com/techpubs/mac/Devices/Devices-126.html#MARKER-14-92
*/
#include <common.h>
#include <command.h>
#include <ide.h>
#include "part_mac.h"
#if defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_MG_DISK) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_SATA) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC) || \
defined(CONFIG_SYSTEMACE)
/* stdlib.h causes some compatibility problems; should fixe these! -- wd */
#ifndef __ldiv_t_defined
typedef struct {
long int quot; /* Quotient */
long int rem; /* Remainder */
} ldiv_t;
extern ldiv_t ldiv (long int __numer, long int __denom);
# define __ldiv_t_defined 1
#endif
static int part_mac_read_ddb (block_dev_desc_t *dev_desc, mac_driver_desc_t *ddb_p);
static int part_mac_read_pdb (block_dev_desc_t *dev_desc, int part, mac_partition_t *pdb_p);
/*
* Test for a valid MAC partition
*/
int test_part_mac (block_dev_desc_t *dev_desc)
{
mac_driver_desc_t ddesc;
mac_partition_t mpart;
ulong i, n;
if (part_mac_read_ddb (dev_desc, &ddesc)) {
/* error reading Driver Desriptor Block, or no valid Signature */
return (-1);
}
n = 1; /* assuming at least one partition */
for (i=1; i<=n; ++i) {
if ((dev_desc->block_read(dev_desc->dev, i, 1, (ulong *)&mpart) != 1) ||
(mpart.signature != MAC_PARTITION_MAGIC) ) {
return (-1);
}
/* update partition count */
n = mpart.map_count;
}
return (0);
}
void print_part_mac (block_dev_desc_t *dev_desc)
{
ulong i, n;
mac_driver_desc_t ddesc;
mac_partition_t mpart;
ldiv_t mb, gb;
if (part_mac_read_ddb (dev_desc, &ddesc)) {
/* error reading Driver Desriptor Block, or no valid Signature */
return;
}
n = ddesc.blk_count;
mb = ldiv(n, ((1024 * 1024) / ddesc.blk_size)); /* MB */
/* round to 1 digit */
mb.rem *= 10 * ddesc.blk_size;
mb.rem += 512 * 1024;
mb.rem /= 1024 * 1024;
gb = ldiv(10 * mb.quot + mb.rem, 10240);
gb.rem += 512;
gb.rem /= 1024;
printf ("Block Size=%d, Number of Blocks=%d, "
"Total Capacity: %ld.%ld MB = %ld.%ld GB\n"
"DeviceType=0x%x, DeviceId=0x%x\n\n"
" #: type name"
" length base (size)\n",
ddesc.blk_size,
ddesc.blk_count,
mb.quot, mb.rem, gb.quot, gb.rem,
ddesc.dev_type, ddesc.dev_id
);
n = 1; /* assuming at least one partition */
for (i=1; i<=n; ++i) {
ulong bytes;
char c;
printf ("%4ld: ", i);
if (dev_desc->block_read (dev_desc->dev, i, 1, (ulong *)&mpart) != 1) {
printf ("** Can't read Partition Map on %d:%ld **\n",
dev_desc->dev, i);
return;
}
if (mpart.signature != MAC_PARTITION_MAGIC) {
printf ("** Bad Signature on %d:%ld - "
"expected 0x%04x, got 0x%04x\n",
dev_desc->dev, i, MAC_PARTITION_MAGIC, mpart.signature);
return;
}
/* update partition count */
n = mpart.map_count;
c = 'k';
bytes = mpart.block_count;
bytes /= (1024 / ddesc.blk_size); /* kB; assumes blk_size == 512 */
if (bytes >= 1024) {
bytes >>= 10;
c = 'M';
}
if (bytes >= 1024) {
bytes >>= 10;
c = 'G';
}
printf ("%20.32s %-18.32s %10u @ %-10u (%3ld%c)\n",
mpart.type,
mpart.name,
mpart.block_count,
mpart.start_block,
bytes, c
);
}
return;
}
/*
* Read Device Descriptor Block
*/
static int part_mac_read_ddb (block_dev_desc_t *dev_desc, mac_driver_desc_t *ddb_p)
{
if (dev_desc->block_read(dev_desc->dev, 0, 1, (ulong *)ddb_p) != 1) {
printf ("** Can't read Driver Desriptor Block **\n");
return (-1);
}
if (ddb_p->signature != MAC_DRIVER_MAGIC) {
#if 0
printf ("** Bad Signature: expected 0x%04x, got 0x%04x\n",
MAC_DRIVER_MAGIC, ddb_p->signature);
#endif
return (-1);
}
return (0);
}
/*
* Read Partition Descriptor Block
*/
static int part_mac_read_pdb (block_dev_desc_t *dev_desc, int part, mac_partition_t *pdb_p)
{
int n = 1;
for (;;) {
/*
* We must always read the descritpor block for
* partition 1 first since this is the only way to
* know how many partitions we have.
*/
if (dev_desc->block_read (dev_desc->dev, n, 1, (ulong *)pdb_p) != 1) {
printf ("** Can't read Partition Map on %d:%d **\n",
dev_desc->dev, n);
return (-1);
}
if (pdb_p->signature != MAC_PARTITION_MAGIC) {
printf ("** Bad Signature on %d:%d: "
"expected 0x%04x, got 0x%04x\n",
dev_desc->dev, n, MAC_PARTITION_MAGIC, pdb_p->signature);
return (-1);
}
if (n == part)
return (0);
if ((part < 1) || (part > pdb_p->map_count)) {
printf ("** Invalid partition %d:%d [%d:1...%d:%d only]\n",
dev_desc->dev, part,
dev_desc->dev,
dev_desc->dev, pdb_p->map_count);
return (-1);
}
/* update partition count */
n = part;
}
/* NOTREACHED */
}
int get_partition_info_mac (block_dev_desc_t *dev_desc, int part, disk_partition_t *info)
{
mac_driver_desc_t ddesc;
mac_partition_t mpart;
if (part_mac_read_ddb (dev_desc, &ddesc)) {
return (-1);
}
info->blksz = ddesc.blk_size;
if (part_mac_read_pdb (dev_desc, part, &mpart)) {
return (-1);
}
info->start = mpart.start_block;
info->size = mpart.block_count;
memcpy (info->type, mpart.type, sizeof(info->type));
memcpy (info->name, mpart.name, sizeof(info->name));
return (0);
}
#endif
|
1001-study-uboot
|
disk/part_mac.c
|
C
|
gpl3
| 6,278
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#ifndef _DISK_PART_DOS_H
#define _DISK_PART_DOS_H
#define DOS_PART_TBL_OFFSET 0x1be
#define DOS_PART_MAGIC_OFFSET 0x1fe
#define DOS_PBR_FSTYPE_OFFSET 0x36
#define DOS_PBR32_FSTYPE_OFFSET 0x52
#define DOS_PBR_MEDIA_TYPE_OFFSET 0x15
#define DOS_MBR 0
#define DOS_PBR 1
typedef struct dos_partition {
unsigned char boot_ind; /* 0x80 - active */
unsigned char head; /* starting head */
unsigned char sector; /* starting sector */
unsigned char cyl; /* starting cylinder */
unsigned char sys_ind; /* What partition type */
unsigned char end_head; /* end head */
unsigned char end_sector; /* end sector */
unsigned char end_cyl; /* end cylinder */
unsigned char start4[4]; /* starting sector counting from 0 */
unsigned char size4[4]; /* nr of sectors in partition */
} dos_partition_t;
#endif /* _DISK_PART_DOS_H */
|
1001-study-uboot
|
disk/part_dos.h
|
C
|
gpl3
| 1,735
|
/*
* (C) Copyright 2001
* Denis Peter, MPL AG Switzerland, d.peter@mpl.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
*/
#ifndef _PART_CD_H
#define _PART_CD_H
#define BRVD 0x11
#define PVD_OFFSET 0x10
typedef struct iso_boot_rec {
unsigned char desctype; /* type of Volume descriptor: 0 = boot record, 1 = primary, 2 = Supplement, 3 = volume part 0xff trminator */
unsigned char stand_ident[5]; /* "CD001" */
unsigned char vers; /* Version */
char ident_str[0x20]; /* Ident String "EL TORITO SPECIFICATION" */
unsigned char unused[0x20]; /* unused */
unsigned char pointer[4]; /* absolute pointer to Boot Catalog */
} iso_boot_rec_t;
typedef struct iso_pri_rec {
unsigned char desctype; /* type of Volume descriptor: 0 = boot record, 1 = primary, 2 = Supplement, 3 = volume part 0xff trminator */
unsigned char stand_ident[5]; /* "CD001" */
unsigned char vers; /* Version */
unsigned char unused;
char sysid[32]; /* system Identifier */
char volid[32]; /* volume Identifier */
unsigned char zeros1[8]; /* unused */
unsigned long volsiz_LE; /* volume size Little Endian */
unsigned long volsiz_BE; /* volume size Big Endian */
unsigned char zeros2[32]; /* unused */
unsigned short setsize_LE; /* volume set size LE */
unsigned short setsize_BE; /* volume set size BE */
unsigned short seqnum_LE; /* volume sequence number LE */
unsigned short seqnum_BE; /* volume sequence number BE */
unsigned short secsize_LE; /* sector size LE */
unsigned short secsize_BE; /* sector size BE */
unsigned long pathtablen_LE;/* Path Table size LE */
unsigned long pathtablen_BE;/* Path Table size BE */
unsigned long firstsek_LEpathtab1_LE; /* location of first occurrence of little endian type path table */
unsigned long firstsek_LEpathtab2_LE; /* location of optional occurrence of little endian type path table */
unsigned long firstsek_BEpathtab1_BE; /* location of first occurrence of big endian type path table */
unsigned long firstsek_BEpathtab2_BE; /* location of optional occurrence of big endian type path table */
unsigned char rootdir[34]; /* directory record for root dir */
char volsetid[128];/* Volume set identifier */
char pubid[128]; /* Publisher identifier */
char dataprepid[128]; /* data preparer identifier */
char appid[128]; /* application identifier */
char copyr[37]; /* copyright string */
char abstractfileid[37]; /* abstract file identifier */
char bibliofileid[37]; /* bibliographic file identifier */
unsigned char creationdate[17]; /* creation date */
unsigned char modify[17]; /* modification date */
unsigned char expire[17]; /* expiring date */
unsigned char effective[17];/* effective date */
unsigned char filestruc_ver; /* file structur version */
} iso_pri_rec_t;
typedef struct iso_sup_rec {
unsigned char desctype; /* type of Volume descriptor: 0 = boot record, 1 = primary, 2 = Supplement, 3 = volume part 0xff trminator */
unsigned char stand_ident[5]; /* "CD001" */
unsigned char vers; /* Version */
unsigned char volumeflags; /* if bit 0 = 0 => all escape sequences are according ISO 2375 */
char sysid[32]; /* system Identifier */
char volid[32]; /* volume Identifier */
unsigned char zeros1[8]; /* unused */
unsigned long volsiz_LE; /* volume size Little Endian */
unsigned long volsiz_BE; /* volume size Big Endian */
unsigned char escapeseq[32];/* Escape sequences */
unsigned short setsize_LE; /* volume set size LE */
unsigned short setsize_BE; /* volume set size BE */
unsigned short seqnum_LE; /* volume sequence number LE */
unsigned short seqnum_BE; /* volume sequence number BE */
unsigned short secsize_LE; /* sector size LE */
unsigned short secsize_BE; /* sector size BE */
unsigned long pathtablen_LE;/* Path Table size LE */
unsigned long pathtablen_BE;/* Path Table size BE */
unsigned long firstsek_LEpathtab1_LE; /* location of first occurrence of little endian type path table */
unsigned long firstsek_LEpathtab2_LE; /* location of optional occurrence of little endian type path table */
unsigned long firstsek_BEpathtab1_BE; /* location of first occurrence of big endian type path table */
unsigned long firstsek_BEpathtab2_BE; /* location of optional occurrence of big endian type path table */
unsigned char rootdir[34]; /* directory record for root dir */
char volsetid[128];/* Volume set identifier */
char pubid[128]; /* Publisher identifier */
char dataprepid[128]; /* data preparer identifier */
char appid[128]; /* application identifier */
char copyr[37]; /* copyright string */
char abstractfileid[37]; /* abstract file identifier */
char bibliofileid[37]; /* bibliographic file identifier */
unsigned char creationdate[17]; /* creation date */
unsigned char modify[17]; /* modification date */
unsigned char expire[17]; /* expiring date */
unsigned char effective[17];/* effective date */
unsigned char filestruc_ver; /* file structur version */
}iso_sup_rec_t;
typedef struct iso_part_rec {
unsigned char desctype; /* type of Volume descriptor: 0 = boot record, 1 = primary, 2 = Supplement, 3 = volume part 0xff trminator */
unsigned char stand_ident[5]; /* "CD001" */
unsigned char vers; /* Version */
unsigned char unused;
char sysid[32]; /* system Identifier */
char volid[32]; /* volume partition Identifier */
unsigned long partloc_LE; /* volume partition location LE */
unsigned long partloc_BE; /* volume partition location BE */
unsigned long partsiz_LE; /* volume partition size LE */
unsigned long partsiz_BE; /* volume partition size BE */
}iso_part_rec_t;
typedef struct iso_val_entry {
unsigned char header_id; /* Header ID must be 0x01 */
unsigned char platform; /* Platform: 0=x86, 1=PowerPC, 2=MAC */
unsigned char res[2]; /* reserved */
char manu_str[0x18]; /* Ident String of manufacturer/developer */
unsigned char chk_sum[2]; /* Check sum (all words must be zero) */
unsigned char key[2]; /* key[0]=55, key[1]=0xAA */
} iso_val_entry_t;
typedef struct iso_header_entry {
unsigned char header_id; /* Header ID must be 0x90 or 0x91 */
unsigned char platform; /* Platform: 0=x86, 1=PowerPC, 2=MAC */
unsigned char numentry[2]; /* number of entries */
char id_str[0x1C]; /* Ident String of sectionr */
} iso_header_entry_t;
typedef struct iso_init_def_entry {
unsigned char boot_ind; /* Boot indicator 0x88=bootable 0=not bootable */
unsigned char boot_media; /* boot Media Type: 0=no Emulation, 1=1.2MB floppy, 2=1.44MB floppy, 3=2.88MB floppy 4=hd (0x80) */
unsigned char ld_seg[2]; /* Load segment (flat model=addr/10) */
unsigned char systype; /* System Type copy of byte5 of part table */
unsigned char res; /* reserved */
unsigned char sec_cnt[2]; /* sector count in VIRTUAL Blocks (0x200) */
unsigned char rel_block_addr[4]; /* relative Block address */
} iso_init_def_entry_t;
void print_partition_cd(int dev);
#endif /* _PART_CD_H */
|
1001-study-uboot
|
disk/part_iso.h
|
C
|
gpl3
| 7,771
|
/*
* (C) Copyright 2001
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <ide.h>
#include <part.h>
#undef PART_DEBUG
#ifdef PART_DEBUG
#define PRINTF(fmt,args...) printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif
#if (defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_MG_DISK) || \
defined(CONFIG_CMD_SATA) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC) || \
defined(CONFIG_SYSTEMACE) )
struct block_drvr {
char *name;
block_dev_desc_t* (*get_dev)(int dev);
};
static const struct block_drvr block_drvr[] = {
#if defined(CONFIG_CMD_IDE)
{ .name = "ide", .get_dev = ide_get_dev, },
#endif
#if defined(CONFIG_CMD_SATA)
{.name = "sata", .get_dev = sata_get_dev, },
#endif
#if defined(CONFIG_CMD_SCSI)
{ .name = "scsi", .get_dev = scsi_get_dev, },
#endif
#if defined(CONFIG_CMD_USB) && defined(CONFIG_USB_STORAGE)
{ .name = "usb", .get_dev = usb_stor_get_dev, },
#endif
#if defined(CONFIG_MMC)
{ .name = "mmc", .get_dev = mmc_get_dev, },
#endif
#if defined(CONFIG_SYSTEMACE)
{ .name = "ace", .get_dev = systemace_get_dev, },
#endif
#if defined(CONFIG_CMD_MG_DISK)
{ .name = "mgd", .get_dev = mg_disk_get_dev, },
#endif
{ },
};
DECLARE_GLOBAL_DATA_PTR;
block_dev_desc_t *get_dev(char* ifname, int dev)
{
const struct block_drvr *drvr = block_drvr;
block_dev_desc_t* (*reloc_get_dev)(int dev);
char *name;
name = drvr->name;
#ifdef CONFIG_NEEDS_MANUAL_RELOC
name += gd->reloc_off;
#endif
while (drvr->name) {
name = drvr->name;
reloc_get_dev = drvr->get_dev;
#ifdef CONFIG_NEEDS_MANUAL_RELOC
name += gd->reloc_off;
reloc_get_dev += gd->reloc_off;
#endif
if (strncmp(ifname, name, strlen(name)) == 0)
return reloc_get_dev(dev);
drvr++;
}
return NULL;
}
#else
block_dev_desc_t *get_dev(char* ifname, int dev)
{
return NULL;
}
#endif
#if (defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_MG_DISK) || \
defined(CONFIG_CMD_SATA) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC) || \
defined(CONFIG_SYSTEMACE) )
/* ------------------------------------------------------------------------- */
/*
* reports device info to the user
*/
#ifdef CONFIG_LBA48
typedef uint64_t lba512_t;
#else
typedef lbaint_t lba512_t;
#endif
/*
* Overflowless variant of (block_count * mul_by / div_by)
* when div_by > mul_by
*/
static lba512_t lba512_muldiv (lba512_t block_count, lba512_t mul_by, lba512_t div_by)
{
lba512_t bc_quot, bc_rem;
/* x * m / d == x / d * m + (x % d) * m / d */
bc_quot = block_count / div_by;
bc_rem = block_count - div_by * bc_quot;
return bc_quot * mul_by + (bc_rem * mul_by) / div_by;
}
void dev_print (block_dev_desc_t *dev_desc)
{
lba512_t lba512; /* number of blocks if 512bytes block size */
if (dev_desc->type == DEV_TYPE_UNKNOWN) {
puts ("not available\n");
return;
}
switch (dev_desc->if_type) {
case IF_TYPE_SCSI:
printf ("(%d:%d) Vendor: %s Prod.: %s Rev: %s\n",
dev_desc->target,dev_desc->lun,
dev_desc->vendor,
dev_desc->product,
dev_desc->revision);
break;
case IF_TYPE_ATAPI:
case IF_TYPE_IDE:
case IF_TYPE_SATA:
printf ("Model: %s Firm: %s Ser#: %s\n",
dev_desc->vendor,
dev_desc->revision,
dev_desc->product);
break;
case IF_TYPE_SD:
case IF_TYPE_MMC:
case IF_TYPE_USB:
printf ("Vendor: %s Rev: %s Prod: %s\n",
dev_desc->vendor,
dev_desc->revision,
dev_desc->product);
break;
case IF_TYPE_DOC:
puts("device type DOC\n");
return;
case IF_TYPE_UNKNOWN:
puts("device type unknown\n");
return;
default:
printf("Unhandled device type: %i\n", dev_desc->if_type);
return;
}
puts (" Type: ");
if (dev_desc->removable)
puts ("Removable ");
switch (dev_desc->type & 0x1F) {
case DEV_TYPE_HARDDISK:
puts ("Hard Disk");
break;
case DEV_TYPE_CDROM:
puts ("CD ROM");
break;
case DEV_TYPE_OPDISK:
puts ("Optical Device");
break;
case DEV_TYPE_TAPE:
puts ("Tape");
break;
default:
printf ("# %02X #", dev_desc->type & 0x1F);
break;
}
puts ("\n");
if ((dev_desc->lba * dev_desc->blksz)>0L) {
ulong mb, mb_quot, mb_rem, gb, gb_quot, gb_rem;
lbaint_t lba;
lba = dev_desc->lba;
lba512 = (lba * (dev_desc->blksz/512));
/* round to 1 digit */
mb = lba512_muldiv(lba512, 10, 2048); /* 2048 = (1024 * 1024) / 512 MB */
mb_quot = mb / 10;
mb_rem = mb - (10 * mb_quot);
gb = mb / 1024;
gb_quot = gb / 10;
gb_rem = gb - (10 * gb_quot);
#ifdef CONFIG_LBA48
if (dev_desc->lba48)
printf (" Supports 48-bit addressing\n");
#endif
#if defined(CONFIG_SYS_64BIT_LBA)
printf (" Capacity: %ld.%ld MB = %ld.%ld GB (%Ld x %ld)\n",
mb_quot, mb_rem,
gb_quot, gb_rem,
lba,
dev_desc->blksz);
#else
printf (" Capacity: %ld.%ld MB = %ld.%ld GB (%ld x %ld)\n",
mb_quot, mb_rem,
gb_quot, gb_rem,
(ulong)lba,
dev_desc->blksz);
#endif
} else {
puts (" Capacity: not available\n");
}
}
#endif
#if (defined(CONFIG_CMD_IDE) || \
defined(CONFIG_CMD_MG_DISK) || \
defined(CONFIG_CMD_SATA) || \
defined(CONFIG_CMD_SCSI) || \
defined(CONFIG_CMD_USB) || \
defined(CONFIG_MMC) || \
defined(CONFIG_SYSTEMACE) )
#if defined(CONFIG_MAC_PARTITION) || \
defined(CONFIG_DOS_PARTITION) || \
defined(CONFIG_ISO_PARTITION) || \
defined(CONFIG_AMIGA_PARTITION) || \
defined(CONFIG_EFI_PARTITION)
void init_part (block_dev_desc_t * dev_desc)
{
#ifdef CONFIG_ISO_PARTITION
if (test_part_iso(dev_desc) == 0) {
dev_desc->part_type = PART_TYPE_ISO;
return;
}
#endif
#ifdef CONFIG_MAC_PARTITION
if (test_part_mac(dev_desc) == 0) {
dev_desc->part_type = PART_TYPE_MAC;
return;
}
#endif
/* must be placed before DOS partition detection */
#ifdef CONFIG_EFI_PARTITION
if (test_part_efi(dev_desc) == 0) {
dev_desc->part_type = PART_TYPE_EFI;
return;
}
#endif
#ifdef CONFIG_DOS_PARTITION
if (test_part_dos(dev_desc) == 0) {
dev_desc->part_type = PART_TYPE_DOS;
return;
}
#endif
#ifdef CONFIG_AMIGA_PARTITION
if (test_part_amiga(dev_desc) == 0) {
dev_desc->part_type = PART_TYPE_AMIGA;
return;
}
#endif
}
int get_partition_info (block_dev_desc_t *dev_desc, int part
, disk_partition_t *info)
{
switch (dev_desc->part_type) {
#ifdef CONFIG_MAC_PARTITION
case PART_TYPE_MAC:
if (get_partition_info_mac(dev_desc,part,info) == 0) {
PRINTF ("## Valid MAC partition found ##\n");
return (0);
}
break;
#endif
#ifdef CONFIG_DOS_PARTITION
case PART_TYPE_DOS:
if (get_partition_info_dos(dev_desc,part,info) == 0) {
PRINTF ("## Valid DOS partition found ##\n");
return (0);
}
break;
#endif
#ifdef CONFIG_ISO_PARTITION
case PART_TYPE_ISO:
if (get_partition_info_iso(dev_desc,part,info) == 0) {
PRINTF ("## Valid ISO boot partition found ##\n");
return (0);
}
break;
#endif
#ifdef CONFIG_AMIGA_PARTITION
case PART_TYPE_AMIGA:
if (get_partition_info_amiga(dev_desc, part, info) == 0)
{
PRINTF ("## Valid Amiga partition found ##\n");
return (0);
}
break;
#endif
#ifdef CONFIG_EFI_PARTITION
case PART_TYPE_EFI:
if (get_partition_info_efi(dev_desc,part,info) == 0) {
PRINTF ("## Valid EFI partition found ##\n");
return (0);
}
break;
#endif
default:
break;
}
return (-1);
}
static void print_part_header (const char *type, block_dev_desc_t * dev_desc)
{
puts ("\nPartition Map for ");
switch (dev_desc->if_type) {
case IF_TYPE_IDE:
puts ("IDE");
break;
case IF_TYPE_SATA:
puts ("SATA");
break;
case IF_TYPE_SCSI:
puts ("SCSI");
break;
case IF_TYPE_ATAPI:
puts ("ATAPI");
break;
case IF_TYPE_USB:
puts ("USB");
break;
case IF_TYPE_DOC:
puts ("DOC");
break;
case IF_TYPE_MMC:
puts ("MMC");
break;
default:
puts ("UNKNOWN");
break;
}
printf (" device %d -- Partition Type: %s\n\n",
dev_desc->dev, type);
}
void print_part (block_dev_desc_t * dev_desc)
{
switch (dev_desc->part_type) {
#ifdef CONFIG_MAC_PARTITION
case PART_TYPE_MAC:
PRINTF ("## Testing for valid MAC partition ##\n");
print_part_header ("MAC", dev_desc);
print_part_mac (dev_desc);
return;
#endif
#ifdef CONFIG_DOS_PARTITION
case PART_TYPE_DOS:
PRINTF ("## Testing for valid DOS partition ##\n");
print_part_header ("DOS", dev_desc);
print_part_dos (dev_desc);
return;
#endif
#ifdef CONFIG_ISO_PARTITION
case PART_TYPE_ISO:
PRINTF ("## Testing for valid ISO Boot partition ##\n");
print_part_header ("ISO", dev_desc);
print_part_iso (dev_desc);
return;
#endif
#ifdef CONFIG_AMIGA_PARTITION
case PART_TYPE_AMIGA:
PRINTF ("## Testing for a valid Amiga partition ##\n");
print_part_header ("AMIGA", dev_desc);
print_part_amiga (dev_desc);
return;
#endif
#ifdef CONFIG_EFI_PARTITION
case PART_TYPE_EFI:
PRINTF ("## Testing for valid EFI partition ##\n");
print_part_header ("EFI", dev_desc);
print_part_efi (dev_desc);
return;
#endif
}
puts ("## Unknown partition table\n");
}
#else /* neither MAC nor DOS nor ISO nor AMIGA nor EFI partition configured */
# error neither CONFIG_MAC_PARTITION nor CONFIG_DOS_PARTITION
# error nor CONFIG_ISO_PARTITION nor CONFIG_AMIGA_PARTITION
# error nor CONFIG_EFI_PARTITION configured!
#endif
#endif
|
1001-study-uboot
|
disk/part.c
|
C
|
gpl3
| 10,104
|
/*
* (C) Copyright 2001
* Erik Theisen, Wave 7 Optics, etheisen@mindspring.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 __ASSEMBLY__
#define __ASSEMBLY__ /* Dirty trick to get only #defines */
#endif
#define __ASM_STUB_PROCESSOR_H__ /* don't include asm/processor. */
#include <config.h>
#undef __ASSEMBLY__
#include <environment.h>
/* Handle HOSTS that have prepended crap on symbol names, not TARGETS. */
#if defined(__APPLE__)
/* Leading underscore on symbols */
# define SYM_CHAR "_"
#else /* No leading character on symbols */
# define SYM_CHAR
#endif
/*
* Generate embedded environment table
* inside U-Boot image, if needed.
*/
#if defined(ENV_IS_EMBEDDED) || defined(CONFIG_BUILD_ENVCRC)
/*
* Only put the environment in it's own section when we are building
* U-Boot proper. The host based program "tools/envcrc" does not need
* a seperate section. Note that ENV_CRC is only defined when building
* U-Boot itself.
*/
#if (defined(CONFIG_SYS_USE_PPCENV) || defined(CONFIG_NAND_U_BOOT)) && \
defined(ENV_CRC) /* Environment embedded in U-Boot .ppcenv section */
/* XXX - This only works with GNU C */
# define __PPCENV__ __attribute__ ((section(".ppcenv")))
# define __PPCTEXT__ __attribute__ ((section(".text")))
#elif defined(USE_HOSTCC) /* Native for 'tools/envcrc' */
# define __PPCENV__ /*XXX DO_NOT_DEL_THIS_COMMENT*/
# define __PPCTEXT__ /*XXX DO_NOT_DEL_THIS_COMMENT*/
#else /* Environment is embedded in U-Boot's .text section */
/* XXX - This only works with GNU C */
# define __PPCENV__ __attribute__ ((section(".text")))
# define __PPCTEXT__ __attribute__ ((section(".text")))
#endif
/*
* Macros to generate global absolutes.
*/
#if defined(__bfin__)
# define GEN_SET_VALUE(name, value) \
asm(".set " GEN_SYMNAME(name) ", " GEN_VALUE(value))
#else
# define GEN_SET_VALUE(name, value) \
asm(GEN_SYMNAME(name) " = " GEN_VALUE(value))
#endif
#define GEN_SYMNAME(str) SYM_CHAR #str
#define GEN_VALUE(str) #str
#define GEN_ABS(name, value) \
asm(".globl " GEN_SYMNAME(name)); \
GEN_SET_VALUE(name, value)
/*
* Macros to transform values
* into environment strings.
*/
#define XMK_STR(x) #x
#define MK_STR(x) XMK_STR(x)
/*
* Check to see if we are building with a
* computed CRC. Otherwise define it as ~0.
*/
#if !defined(ENV_CRC)
# define ENV_CRC (~0)
#endif
env_t environment __PPCENV__ = {
ENV_CRC, /* CRC Sum */
#ifdef CONFIG_SYS_REDUNDAND_ENVIRONMENT
1, /* Flags: valid */
#endif
{
#if defined(CONFIG_BOOTARGS)
"bootargs=" CONFIG_BOOTARGS "\0"
#endif
#if defined(CONFIG_BOOTCOMMAND)
"bootcmd=" CONFIG_BOOTCOMMAND "\0"
#endif
#if defined(CONFIG_RAMBOOTCOMMAND)
"ramboot=" CONFIG_RAMBOOTCOMMAND "\0"
#endif
#if defined(CONFIG_NFSBOOTCOMMAND)
"nfsboot=" CONFIG_NFSBOOTCOMMAND "\0"
#endif
#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
"bootdelay=" MK_STR(CONFIG_BOOTDELAY) "\0"
#endif
#if defined(CONFIG_BAUDRATE) && (CONFIG_BAUDRATE >= 0)
"baudrate=" MK_STR(CONFIG_BAUDRATE) "\0"
#endif
#ifdef CONFIG_LOADS_ECHO
"loads_echo=" MK_STR(CONFIG_LOADS_ECHO) "\0"
#endif
#ifdef CONFIG_ETHADDR
"ethaddr=" MK_STR(CONFIG_ETHADDR) "\0"
#endif
#ifdef CONFIG_ETH1ADDR
"eth1addr=" MK_STR(CONFIG_ETH1ADDR) "\0"
#endif
#ifdef CONFIG_ETH2ADDR
"eth2addr=" MK_STR(CONFIG_ETH2ADDR) "\0"
#endif
#ifdef CONFIG_ETH3ADDR
"eth3addr=" MK_STR(CONFIG_ETH3ADDR) "\0"
#endif
#ifdef CONFIG_ETH4ADDR
"eth4addr=" MK_STR(CONFIG_ETH4ADDR) "\0"
#endif
#ifdef CONFIG_ETH5ADDR
"eth5addr=" MK_STR(CONFIG_ETH5ADDR) "\0"
#endif
#ifdef CONFIG_ETHPRIME
"ethprime=" CONFIG_ETHPRIME "\0"
#endif
#ifdef CONFIG_IPADDR
"ipaddr=" MK_STR(CONFIG_IPADDR) "\0"
#endif
#ifdef CONFIG_SERVERIP
"serverip=" MK_STR(CONFIG_SERVERIP) "\0"
#endif
#ifdef CONFIG_SYS_AUTOLOAD
"autoload=" CONFIG_SYS_AUTOLOAD "\0"
#endif
#ifdef CONFIG_ROOTPATH
"rootpath=" CONFIG_ROOTPATH "\0"
#endif
#ifdef CONFIG_GATEWAYIP
"gatewayip=" MK_STR(CONFIG_GATEWAYIP) "\0"
#endif
#ifdef CONFIG_NETMASK
"netmask=" MK_STR(CONFIG_NETMASK) "\0"
#endif
#ifdef CONFIG_HOSTNAME
"hostname=" MK_STR(CONFIG_HOSTNAME) "\0"
#endif
#ifdef CONFIG_BOOTFILE
"bootfile=" CONFIG_BOOTFILE "\0"
#endif
#ifdef CONFIG_LOADADDR
"loadaddr=" MK_STR(CONFIG_LOADADDR) "\0"
#endif
#ifdef CONFIG_PREBOOT
"preboot=" CONFIG_PREBOOT "\0"
#endif
#ifdef CONFIG_CLOCKS_IN_MHZ
"clocks_in_mhz=" "1" "\0"
#endif
#if defined(CONFIG_PCI_BOOTDELAY) && (CONFIG_PCI_BOOTDELAY > 0)
"pcidelay=" MK_STR(CONFIG_PCI_BOOTDELAY) "\0"
#endif
#ifdef CONFIG_EXTRA_ENV_SETTINGS
CONFIG_EXTRA_ENV_SETTINGS
#endif
"\0" /* Term. env_t.data with 2 NULs */
}
};
#ifdef CONFIG_ENV_ADDR_REDUND
env_t redundand_environment __PPCENV__ = {
0, /* CRC Sum: invalid */
0, /* Flags: invalid */
{
"\0"
}
};
#endif /* CONFIG_ENV_ADDR_REDUND */
/*
* These will end up in the .text section
* if the environment strings are embedded
* in the image. When this is used for
* tools/envcrc, they are placed in the
* .data/.sdata section.
*
*/
unsigned long env_size __PPCTEXT__ = sizeof(env_t);
/*
* Add in absolutes.
*/
GEN_ABS(env_offset, CONFIG_ENV_OFFSET);
#endif /* ENV_IS_EMBEDDED */
|
1001-study-uboot
|
common/env_embedded.c
|
C
|
gpl3
| 5,855
|
/*
* (C) Copyright 2000-2010
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Andreas Heppel <aheppel@sysgo.de>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <environment.h>
#include <linux/stddef.h>
#include <search.h>
#include <errno.h>
#include <malloc.h>
DECLARE_GLOBAL_DATA_PTR;
/************************************************************************
* Default settings to be used when no valid environment is found
*/
#define XMK_STR(x) #x
#define MK_STR(x) XMK_STR(x)
const uchar default_environment[] = {
#ifdef CONFIG_BOOTARGS
"bootargs=" CONFIG_BOOTARGS "\0"
#endif
#ifdef CONFIG_BOOTCOMMAND
"bootcmd=" CONFIG_BOOTCOMMAND "\0"
#endif
#ifdef CONFIG_RAMBOOTCOMMAND
"ramboot=" CONFIG_RAMBOOTCOMMAND "\0"
#endif
#ifdef CONFIG_NFSBOOTCOMMAND
"nfsboot=" CONFIG_NFSBOOTCOMMAND "\0"
#endif
#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
"bootdelay=" MK_STR(CONFIG_BOOTDELAY) "\0"
#endif
#if defined(CONFIG_BAUDRATE) && (CONFIG_BAUDRATE >= 0)
"baudrate=" MK_STR(CONFIG_BAUDRATE) "\0"
#endif
#ifdef CONFIG_LOADS_ECHO
"loads_echo=" MK_STR(CONFIG_LOADS_ECHO) "\0"
#endif
#ifdef CONFIG_ETHADDR
"ethaddr=" MK_STR(CONFIG_ETHADDR) "\0"
#endif
#ifdef CONFIG_ETH1ADDR
"eth1addr=" MK_STR(CONFIG_ETH1ADDR) "\0"
#endif
#ifdef CONFIG_ETH2ADDR
"eth2addr=" MK_STR(CONFIG_ETH2ADDR) "\0"
#endif
#ifdef CONFIG_ETH3ADDR
"eth3addr=" MK_STR(CONFIG_ETH3ADDR) "\0"
#endif
#ifdef CONFIG_ETH4ADDR
"eth4addr=" MK_STR(CONFIG_ETH4ADDR) "\0"
#endif
#ifdef CONFIG_ETH5ADDR
"eth5addr=" MK_STR(CONFIG_ETH5ADDR) "\0"
#endif
#ifdef CONFIG_IPADDR
"ipaddr=" MK_STR(CONFIG_IPADDR) "\0"
#endif
#ifdef CONFIG_SERVERIP
"serverip=" MK_STR(CONFIG_SERVERIP) "\0"
#endif
#ifdef CONFIG_SYS_AUTOLOAD
"autoload=" CONFIG_SYS_AUTOLOAD "\0"
#endif
#ifdef CONFIG_PREBOOT
"preboot=" CONFIG_PREBOOT "\0"
#endif
#ifdef CONFIG_ROOTPATH
"rootpath=" CONFIG_ROOTPATH "\0"
#endif
#ifdef CONFIG_GATEWAYIP
"gatewayip=" MK_STR(CONFIG_GATEWAYIP) "\0"
#endif
#ifdef CONFIG_NETMASK
"netmask=" MK_STR(CONFIG_NETMASK) "\0"
#endif
#ifdef CONFIG_HOSTNAME
"hostname=" MK_STR(CONFIG_HOSTNAME) "\0"
#endif
#ifdef CONFIG_BOOTFILE
"bootfile=" CONFIG_BOOTFILE "\0"
#endif
#ifdef CONFIG_LOADADDR
"loadaddr=" MK_STR(CONFIG_LOADADDR) "\0"
#endif
#ifdef CONFIG_CLOCKS_IN_MHZ
"clocks_in_mhz=1\0"
#endif
#if defined(CONFIG_PCI_BOOTDELAY) && (CONFIG_PCI_BOOTDELAY > 0)
"pcidelay=" MK_STR(CONFIG_PCI_BOOTDELAY) "\0"
#endif
#ifdef CONFIG_EXTRA_ENV_SETTINGS
CONFIG_EXTRA_ENV_SETTINGS
#endif
#ifdef INSTALL_UBOOT_COMMAND
"install-uboot=" INSTALL_UBOOT_COMMAND "\0"
#endif
#ifdef INSTALL_KERNEL_COMMAND
"install-kernel=" INSTALL_KERNEL_COMMAND "\0"
#endif
#ifdef INSTALL_ROOTFS_COMMAND
"install-rootfs=" INSTALL_ROOTFS_COMMAND "\0"
#endif
#ifdef ERASE_PARAM_COMMAND
"erase-param=" ERASE_PARAM_COMMAND "\0"
#endif
#ifdef SET_YAFFSFS_BOOTARGS_COMMAND
"use-yaffs=" SET_YAFFSFS_BOOTARGS_COMMAND "\0"
#endif
#ifdef SET_CRAMFS_BOOTARGS_COMMAND
"use-cramfs=" SET_CRAMFS_BOOTARGS_COMMAND "\0"
#endif
#ifdef SET_RAMFS_P_BOOTARGS_COMMAND
"use-ramfs_p=" SET_RAMFS_P_BOOTARGS_COMMAND "\0"
#endif
#ifdef SET_RAMDISK_BOOTARGS_COMMAND
"use-ramdisk=" SET_RAMDISK_BOOTARGS_COMMAND "\0"
#endif
#ifdef BOOT_FROM_TFTP_COMMAND
"boot-from-tftp=" BOOT_FROM_TFTP_COMMAND "\0"
#endif
#ifdef BOOT_FROM_NAND_COMMAND
"boot-from-nand=" BOOT_FROM_NAND_COMMAND "\0"
#endif
#ifdef BOOT_FROM_RAMDISK_COMMAND
"boot-from-ramdisk=" BOOT_FROM_RAMDISK_COMMAND "\0"
#endif
"\0"
};
struct hsearch_data env_htab;
static uchar env_get_char_init(int index)
{
/* if crc was bad, use the default environment */
if (gd->env_valid)
return env_get_char_spec(index);
else
return default_environment[index];
}
uchar env_get_char_memory(int index)
{
return *env_get_addr(index);
}
uchar env_get_char(int index)
{
/* if relocated to RAM */
if (gd->flags & GD_FLG_RELOC)
return env_get_char_memory(index);
else
return env_get_char_init(index);
}
const uchar *env_get_addr(int index)
{
if (gd->env_valid)
return (uchar *)(gd->env_addr + index);
else
return &default_environment[index];
}
void set_default_env(const char *s)
{
if (sizeof(default_environment) > ENV_SIZE) {
puts("*** Error - default environment is too large\n\n");
return;
}
if (s) {
if (*s == '!') {
printf("*** Warning - %s, "
"using default environment\n\n",
s + 1);
} else {
puts(s);
}
} else {
puts("Using default environment\n\n");
}
if (himport_r(&env_htab, (char *)default_environment,
sizeof(default_environment), '\0', 0) == 0)
error("Environment import failed: errno = %d\n", errno);
gd->flags |= GD_FLG_ENV_READY;
}
/*
* Check if CRC is valid and (if yes) import the environment.
* Note that "buf" may or may not be aligned.
*/
int env_import(const char *buf, int check)
{
env_t *ep = (env_t *)buf;
if (check) {
uint32_t crc;
memcpy(&crc, &ep->crc, sizeof(crc));
if (crc32(0, ep->data, ENV_SIZE) != crc) {
set_default_env("!bad CRC");
return 0;
}
}
if (himport_r(&env_htab, (char *)ep->data, ENV_SIZE, '\0', 0)) {
gd->flags |= GD_FLG_ENV_READY;
return 1;
}
error("Cannot import environment: errno = %d\n", errno);
set_default_env("!import failed");
return 0;
}
void env_relocate(void)
{
#if defined(CONFIG_NEEDS_MANUAL_RELOC)
env_reloc();
#endif
if (gd->env_valid == 0) {
#if defined(CONFIG_ENV_IS_NOWHERE) /* Environment not changable */
set_default_env(NULL);
#else
show_boot_progress(-60);
set_default_env("!bad CRC");
#endif
} else {
env_relocate_spec();
}
}
#ifdef CONFIG_AUTO_COMPLETE
int env_complete(char *var, int maxv, char *cmdv[], int bufsz, char *buf)
{
ENTRY *match;
int found, idx;
idx = 0;
found = 0;
cmdv[0] = NULL;
while ((idx = hmatch_r(var, idx, &match, &env_htab))) {
int vallen = strlen(match->key) + 1;
if (found >= maxv - 2 || bufsz < vallen)
break;
cmdv[found++] = buf;
memcpy(buf, match->key, vallen);
buf += vallen;
bufsz -= vallen;
}
qsort(cmdv, found, sizeof(cmdv[0]), strcmp_compar);
if (idx)
cmdv[found++] = "...";
cmdv[found] = NULL;
return found;
}
#endif
|
1001-study-uboot
|
common/env_common.c
|
C
|
gpl3
| 7,009
|
/*
* (C) Copyright 2000-2010
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Andreas Heppel <aheppel@sysgo.de>
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <environment.h>
#include <linux/stddef.h>
DECLARE_GLOBAL_DATA_PTR;
env_t *env_ptr;
void env_relocate_spec(void)
{
}
uchar env_get_char_spec(int index)
{
return *((uchar *)(gd->env_addr + index));
}
/*
* Initialize Environment use
*
* We are still running from ROM, so data use is limited
*/
int env_init(void)
{
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 0;
return 0;
}
|
1001-study-uboot
|
common/env_nowhere.c
|
C
|
gpl3
| 1,450
|
/*
* (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
*/
/*
* Dos floppy support
*/
#include <common.h>
#include <config.h>
#include <command.h>
#include <fdc.h>
/*-----------------------------------------------------------------------------
* do_fdosboot --
*-----------------------------------------------------------------------------
*/
int do_fdosboot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *name;
char *ep;
int size;
char buf [12];
int drive = CONFIG_SYS_FDC_DRIVE_NUMBER;
/* pre-set load_addr */
if ((ep = getenv("loadaddr")) != NULL) {
load_addr = simple_strtoul(ep, NULL, 16);
}
/* pre-set Boot file name */
if ((name = getenv("bootfile")) == NULL) {
name = "uImage";
}
switch (argc) {
case 1:
break;
case 2:
/* only one arg - accept two forms:
* just load address, or just boot file name.
* The latter form must be written "filename" here.
*/
if (argv[1][0] == '"') { /* just boot filename */
name = argv [1];
} else { /* load address */
load_addr = simple_strtoul(argv[1], NULL, 16);
}
break;
case 3:
load_addr = simple_strtoul(argv[1], NULL, 16);
name = argv [2];
break;
default:
return cmd_usage(cmdtp);
}
/* Init physical layer */
if (!fdc_fdos_init (drive)) {
return (-1);
}
/* Open file */
if (dos_open (name) < 0) {
printf ("Unable to open %s\n", name);
return 1;
}
if ((size = dos_read (load_addr)) < 0) {
printf ("boot error\n");
return 1;
}
flush_cache (load_addr, size);
sprintf(buf, "%x", size);
setenv("filesize", buf);
printf("Floppy DOS load complete: %d bytes loaded to 0x%lx\n",
size, load_addr);
return bootm_maybe_autostart(cmdtp, argv[0]);
}
/*-----------------------------------------------------------------------------
* do_fdosls --
*-----------------------------------------------------------------------------
*/
int do_fdosls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *path = "";
int drive = CONFIG_SYS_FDC_DRIVE_NUMBER;
switch (argc) {
case 1:
break;
case 2:
path = argv [1];
break;
}
/* Init physical layer */
if (!fdc_fdos_init (drive)) {
return (-1);
}
/* Open directory */
if (dos_open (path) < 0) {
printf ("Unable to open %s\n", path);
return 1;
}
return (dos_dir ());
}
U_BOOT_CMD(
fdosboot, 3, 0, do_fdosboot,
"boot from a dos floppy file",
"[loadAddr] [filename]"
);
U_BOOT_CMD(
fdosls, 2, 0, do_fdosls,
"list files in a directory",
"[directory]"
);
|
1001-study-uboot
|
common/cmd_fdos.c
|
C
|
gpl3
| 3,657
|
/*
* (C) Copyright 2007
* Daniel Hellstrom, Gaisler Research, daniel@gaisler.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
*/
/*
* AMBA Plug&Play information list command
*
*/
#include <common.h>
#include <command.h>
#include <ambapp.h>
DECLARE_GLOBAL_DATA_PTR;
/* We put these variables into .data section so that they are zero
* when entering the AMBA Plug & Play routines (in cpu/cpu/ambapp.c)
* the first time. BSS is not garantueed to be zero since BSS
* hasn't been cleared the first times entering the CPU AMBA functions.
*
* The AMBA PnP routines call these functions if ambapp_???_print is set.
*
*/
int ambapp_apb_print __attribute__ ((section(".data"))) = 0;
int ambapp_ahb_print __attribute__ ((section(".data"))) = 0;
typedef struct {
int device_id;
char *name;
} ambapp_device_name;
static ambapp_device_name gaisler_devices[] = {
{GAISLER_LEON3, "GAISLER_LEON3"},
{GAISLER_LEON3DSU, "GAISLER_LEON3DSU"},
{GAISLER_ETHAHB, "GAISLER_ETHAHB"},
{GAISLER_ETHMAC, "GAISLER_ETHMAC"},
{GAISLER_APBMST, "GAISLER_APBMST"},
{GAISLER_AHBUART, "GAISLER_AHBUART"},
{GAISLER_SRCTRL, "GAISLER_SRCTRL"},
{GAISLER_SDCTRL, "GAISLER_SDCTRL"},
{GAISLER_APBUART, "GAISLER_APBUART"},
{GAISLER_IRQMP, "GAISLER_IRQMP"},
{GAISLER_AHBRAM, "GAISLER_AHBRAM"},
{GAISLER_GPTIMER, "GAISLER_GPTIMER"},
{GAISLER_PCITRG, "GAISLER_PCITRG"},
{GAISLER_PCISBRG, "GAISLER_PCISBRG"},
{GAISLER_PCIFBRG, "GAISLER_PCIFBRG"},
{GAISLER_PCITRACE, "GAISLER_PCITRACE"},
{GAISLER_AHBTRACE, "GAISLER_AHBTRACE"},
{GAISLER_ETHDSU, "GAISLER_ETHDSU"},
{GAISLER_PIOPORT, "GAISLER_PIOPORT"},
{GAISLER_AHBJTAG, "GAISLER_AHBJTAG"},
{GAISLER_ATACTRL, "GAISLER_ATACTRL"},
{GAISLER_VGA, "GAISLER_VGA"},
{GAISLER_KBD, "GAISLER_KBD"},
{GAISLER_L2TIME, "GAISLER_L2TIME"},
{GAISLER_L2C, "GAISLER_L2C"},
{GAISLER_PLUGPLAY, "GAISLER_PLUGPLAY"},
{GAISLER_SPW, "GAISLER_SPW"},
{GAISLER_SPW2, "GAISLER_SPW2"},
{GAISLER_EHCI, "GAISLER_EHCI"},
{GAISLER_UHCI, "GAISLER_UHCI"},
{GAISLER_AHBSTAT, "GAISLER_AHBSTAT"},
{GAISLER_DDR2SPA, "GAISLER_DDR2SPA"},
{GAISLER_DDRSPA, "GAISLER_DDRSPA"},
{0, NULL}
};
static ambapp_device_name esa_devices[] = {
{ESA_LEON2, "ESA_LEON2"},
{ESA_MCTRL, "ESA_MCTRL"},
{0, NULL}
};
static ambapp_device_name opencores_devices[] = {
{OPENCORES_PCIBR, "OPENCORES_PCIBR"},
{OPENCORES_ETHMAC, "OPENCORES_ETHMAC"},
{0, NULL}
};
typedef struct {
unsigned int vendor_id;
char *name;
ambapp_device_name *devices;
} ambapp_vendor_devnames;
static ambapp_vendor_devnames vendors[] = {
{VENDOR_GAISLER, "VENDOR_GAISLER", gaisler_devices},
{VENDOR_ESA, "VENDOR_ESA", esa_devices},
{VENDOR_OPENCORES, "VENDOR_OPENCORES", opencores_devices},
{0, NULL, 0}
};
static char *ambapp_get_devname(ambapp_device_name * devs, int id)
{
if (!devs)
return NULL;
while (devs->device_id > 0) {
if (devs->device_id == id)
return devs->name;
devs++;
}
return NULL;
}
char *ambapp_device_id2str(int vendor, int id)
{
ambapp_vendor_devnames *ven = &vendors[0];
while (ven->vendor_id > 0) {
if (ven->vendor_id == vendor) {
return ambapp_get_devname(ven->devices, id);
}
ven++;
}
return NULL;
}
char *ambapp_vendor_id2str(int vendor)
{
ambapp_vendor_devnames *ven = &vendors[0];
while (ven->vendor_id > 0) {
if (ven->vendor_id == vendor) {
return ven->name;
}
ven++;
}
return NULL;
}
static char *unknown = "unknown";
/* Print one APB device */
void ambapp_print_apb(apbctrl_pp_dev * apb, ambapp_ahbdev * apbmst, int index)
{
char *dev_str, *ven_str;
int irq, ver, vendor, deviceid;
unsigned int address, apbmst_base, mask;
vendor = amba_vendor(apb->conf);
deviceid = amba_device(apb->conf);
irq = amba_irq(apb->conf);
ver = amba_ver(apb->conf);
apbmst_base = apbmst->address[0] & LEON3_IO_AREA;
address = (apbmst_base | (((apb->bar & 0xfff00000) >> 12))) &
(((apb->bar & 0x0000fff0) << 4) | 0xfff00000);
mask = amba_membar_mask(apb->bar) << 8;
mask = ((~mask) & 0x000fffff) + 1;
ven_str = ambapp_vendor_id2str(vendor);
if (!ven_str) {
ven_str = unknown;
dev_str = unknown;
} else {
dev_str = ambapp_device_id2str(vendor, deviceid);
if (!dev_str)
dev_str = unknown;
}
printf("0x%02x:0x%02x:0x%02x: %s %s\n"
" apb: 0x%08x - 0x%08x\n"
" irq: %-2d (ver: %-2d)\n",
index, vendor, deviceid, ven_str, dev_str, address,
address + mask, irq, ver);
}
void ambapp_print_ahb(ahbctrl_pp_dev * ahb, int index)
{
char *dev_str, *ven_str;
int irq, ver, vendor, deviceid;
unsigned int addr, mask;
int j;
vendor = amba_vendor(ahb->conf);
deviceid = amba_device(ahb->conf);
irq = amba_irq(ahb->conf);
ver = amba_ver(ahb->conf);
ven_str = ambapp_vendor_id2str(vendor);
if (!ven_str) {
ven_str = unknown;
dev_str = unknown;
} else {
dev_str = ambapp_device_id2str(vendor, deviceid);
if (!dev_str)
dev_str = unknown;
}
printf("0x%02x:0x%02x:0x%02x: %s %s\n",
index, vendor, deviceid, ven_str, dev_str);
for (j = 0; j < 4; j++) {
addr = amba_membar_start(ahb->bars[j]);
if (amba_membar_type(ahb->bars[j]) == 0)
continue;
if (amba_membar_type(ahb->bars[j]) == AMBA_TYPE_AHBIO)
addr = AMBA_TYPE_AHBIO_ADDR(addr);
mask = amba_membar_mask(ahb->bars[j]) << 20;
printf(" mem: 0x%08x - 0x%08x\n", addr, addr + ((~mask) + 1));
}
printf(" irq: %-2d (ver: %d)\n", irq, ver);
}
int do_ambapp_print(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
/* Print AHB Masters */
puts("--------- AHB Masters ---------\n");
ambapp_apb_print = 0;
ambapp_ahb_print = 1;
ambapp_ahbmst_count(99, 99); /* Get vendor&device 99 = nonexistent... */
/* Print AHB Slaves */
puts("--------- AHB Slaves ---------\n");
ambapp_ahbslv_count(99, 99); /* Get vendor&device 99 = nonexistent... */
/* Print APB Slaves */
puts("--------- APB Slaves ---------\n");
ambapp_apb_print = 1;
ambapp_ahb_print = 0;
ambapp_apb_count(99, 99); /* Get vendor&device 99 = nonexistent... */
/* Reset, no futher printing */
ambapp_apb_print = 0;
ambapp_ahb_print = 0;
puts("\n");
return 0;
}
int ambapp_init_reloc(void)
{
ambapp_vendor_devnames *vend = vendors;
ambapp_device_name *dev;
while (vend->vendor_id && vend->name) {
vend->name = (char *)((unsigned int)vend->name + gd->reloc_off);
vend->devices =
(ambapp_device_name *) ((unsigned int)vend->devices +
gd->reloc_off);;
dev = vend->devices;
vend++;
if (!dev)
continue;
while (dev->device_id && dev->name) {
dev->name =
(char *)((unsigned int)dev->name + gd->reloc_off);;
dev++;
}
}
return 0;
}
U_BOOT_CMD(
ambapp, 1, 1, do_ambapp_print,
"list AMBA Plug&Play information",
"ambapp\n"
" - lists AMBA (AHB & APB) Plug&Play devices present on the system"
);
|
1001-study-uboot
|
common/cmd_ambapp.c
|
C
|
gpl3
| 7,477
|
/*
* (C) Copyright 2000
* Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <stdarg.h>
#include <malloc.h>
#include <stdio_dev.h>
#include <exports.h>
DECLARE_GLOBAL_DATA_PTR;
#ifdef CONFIG_SYS_CONSOLE_IS_IN_ENV
/*
* if overwrite_console returns 1, the stdin, stderr and stdout
* are switched to the serial port, else the settings in the
* environment are used
*/
#ifdef CONFIG_SYS_CONSOLE_OVERWRITE_ROUTINE
extern int overwrite_console(void);
#define OVERWRITE_CONSOLE overwrite_console()
#else
#define OVERWRITE_CONSOLE 0
#endif /* CONFIG_SYS_CONSOLE_OVERWRITE_ROUTINE */
#endif /* CONFIG_SYS_CONSOLE_IS_IN_ENV */
static int console_setfile(int file, struct stdio_dev * dev)
{
int error = 0;
if (dev == NULL)
return -1;
switch (file) {
case stdin:
case stdout:
case stderr:
/* Start new device */
if (dev->start) {
error = dev->start();
/* If it's not started dont use it */
if (error < 0)
break;
}
/* Assign the new device (leaving the existing one started) */
stdio_devices[file] = dev;
/*
* Update monitor functions
* (to use the console stuff by other applications)
*/
switch (file) {
case stdin:
gd->jt[XF_getc] = dev->getc;
gd->jt[XF_tstc] = dev->tstc;
break;
case stdout:
gd->jt[XF_putc] = dev->putc;
gd->jt[XF_puts] = dev->puts;
gd->jt[XF_printf] = printf;
break;
}
break;
default: /* Invalid file ID */
error = -1;
}
return error;
}
#if defined(CONFIG_CONSOLE_MUX)
/** Console I/O multiplexing *******************************************/
static struct stdio_dev *tstcdev;
struct stdio_dev **console_devices[MAX_FILES];
int cd_count[MAX_FILES];
/*
* This depends on tstc() always being called before getc().
* This is guaranteed to be true because this routine is called
* only from fgetc() which assures it.
* No attempt is made to demultiplex multiple input sources.
*/
static int console_getc(int file)
{
unsigned char ret;
/* This is never called with testcdev == NULL */
ret = tstcdev->getc();
tstcdev = NULL;
return ret;
}
static int console_tstc(int file)
{
int i, ret;
struct stdio_dev *dev;
disable_ctrlc(1);
for (i = 0; i < cd_count[file]; i++) {
dev = console_devices[file][i];
if (dev->tstc != NULL) {
ret = dev->tstc();
if (ret > 0) {
tstcdev = dev;
disable_ctrlc(0);
return ret;
}
}
}
disable_ctrlc(0);
return 0;
}
static void console_putc(int file, const char c)
{
int i;
struct stdio_dev *dev;
for (i = 0; i < cd_count[file]; i++) {
dev = console_devices[file][i];
if (dev->putc != NULL)
dev->putc(c);
}
}
static void console_puts(int file, const char *s)
{
int i;
struct stdio_dev *dev;
for (i = 0; i < cd_count[file]; i++) {
dev = console_devices[file][i];
if (dev->puts != NULL)
dev->puts(s);
}
}
static inline void console_printdevs(int file)
{
iomux_printdevs(file);
}
static inline void console_doenv(int file, struct stdio_dev *dev)
{
iomux_doenv(file, dev->name);
}
#else
static inline int console_getc(int file)
{
return stdio_devices[file]->getc();
}
static inline int console_tstc(int file)
{
return stdio_devices[file]->tstc();
}
static inline void console_putc(int file, const char c)
{
stdio_devices[file]->putc(c);
}
static inline void console_puts(int file, const char *s)
{
stdio_devices[file]->puts(s);
}
static inline void console_printdevs(int file)
{
printf("%s\n", stdio_devices[file]->name);
}
static inline void console_doenv(int file, struct stdio_dev *dev)
{
console_setfile(file, dev);
}
#endif /* defined(CONFIG_CONSOLE_MUX) */
/** U-Boot INITIAL CONSOLE-NOT COMPATIBLE FUNCTIONS *************************/
int serial_printf(const char *fmt, ...)
{
va_list args;
uint i;
char printbuffer[CONFIG_SYS_PBSIZE];
va_start(args, fmt);
/* For this to work, printbuffer must be larger than
* anything we ever want to print.
*/
i = vsprintf(printbuffer, fmt, args);
va_end(args);
serial_puts(printbuffer);
return i;
}
int fgetc(int file)
{
if (file < MAX_FILES) {
#if defined(CONFIG_CONSOLE_MUX)
/*
* Effectively poll for input wherever it may be available.
*/
for (;;) {
/*
* Upper layer may have already called tstc() so
* check for that first.
*/
if (tstcdev != NULL)
return console_getc(file);
console_tstc(file);
#ifdef CONFIG_WATCHDOG
/*
* If the watchdog must be rate-limited then it should
* already be handled in board-specific code.
*/
udelay(1);
#endif
}
#else
return console_getc(file);
#endif
}
return -1;
}
int ftstc(int file)
{
if (file < MAX_FILES)
return console_tstc(file);
return -1;
}
void fputc(int file, const char c)
{
if (file < MAX_FILES)
console_putc(file, c);
}
void fputs(int file, const char *s)
{
if (file < MAX_FILES)
console_puts(file, s);
}
int fprintf(int file, const char *fmt, ...)
{
va_list args;
uint i;
char printbuffer[CONFIG_SYS_PBSIZE];
va_start(args, fmt);
/* For this to work, printbuffer must be larger than
* anything we ever want to print.
*/
i = vsprintf(printbuffer, fmt, args);
va_end(args);
/* Send to desired file */
fputs(file, printbuffer);
return i;
}
/** U-Boot INITIAL CONSOLE-COMPATIBLE FUNCTION *****************************/
int getc(void)
{
#ifdef CONFIG_DISABLE_CONSOLE
if (gd->flags & GD_FLG_DISABLE_CONSOLE)
return 0;
#endif
if (!gd->have_console)
return 0;
if (gd->flags & GD_FLG_DEVINIT) {
/* Get from the standard input */
return fgetc(stdin);
}
/* Send directly to the handler */
return serial_getc();
}
int tstc(void)
{
#ifdef CONFIG_DISABLE_CONSOLE
if (gd->flags & GD_FLG_DISABLE_CONSOLE)
return 0;
#endif
if (!gd->have_console)
return 0;
if (gd->flags & GD_FLG_DEVINIT) {
/* Test the standard input */
return ftstc(stdin);
}
/* Send directly to the handler */
return serial_tstc();
}
#if defined(CONFIG_PRE_CONSOLE_BUFFER) || defined(CONFIG_PRE_CONSOLE_PUTC)
#define CIRC_BUF_IDX(idx) ((idx) % (unsigned long)CONFIG_PRE_CON_BUF_SZ)
static void pre_console_putc(const char c)
{
#ifdef CONFIG_PRE_CONSOLE_BUFFER
char *buffer = (char *)CONFIG_PRE_CON_BUF_ADDR;
buffer[CIRC_BUF_IDX(gd->precon_buf_idx++)] = c;
#endif
#ifdef CONFIG_PRE_CONSOLE_PUTC
board_pre_console_putc(c);
#endif
}
static void pre_console_puts(const char *s)
{
while (*s)
pre_console_putc(*s++);
}
static void print_pre_console_buffer(void)
{
#ifdef CONFIG_PRE_CONSOLE_BUFFER
unsigned long i = 0;
char *buffer = (char *)CONFIG_PRE_CON_BUF_ADDR;
if (gd->precon_buf_idx > CONFIG_PRE_CON_BUF_SZ)
i = gd->precon_buf_idx - CONFIG_PRE_CON_BUF_SZ;
while (i < gd->precon_buf_idx)
putc(buffer[CIRC_BUF_IDX(i++)]);
#endif
}
#else
static inline void pre_console_putc(const char c) {}
static inline void pre_console_puts(const char *s) {}
static inline void print_pre_console_buffer(void) {}
#endif
void putc(const char c)
{
#ifdef CONFIG_SILENT_CONSOLE
if (gd->flags & GD_FLG_SILENT)
return;
#endif
#ifdef CONFIG_DISABLE_CONSOLE
if (gd->flags & GD_FLG_DISABLE_CONSOLE)
return;
#endif
if (!gd->have_console)
return pre_console_putc(c);
if (gd->flags & GD_FLG_DEVINIT) {
/* Send to the standard output */
fputc(stdout, c);
} else {
/* Send directly to the handler */
serial_putc(c);
}
}
void puts(const char *s)
{
#ifdef CONFIG_SILENT_CONSOLE
if (gd->flags & GD_FLG_SILENT)
return;
#endif
#ifdef CONFIG_DISABLE_CONSOLE
if (gd->flags & GD_FLG_DISABLE_CONSOLE)
return;
#endif
if (!gd->have_console)
return pre_console_puts(s);
if (gd->flags & GD_FLG_DEVINIT) {
/* Send to the standard output */
fputs(stdout, s);
} else {
/* Send directly to the handler */
serial_puts(s);
}
}
int printf(const char *fmt, ...)
{
va_list args;
uint i;
char printbuffer[CONFIG_SYS_PBSIZE];
#ifndef CONFIG_PRE_CONSOLE_BUFFER
if (!gd->have_console)
return 0;
#endif
va_start(args, fmt);
/* For this to work, printbuffer must be larger than
* anything we ever want to print.
*/
i = vsprintf(printbuffer, fmt, args);
va_end(args);
/* Print the string */
puts(printbuffer);
return i;
}
int vprintf(const char *fmt, va_list args)
{
uint i;
char printbuffer[CONFIG_SYS_PBSIZE];
#ifndef CONFIG_PRE_CONSOLE_BUFFER
if (!gd->have_console)
return 0;
#endif
/* For this to work, printbuffer must be larger than
* anything we ever want to print.
*/
i = vsprintf(printbuffer, fmt, args);
/* Print the string */
puts(printbuffer);
return i;
}
/* test if ctrl-c was pressed */
static int ctrlc_disabled = 0; /* see disable_ctrl() */
static int ctrlc_was_pressed = 0;
int ctrlc(void)
{
if (!ctrlc_disabled && gd->have_console) {
if (tstc()) {
switch (getc()) {
case 0x03: /* ^C - Control C */
ctrlc_was_pressed = 1;
return 1;
default:
break;
}
}
}
return 0;
}
/* pass 1 to disable ctrlc() checking, 0 to enable.
* returns previous state
*/
int disable_ctrlc(int disable)
{
int prev = ctrlc_disabled; /* save previous state */
ctrlc_disabled = disable;
return prev;
}
int had_ctrlc (void)
{
return ctrlc_was_pressed;
}
void clear_ctrlc(void)
{
ctrlc_was_pressed = 0;
}
#ifdef CONFIG_MODEM_SUPPORT_DEBUG
char screen[1024];
char *cursor = screen;
int once = 0;
inline void dbg(const char *fmt, ...)
{
va_list args;
uint i;
char printbuffer[CONFIG_SYS_PBSIZE];
if (!once) {
memset(screen, 0, sizeof(screen));
once++;
}
va_start(args, fmt);
/* For this to work, printbuffer must be larger than
* anything we ever want to print.
*/
i = vsprintf(printbuffer, fmt, args);
va_end(args);
if ((screen + sizeof(screen) - 1 - cursor)
< strlen(printbuffer) + 1) {
memset(screen, 0, sizeof(screen));
cursor = screen;
}
sprintf(cursor, printbuffer);
cursor += strlen(printbuffer);
}
#else
inline void dbg(const char *fmt, ...)
{
}
#endif
/** U-Boot INIT FUNCTIONS *************************************************/
struct stdio_dev *search_device(int flags, const char *name)
{
struct stdio_dev *dev;
dev = stdio_get_by_name(name);
if (dev && (dev->flags & flags))
return dev;
return NULL;
}
int console_assign(int file, const char *devname)
{
int flag;
struct stdio_dev *dev;
/* Check for valid file */
switch (file) {
case stdin:
flag = DEV_FLAGS_INPUT;
break;
case stdout:
case stderr:
flag = DEV_FLAGS_OUTPUT;
break;
default:
return -1;
}
/* Check for valid device name */
dev = search_device(flag, devname);
if (dev)
return console_setfile(file, dev);
return -1;
}
/* Called before relocation - use serial functions */
int console_init_f(void)
{
gd->have_console = 1;
#ifdef CONFIG_SILENT_CONSOLE
if (getenv("silent") != NULL)
gd->flags |= GD_FLG_SILENT;
#endif
print_pre_console_buffer();
return 0;
}
void stdio_print_current_devices(void)
{
#ifndef CONFIG_SYS_CONSOLE_INFO_QUIET
/* Print information */
puts("In: ");
if (stdio_devices[stdin] == NULL) {
puts("No input devices available!\n");
} else {
printf ("%s\n", stdio_devices[stdin]->name);
}
puts("Out: ");
if (stdio_devices[stdout] == NULL) {
puts("No output devices available!\n");
} else {
printf ("%s\n", stdio_devices[stdout]->name);
}
puts("Err: ");
if (stdio_devices[stderr] == NULL) {
puts("No error devices available!\n");
} else {
printf ("%s\n", stdio_devices[stderr]->name);
}
#endif /* CONFIG_SYS_CONSOLE_INFO_QUIET */
}
#ifdef CONFIG_SYS_CONSOLE_IS_IN_ENV
/* Called after the relocation - use desired console functions */
int console_init_r(void)
{
char *stdinname, *stdoutname, *stderrname;
struct stdio_dev *inputdev = NULL, *outputdev = NULL, *errdev = NULL;
#ifdef CONFIG_SYS_CONSOLE_ENV_OVERWRITE
int i;
#endif /* CONFIG_SYS_CONSOLE_ENV_OVERWRITE */
#ifdef CONFIG_CONSOLE_MUX
int iomux_err = 0;
#endif
/* set default handlers at first */
gd->jt[XF_getc] = serial_getc;
gd->jt[XF_tstc] = serial_tstc;
gd->jt[XF_putc] = serial_putc;
gd->jt[XF_puts] = serial_puts;
gd->jt[XF_printf] = serial_printf;
/* stdin stdout and stderr are in environment */
/* scan for it */
stdinname = getenv("stdin");
stdoutname = getenv("stdout");
stderrname = getenv("stderr");
if (OVERWRITE_CONSOLE == 0) { /* if not overwritten by config switch */
inputdev = search_device(DEV_FLAGS_INPUT, stdinname);
outputdev = search_device(DEV_FLAGS_OUTPUT, stdoutname);
errdev = search_device(DEV_FLAGS_OUTPUT, stderrname);
#ifdef CONFIG_CONSOLE_MUX
iomux_err = iomux_doenv(stdin, stdinname);
iomux_err += iomux_doenv(stdout, stdoutname);
iomux_err += iomux_doenv(stderr, stderrname);
if (!iomux_err)
/* Successful, so skip all the code below. */
goto done;
#endif
}
/* if the devices are overwritten or not found, use default device */
if (inputdev == NULL) {
inputdev = search_device(DEV_FLAGS_INPUT, "serial");
}
if (outputdev == NULL) {
outputdev = search_device(DEV_FLAGS_OUTPUT, "serial");
}
if (errdev == NULL) {
errdev = search_device(DEV_FLAGS_OUTPUT, "serial");
}
/* Initializes output console first */
if (outputdev != NULL) {
/* need to set a console if not done above. */
console_doenv(stdout, outputdev);
}
if (errdev != NULL) {
/* need to set a console if not done above. */
console_doenv(stderr, errdev);
}
if (inputdev != NULL) {
/* need to set a console if not done above. */
console_doenv(stdin, inputdev);
}
#ifdef CONFIG_CONSOLE_MUX
done:
#endif
gd->flags |= GD_FLG_DEVINIT; /* device initialization completed */
stdio_print_current_devices();
#ifdef CONFIG_SYS_CONSOLE_ENV_OVERWRITE
/* set the environment variables (will overwrite previous env settings) */
for (i = 0; i < 3; i++) {
setenv(stdio_names[i], stdio_devices[i]->name);
}
#endif /* CONFIG_SYS_CONSOLE_ENV_OVERWRITE */
#if 0
/* If nothing usable installed, use only the initial console */
if ((stdio_devices[stdin] == NULL) && (stdio_devices[stdout] == NULL))
return 0;
#endif
return 0;
}
#else /* CONFIG_SYS_CONSOLE_IS_IN_ENV */
/* Called after the relocation - use desired console functions */
int console_init_r(void)
{
struct stdio_dev *inputdev = NULL, *outputdev = NULL;
int i;
struct list_head *list = stdio_get_list();
struct list_head *pos;
struct stdio_dev *dev;
#ifdef CONFIG_SPLASH_SCREEN
/*
* suppress all output if splash screen is enabled and we have
* a bmp to display. We redirect the output from frame buffer
* console to serial console in this case or suppress it if
* "silent" mode was requested.
*/
if (getenv("splashimage") != NULL) {
if (!(gd->flags & GD_FLG_SILENT))
outputdev = search_device (DEV_FLAGS_OUTPUT, "serial");
}
#endif
/* Scan devices looking for input and output devices */
list_for_each(pos, list) {
dev = list_entry(pos, struct stdio_dev, list);
if ((dev->flags & DEV_FLAGS_INPUT) && (inputdev == NULL)) {
inputdev = dev;
}
if ((dev->flags & DEV_FLAGS_OUTPUT) && (outputdev == NULL)) {
outputdev = dev;
}
if(inputdev && outputdev)
break;
}
/* Initializes output console first */
if (outputdev != NULL) {
console_setfile(stdout, outputdev);
console_setfile(stderr, outputdev);
#ifdef CONFIG_CONSOLE_MUX
console_devices[stdout][0] = outputdev;
console_devices[stderr][0] = outputdev;
#endif
}
/* Initializes input console */
if (inputdev != NULL) {
console_setfile(stdin, inputdev);
#ifdef CONFIG_CONSOLE_MUX
console_devices[stdin][0] = inputdev;
#endif
}
gd->flags |= GD_FLG_DEVINIT; /* device initialization completed */
stdio_print_current_devices();
/* Setting environment variables */
for (i = 0; i < 3; i++) {
setenv(stdio_names[i], stdio_devices[i]->name);
}
#if 0
/* If nothing usable installed, use only the initial console */
if ((stdio_devices[stdin] == NULL) && (stdio_devices[stdout] == NULL))
return 0;
#endif
return 0;
}
#endif /* CONFIG_SYS_CONSOLE_IS_IN_ENV */
|
1001-study-uboot
|
common/console.c
|
C
|
gpl3
| 16,613
|
#include <common.h>
#if 0 /* Moved to malloc.h */
/* ---------- To make a malloc.h, start cutting here ------------ */
/*
A version of malloc/free/realloc written by Doug Lea and released to the
public domain. Send questions/comments/complaints/performance data
to dl@cs.oswego.edu
* VERSION 2.6.6 Sun Mar 5 19:10:03 2000 Doug Lea (dl at gee)
Note: There may be an updated version of this malloc obtainable at
ftp://g.oswego.edu/pub/misc/malloc.c
Check before installing!
* Why use this malloc?
This is not the fastest, most space-conserving, most portable, or
most tunable malloc ever written. However it is among the fastest
while also being among the most space-conserving, portable and tunable.
Consistent balance across these factors results in a good general-purpose
allocator. For a high-level description, see
http://g.oswego.edu/dl/html/malloc.html
* Synopsis of public routines
(Much fuller descriptions are contained in the program documentation below.)
malloc(size_t n);
Return a pointer to a newly allocated chunk of at least n bytes, or null
if no space is available.
free(Void_t* p);
Release the chunk of memory pointed to by p, or no effect if p is null.
realloc(Void_t* p, size_t n);
Return a pointer to a chunk of size n that contains the same data
as does chunk p up to the minimum of (n, p's size) bytes, or null
if no space is available. The returned pointer may or may not be
the same as p. If p is null, equivalent to malloc. Unless the
#define REALLOC_ZERO_BYTES_FREES below is set, realloc with a
size argument of zero (re)allocates a minimum-sized chunk.
memalign(size_t alignment, size_t n);
Return a pointer to a newly allocated chunk of n bytes, aligned
in accord with the alignment argument, which must be a power of
two.
valloc(size_t n);
Equivalent to memalign(pagesize, n), where pagesize is the page
size of the system (or as near to this as can be figured out from
all the includes/defines below.)
pvalloc(size_t n);
Equivalent to valloc(minimum-page-that-holds(n)), that is,
round up n to nearest pagesize.
calloc(size_t unit, size_t quantity);
Returns a pointer to quantity * unit bytes, with all locations
set to zero.
cfree(Void_t* p);
Equivalent to free(p).
malloc_trim(size_t pad);
Release all but pad bytes of freed top-most memory back
to the system. Return 1 if successful, else 0.
malloc_usable_size(Void_t* p);
Report the number usable allocated bytes associated with allocated
chunk p. This may or may not report more bytes than were requested,
due to alignment and minimum size constraints.
malloc_stats();
Prints brief summary statistics.
mallinfo()
Returns (by copy) a struct containing various summary statistics.
mallopt(int parameter_number, int parameter_value)
Changes one of the tunable parameters described below. Returns
1 if successful in changing the parameter, else 0.
* Vital statistics:
Alignment: 8-byte
8 byte alignment is currently hardwired into the design. This
seems to suffice for all current machines and C compilers.
Assumed pointer representation: 4 or 8 bytes
Code for 8-byte pointers is untested by me but has worked
reliably by Wolfram Gloger, who contributed most of the
changes supporting this.
Assumed size_t representation: 4 or 8 bytes
Note that size_t is allowed to be 4 bytes even if pointers are 8.
Minimum overhead per allocated chunk: 4 or 8 bytes
Each malloced chunk has a hidden overhead of 4 bytes holding size
and status information.
Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
needed; 4 (8) for a trailing size field
and 8 (16) bytes for free list pointers. Thus, the minimum
allocatable size is 16/24/32 bytes.
Even a request for zero bytes (i.e., malloc(0)) returns a
pointer to something of the minimum allocatable size.
Maximum allocated size: 4-byte size_t: 2^31 - 8 bytes
8-byte size_t: 2^63 - 16 bytes
It is assumed that (possibly signed) size_t bit values suffice to
represent chunk sizes. `Possibly signed' is due to the fact
that `size_t' may be defined on a system as either a signed or
an unsigned type. To be conservative, values that would appear
as negative numbers are avoided.
Requests for sizes with a negative sign bit when the request
size is treaded as a long will return null.
Maximum overhead wastage per allocated chunk: normally 15 bytes
Alignnment demands, plus the minimum allocatable size restriction
make the normal worst-case wastage 15 bytes (i.e., up to 15
more bytes will be allocated than were requested in malloc), with
two exceptions:
1. Because requests for zero bytes allocate non-zero space,
the worst case wastage for a request of zero bytes is 24 bytes.
2. For requests >= mmap_threshold that are serviced via
mmap(), the worst case wastage is 8 bytes plus the remainder
from a system page (the minimal mmap unit); typically 4096 bytes.
* Limitations
Here are some features that are NOT currently supported
* No user-definable hooks for callbacks and the like.
* No automated mechanism for fully checking that all accesses
to malloced memory stay within their bounds.
* No support for compaction.
* Synopsis of compile-time options:
People have reported using previous versions of this malloc on all
versions of Unix, sometimes by tweaking some of the defines
below. It has been tested most extensively on Solaris and
Linux. It is also reported to work on WIN32 platforms.
People have also reported adapting this malloc for use in
stand-alone embedded systems.
The implementation is in straight, hand-tuned ANSI C. Among other
consequences, it uses a lot of macros. Because of this, to be at
all usable, this code should be compiled using an optimizing compiler
(for example gcc -O2) that can simplify expressions and control
paths.
__STD_C (default: derived from C compiler defines)
Nonzero if using ANSI-standard C compiler, a C++ compiler, or
a C compiler sufficiently close to ANSI to get away with it.
DEBUG (default: NOT defined)
Define to enable debugging. Adds fairly extensive assertion-based
checking to help track down memory errors, but noticeably slows down
execution.
REALLOC_ZERO_BYTES_FREES (default: NOT defined)
Define this if you think that realloc(p, 0) should be equivalent
to free(p). Otherwise, since malloc returns a unique pointer for
malloc(0), so does realloc(p, 0).
HAVE_MEMCPY (default: defined)
Define if you are not otherwise using ANSI STD C, but still
have memcpy and memset in your C library and want to use them.
Otherwise, simple internal versions are supplied.
USE_MEMCPY (default: 1 if HAVE_MEMCPY is defined, 0 otherwise)
Define as 1 if you want the C library versions of memset and
memcpy called in realloc and calloc (otherwise macro versions are used).
At least on some platforms, the simple macro versions usually
outperform libc versions.
HAVE_MMAP (default: defined as 1)
Define to non-zero to optionally make malloc() use mmap() to
allocate very large blocks.
HAVE_MREMAP (default: defined as 0 unless Linux libc set)
Define to non-zero to optionally make realloc() use mremap() to
reallocate very large blocks.
malloc_getpagesize (default: derived from system #includes)
Either a constant or routine call returning the system page size.
HAVE_USR_INCLUDE_MALLOC_H (default: NOT defined)
Optionally define if you are on a system with a /usr/include/malloc.h
that declares struct mallinfo. It is not at all necessary to
define this even if you do, but will ensure consistency.
INTERNAL_SIZE_T (default: size_t)
Define to a 32-bit type (probably `unsigned int') if you are on a
64-bit machine, yet do not want or need to allow malloc requests of
greater than 2^31 to be handled. This saves space, especially for
very small chunks.
INTERNAL_LINUX_C_LIB (default: NOT defined)
Defined only when compiled as part of Linux libc.
Also note that there is some odd internal name-mangling via defines
(for example, internally, `malloc' is named `mALLOc') needed
when compiling in this case. These look funny but don't otherwise
affect anything.
WIN32 (default: undefined)
Define this on MS win (95, nt) platforms to compile in sbrk emulation.
LACKS_UNISTD_H (default: undefined if not WIN32)
Define this if your system does not have a <unistd.h>.
LACKS_SYS_PARAM_H (default: undefined if not WIN32)
Define this if your system does not have a <sys/param.h>.
MORECORE (default: sbrk)
The name of the routine to call to obtain more memory from the system.
MORECORE_FAILURE (default: -1)
The value returned upon failure of MORECORE.
MORECORE_CLEARS (default 1)
True (1) if the routine mapped to MORECORE zeroes out memory (which
holds for sbrk).
DEFAULT_TRIM_THRESHOLD
DEFAULT_TOP_PAD
DEFAULT_MMAP_THRESHOLD
DEFAULT_MMAP_MAX
Default values of tunable parameters (described in detail below)
controlling interaction with host system routines (sbrk, mmap, etc).
These values may also be changed dynamically via mallopt(). The
preset defaults are those that give best performance for typical
programs/systems.
USE_DL_PREFIX (default: undefined)
Prefix all public routines with the string 'dl'. Useful to
quickly avoid procedure declaration conflicts and linker symbol
conflicts with existing memory allocation routines.
*/
/* Preliminaries */
#ifndef __STD_C
#ifdef __STDC__
#define __STD_C 1
#else
#if __cplusplus
#define __STD_C 1
#else
#define __STD_C 0
#endif /*__cplusplus*/
#endif /*__STDC__*/
#endif /*__STD_C*/
#ifndef Void_t
#if (__STD_C || defined(WIN32))
#define Void_t void
#else
#define Void_t char
#endif
#endif /*Void_t*/
#if __STD_C
#include <stddef.h> /* for size_t */
#else
#include <sys/types.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h> /* needed for malloc_stats */
/*
Compile-time options
*/
/*
Debugging:
Because freed chunks may be overwritten with link fields, this
malloc will often die when freed memory is overwritten by user
programs. This can be very effective (albeit in an annoying way)
in helping track down dangling pointers.
If you compile with -DDEBUG, a number of assertion checks are
enabled that will catch more memory errors. You probably won't be
able to make much sense of the actual assertion errors, but they
should help you locate incorrectly overwritten memory. The
checking is fairly extensive, and will slow down execution
noticeably. Calling malloc_stats or mallinfo with DEBUG set will
attempt to check every non-mmapped allocated and free chunk in the
course of computing the summmaries. (By nature, mmapped regions
cannot be checked very much automatically.)
Setting DEBUG may also be helpful if you are trying to modify
this code. The assertions in the check routines spell out in more
detail the assumptions and invariants underlying the algorithms.
*/
/*
INTERNAL_SIZE_T is the word-size used for internal bookkeeping
of chunk sizes. On a 64-bit machine, you can reduce malloc
overhead by defining INTERNAL_SIZE_T to be a 32 bit `unsigned int'
at the expense of not being able to handle requests greater than
2^31. This limitation is hardly ever a concern; you are encouraged
to set this. However, the default version is the same as size_t.
*/
#ifndef INTERNAL_SIZE_T
#define INTERNAL_SIZE_T size_t
#endif
/*
REALLOC_ZERO_BYTES_FREES should be set if a call to
realloc with zero bytes should be the same as a call to free.
Some people think it should. Otherwise, since this malloc
returns a unique pointer for malloc(0), so does realloc(p, 0).
*/
/* #define REALLOC_ZERO_BYTES_FREES */
/*
WIN32 causes an emulation of sbrk to be compiled in
mmap-based options are not currently supported in WIN32.
*/
/* #define WIN32 */
#ifdef WIN32
#define MORECORE wsbrk
#define HAVE_MMAP 0
#define LACKS_UNISTD_H
#define LACKS_SYS_PARAM_H
/*
Include 'windows.h' to get the necessary declarations for the
Microsoft Visual C++ data structures and routines used in the 'sbrk'
emulation.
Define WIN32_LEAN_AND_MEAN so that only the essential Microsoft
Visual C++ header files are included.
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
/*
HAVE_MEMCPY should be defined if you are not otherwise using
ANSI STD C, but still have memcpy and memset in your C library
and want to use them in calloc and realloc. Otherwise simple
macro versions are defined here.
USE_MEMCPY should be defined as 1 if you actually want to
have memset and memcpy called. People report that the macro
versions are often enough faster than libc versions on many
systems that it is better to use them.
*/
#define HAVE_MEMCPY
#ifndef USE_MEMCPY
#ifdef HAVE_MEMCPY
#define USE_MEMCPY 1
#else
#define USE_MEMCPY 0
#endif
#endif
#if (__STD_C || defined(HAVE_MEMCPY))
#if __STD_C
void* memset(void*, int, size_t);
void* memcpy(void*, const void*, size_t);
#else
#ifdef WIN32
/* On Win32 platforms, 'memset()' and 'memcpy()' are already declared in */
/* 'windows.h' */
#else
Void_t* memset();
Void_t* memcpy();
#endif
#endif
#endif
#if USE_MEMCPY
/* The following macros are only invoked with (2n+1)-multiples of
INTERNAL_SIZE_T units, with a positive integer n. This is exploited
for fast inline execution when n is small. */
#define MALLOC_ZERO(charp, nbytes) \
do { \
INTERNAL_SIZE_T mzsz = (nbytes); \
if(mzsz <= 9*sizeof(mzsz)) { \
INTERNAL_SIZE_T* mz = (INTERNAL_SIZE_T*) (charp); \
if(mzsz >= 5*sizeof(mzsz)) { *mz++ = 0; \
*mz++ = 0; \
if(mzsz >= 7*sizeof(mzsz)) { *mz++ = 0; \
*mz++ = 0; \
if(mzsz >= 9*sizeof(mzsz)) { *mz++ = 0; \
*mz++ = 0; }}} \
*mz++ = 0; \
*mz++ = 0; \
*mz = 0; \
} else memset((charp), 0, mzsz); \
} while(0)
#define MALLOC_COPY(dest,src,nbytes) \
do { \
INTERNAL_SIZE_T mcsz = (nbytes); \
if(mcsz <= 9*sizeof(mcsz)) { \
INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) (src); \
INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) (dest); \
if(mcsz >= 5*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
*mcdst++ = *mcsrc++; \
if(mcsz >= 7*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
*mcdst++ = *mcsrc++; \
if(mcsz >= 9*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
*mcdst++ = *mcsrc++; }}} \
*mcdst++ = *mcsrc++; \
*mcdst++ = *mcsrc++; \
*mcdst = *mcsrc ; \
} else memcpy(dest, src, mcsz); \
} while(0)
#else /* !USE_MEMCPY */
/* Use Duff's device for good zeroing/copying performance. */
#define MALLOC_ZERO(charp, nbytes) \
do { \
INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \
long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
switch (mctmp) { \
case 0: for(;;) { *mzp++ = 0; \
case 7: *mzp++ = 0; \
case 6: *mzp++ = 0; \
case 5: *mzp++ = 0; \
case 4: *mzp++ = 0; \
case 3: *mzp++ = 0; \
case 2: *mzp++ = 0; \
case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \
} \
} while(0)
#define MALLOC_COPY(dest,src,nbytes) \
do { \
INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \
INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \
long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
switch (mctmp) { \
case 0: for(;;) { *mcdst++ = *mcsrc++; \
case 7: *mcdst++ = *mcsrc++; \
case 6: *mcdst++ = *mcsrc++; \
case 5: *mcdst++ = *mcsrc++; \
case 4: *mcdst++ = *mcsrc++; \
case 3: *mcdst++ = *mcsrc++; \
case 2: *mcdst++ = *mcsrc++; \
case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \
} \
} while(0)
#endif
/*
Define HAVE_MMAP to optionally make malloc() use mmap() to
allocate very large blocks. These will be returned to the
operating system immediately after a free().
*/
#ifndef HAVE_MMAP
#define HAVE_MMAP 1
#endif
/*
Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
large blocks. This is currently only possible on Linux with
kernel versions newer than 1.3.77.
*/
#ifndef HAVE_MREMAP
#ifdef INTERNAL_LINUX_C_LIB
#define HAVE_MREMAP 1
#else
#define HAVE_MREMAP 0
#endif
#endif
#if HAVE_MMAP
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
#define MAP_ANONYMOUS MAP_ANON
#endif
#endif /* HAVE_MMAP */
/*
Access to system page size. To the extent possible, this malloc
manages memory from the system in page-size units.
The following mechanics for getpagesize were adapted from
bsd/gnu getpagesize.h
*/
#ifndef LACKS_UNISTD_H
# include <unistd.h>
#endif
#ifndef malloc_getpagesize
# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
# ifndef _SC_PAGE_SIZE
# define _SC_PAGE_SIZE _SC_PAGESIZE
# endif
# endif
# ifdef _SC_PAGE_SIZE
# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
# else
# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
extern size_t getpagesize();
# define malloc_getpagesize getpagesize()
# else
# ifdef WIN32
# define malloc_getpagesize (4096) /* TBD: Use 'GetSystemInfo' instead */
# else
# ifndef LACKS_SYS_PARAM_H
# include <sys/param.h>
# endif
# ifdef EXEC_PAGESIZE
# define malloc_getpagesize EXEC_PAGESIZE
# else
# ifdef NBPG
# ifndef CLSIZE
# define malloc_getpagesize NBPG
# else
# define malloc_getpagesize (NBPG * CLSIZE)
# endif
# else
# ifdef NBPC
# define malloc_getpagesize NBPC
# else
# ifdef PAGESIZE
# define malloc_getpagesize PAGESIZE
# else
# define malloc_getpagesize (4096) /* just guess */
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
/*
This version of malloc supports the standard SVID/XPG mallinfo
routine that returns a struct containing the same kind of
information you can get from malloc_stats. It should work on
any SVID/XPG compliant system that has a /usr/include/malloc.h
defining struct mallinfo. (If you'd like to install such a thing
yourself, cut out the preliminary declarations as described above
and below and save them in a malloc.h file. But there's no
compelling reason to bother to do this.)
The main declaration needed is the mallinfo struct that is returned
(by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
bunch of fields, most of which are not even meaningful in this
version of malloc. Some of these fields are are instead filled by
mallinfo() with other numbers that might possibly be of interest.
HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
/usr/include/malloc.h file that includes a declaration of struct
mallinfo. If so, it is included; else an SVID2/XPG2 compliant
version is declared below. These must be precisely the same for
mallinfo() to work.
*/
/* #define HAVE_USR_INCLUDE_MALLOC_H */
#if HAVE_USR_INCLUDE_MALLOC_H
#include "/usr/include/malloc.h"
#else
/* SVID2/XPG mallinfo structure */
struct mallinfo {
int arena; /* total space allocated from system */
int ordblks; /* number of non-inuse chunks */
int smblks; /* unused -- always zero */
int hblks; /* number of mmapped regions */
int hblkhd; /* total space in mmapped regions */
int usmblks; /* unused -- always zero */
int fsmblks; /* unused -- always zero */
int uordblks; /* total allocated space */
int fordblks; /* total non-inuse space */
int keepcost; /* top-most, releasable (via malloc_trim) space */
};
/* SVID2/XPG mallopt options */
#define M_MXFAST 1 /* UNUSED in this malloc */
#define M_NLBLKS 2 /* UNUSED in this malloc */
#define M_GRAIN 3 /* UNUSED in this malloc */
#define M_KEEP 4 /* UNUSED in this malloc */
#endif
/* mallopt options that actually do something */
#define M_TRIM_THRESHOLD -1
#define M_TOP_PAD -2
#define M_MMAP_THRESHOLD -3
#define M_MMAP_MAX -4
#ifndef DEFAULT_TRIM_THRESHOLD
#define DEFAULT_TRIM_THRESHOLD (128 * 1024)
#endif
/*
M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
to keep before releasing via malloc_trim in free().
Automatic trimming is mainly useful in long-lived programs.
Because trimming via sbrk can be slow on some systems, and can
sometimes be wasteful (in cases where programs immediately
afterward allocate more large chunks) the value should be high
enough so that your overall system performance would improve by
releasing.
The trim threshold and the mmap control parameters (see below)
can be traded off with one another. Trimming and mmapping are
two different ways of releasing unused memory back to the
system. Between these two, it is often possible to keep
system-level demands of a long-lived program down to a bare
minimum. For example, in one test suite of sessions measuring
the XF86 X server on Linux, using a trim threshold of 128K and a
mmap threshold of 192K led to near-minimal long term resource
consumption.
If you are using this malloc in a long-lived program, it should
pay to experiment with these values. As a rough guide, you
might set to a value close to the average size of a process
(program) running on your system. Releasing this much memory
would allow such a process to run in memory. Generally, it's
worth it to tune for trimming rather tham memory mapping when a
program undergoes phases where several large chunks are
allocated and released in ways that can reuse each other's
storage, perhaps mixed with phases where there are no such
chunks at all. And in well-behaved long-lived programs,
controlling release of large blocks via trimming versus mapping
is usually faster.
However, in most programs, these parameters serve mainly as
protection against the system-level effects of carrying around
massive amounts of unneeded memory. Since frequent calls to
sbrk, mmap, and munmap otherwise degrade performance, the default
parameters are set to relatively high values that serve only as
safeguards.
The default trim value is high enough to cause trimming only in
fairly extreme (by current memory consumption standards) cases.
It must be greater than page size to have any useful effect. To
disable trimming completely, you can set to (unsigned long)(-1);
*/
#ifndef DEFAULT_TOP_PAD
#define DEFAULT_TOP_PAD (0)
#endif
/*
M_TOP_PAD is the amount of extra `padding' space to allocate or
retain whenever sbrk is called. It is used in two ways internally:
* When sbrk is called to extend the top of the arena to satisfy
a new malloc request, this much padding is added to the sbrk
request.
* When malloc_trim is called automatically from free(),
it is used as the `pad' argument.
In both cases, the actual amount of padding is rounded
so that the end of the arena is always a system page boundary.
The main reason for using padding is to avoid calling sbrk so
often. Having even a small pad greatly reduces the likelihood
that nearly every malloc request during program start-up (or
after trimming) will invoke sbrk, which needlessly wastes
time.
Automatic rounding-up to page-size units is normally sufficient
to avoid measurable overhead, so the default is 0. However, in
systems where sbrk is relatively slow, it can pay to increase
this value, at the expense of carrying around more memory than
the program needs.
*/
#ifndef DEFAULT_MMAP_THRESHOLD
#define DEFAULT_MMAP_THRESHOLD (128 * 1024)
#endif
/*
M_MMAP_THRESHOLD is the request size threshold for using mmap()
to service a request. Requests of at least this size that cannot
be allocated using already-existing space will be serviced via mmap.
(If enough normal freed space already exists it is used instead.)
Using mmap segregates relatively large chunks of memory so that
they can be individually obtained and released from the host
system. A request serviced through mmap is never reused by any
other request (at least not directly; the system may just so
happen to remap successive requests to the same locations).
Segregating space in this way has the benefit that mmapped space
can ALWAYS be individually released back to the system, which
helps keep the system level memory demands of a long-lived
program low. Mapped memory can never become `locked' between
other chunks, as can happen with normally allocated chunks, which
menas that even trimming via malloc_trim would not release them.
However, it has the disadvantages that:
1. The space cannot be reclaimed, consolidated, and then
used to service later requests, as happens with normal chunks.
2. It can lead to more wastage because of mmap page alignment
requirements
3. It causes malloc performance to be more dependent on host
system memory management support routines which may vary in
implementation quality and may impose arbitrary
limitations. Generally, servicing a request via normal
malloc steps is faster than going through a system's mmap.
All together, these considerations should lead you to use mmap
only for relatively large requests.
*/
#ifndef DEFAULT_MMAP_MAX
#if HAVE_MMAP
#define DEFAULT_MMAP_MAX (64)
#else
#define DEFAULT_MMAP_MAX (0)
#endif
#endif
/*
M_MMAP_MAX is the maximum number of requests to simultaneously
service using mmap. This parameter exists because:
1. Some systems have a limited number of internal tables for
use by mmap.
2. In most systems, overreliance on mmap can degrade overall
performance.
3. If a program allocates many large regions, it is probably
better off using normal sbrk-based allocation routines that
can reclaim and reallocate normal heap memory. Using a
small value allows transition into this mode after the
first few allocations.
Setting to 0 disables all use of mmap. If HAVE_MMAP is not set,
the default value is 0, and attempts to set it to non-zero values
in mallopt will fail.
*/
/*
USE_DL_PREFIX will prefix all public routines with the string 'dl'.
Useful to quickly avoid procedure declaration conflicts and linker
symbol conflicts with existing memory allocation routines.
*/
/* #define USE_DL_PREFIX */
/*
Special defines for linux libc
Except when compiled using these special defines for Linux libc
using weak aliases, this malloc is NOT designed to work in
multithreaded applications. No semaphores or other concurrency
control are provided to ensure that multiple malloc or free calls
don't run at the same time, which could be disasterous. A single
semaphore could be used across malloc, realloc, and free (which is
essentially the effect of the linux weak alias approach). It would
be hard to obtain finer granularity.
*/
#ifdef INTERNAL_LINUX_C_LIB
#if __STD_C
Void_t * __default_morecore_init (ptrdiff_t);
Void_t *(*__morecore)(ptrdiff_t) = __default_morecore_init;
#else
Void_t * __default_morecore_init ();
Void_t *(*__morecore)() = __default_morecore_init;
#endif
#define MORECORE (*__morecore)
#define MORECORE_FAILURE 0
#define MORECORE_CLEARS 1
#else /* INTERNAL_LINUX_C_LIB */
#if __STD_C
extern Void_t* sbrk(ptrdiff_t);
#else
extern Void_t* sbrk();
#endif
#ifndef MORECORE
#define MORECORE sbrk
#endif
#ifndef MORECORE_FAILURE
#define MORECORE_FAILURE -1
#endif
#ifndef MORECORE_CLEARS
#define MORECORE_CLEARS 1
#endif
#endif /* INTERNAL_LINUX_C_LIB */
#if defined(INTERNAL_LINUX_C_LIB) && defined(__ELF__)
#define cALLOc __libc_calloc
#define fREe __libc_free
#define mALLOc __libc_malloc
#define mEMALIGn __libc_memalign
#define rEALLOc __libc_realloc
#define vALLOc __libc_valloc
#define pvALLOc __libc_pvalloc
#define mALLINFo __libc_mallinfo
#define mALLOPt __libc_mallopt
#pragma weak calloc = __libc_calloc
#pragma weak free = __libc_free
#pragma weak cfree = __libc_free
#pragma weak malloc = __libc_malloc
#pragma weak memalign = __libc_memalign
#pragma weak realloc = __libc_realloc
#pragma weak valloc = __libc_valloc
#pragma weak pvalloc = __libc_pvalloc
#pragma weak mallinfo = __libc_mallinfo
#pragma weak mallopt = __libc_mallopt
#else
#ifdef USE_DL_PREFIX
#define cALLOc dlcalloc
#define fREe dlfree
#define mALLOc dlmalloc
#define mEMALIGn dlmemalign
#define rEALLOc dlrealloc
#define vALLOc dlvalloc
#define pvALLOc dlpvalloc
#define mALLINFo dlmallinfo
#define mALLOPt dlmallopt
#else /* USE_DL_PREFIX */
#define cALLOc calloc
#define fREe free
#define mALLOc malloc
#define mEMALIGn memalign
#define rEALLOc realloc
#define vALLOc valloc
#define pvALLOc pvalloc
#define mALLINFo mallinfo
#define mALLOPt mallopt
#endif /* USE_DL_PREFIX */
#endif
/* Public routines */
#if __STD_C
Void_t* mALLOc(size_t);
void fREe(Void_t*);
Void_t* rEALLOc(Void_t*, size_t);
Void_t* mEMALIGn(size_t, size_t);
Void_t* vALLOc(size_t);
Void_t* pvALLOc(size_t);
Void_t* cALLOc(size_t, size_t);
void cfree(Void_t*);
int malloc_trim(size_t);
size_t malloc_usable_size(Void_t*);
void malloc_stats();
int mALLOPt(int, int);
struct mallinfo mALLINFo(void);
#else
Void_t* mALLOc();
void fREe();
Void_t* rEALLOc();
Void_t* mEMALIGn();
Void_t* vALLOc();
Void_t* pvALLOc();
Void_t* cALLOc();
void cfree();
int malloc_trim();
size_t malloc_usable_size();
void malloc_stats();
int mALLOPt();
struct mallinfo mALLINFo();
#endif
#ifdef __cplusplus
}; /* end of extern "C" */
#endif
/* ---------- To make a malloc.h, end cutting here ------------ */
#endif /* 0 */ /* Moved to malloc.h */
#include <malloc.h>
#ifdef DEBUG
#if __STD_C
static void malloc_update_mallinfo (void);
void malloc_stats (void);
#else
static void malloc_update_mallinfo ();
void malloc_stats();
#endif
#endif /* DEBUG */
DECLARE_GLOBAL_DATA_PTR;
/*
Emulation of sbrk for WIN32
All code within the ifdef WIN32 is untested by me.
Thanks to Martin Fong and others for supplying this.
*/
#ifdef WIN32
#define AlignPage(add) (((add) + (malloc_getpagesize-1)) & \
~(malloc_getpagesize-1))
#define AlignPage64K(add) (((add) + (0x10000 - 1)) & ~(0x10000 - 1))
/* resrve 64MB to insure large contiguous space */
#define RESERVED_SIZE (1024*1024*64)
#define NEXT_SIZE (2048*1024)
#define TOP_MEMORY ((unsigned long)2*1024*1024*1024)
struct GmListElement;
typedef struct GmListElement GmListElement;
struct GmListElement
{
GmListElement* next;
void* base;
};
static GmListElement* head = 0;
static unsigned int gNextAddress = 0;
static unsigned int gAddressBase = 0;
static unsigned int gAllocatedSize = 0;
static
GmListElement* makeGmListElement (void* bas)
{
GmListElement* this;
this = (GmListElement*)(void*)LocalAlloc (0, sizeof (GmListElement));
assert (this);
if (this)
{
this->base = bas;
this->next = head;
head = this;
}
return this;
}
void gcleanup ()
{
BOOL rval;
assert ( (head == NULL) || (head->base == (void*)gAddressBase));
if (gAddressBase && (gNextAddress - gAddressBase))
{
rval = VirtualFree ((void*)gAddressBase,
gNextAddress - gAddressBase,
MEM_DECOMMIT);
assert (rval);
}
while (head)
{
GmListElement* next = head->next;
rval = VirtualFree (head->base, 0, MEM_RELEASE);
assert (rval);
LocalFree (head);
head = next;
}
}
static
void* findRegion (void* start_address, unsigned long size)
{
MEMORY_BASIC_INFORMATION info;
if (size >= TOP_MEMORY) return NULL;
while ((unsigned long)start_address + size < TOP_MEMORY)
{
VirtualQuery (start_address, &info, sizeof (info));
if ((info.State == MEM_FREE) && (info.RegionSize >= size))
return start_address;
else
{
/* Requested region is not available so see if the */
/* next region is available. Set 'start_address' */
/* to the next region and call 'VirtualQuery()' */
/* again. */
start_address = (char*)info.BaseAddress + info.RegionSize;
/* Make sure we start looking for the next region */
/* on the *next* 64K boundary. Otherwise, even if */
/* the new region is free according to */
/* 'VirtualQuery()', the subsequent call to */
/* 'VirtualAlloc()' (which follows the call to */
/* this routine in 'wsbrk()') will round *down* */
/* the requested address to a 64K boundary which */
/* we already know is an address in the */
/* unavailable region. Thus, the subsequent call */
/* to 'VirtualAlloc()' will fail and bring us back */
/* here, causing us to go into an infinite loop. */
start_address =
(void *) AlignPage64K((unsigned long) start_address);
}
}
return NULL;
}
void* wsbrk (long size)
{
void* tmp;
if (size > 0)
{
if (gAddressBase == 0)
{
gAllocatedSize = max (RESERVED_SIZE, AlignPage (size));
gNextAddress = gAddressBase =
(unsigned int)VirtualAlloc (NULL, gAllocatedSize,
MEM_RESERVE, PAGE_NOACCESS);
} else if (AlignPage (gNextAddress + size) > (gAddressBase +
gAllocatedSize))
{
long new_size = max (NEXT_SIZE, AlignPage (size));
void* new_address = (void*)(gAddressBase+gAllocatedSize);
do
{
new_address = findRegion (new_address, new_size);
if (new_address == 0)
return (void*)-1;
gAddressBase = gNextAddress =
(unsigned int)VirtualAlloc (new_address, new_size,
MEM_RESERVE, PAGE_NOACCESS);
/* repeat in case of race condition */
/* The region that we found has been snagged */
/* by another thread */
}
while (gAddressBase == 0);
assert (new_address == (void*)gAddressBase);
gAllocatedSize = new_size;
if (!makeGmListElement ((void*)gAddressBase))
return (void*)-1;
}
if ((size + gNextAddress) > AlignPage (gNextAddress))
{
void* res;
res = VirtualAlloc ((void*)AlignPage (gNextAddress),
(size + gNextAddress -
AlignPage (gNextAddress)),
MEM_COMMIT, PAGE_READWRITE);
if (res == 0)
return (void*)-1;
}
tmp = (void*)gNextAddress;
gNextAddress = (unsigned int)tmp + size;
return tmp;
}
else if (size < 0)
{
unsigned int alignedGoal = AlignPage (gNextAddress + size);
/* Trim by releasing the virtual memory */
if (alignedGoal >= gAddressBase)
{
VirtualFree ((void*)alignedGoal, gNextAddress - alignedGoal,
MEM_DECOMMIT);
gNextAddress = gNextAddress + size;
return (void*)gNextAddress;
}
else
{
VirtualFree ((void*)gAddressBase, gNextAddress - gAddressBase,
MEM_DECOMMIT);
gNextAddress = gAddressBase;
return (void*)-1;
}
}
else
{
return (void*)gNextAddress;
}
}
#endif
/*
Type declarations
*/
struct malloc_chunk
{
INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
struct malloc_chunk* fd; /* double links -- used only if free. */
struct malloc_chunk* bk;
} __attribute__((__may_alias__)) ;
typedef struct malloc_chunk* mchunkptr;
/*
malloc_chunk details:
(The following includes lightly edited explanations by Colin Plumb.)
Chunks of memory are maintained using a `boundary tag' method as
described in e.g., Knuth or Standish. (See the paper by Paul
Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
survey of such techniques.) Sizes of free chunks are stored both
in the front of each chunk and at the end. This makes
consolidating fragmented chunks into bigger chunks very fast. The
size fields also hold bits representing whether chunks are free or
in use.
An allocated chunk looks like this:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk, if allocated | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| User data starts here... .
. .
. (malloc_usable_space() bytes) .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Where "chunk" is the front of the chunk for the purpose of most of
the malloc code, but "mem" is the pointer that is returned to the
user. "Nextchunk" is the beginning of the next contiguous chunk.
Chunks always begin on even word boundries, so the mem portion
(which is returned to the user) is also on an even word boundary, and
thus double-word aligned.
Free chunks are stored in circular doubly-linked lists, and look like this:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space (may be 0 bytes long) .
. .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
The P (PREV_INUSE) bit, stored in the unused low-order bit of the
chunk size (which is always a multiple of two words), is an in-use
bit for the *previous* chunk. If that bit is *clear*, then the
word before the current chunk size contains the previous chunk
size, and can be used to find the front of the previous chunk.
(The very first chunk allocated always has this bit set,
preventing access to non-existent (or non-owned) memory.)
Note that the `foot' of the current chunk is actually represented
as the prev_size of the NEXT chunk. (This makes it easier to
deal with alignments etc).
The two exceptions to all this are
1. The special chunk `top', which doesn't bother using the
trailing size field since there is no
next contiguous chunk that would have to index off it. (After
initialization, `top' is forced to always exist. If it would
become less than MINSIZE bytes long, it is replenished via
malloc_extend_top.)
2. Chunks allocated via mmap, which have the second-lowest-order
bit (IS_MMAPPED) set in their size fields. Because they are
never merged or traversed from any other chunk, they have no
foot size or inuse information.
Available chunks are kept in any of several places (all declared below):
* `av': An array of chunks serving as bin headers for consolidated
chunks. Each bin is doubly linked. The bins are approximately
proportionally (log) spaced. There are a lot of these bins
(128). This may look excessive, but works very well in
practice. All procedures maintain the invariant that no
consolidated chunk physically borders another one. Chunks in
bins are kept in size order, with ties going to the
approximately least recently used chunk.
The chunks in each bin are maintained in decreasing sorted order by
size. This is irrelevant for the small bins, which all contain
the same-sized chunks, but facilitates best-fit allocation for
larger chunks. (These lists are just sequential. Keeping them in
order almost never requires enough traversal to warrant using
fancier ordered data structures.) Chunks of the same size are
linked with the most recently freed at the front, and allocations
are taken from the back. This results in LRU or FIFO allocation
order, which tends to give each chunk an equal opportunity to be
consolidated with adjacent freed chunks, resulting in larger free
chunks and less fragmentation.
* `top': The top-most available chunk (i.e., the one bordering the
end of available memory) is treated specially. It is never
included in any bin, is used only if no other chunk is
available, and is released back to the system if it is very
large (see M_TRIM_THRESHOLD).
* `last_remainder': A bin holding only the remainder of the
most recently split (non-top) chunk. This bin is checked
before other non-fitting chunks, so as to provide better
locality for runs of sequentially allocated chunks.
* Implicitly, through the host system's memory mapping tables.
If supported, requests greater than a threshold are usually
serviced via calls to mmap, and then later released via munmap.
*/
/* sizes, alignments */
#define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
#define MALLOC_ALIGNMENT (SIZE_SZ + SIZE_SZ)
#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
#define MINSIZE (sizeof(struct malloc_chunk))
/* conversion from malloc headers to user pointers, and back */
#define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
/* pad request bytes into a usable size */
#define request2size(req) \
(((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
(long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
(((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
/* Check if m has acceptable alignment */
#define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
/*
Physical chunk operations
*/
/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
#define PREV_INUSE 0x1
/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
#define IS_MMAPPED 0x2
/* Bits to mask off when extracting size */
#define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
/* Ptr to next physical malloc_chunk. */
#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
/* Ptr to previous physical malloc_chunk */
#define prev_chunk(p)\
((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
/* Treat space at ptr + offset as a chunk */
#define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
/*
Dealing with use bits
*/
/* extract p's inuse bit */
#define inuse(p)\
((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
/* extract inuse bit of previous chunk */
#define prev_inuse(p) ((p)->size & PREV_INUSE)
/* check for mmap()'ed chunk */
#define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
/* set/clear chunk as in use without otherwise disturbing */
#define set_inuse(p)\
((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
#define clear_inuse(p)\
((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
/* check/set/clear inuse bits in known places */
#define inuse_bit_at_offset(p, s)\
(((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
#define set_inuse_bit_at_offset(p, s)\
(((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
#define clear_inuse_bit_at_offset(p, s)\
(((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
/*
Dealing with size fields
*/
/* Get size, ignoring use bits */
#define chunksize(p) ((p)->size & ~(SIZE_BITS))
/* Set size at head, without disturbing its use bit */
#define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
/* Set size/use ignoring previous bits in header */
#define set_head(p, s) ((p)->size = (s))
/* Set size at footer (only when chunk is not in use) */
#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
/*
Bins
The bins, `av_' are an array of pairs of pointers serving as the
heads of (initially empty) doubly-linked lists of chunks, laid out
in a way so that each pair can be treated as if it were in a
malloc_chunk. (This way, the fd/bk offsets for linking bin heads
and chunks are the same).
Bins for sizes < 512 bytes contain chunks of all the same size, spaced
8 bytes apart. Larger bins are approximately logarithmically
spaced. (See the table below.) The `av_' array is never mentioned
directly in the code, but instead via bin access macros.
Bin layout:
64 bins of size 8
32 bins of size 64
16 bins of size 512
8 bins of size 4096
4 bins of size 32768
2 bins of size 262144
1 bin of size what's left
There is actually a little bit of slop in the numbers in bin_index
for the sake of speed. This makes no difference elsewhere.
The special chunks `top' and `last_remainder' get their own bins,
(this is implemented via yet more trickery with the av_ array),
although `top' is never properly linked to its bin since it is
always handled specially.
*/
#define NAV 128 /* number of bins */
typedef struct malloc_chunk* mbinptr;
/* access macros */
#define bin_at(i) ((mbinptr)((char*)&(av_[2*(i) + 2]) - 2*SIZE_SZ))
#define next_bin(b) ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
#define prev_bin(b) ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
/*
The first 2 bins are never indexed. The corresponding av_ cells are instead
used for bookkeeping. This is not to save space, but to simplify
indexing, maintain locality, and avoid some initialization tests.
*/
#define top (av_[2]) /* The topmost chunk */
#define last_remainder (bin_at(1)) /* remainder from last split */
/*
Because top initially points to its own bin with initial
zero size, thus forcing extension on the first malloc request,
we avoid having any special code in malloc to check whether
it even exists yet. But we still need to in malloc_extend_top.
*/
#define initial_top ((mchunkptr)(bin_at(0)))
/* Helper macro to initialize bins */
#define IAV(i) bin_at(i), bin_at(i)
static mbinptr av_[NAV * 2 + 2] = {
0, 0,
IAV(0), IAV(1), IAV(2), IAV(3), IAV(4), IAV(5), IAV(6), IAV(7),
IAV(8), IAV(9), IAV(10), IAV(11), IAV(12), IAV(13), IAV(14), IAV(15),
IAV(16), IAV(17), IAV(18), IAV(19), IAV(20), IAV(21), IAV(22), IAV(23),
IAV(24), IAV(25), IAV(26), IAV(27), IAV(28), IAV(29), IAV(30), IAV(31),
IAV(32), IAV(33), IAV(34), IAV(35), IAV(36), IAV(37), IAV(38), IAV(39),
IAV(40), IAV(41), IAV(42), IAV(43), IAV(44), IAV(45), IAV(46), IAV(47),
IAV(48), IAV(49), IAV(50), IAV(51), IAV(52), IAV(53), IAV(54), IAV(55),
IAV(56), IAV(57), IAV(58), IAV(59), IAV(60), IAV(61), IAV(62), IAV(63),
IAV(64), IAV(65), IAV(66), IAV(67), IAV(68), IAV(69), IAV(70), IAV(71),
IAV(72), IAV(73), IAV(74), IAV(75), IAV(76), IAV(77), IAV(78), IAV(79),
IAV(80), IAV(81), IAV(82), IAV(83), IAV(84), IAV(85), IAV(86), IAV(87),
IAV(88), IAV(89), IAV(90), IAV(91), IAV(92), IAV(93), IAV(94), IAV(95),
IAV(96), IAV(97), IAV(98), IAV(99), IAV(100), IAV(101), IAV(102), IAV(103),
IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
};
#ifdef CONFIG_NEEDS_MANUAL_RELOC
void malloc_bin_reloc (void)
{
unsigned long *p = (unsigned long *)(&av_[2]);
int i;
for (i=2; i<(sizeof(av_)/sizeof(mbinptr)); ++i) {
*p++ += gd->reloc_off;
}
}
#endif
ulong mem_malloc_start = 0;
ulong mem_malloc_end = 0;
ulong mem_malloc_brk = 0;
void *sbrk(ptrdiff_t increment)
{
ulong old = mem_malloc_brk;
ulong new = old + increment;
/*
* if we are giving memory back make sure we clear it out since
* we set MORECORE_CLEARS to 1
*/
if (increment < 0)
memset((void *)new, 0, -increment);
if ((new < mem_malloc_start) || (new > mem_malloc_end))
return (void *)MORECORE_FAILURE;
mem_malloc_brk = new;
return (void *)old;
}
void mem_malloc_init(ulong start, ulong size)
{
mem_malloc_start = start;
mem_malloc_end = start + size;
mem_malloc_brk = start;
memset((void *)mem_malloc_start, 0, size);
}
/* field-extraction macros */
#define first(b) ((b)->fd)
#define last(b) ((b)->bk)
/*
Indexing into bins
*/
#define bin_index(sz) \
(((((unsigned long)(sz)) >> 9) == 0) ? (((unsigned long)(sz)) >> 3): \
((((unsigned long)(sz)) >> 9) <= 4) ? 56 + (((unsigned long)(sz)) >> 6): \
((((unsigned long)(sz)) >> 9) <= 20) ? 91 + (((unsigned long)(sz)) >> 9): \
((((unsigned long)(sz)) >> 9) <= 84) ? 110 + (((unsigned long)(sz)) >> 12): \
((((unsigned long)(sz)) >> 9) <= 340) ? 119 + (((unsigned long)(sz)) >> 15): \
((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18): \
126)
/*
bins for chunks < 512 are all spaced 8 bytes apart, and hold
identically sized chunks. This is exploited in malloc.
*/
#define MAX_SMALLBIN 63
#define MAX_SMALLBIN_SIZE 512
#define SMALLBIN_WIDTH 8
#define smallbin_index(sz) (((unsigned long)(sz)) >> 3)
/*
Requests are `small' if both the corresponding and the next bin are small
*/
#define is_small_request(nb) (nb < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
/*
To help compensate for the large number of bins, a one-level index
structure is used for bin-by-bin searching. `binblocks' is a
one-word bitvector recording whether groups of BINBLOCKWIDTH bins
have any (possibly) non-empty bins, so they can be skipped over
all at once during during traversals. The bits are NOT always
cleared as soon as all bins in a block are empty, but instead only
when all are noticed to be empty during traversal in malloc.
*/
#define BINBLOCKWIDTH 4 /* bins per block */
#define binblocks_r ((INTERNAL_SIZE_T)av_[1]) /* bitvector of nonempty blocks */
#define binblocks_w (av_[1])
/* bin<->block macros */
#define idx2binblock(ix) ((unsigned)1 << (ix / BINBLOCKWIDTH))
#define mark_binblock(ii) (binblocks_w = (mbinptr)(binblocks_r | idx2binblock(ii)))
#define clear_binblock(ii) (binblocks_w = (mbinptr)(binblocks_r & ~(idx2binblock(ii))))
/* Other static bookkeeping data */
/* variables holding tunable values */
static unsigned long trim_threshold = DEFAULT_TRIM_THRESHOLD;
static unsigned long top_pad = DEFAULT_TOP_PAD;
static unsigned int n_mmaps_max = DEFAULT_MMAP_MAX;
static unsigned long mmap_threshold = DEFAULT_MMAP_THRESHOLD;
/* The first value returned from sbrk */
static char* sbrk_base = (char*)(-1);
/* The maximum memory obtained from system via sbrk */
static unsigned long max_sbrked_mem = 0;
/* The maximum via either sbrk or mmap */
static unsigned long max_total_mem = 0;
/* internal working copy of mallinfo */
static struct mallinfo current_mallinfo = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/* The total memory obtained from system via sbrk */
#define sbrked_mem (current_mallinfo.arena)
/* Tracking mmaps */
#ifdef DEBUG
static unsigned int n_mmaps = 0;
#endif /* DEBUG */
static unsigned long mmapped_mem = 0;
#if HAVE_MMAP
static unsigned int max_n_mmaps = 0;
static unsigned long max_mmapped_mem = 0;
#endif
/*
Debugging support
*/
#ifdef DEBUG
/*
These routines make a number of assertions about the states
of data structures that should be true at all times. If any
are not true, it's very likely that a user program has somehow
trashed memory. (It's also possible that there is a coding error
in malloc. In which case, please report it!)
*/
#if __STD_C
static void do_check_chunk(mchunkptr p)
#else
static void do_check_chunk(p) mchunkptr p;
#endif
{
INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
/* No checkable chunk is mmapped */
assert(!chunk_is_mmapped(p));
/* Check for legal address ... */
assert((char*)p >= sbrk_base);
if (p != top)
assert((char*)p + sz <= (char*)top);
else
assert((char*)p + sz <= sbrk_base + sbrked_mem);
}
#if __STD_C
static void do_check_free_chunk(mchunkptr p)
#else
static void do_check_free_chunk(p) mchunkptr p;
#endif
{
INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
mchunkptr next = chunk_at_offset(p, sz);
do_check_chunk(p);
/* Check whether it claims to be free ... */
assert(!inuse(p));
/* Unless a special marker, must have OK fields */
if ((long)sz >= (long)MINSIZE)
{
assert((sz & MALLOC_ALIGN_MASK) == 0);
assert(aligned_OK(chunk2mem(p)));
/* ... matching footer field */
assert(next->prev_size == sz);
/* ... and is fully consolidated */
assert(prev_inuse(p));
assert (next == top || inuse(next));
/* ... and has minimally sane links */
assert(p->fd->bk == p);
assert(p->bk->fd == p);
}
else /* markers are always of size SIZE_SZ */
assert(sz == SIZE_SZ);
}
#if __STD_C
static void do_check_inuse_chunk(mchunkptr p)
#else
static void do_check_inuse_chunk(p) mchunkptr p;
#endif
{
mchunkptr next = next_chunk(p);
do_check_chunk(p);
/* Check whether it claims to be in use ... */
assert(inuse(p));
/* ... and is surrounded by OK chunks.
Since more things can be checked with free chunks than inuse ones,
if an inuse chunk borders them and debug is on, it's worth doing them.
*/
if (!prev_inuse(p))
{
mchunkptr prv = prev_chunk(p);
assert(next_chunk(prv) == p);
do_check_free_chunk(prv);
}
if (next == top)
{
assert(prev_inuse(next));
assert(chunksize(next) >= MINSIZE);
}
else if (!inuse(next))
do_check_free_chunk(next);
}
#if __STD_C
static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
#else
static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
#endif
{
INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
long room = sz - s;
do_check_inuse_chunk(p);
/* Legal size ... */
assert((long)sz >= (long)MINSIZE);
assert((sz & MALLOC_ALIGN_MASK) == 0);
assert(room >= 0);
assert(room < (long)MINSIZE);
/* ... and alignment */
assert(aligned_OK(chunk2mem(p)));
/* ... and was allocated at front of an available chunk */
assert(prev_inuse(p));
}
#define check_free_chunk(P) do_check_free_chunk(P)
#define check_inuse_chunk(P) do_check_inuse_chunk(P)
#define check_chunk(P) do_check_chunk(P)
#define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)
#else
#define check_free_chunk(P)
#define check_inuse_chunk(P)
#define check_chunk(P)
#define check_malloced_chunk(P,N)
#endif
/*
Macro-based internal utilities
*/
/*
Linking chunks in bin lists.
Call these only with variables, not arbitrary expressions, as arguments.
*/
/*
Place chunk p of size s in its bin, in size order,
putting it ahead of others of same size.
*/
#define frontlink(P, S, IDX, BK, FD) \
{ \
if (S < MAX_SMALLBIN_SIZE) \
{ \
IDX = smallbin_index(S); \
mark_binblock(IDX); \
BK = bin_at(IDX); \
FD = BK->fd; \
P->bk = BK; \
P->fd = FD; \
FD->bk = BK->fd = P; \
} \
else \
{ \
IDX = bin_index(S); \
BK = bin_at(IDX); \
FD = BK->fd; \
if (FD == BK) mark_binblock(IDX); \
else \
{ \
while (FD != BK && S < chunksize(FD)) FD = FD->fd; \
BK = FD->bk; \
} \
P->bk = BK; \
P->fd = FD; \
FD->bk = BK->fd = P; \
} \
}
/* take a chunk off a list */
#define unlink(P, BK, FD) \
{ \
BK = P->bk; \
FD = P->fd; \
FD->bk = BK; \
BK->fd = FD; \
} \
/* Place p as the last remainder */
#define link_last_remainder(P) \
{ \
last_remainder->fd = last_remainder->bk = P; \
P->fd = P->bk = last_remainder; \
}
/* Clear the last_remainder bin */
#define clear_last_remainder \
(last_remainder->fd = last_remainder->bk = last_remainder)
/* Routines dealing with mmap(). */
#if HAVE_MMAP
#if __STD_C
static mchunkptr mmap_chunk(size_t size)
#else
static mchunkptr mmap_chunk(size) size_t size;
#endif
{
size_t page_mask = malloc_getpagesize - 1;
mchunkptr p;
#ifndef MAP_ANONYMOUS
static int fd = -1;
#endif
if(n_mmaps >= n_mmaps_max) return 0; /* too many regions */
/* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
* there is no following chunk whose prev_size field could be used.
*/
size = (size + SIZE_SZ + page_mask) & ~page_mask;
#ifdef MAP_ANONYMOUS
p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
#else /* !MAP_ANONYMOUS */
if (fd < 0)
{
fd = open("/dev/zero", O_RDWR);
if(fd < 0) return 0;
}
p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
#endif
if(p == (mchunkptr)-1) return 0;
n_mmaps++;
if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
/* We demand that eight bytes into a page must be 8-byte aligned. */
assert(aligned_OK(chunk2mem(p)));
/* The offset to the start of the mmapped region is stored
* in the prev_size field of the chunk; normally it is zero,
* but that can be changed in memalign().
*/
p->prev_size = 0;
set_head(p, size|IS_MMAPPED);
mmapped_mem += size;
if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
max_mmapped_mem = mmapped_mem;
if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
max_total_mem = mmapped_mem + sbrked_mem;
return p;
}
#if __STD_C
static void munmap_chunk(mchunkptr p)
#else
static void munmap_chunk(p) mchunkptr p;
#endif
{
INTERNAL_SIZE_T size = chunksize(p);
int ret;
assert (chunk_is_mmapped(p));
assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
assert((n_mmaps > 0));
assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
n_mmaps--;
mmapped_mem -= (size + p->prev_size);
ret = munmap((char *)p - p->prev_size, size + p->prev_size);
/* munmap returns non-zero on failure */
assert(ret == 0);
}
#if HAVE_MREMAP
#if __STD_C
static mchunkptr mremap_chunk(mchunkptr p, size_t new_size)
#else
static mchunkptr mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
#endif
{
size_t page_mask = malloc_getpagesize - 1;
INTERNAL_SIZE_T offset = p->prev_size;
INTERNAL_SIZE_T size = chunksize(p);
char *cp;
assert (chunk_is_mmapped(p));
assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
assert((n_mmaps > 0));
assert(((size + offset) & (malloc_getpagesize-1)) == 0);
/* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
cp = (char *)mremap((char *)p - offset, size + offset, new_size, 1);
if (cp == (char *)-1) return 0;
p = (mchunkptr)(cp + offset);
assert(aligned_OK(chunk2mem(p)));
assert((p->prev_size == offset));
set_head(p, (new_size - offset)|IS_MMAPPED);
mmapped_mem -= size + offset;
mmapped_mem += new_size;
if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
max_mmapped_mem = mmapped_mem;
if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
max_total_mem = mmapped_mem + sbrked_mem;
return p;
}
#endif /* HAVE_MREMAP */
#endif /* HAVE_MMAP */
/*
Extend the top-most chunk by obtaining memory from system.
Main interface to sbrk (but see also malloc_trim).
*/
#if __STD_C
static void malloc_extend_top(INTERNAL_SIZE_T nb)
#else
static void malloc_extend_top(nb) INTERNAL_SIZE_T nb;
#endif
{
char* brk; /* return value from sbrk */
INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
INTERNAL_SIZE_T correction; /* bytes for 2nd sbrk call */
char* new_brk; /* return of 2nd sbrk call */
INTERNAL_SIZE_T top_size; /* new size of top chunk */
mchunkptr old_top = top; /* Record state of old top */
INTERNAL_SIZE_T old_top_size = chunksize(old_top);
char* old_end = (char*)(chunk_at_offset(old_top, old_top_size));
/* Pad request with top_pad plus minimal overhead */
INTERNAL_SIZE_T sbrk_size = nb + top_pad + MINSIZE;
unsigned long pagesz = malloc_getpagesize;
/* If not the first time through, round to preserve page boundary */
/* Otherwise, we need to correct to a page size below anyway. */
/* (We also correct below if an intervening foreign sbrk call.) */
if (sbrk_base != (char*)(-1))
sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
brk = (char*)(MORECORE (sbrk_size));
/* Fail if sbrk failed or if a foreign sbrk call killed our space */
if (brk == (char*)(MORECORE_FAILURE) ||
(brk < old_end && old_top != initial_top))
return;
sbrked_mem += sbrk_size;
if (brk == old_end) /* can just add bytes to current top */
{
top_size = sbrk_size + old_top_size;
set_head(top, top_size | PREV_INUSE);
}
else
{
if (sbrk_base == (char*)(-1)) /* First time through. Record base */
sbrk_base = brk;
else /* Someone else called sbrk(). Count those bytes as sbrked_mem. */
sbrked_mem += brk - (char*)old_end;
/* Guarantee alignment of first new chunk made from this space */
front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
if (front_misalign > 0)
{
correction = (MALLOC_ALIGNMENT) - front_misalign;
brk += correction;
}
else
correction = 0;
/* Guarantee the next brk will be at a page boundary */
correction += ((((unsigned long)(brk + sbrk_size))+(pagesz-1)) &
~(pagesz - 1)) - ((unsigned long)(brk + sbrk_size));
/* Allocate correction */
new_brk = (char*)(MORECORE (correction));
if (new_brk == (char*)(MORECORE_FAILURE)) return;
sbrked_mem += correction;
top = (mchunkptr)brk;
top_size = new_brk - brk + correction;
set_head(top, top_size | PREV_INUSE);
if (old_top != initial_top)
{
/* There must have been an intervening foreign sbrk call. */
/* A double fencepost is necessary to prevent consolidation */
/* If not enough space to do this, then user did something very wrong */
if (old_top_size < MINSIZE)
{
set_head(top, PREV_INUSE); /* will force null return from malloc */
return;
}
/* Also keep size a multiple of MALLOC_ALIGNMENT */
old_top_size = (old_top_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
set_head_size(old_top, old_top_size);
chunk_at_offset(old_top, old_top_size )->size =
SIZE_SZ|PREV_INUSE;
chunk_at_offset(old_top, old_top_size + SIZE_SZ)->size =
SIZE_SZ|PREV_INUSE;
/* If possible, release the rest. */
if (old_top_size >= MINSIZE)
fREe(chunk2mem(old_top));
}
}
if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
max_sbrked_mem = sbrked_mem;
if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
max_total_mem = mmapped_mem + sbrked_mem;
/* We always land on a page boundary */
assert(((unsigned long)((char*)top + top_size) & (pagesz - 1)) == 0);
}
/* Main public routines */
/*
Malloc Algorthim:
The requested size is first converted into a usable form, `nb'.
This currently means to add 4 bytes overhead plus possibly more to
obtain 8-byte alignment and/or to obtain a size of at least
MINSIZE (currently 16 bytes), the smallest allocatable size.
(All fits are considered `exact' if they are within MINSIZE bytes.)
From there, the first successful of the following steps is taken:
1. The bin corresponding to the request size is scanned, and if
a chunk of exactly the right size is found, it is taken.
2. The most recently remaindered chunk is used if it is big
enough. This is a form of (roving) first fit, used only in
the absence of exact fits. Runs of consecutive requests use
the remainder of the chunk used for the previous such request
whenever possible. This limited use of a first-fit style
allocation strategy tends to give contiguous chunks
coextensive lifetimes, which improves locality and can reduce
fragmentation in the long run.
3. Other bins are scanned in increasing size order, using a
chunk big enough to fulfill the request, and splitting off
any remainder. This search is strictly by best-fit; i.e.,
the smallest (with ties going to approximately the least
recently used) chunk that fits is selected.
4. If large enough, the chunk bordering the end of memory
(`top') is split off. (This use of `top' is in accord with
the best-fit search rule. In effect, `top' is treated as
larger (and thus less well fitting) than any other available
chunk since it can be extended to be as large as necessary
(up to system limitations).
5. If the request size meets the mmap threshold and the
system supports mmap, and there are few enough currently
allocated mmapped regions, and a call to mmap succeeds,
the request is allocated via direct memory mapping.
6. Otherwise, the top of memory is extended by
obtaining more space from the system (normally using sbrk,
but definable to anything else via the MORECORE macro).
Memory is gathered from the system (in system page-sized
units) in a way that allows chunks obtained across different
sbrk calls to be consolidated, but does not require
contiguous memory. Thus, it should be safe to intersperse
mallocs with other sbrk calls.
All allocations are made from the the `lowest' part of any found
chunk. (The implementation invariant is that prev_inuse is
always true of any allocated chunk; i.e., that each allocated
chunk borders either a previously allocated and still in-use chunk,
or the base of its memory arena.)
*/
#if __STD_C
Void_t* mALLOc(size_t bytes)
#else
Void_t* mALLOc(bytes) size_t bytes;
#endif
{
mchunkptr victim; /* inspected/selected chunk */
INTERNAL_SIZE_T victim_size; /* its size */
int idx; /* index for bin traversal */
mbinptr bin; /* associated bin */
mchunkptr remainder; /* remainder from a split */
long remainder_size; /* its size */
int remainder_index; /* its bin index */
unsigned long block; /* block traverser bit */
int startidx; /* first bin of a traversed block */
mchunkptr fwd; /* misc temp for linking */
mchunkptr bck; /* misc temp for linking */
mbinptr q; /* misc temp */
INTERNAL_SIZE_T nb;
/* check if mem_malloc_init() was run */
if ((mem_malloc_start == 0) && (mem_malloc_end == 0)) {
/* not initialized yet */
return 0;
}
if ((long)bytes < 0) return 0;
nb = request2size(bytes); /* padded request size; */
/* Check for exact match in a bin */
if (is_small_request(nb)) /* Faster version for small requests */
{
idx = smallbin_index(nb);
/* No traversal or size check necessary for small bins. */
q = bin_at(idx);
victim = last(q);
/* Also scan the next one, since it would have a remainder < MINSIZE */
if (victim == q)
{
q = next_bin(q);
victim = last(q);
}
if (victim != q)
{
victim_size = chunksize(victim);
unlink(victim, bck, fwd);
set_inuse_bit_at_offset(victim, victim_size);
check_malloced_chunk(victim, nb);
return chunk2mem(victim);
}
idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
}
else
{
idx = bin_index(nb);
bin = bin_at(idx);
for (victim = last(bin); victim != bin; victim = victim->bk)
{
victim_size = chunksize(victim);
remainder_size = victim_size - nb;
if (remainder_size >= (long)MINSIZE) /* too big */
{
--idx; /* adjust to rescan below after checking last remainder */
break;
}
else if (remainder_size >= 0) /* exact fit */
{
unlink(victim, bck, fwd);
set_inuse_bit_at_offset(victim, victim_size);
check_malloced_chunk(victim, nb);
return chunk2mem(victim);
}
}
++idx;
}
/* Try to use the last split-off remainder */
if ( (victim = last_remainder->fd) != last_remainder)
{
victim_size = chunksize(victim);
remainder_size = victim_size - nb;
if (remainder_size >= (long)MINSIZE) /* re-split */
{
remainder = chunk_at_offset(victim, nb);
set_head(victim, nb | PREV_INUSE);
link_last_remainder(remainder);
set_head(remainder, remainder_size | PREV_INUSE);
set_foot(remainder, remainder_size);
check_malloced_chunk(victim, nb);
return chunk2mem(victim);
}
clear_last_remainder;
if (remainder_size >= 0) /* exhaust */
{
set_inuse_bit_at_offset(victim, victim_size);
check_malloced_chunk(victim, nb);
return chunk2mem(victim);
}
/* Else place in bin */
frontlink(victim, victim_size, remainder_index, bck, fwd);
}
/*
If there are any possibly nonempty big-enough blocks,
search for best fitting chunk by scanning bins in blockwidth units.
*/
if ( (block = idx2binblock(idx)) <= binblocks_r)
{
/* Get to the first marked block */
if ( (block & binblocks_r) == 0)
{
/* force to an even block boundary */
idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
block <<= 1;
while ((block & binblocks_r) == 0)
{
idx += BINBLOCKWIDTH;
block <<= 1;
}
}
/* For each possibly nonempty block ... */
for (;;)
{
startidx = idx; /* (track incomplete blocks) */
q = bin = bin_at(idx);
/* For each bin in this block ... */
do
{
/* Find and use first big enough chunk ... */
for (victim = last(bin); victim != bin; victim = victim->bk)
{
victim_size = chunksize(victim);
remainder_size = victim_size - nb;
if (remainder_size >= (long)MINSIZE) /* split */
{
remainder = chunk_at_offset(victim, nb);
set_head(victim, nb | PREV_INUSE);
unlink(victim, bck, fwd);
link_last_remainder(remainder);
set_head(remainder, remainder_size | PREV_INUSE);
set_foot(remainder, remainder_size);
check_malloced_chunk(victim, nb);
return chunk2mem(victim);
}
else if (remainder_size >= 0) /* take */
{
set_inuse_bit_at_offset(victim, victim_size);
unlink(victim, bck, fwd);
check_malloced_chunk(victim, nb);
return chunk2mem(victim);
}
}
bin = next_bin(bin);
} while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
/* Clear out the block bit. */
do /* Possibly backtrack to try to clear a partial block */
{
if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
{
av_[1] = (mbinptr)(binblocks_r & ~block);
break;
}
--startidx;
q = prev_bin(q);
} while (first(q) == q);
/* Get to the next possibly nonempty block */
if ( (block <<= 1) <= binblocks_r && (block != 0) )
{
while ((block & binblocks_r) == 0)
{
idx += BINBLOCKWIDTH;
block <<= 1;
}
}
else
break;
}
}
/* Try to use top chunk */
/* Require that there be a remainder, ensuring top always exists */
if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
{
#if HAVE_MMAP
/* If big and would otherwise need to extend, try to use mmap instead */
if ((unsigned long)nb >= (unsigned long)mmap_threshold &&
(victim = mmap_chunk(nb)) != 0)
return chunk2mem(victim);
#endif
/* Try to extend */
malloc_extend_top(nb);
if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
return 0; /* propagate failure */
}
victim = top;
set_head(victim, nb | PREV_INUSE);
top = chunk_at_offset(victim, nb);
set_head(top, remainder_size | PREV_INUSE);
check_malloced_chunk(victim, nb);
return chunk2mem(victim);
}
/*
free() algorithm :
cases:
1. free(0) has no effect.
2. If the chunk was allocated via mmap, it is release via munmap().
3. If a returned chunk borders the current high end of memory,
it is consolidated into the top, and if the total unused
topmost memory exceeds the trim threshold, malloc_trim is
called.
4. Other chunks are consolidated as they arrive, and
placed in corresponding bins. (This includes the case of
consolidating with the current `last_remainder').
*/
#if __STD_C
void fREe(Void_t* mem)
#else
void fREe(mem) Void_t* mem;
#endif
{
mchunkptr p; /* chunk corresponding to mem */
INTERNAL_SIZE_T hd; /* its head field */
INTERNAL_SIZE_T sz; /* its size */
int idx; /* its bin index */
mchunkptr next; /* next contiguous chunk */
INTERNAL_SIZE_T nextsz; /* its size */
INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
mchunkptr bck; /* misc temp for linking */
mchunkptr fwd; /* misc temp for linking */
int islr; /* track whether merging with last_remainder */
if (mem == 0) /* free(0) has no effect */
return;
p = mem2chunk(mem);
hd = p->size;
#if HAVE_MMAP
if (hd & IS_MMAPPED) /* release mmapped memory. */
{
munmap_chunk(p);
return;
}
#endif
check_inuse_chunk(p);
sz = hd & ~PREV_INUSE;
next = chunk_at_offset(p, sz);
nextsz = chunksize(next);
if (next == top) /* merge with top */
{
sz += nextsz;
if (!(hd & PREV_INUSE)) /* consolidate backward */
{
prevsz = p->prev_size;
p = chunk_at_offset(p, -((long) prevsz));
sz += prevsz;
unlink(p, bck, fwd);
}
set_head(p, sz | PREV_INUSE);
top = p;
if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
malloc_trim(top_pad);
return;
}
set_head(next, nextsz); /* clear inuse bit */
islr = 0;
if (!(hd & PREV_INUSE)) /* consolidate backward */
{
prevsz = p->prev_size;
p = chunk_at_offset(p, -((long) prevsz));
sz += prevsz;
if (p->fd == last_remainder) /* keep as last_remainder */
islr = 1;
else
unlink(p, bck, fwd);
}
if (!(inuse_bit_at_offset(next, nextsz))) /* consolidate forward */
{
sz += nextsz;
if (!islr && next->fd == last_remainder) /* re-insert last_remainder */
{
islr = 1;
link_last_remainder(p);
}
else
unlink(next, bck, fwd);
}
set_head(p, sz | PREV_INUSE);
set_foot(p, sz);
if (!islr)
frontlink(p, sz, idx, bck, fwd);
}
/*
Realloc algorithm:
Chunks that were obtained via mmap cannot be extended or shrunk
unless HAVE_MREMAP is defined, in which case mremap is used.
Otherwise, if their reallocation is for additional space, they are
copied. If for less, they are just left alone.
Otherwise, if the reallocation is for additional space, and the
chunk can be extended, it is, else a malloc-copy-free sequence is
taken. There are several different ways that a chunk could be
extended. All are tried:
* Extending forward into following adjacent free chunk.
* Shifting backwards, joining preceding adjacent space
* Both shifting backwards and extending forward.
* Extending into newly sbrked space
Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
size argument of zero (re)allocates a minimum-sized chunk.
If the reallocation is for less space, and the new request is for
a `small' (<512 bytes) size, then the newly unused space is lopped
off and freed.
The old unix realloc convention of allowing the last-free'd chunk
to be used as an argument to realloc is no longer supported.
I don't know of any programs still relying on this feature,
and allowing it would also allow too many other incorrect
usages of realloc to be sensible.
*/
#if __STD_C
Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
#else
Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
#endif
{
INTERNAL_SIZE_T nb; /* padded request size */
mchunkptr oldp; /* chunk corresponding to oldmem */
INTERNAL_SIZE_T oldsize; /* its size */
mchunkptr newp; /* chunk to return */
INTERNAL_SIZE_T newsize; /* its size */
Void_t* newmem; /* corresponding user mem */
mchunkptr next; /* next contiguous chunk after oldp */
INTERNAL_SIZE_T nextsize; /* its size */
mchunkptr prev; /* previous contiguous chunk before oldp */
INTERNAL_SIZE_T prevsize; /* its size */
mchunkptr remainder; /* holds split off extra space from newp */
INTERNAL_SIZE_T remainder_size; /* its size */
mchunkptr bck; /* misc temp for linking */
mchunkptr fwd; /* misc temp for linking */
#ifdef REALLOC_ZERO_BYTES_FREES
if (bytes == 0) { fREe(oldmem); return 0; }
#endif
if ((long)bytes < 0) return 0;
/* realloc of null is supposed to be same as malloc */
if (oldmem == 0) return mALLOc(bytes);
newp = oldp = mem2chunk(oldmem);
newsize = oldsize = chunksize(oldp);
nb = request2size(bytes);
#if HAVE_MMAP
if (chunk_is_mmapped(oldp))
{
#if HAVE_MREMAP
newp = mremap_chunk(oldp, nb);
if(newp) return chunk2mem(newp);
#endif
/* Note the extra SIZE_SZ overhead. */
if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
/* Must alloc, copy, free. */
newmem = mALLOc(bytes);
if (newmem == 0) return 0; /* propagate failure */
MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
munmap_chunk(oldp);
return newmem;
}
#endif
check_inuse_chunk(oldp);
if ((long)(oldsize) < (long)(nb))
{
/* Try expanding forward */
next = chunk_at_offset(oldp, oldsize);
if (next == top || !inuse(next))
{
nextsize = chunksize(next);
/* Forward into top only if a remainder */
if (next == top)
{
if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
{
newsize += nextsize;
top = chunk_at_offset(oldp, nb);
set_head(top, (newsize - nb) | PREV_INUSE);
set_head_size(oldp, nb);
return chunk2mem(oldp);
}
}
/* Forward into next chunk */
else if (((long)(nextsize + newsize) >= (long)(nb)))
{
unlink(next, bck, fwd);
newsize += nextsize;
goto split;
}
}
else
{
next = 0;
nextsize = 0;
}
/* Try shifting backwards. */
if (!prev_inuse(oldp))
{
prev = prev_chunk(oldp);
prevsize = chunksize(prev);
/* try forward + backward first to save a later consolidation */
if (next != 0)
{
/* into top */
if (next == top)
{
if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
{
unlink(prev, bck, fwd);
newp = prev;
newsize += prevsize + nextsize;
newmem = chunk2mem(newp);
MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
top = chunk_at_offset(newp, nb);
set_head(top, (newsize - nb) | PREV_INUSE);
set_head_size(newp, nb);
return newmem;
}
}
/* into next chunk */
else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
{
unlink(next, bck, fwd);
unlink(prev, bck, fwd);
newp = prev;
newsize += nextsize + prevsize;
newmem = chunk2mem(newp);
MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
goto split;
}
}
/* backward only */
if (prev != 0 && (long)(prevsize + newsize) >= (long)nb)
{
unlink(prev, bck, fwd);
newp = prev;
newsize += prevsize;
newmem = chunk2mem(newp);
MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
goto split;
}
}
/* Must allocate */
newmem = mALLOc (bytes);
if (newmem == 0) /* propagate failure */
return 0;
/* Avoid copy if newp is next chunk after oldp. */
/* (This can only happen when new chunk is sbrk'ed.) */
if ( (newp = mem2chunk(newmem)) == next_chunk(oldp))
{
newsize += chunksize(newp);
newp = oldp;
goto split;
}
/* Otherwise copy, free, and exit */
MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
fREe(oldmem);
return newmem;
}
split: /* split off extra room in old or expanded chunk */
if (newsize - nb >= MINSIZE) /* split off remainder */
{
remainder = chunk_at_offset(newp, nb);
remainder_size = newsize - nb;
set_head_size(newp, nb);
set_head(remainder, remainder_size | PREV_INUSE);
set_inuse_bit_at_offset(remainder, remainder_size);
fREe(chunk2mem(remainder)); /* let free() deal with it */
}
else
{
set_head_size(newp, newsize);
set_inuse_bit_at_offset(newp, newsize);
}
check_inuse_chunk(newp);
return chunk2mem(newp);
}
/*
memalign algorithm:
memalign requests more than enough space from malloc, finds a spot
within that chunk that meets the alignment request, and then
possibly frees the leading and trailing space.
The alignment argument must be a power of two. This property is not
checked by memalign, so misuse may result in random runtime errors.
8-byte alignment is guaranteed by normal malloc calls, so don't
bother calling memalign with an argument of 8 or less.
Overreliance on memalign is a sure way to fragment space.
*/
#if __STD_C
Void_t* mEMALIGn(size_t alignment, size_t bytes)
#else
Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
#endif
{
INTERNAL_SIZE_T nb; /* padded request size */
char* m; /* memory returned by malloc call */
mchunkptr p; /* corresponding chunk */
char* brk; /* alignment point within p */
mchunkptr newp; /* chunk to return */
INTERNAL_SIZE_T newsize; /* its size */
INTERNAL_SIZE_T leadsize; /* leading space befor alignment point */
mchunkptr remainder; /* spare room at end to split off */
long remainder_size; /* its size */
if ((long)bytes < 0) return 0;
/* If need less alignment than we give anyway, just relay to malloc */
if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
/* Otherwise, ensure that it is at least a minimum chunk size */
if (alignment < MINSIZE) alignment = MINSIZE;
/* Call malloc with worst case padding to hit alignment. */
nb = request2size(bytes);
m = (char*)(mALLOc(nb + alignment + MINSIZE));
if (m == 0) return 0; /* propagate failure */
p = mem2chunk(m);
if ((((unsigned long)(m)) % alignment) == 0) /* aligned */
{
#if HAVE_MMAP
if(chunk_is_mmapped(p))
return chunk2mem(p); /* nothing more to do */
#endif
}
else /* misaligned */
{
/*
Find an aligned spot inside chunk.
Since we need to give back leading space in a chunk of at
least MINSIZE, if the first calculation places us at
a spot with less than MINSIZE leader, we can move to the
next aligned spot -- we've allocated enough total room so that
this is always possible.
*/
brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & -((signed) alignment));
if ((long)(brk - (char*)(p)) < MINSIZE) brk = brk + alignment;
newp = (mchunkptr)brk;
leadsize = brk - (char*)(p);
newsize = chunksize(p) - leadsize;
#if HAVE_MMAP
if(chunk_is_mmapped(p))
{
newp->prev_size = p->prev_size + leadsize;
set_head(newp, newsize|IS_MMAPPED);
return chunk2mem(newp);
}
#endif
/* give back leader, use the rest */
set_head(newp, newsize | PREV_INUSE);
set_inuse_bit_at_offset(newp, newsize);
set_head_size(p, leadsize);
fREe(chunk2mem(p));
p = newp;
assert (newsize >= nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
}
/* Also give back spare room at the end */
remainder_size = chunksize(p) - nb;
if (remainder_size >= (long)MINSIZE)
{
remainder = chunk_at_offset(p, nb);
set_head(remainder, remainder_size | PREV_INUSE);
set_head_size(p, nb);
fREe(chunk2mem(remainder));
}
check_inuse_chunk(p);
return chunk2mem(p);
}
/*
valloc just invokes memalign with alignment argument equal
to the page size of the system (or as near to this as can
be figured out from all the includes/defines above.)
*/
#if __STD_C
Void_t* vALLOc(size_t bytes)
#else
Void_t* vALLOc(bytes) size_t bytes;
#endif
{
return mEMALIGn (malloc_getpagesize, bytes);
}
/*
pvalloc just invokes valloc for the nearest pagesize
that will accommodate request
*/
#if __STD_C
Void_t* pvALLOc(size_t bytes)
#else
Void_t* pvALLOc(bytes) size_t bytes;
#endif
{
size_t pagesize = malloc_getpagesize;
return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
}
/*
calloc calls malloc, then zeroes out the allocated chunk.
*/
#if __STD_C
Void_t* cALLOc(size_t n, size_t elem_size)
#else
Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
#endif
{
mchunkptr p;
INTERNAL_SIZE_T csz;
INTERNAL_SIZE_T sz = n * elem_size;
/* check if expand_top called, in which case don't need to clear */
#if MORECORE_CLEARS
mchunkptr oldtop = top;
INTERNAL_SIZE_T oldtopsize = chunksize(top);
#endif
Void_t* mem = mALLOc (sz);
if ((long)n < 0) return 0;
if (mem == 0)
return 0;
else
{
p = mem2chunk(mem);
/* Two optional cases in which clearing not necessary */
#if HAVE_MMAP
if (chunk_is_mmapped(p)) return mem;
#endif
csz = chunksize(p);
#if MORECORE_CLEARS
if (p == oldtop && csz > oldtopsize)
{
/* clear only the bytes from non-freshly-sbrked memory */
csz = oldtopsize;
}
#endif
MALLOC_ZERO(mem, csz - SIZE_SZ);
return mem;
}
}
/*
cfree just calls free. It is needed/defined on some systems
that pair it with calloc, presumably for odd historical reasons.
*/
#if !defined(INTERNAL_LINUX_C_LIB) || !defined(__ELF__)
#if __STD_C
void cfree(Void_t *mem)
#else
void cfree(mem) Void_t *mem;
#endif
{
fREe(mem);
}
#endif
/*
Malloc_trim gives memory back to the system (via negative
arguments to sbrk) if there is unused memory at the `high' end of
the malloc pool. You can call this after freeing large blocks of
memory to potentially reduce the system-level memory requirements
of a program. However, it cannot guarantee to reduce memory. Under
some allocation patterns, some large free blocks of memory will be
locked between two used chunks, so they cannot be given back to
the system.
The `pad' argument to malloc_trim represents the amount of free
trailing space to leave untrimmed. If this argument is zero,
only the minimum amount of memory to maintain internal data
structures will be left (one page or less). Non-zero arguments
can be supplied to maintain enough trailing space to service
future expected allocations without having to re-obtain memory
from the system.
Malloc_trim returns 1 if it actually released any memory, else 0.
*/
#if __STD_C
int malloc_trim(size_t pad)
#else
int malloc_trim(pad) size_t pad;
#endif
{
long top_size; /* Amount of top-most memory */
long extra; /* Amount to release */
char* current_brk; /* address returned by pre-check sbrk call */
char* new_brk; /* address returned by negative sbrk call */
unsigned long pagesz = malloc_getpagesize;
top_size = chunksize(top);
extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
if (extra < (long)pagesz) /* Not enough memory to release */
return 0;
else
{
/* Test to make sure no one else called sbrk */
current_brk = (char*)(MORECORE (0));
if (current_brk != (char*)(top) + top_size)
return 0; /* Apparently we don't own memory; must fail */
else
{
new_brk = (char*)(MORECORE (-extra));
if (new_brk == (char*)(MORECORE_FAILURE)) /* sbrk failed? */
{
/* Try to figure out what we have */
current_brk = (char*)(MORECORE (0));
top_size = current_brk - (char*)top;
if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
{
sbrked_mem = current_brk - sbrk_base;
set_head(top, top_size | PREV_INUSE);
}
check_chunk(top);
return 0;
}
else
{
/* Success. Adjust top accordingly. */
set_head(top, (top_size - extra) | PREV_INUSE);
sbrked_mem -= extra;
check_chunk(top);
return 1;
}
}
}
}
/*
malloc_usable_size:
This routine tells you how many bytes you can actually use in an
allocated chunk, which may be more than you requested (although
often not). You can use this many bytes without worrying about
overwriting other allocated objects. Not a particularly great
programming practice, but still sometimes useful.
*/
#if __STD_C
size_t malloc_usable_size(Void_t* mem)
#else
size_t malloc_usable_size(mem) Void_t* mem;
#endif
{
mchunkptr p;
if (mem == 0)
return 0;
else
{
p = mem2chunk(mem);
if(!chunk_is_mmapped(p))
{
if (!inuse(p)) return 0;
check_inuse_chunk(p);
return chunksize(p) - SIZE_SZ;
}
return chunksize(p) - 2*SIZE_SZ;
}
}
/* Utility to update current_mallinfo for malloc_stats and mallinfo() */
#ifdef DEBUG
static void malloc_update_mallinfo()
{
int i;
mbinptr b;
mchunkptr p;
#ifdef DEBUG
mchunkptr q;
#endif
INTERNAL_SIZE_T avail = chunksize(top);
int navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
for (i = 1; i < NAV; ++i)
{
b = bin_at(i);
for (p = last(b); p != b; p = p->bk)
{
#ifdef DEBUG
check_free_chunk(p);
for (q = next_chunk(p);
q < top && inuse(q) && (long)(chunksize(q)) >= (long)MINSIZE;
q = next_chunk(q))
check_inuse_chunk(q);
#endif
avail += chunksize(p);
navail++;
}
}
current_mallinfo.ordblks = navail;
current_mallinfo.uordblks = sbrked_mem - avail;
current_mallinfo.fordblks = avail;
current_mallinfo.hblks = n_mmaps;
current_mallinfo.hblkhd = mmapped_mem;
current_mallinfo.keepcost = chunksize(top);
}
#endif /* DEBUG */
/*
malloc_stats:
Prints on the amount of space obtain from the system (both
via sbrk and mmap), the maximum amount (which may be more than
current if malloc_trim and/or munmap got called), the maximum
number of simultaneous mmap regions used, and the current number
of bytes allocated via malloc (or realloc, etc) but not yet
freed. (Note that this is the number of bytes allocated, not the
number requested. It will be larger than the number requested
because of alignment and bookkeeping overhead.)
*/
#ifdef DEBUG
void malloc_stats()
{
malloc_update_mallinfo();
printf("max system bytes = %10u\n",
(unsigned int)(max_total_mem));
printf("system bytes = %10u\n",
(unsigned int)(sbrked_mem + mmapped_mem));
printf("in use bytes = %10u\n",
(unsigned int)(current_mallinfo.uordblks + mmapped_mem));
#if HAVE_MMAP
printf("max mmap regions = %10u\n",
(unsigned int)max_n_mmaps);
#endif
}
#endif /* DEBUG */
/*
mallinfo returns a copy of updated current mallinfo.
*/
#ifdef DEBUG
struct mallinfo mALLINFo()
{
malloc_update_mallinfo();
return current_mallinfo;
}
#endif /* DEBUG */
/*
mallopt:
mallopt is the general SVID/XPG interface to tunable parameters.
The format is to provide a (parameter-number, parameter-value) pair.
mallopt then sets the corresponding parameter to the argument
value if it can (i.e., so long as the value is meaningful),
and returns 1 if successful else 0.
See descriptions of tunable parameters above.
*/
#if __STD_C
int mALLOPt(int param_number, int value)
#else
int mALLOPt(param_number, value) int param_number; int value;
#endif
{
switch(param_number)
{
case M_TRIM_THRESHOLD:
trim_threshold = value; return 1;
case M_TOP_PAD:
top_pad = value; return 1;
case M_MMAP_THRESHOLD:
mmap_threshold = value; return 1;
case M_MMAP_MAX:
#if HAVE_MMAP
n_mmaps_max = value; return 1;
#else
if (value != 0) return 0; else n_mmaps_max = value; return 1;
#endif
default:
return 0;
}
}
/*
History:
V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
* return null for negative arguments
* Added Several WIN32 cleanups from Martin C. Fong <mcfong@yahoo.com>
* Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
(e.g. WIN32 platforms)
* Cleanup up header file inclusion for WIN32 platforms
* Cleanup code to avoid Microsoft Visual C++ compiler complaints
* Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
memory allocation routines
* Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
* Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
usage of 'assert' in non-WIN32 code
* Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
avoid infinite loop
* Always call 'fREe()' rather than 'free()'
V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
* Fixed ordering problem with boundary-stamping
V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
* Added pvalloc, as recommended by H.J. Liu
* Added 64bit pointer support mainly from Wolfram Gloger
* Added anonymously donated WIN32 sbrk emulation
* Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
* malloc_extend_top: fix mask error that caused wastage after
foreign sbrks
* Add linux mremap support code from HJ Liu
V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
* Integrated most documentation with the code.
* Add support for mmap, with help from
Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
* Use last_remainder in more cases.
* Pack bins using idea from colin@nyx10.cs.du.edu
* Use ordered bins instead of best-fit threshhold
* Eliminate block-local decls to simplify tracing and debugging.
* Support another case of realloc via move into top
* Fix error occuring when initial sbrk_base not word-aligned.
* Rely on page size for units instead of SBRK_UNIT to
avoid surprises about sbrk alignment conventions.
* Add mallinfo, mallopt. Thanks to Raymond Nijssen
(raymond@es.ele.tue.nl) for the suggestion.
* Add `pad' argument to malloc_trim and top_pad mallopt parameter.
* More precautions for cases where other routines call sbrk,
courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
* Added macros etc., allowing use in linux libc from
H.J. Lu (hjl@gnu.ai.mit.edu)
* Inverted this history list
V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
* Re-tuned and fixed to behave more nicely with V2.6.0 changes.
* Removed all preallocation code since under current scheme
the work required to undo bad preallocations exceeds
the work saved in good cases for most test programs.
* No longer use return list or unconsolidated bins since
no scheme using them consistently outperforms those that don't
given above changes.
* Use best fit for very large chunks to prevent some worst-cases.
* Added some support for debugging
V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
* Removed footers when chunks are in use. Thanks to
Paul Wilson (wilson@cs.texas.edu) for the suggestion.
V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
* Added malloc_trim, with help from Wolfram Gloger
(wmglo@Dent.MED.Uni-Muenchen.DE).
V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
* realloc: try to expand in both directions
* malloc: swap order of clean-bin strategy;
* realloc: only conditionally expand backwards
* Try not to scavenge used bins
* Use bin counts as a guide to preallocation
* Occasionally bin return list chunks in first scan
* Add a few optimizations from colin@nyx10.cs.du.edu
V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
* faster bin computation & slightly different binning
* merged all consolidations to one part of malloc proper
(eliminating old malloc_find_space & malloc_clean_bin)
* Scan 2 returns chunks (not just 1)
* Propagate failure in realloc if malloc returns 0
* Add stuff to allow compilation on non-ANSI compilers
from kpv@research.att.com
V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
* removed potential for odd address access in prev_chunk
* removed dependency on getpagesize.h
* misc cosmetics and a bit more internal documentation
* anticosmetics: mangled names in macros to evade debugger strangeness
* tested on sparc, hp-700, dec-mips, rs6000
with gcc & native cc (hp, dec only) allowing
Detlefs & Zorn comparison study (in SIGPLAN Notices.)
Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
* Based loosely on libg++-1.2X malloc. (It retains some of the overall
structure of old version, but most details differ.)
*/
|
1001-study-uboot
|
common/dlmalloc.c
|
C
|
gpl3
| 103,626
|
/*
* Unsorted Block Image commands
*
* Copyright (C) 2008 Samsung Electronics
* Kyungmin Park <kyungmin.park@samsung.com>
*
* Copyright 2008-2009 Stefan Roese <sr@denx.de>, DENX Software Engineering
*
* 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.
*/
#include <common.h>
#include <command.h>
#include <exports.h>
#include <nand.h>
#include <onenand_uboot.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <ubi_uboot.h>
#include <asm/errno.h>
#include <jffs2/load_kernel.h>
#define DEV_TYPE_NONE 0
#define DEV_TYPE_NAND 1
#define DEV_TYPE_ONENAND 2
#define DEV_TYPE_NOR 3
/* Private own data */
static struct ubi_device *ubi;
static char buffer[80];
static int ubi_initialized;
struct selected_dev {
char part_name[80];
int selected;
int nr;
struct mtd_info *mtd_info;
};
static struct selected_dev ubi_dev;
#ifdef CONFIG_CMD_UBIFS
int ubifs_is_mounted(void);
void cmd_ubifs_umount(void);
#endif
static void ubi_dump_vol_info(const struct ubi_volume *vol)
{
ubi_msg("volume information dump:");
ubi_msg("vol_id %d", vol->vol_id);
ubi_msg("reserved_pebs %d", vol->reserved_pebs);
ubi_msg("alignment %d", vol->alignment);
ubi_msg("data_pad %d", vol->data_pad);
ubi_msg("vol_type %d", vol->vol_type);
ubi_msg("name_len %d", vol->name_len);
ubi_msg("usable_leb_size %d", vol->usable_leb_size);
ubi_msg("used_ebs %d", vol->used_ebs);
ubi_msg("used_bytes %lld", vol->used_bytes);
ubi_msg("last_eb_bytes %d", vol->last_eb_bytes);
ubi_msg("corrupted %d", vol->corrupted);
ubi_msg("upd_marker %d", vol->upd_marker);
if (vol->name_len <= UBI_VOL_NAME_MAX &&
strnlen(vol->name, vol->name_len + 1) == vol->name_len) {
ubi_msg("name %s", vol->name);
} else {
ubi_msg("the 1st 5 characters of the name: %c%c%c%c%c",
vol->name[0], vol->name[1], vol->name[2],
vol->name[3], vol->name[4]);
}
printf("\n");
}
static void display_volume_info(struct ubi_device *ubi)
{
int i;
for (i = 0; i < (ubi->vtbl_slots + 1); i++) {
if (!ubi->volumes[i])
continue; /* Empty record */
ubi_dump_vol_info(ubi->volumes[i]);
}
}
static void display_ubi_info(struct ubi_device *ubi)
{
ubi_msg("MTD device name: \"%s\"", ubi->mtd->name);
ubi_msg("MTD device size: %llu MiB", ubi->flash_size >> 20);
ubi_msg("physical eraseblock size: %d bytes (%d KiB)",
ubi->peb_size, ubi->peb_size >> 10);
ubi_msg("logical eraseblock size: %d bytes", ubi->leb_size);
ubi_msg("number of good PEBs: %d", ubi->good_peb_count);
ubi_msg("number of bad PEBs: %d", ubi->bad_peb_count);
ubi_msg("smallest flash I/O unit: %d", ubi->min_io_size);
ubi_msg("VID header offset: %d (aligned %d)",
ubi->vid_hdr_offset, ubi->vid_hdr_aloffset);
ubi_msg("data offset: %d", ubi->leb_start);
ubi_msg("max. allowed volumes: %d", ubi->vtbl_slots);
ubi_msg("wear-leveling threshold: %d", CONFIG_MTD_UBI_WL_THRESHOLD);
ubi_msg("number of internal volumes: %d", UBI_INT_VOL_COUNT);
ubi_msg("number of user volumes: %d",
ubi->vol_count - UBI_INT_VOL_COUNT);
ubi_msg("available PEBs: %d", ubi->avail_pebs);
ubi_msg("total number of reserved PEBs: %d", ubi->rsvd_pebs);
ubi_msg("number of PEBs reserved for bad PEB handling: %d",
ubi->beb_rsvd_pebs);
ubi_msg("max/mean erase counter: %d/%d", ubi->max_ec, ubi->mean_ec);
}
static int ubi_info(int layout)
{
if (layout)
display_volume_info(ubi);
else
display_ubi_info(ubi);
return 0;
}
static int verify_mkvol_req(const struct ubi_device *ubi,
const struct ubi_mkvol_req *req)
{
int n, err = EINVAL;
if (req->bytes < 0 || req->alignment < 0 || req->vol_type < 0 ||
req->name_len < 0)
goto bad;
if ((req->vol_id < 0 || req->vol_id >= ubi->vtbl_slots) &&
req->vol_id != UBI_VOL_NUM_AUTO)
goto bad;
if (req->alignment == 0)
goto bad;
if (req->bytes == 0) {
printf("No space left in UBI device!\n");
err = ENOMEM;
goto bad;
}
if (req->vol_type != UBI_DYNAMIC_VOLUME &&
req->vol_type != UBI_STATIC_VOLUME)
goto bad;
if (req->alignment > ubi->leb_size)
goto bad;
n = req->alignment % ubi->min_io_size;
if (req->alignment != 1 && n)
goto bad;
if (req->name_len > UBI_VOL_NAME_MAX) {
printf("Name too long!\n");
err = ENAMETOOLONG;
goto bad;
}
return 0;
bad:
return err;
}
static int ubi_create_vol(char *volume, int size, int dynamic)
{
struct ubi_mkvol_req req;
int err;
if (dynamic)
req.vol_type = UBI_DYNAMIC_VOLUME;
else
req.vol_type = UBI_STATIC_VOLUME;
req.vol_id = UBI_VOL_NUM_AUTO;
req.alignment = 1;
req.bytes = size;
strcpy(req.name, volume);
req.name_len = strlen(volume);
req.name[req.name_len] = '\0';
req.padding1 = 0;
/* It's duplicated at drivers/mtd/ubi/cdev.c */
err = verify_mkvol_req(ubi, &req);
if (err) {
printf("verify_mkvol_req failed %d\n", err);
return err;
}
printf("Creating %s volume %s of size %d\n",
dynamic ? "dynamic" : "static", volume, size);
/* Call real ubi create volume */
return ubi_create_volume(ubi, &req);
}
static struct ubi_volume *ubi_find_volume(char *volume)
{
struct ubi_volume *vol = NULL;
int i;
for (i = 0; i < ubi->vtbl_slots; i++) {
vol = ubi->volumes[i];
if (vol && !strcmp(vol->name, volume))
return vol;
}
printf("Volume %s not found!\n", volume);
return NULL;
}
static int ubi_remove_vol(char *volume)
{
int err, reserved_pebs, i;
struct ubi_volume *vol;
vol = ubi_find_volume(volume);
if (vol == NULL)
return ENODEV;
printf("Remove UBI volume %s (id %d)\n", vol->name, vol->vol_id);
if (ubi->ro_mode) {
printf("It's read-only mode\n");
err = EROFS;
goto out_err;
}
err = ubi_change_vtbl_record(ubi, vol->vol_id, NULL);
if (err) {
printf("Error changing Vol tabel record err=%x\n", err);
goto out_err;
}
reserved_pebs = vol->reserved_pebs;
for (i = 0; i < vol->reserved_pebs; i++) {
err = ubi_eba_unmap_leb(ubi, vol, i);
if (err)
goto out_err;
}
kfree(vol->eba_tbl);
ubi->volumes[vol->vol_id]->eba_tbl = NULL;
ubi->volumes[vol->vol_id] = NULL;
ubi->rsvd_pebs -= reserved_pebs;
ubi->avail_pebs += reserved_pebs;
i = ubi->beb_rsvd_level - ubi->beb_rsvd_pebs;
if (i > 0) {
i = ubi->avail_pebs >= i ? i : ubi->avail_pebs;
ubi->avail_pebs -= i;
ubi->rsvd_pebs += i;
ubi->beb_rsvd_pebs += i;
if (i > 0)
ubi_msg("reserve more %d PEBs", i);
}
ubi->vol_count -= 1;
return 0;
out_err:
ubi_err("cannot remove volume %s, error %d", volume, err);
if (err < 0)
err = -err;
return err;
}
static int ubi_volume_write(char *volume, void *buf, size_t size)
{
int err = 1;
int rsvd_bytes = 0;
struct ubi_volume *vol;
vol = ubi_find_volume(volume);
if (vol == NULL)
return ENODEV;
rsvd_bytes = vol->reserved_pebs * (ubi->leb_size - vol->data_pad);
if (size < 0 || size > rsvd_bytes) {
printf("size > volume size! Aborting!\n");
return EINVAL;
}
err = ubi_start_update(ubi, vol, size);
if (err < 0) {
printf("Cannot start volume update\n");
return -err;
}
err = ubi_more_update_data(ubi, vol, buf, size);
if (err < 0) {
printf("Couldnt or partially wrote data\n");
return -err;
}
if (err) {
size = err;
err = ubi_check_volume(ubi, vol->vol_id);
if (err < 0)
return -err;
if (err) {
ubi_warn("volume %d on UBI device %d is corrupted",
vol->vol_id, ubi->ubi_num);
vol->corrupted = 1;
}
vol->checked = 1;
ubi_gluebi_updated(vol);
}
printf("%d bytes written to volume %s\n", size, volume);
return 0;
}
static int ubi_volume_read(char *volume, char *buf, size_t size)
{
int err, lnum, off, len, tbuf_size;
void *tbuf;
unsigned long long tmp;
struct ubi_volume *vol;
loff_t offp = 0;
vol = ubi_find_volume(volume);
if (vol == NULL)
return ENODEV;
printf("Read %d bytes from volume %s to %p\n", size, volume, buf);
if (vol->updating) {
printf("updating");
return EBUSY;
}
if (vol->upd_marker) {
printf("damaged volume, update marker is set");
return EBADF;
}
if (offp == vol->used_bytes)
return 0;
if (size == 0) {
printf("No size specified -> Using max size (%lld)\n", vol->used_bytes);
size = vol->used_bytes;
}
if (vol->corrupted)
printf("read from corrupted volume %d", vol->vol_id);
if (offp + size > vol->used_bytes)
size = vol->used_bytes - offp;
tbuf_size = vol->usable_leb_size;
if (size < tbuf_size)
tbuf_size = ALIGN(size, ubi->min_io_size);
tbuf = malloc(tbuf_size);
if (!tbuf) {
printf("NO MEM\n");
return ENOMEM;
}
len = size > tbuf_size ? tbuf_size : size;
tmp = offp;
off = do_div(tmp, vol->usable_leb_size);
lnum = tmp;
do {
if (off + len >= vol->usable_leb_size)
len = vol->usable_leb_size - off;
err = ubi_eba_read_leb(ubi, vol, lnum, tbuf, off, len, 0);
if (err) {
printf("read err %x\n", err);
err = -err;
break;
}
off += len;
if (off == vol->usable_leb_size) {
lnum += 1;
off -= vol->usable_leb_size;
}
size -= len;
offp += len;
memcpy(buf, tbuf, len);
buf += len;
len = size > tbuf_size ? tbuf_size : size;
} while (size);
free(tbuf);
return err;
}
static int ubi_dev_scan(struct mtd_info *info, char *ubidev,
const char *vid_header_offset)
{
struct mtd_device *dev;
struct part_info *part;
struct mtd_partition mtd_part;
char ubi_mtd_param_buffer[80];
u8 pnum;
int err;
if (find_dev_and_part(ubidev, &dev, &pnum, &part) != 0)
return 1;
sprintf(buffer, "mtd=%d", pnum);
memset(&mtd_part, 0, sizeof(mtd_part));
mtd_part.name = buffer;
mtd_part.size = part->size;
mtd_part.offset = part->offset;
add_mtd_partitions(info, &mtd_part, 1);
strcpy(ubi_mtd_param_buffer, buffer);
if (vid_header_offset)
sprintf(ubi_mtd_param_buffer, "mtd=%d,%s", pnum,
vid_header_offset);
err = ubi_mtd_param_parse(ubi_mtd_param_buffer, NULL);
if (err) {
del_mtd_partitions(info);
return -err;
}
err = ubi_init();
if (err) {
del_mtd_partitions(info);
return -err;
}
ubi_initialized = 1;
return 0;
}
static int do_ubi(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
size_t size = 0;
ulong addr = 0;
int err = 0;
if (argc < 2)
return cmd_usage(cmdtp);
if (mtdparts_init() != 0) {
printf("Error initializing mtdparts!\n");
return 1;
}
if (strcmp(argv[1], "part") == 0) {
char mtd_dev[16];
struct mtd_device *dev;
struct part_info *part;
const char *vid_header_offset = NULL;
u8 pnum;
/* Print current partition */
if (argc == 2) {
if (!ubi_dev.selected) {
printf("Error, no UBI device/partition selected!\n");
return 1;
}
printf("Device %d: %s, partition %s\n",
ubi_dev.nr, ubi_dev.mtd_info->name, ubi_dev.part_name);
return 0;
}
if (argc < 3)
return cmd_usage(cmdtp);
#ifdef CONFIG_CMD_UBIFS
/*
* Automatically unmount UBIFS partition when user
* changes the UBI device. Otherwise the following
* UBIFS commands will crash.
*/
if (ubifs_is_mounted())
cmd_ubifs_umount();
#endif
/* todo: get dev number for NAND... */
ubi_dev.nr = 0;
/*
* Call ubi_exit() before re-initializing the UBI subsystem
*/
if (ubi_initialized) {
ubi_exit();
del_mtd_partitions(ubi_dev.mtd_info);
}
/*
* Search the mtd device number where this partition
* is located
*/
if (find_dev_and_part(argv[2], &dev, &pnum, &part)) {
printf("Partition %s not found!\n", argv[2]);
return 1;
}
sprintf(mtd_dev, "%s%d", MTD_DEV_TYPE(dev->id->type), dev->id->num);
ubi_dev.mtd_info = get_mtd_device_nm(mtd_dev);
if (IS_ERR(ubi_dev.mtd_info)) {
printf("Partition %s not found on device %s!\n", argv[2], mtd_dev);
return 1;
}
ubi_dev.selected = 1;
if (argc > 3)
vid_header_offset = argv[3];
strcpy(ubi_dev.part_name, argv[2]);
err = ubi_dev_scan(ubi_dev.mtd_info, ubi_dev.part_name,
vid_header_offset);
if (err) {
printf("UBI init error %d\n", err);
ubi_dev.selected = 0;
return err;
}
ubi = ubi_devices[0];
return 0;
}
if ((strcmp(argv[1], "part") != 0) && (!ubi_dev.selected)) {
printf("Error, no UBI device/partition selected!\n");
return 1;
}
if (strcmp(argv[1], "info") == 0) {
int layout = 0;
if (argc > 2 && !strncmp(argv[2], "l", 1))
layout = 1;
return ubi_info(layout);
}
if (strncmp(argv[1], "create", 6) == 0) {
int dynamic = 1; /* default: dynamic volume */
/* Use maximum available size */
size = 0;
/* E.g., create volume size type */
if (argc == 5) {
if (strncmp(argv[4], "s", 1) == 0)
dynamic = 0;
else if (strncmp(argv[4], "d", 1) != 0) {
printf("Incorrect type\n");
return 1;
}
argc--;
}
/* E.g., create volume size */
if (argc == 4) {
size = simple_strtoul(argv[3], NULL, 16);
argc--;
}
/* Use maximum available size */
if (!size) {
size = ubi->avail_pebs * ubi->leb_size;
printf("No size specified -> Using max size (%u)\n", size);
}
/* E.g., create volume */
if (argc == 3)
return ubi_create_vol(argv[2], size, dynamic);
}
if (strncmp(argv[1], "remove", 6) == 0) {
/* E.g., remove volume */
if (argc == 3)
return ubi_remove_vol(argv[2]);
}
if (strncmp(argv[1], "write", 5) == 0) {
if (argc < 5) {
printf("Please see usage\n");
return 1;
}
addr = simple_strtoul(argv[2], NULL, 16);
size = simple_strtoul(argv[4], NULL, 16);
return ubi_volume_write(argv[3], (void *)addr, size);
}
if (strncmp(argv[1], "read", 4) == 0) {
size = 0;
/* E.g., read volume size */
if (argc == 5) {
size = simple_strtoul(argv[4], NULL, 16);
argc--;
}
/* E.g., read volume */
if (argc == 4) {
addr = simple_strtoul(argv[2], NULL, 16);
argc--;
}
if (argc == 3)
return ubi_volume_read(argv[3], (char *)addr, size);
}
printf("Please see usage\n");
return 1;
}
U_BOOT_CMD(
ubi, 6, 1, do_ubi,
"ubi commands",
"part [part] [offset]\n"
" - Show or set current partition (with optional VID"
" header offset)\n"
"ubi info [l[ayout]]"
" - Display volume and ubi layout information\n"
"ubi create[vol] volume [size] [type]"
" - create volume name with size\n"
"ubi write[vol] address volume size"
" - Write volume from address with size\n"
"ubi read[vol] address volume [size]"
" - Read volume to address with size\n"
"ubi remove[vol] volume"
" - Remove volume\n"
"[Legends]\n"
" volume: character name\n"
" size: specified in bytes\n"
" type: s[tatic] or d[ynamic] (default=dynamic)"
);
|
1001-study-uboot
|
common/cmd_ubi.c
|
C
|
gpl3
| 14,562
|
/*
* (C) Copyright 2004
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <serial.h>
#include <stdio_dev.h>
#include <post.h>
#include <linux/compiler.h>
DECLARE_GLOBAL_DATA_PTR;
static struct serial_device *serial_devices;
static struct serial_device *serial_current;
void serial_register(struct serial_device *dev)
{
#ifdef CONFIG_NEEDS_MANUAL_RELOC
dev->init += gd->reloc_off;
dev->setbrg += gd->reloc_off;
dev->getc += gd->reloc_off;
dev->tstc += gd->reloc_off;
dev->putc += gd->reloc_off;
dev->puts += gd->reloc_off;
#endif
dev->next = serial_devices;
serial_devices = dev;
}
void serial_initialize(void)
{
#if defined(CONFIG_8xx_CONS_SMC1) || defined(CONFIG_8xx_CONS_SMC2)
serial_register(&serial_smc_device);
#endif
#if defined(CONFIG_8xx_CONS_SCC1) || defined(CONFIG_8xx_CONS_SCC2) || \
defined(CONFIG_8xx_CONS_SCC3) || defined(CONFIG_8xx_CONS_SCC4)
serial_register(&serial_scc_device);
#endif
#if defined(CONFIG_SYS_NS16550_SERIAL)
#if defined(CONFIG_SYS_NS16550_COM1)
serial_register(&eserial1_device);
#endif
#if defined(CONFIG_SYS_NS16550_COM2)
serial_register(&eserial2_device);
#endif
#if defined(CONFIG_SYS_NS16550_COM3)
serial_register(&eserial3_device);
#endif
#if defined(CONFIG_SYS_NS16550_COM4)
serial_register(&eserial4_device);
#endif
#endif /* CONFIG_SYS_NS16550_SERIAL */
#if defined(CONFIG_FFUART)
serial_register(&serial_ffuart_device);
#endif
#if defined(CONFIG_BTUART)
serial_register(&serial_btuart_device);
#endif
#if defined(CONFIG_STUART)
serial_register(&serial_stuart_device);
#endif
#if defined(CONFIG_S3C2410)
serial_register(&s3c24xx_serial0_device);
serial_register(&s3c24xx_serial1_device);
serial_register(&s3c24xx_serial2_device);
#endif
#if defined(CONFIG_S5P)
serial_register(&s5p_serial0_device);
serial_register(&s5p_serial1_device);
serial_register(&s5p_serial2_device);
serial_register(&s5p_serial3_device);
#endif
#if defined(CONFIG_MPC512X)
#if defined(CONFIG_SYS_PSC1)
serial_register(&serial1_device);
#endif
#if defined(CONFIG_SYS_PSC3)
serial_register(&serial3_device);
#endif
#if defined(CONFIG_SYS_PSC4)
serial_register(&serial4_device);
#endif
#if defined(CONFIG_SYS_PSC6)
serial_register(&serial6_device);
#endif
#endif
#if defined(CONFIG_SYS_BFIN_UART)
serial_register_bfin_uart();
#endif
#if defined(CONFIG_XILINX_UARTLITE)
# ifdef XILINX_UARTLITE_BASEADDR
serial_register(&uartlite_serial0_device);
# endif /* XILINX_UARTLITE_BASEADDR */
# ifdef XILINX_UARTLITE_BASEADDR1
serial_register(&uartlite_serial1_device);
# endif /* XILINX_UARTLITE_BASEADDR1 */
# ifdef XILINX_UARTLITE_BASEADDR2
serial_register(&uartlite_serial2_device);
# endif /* XILINX_UARTLITE_BASEADDR2 */
# ifdef XILINX_UARTLITE_BASEADDR3
serial_register(&uartlite_serial3_device);
# endif /* XILINX_UARTLITE_BASEADDR3 */
#endif /* CONFIG_XILINX_UARTLITE */
serial_assign(default_serial_console()->name);
}
void serial_stdio_init(void)
{
struct stdio_dev dev;
struct serial_device *s = serial_devices;
while (s) {
memset(&dev, 0, sizeof(dev));
strcpy(dev.name, s->name);
dev.flags = DEV_FLAGS_OUTPUT | DEV_FLAGS_INPUT;
dev.start = s->init;
dev.stop = s->uninit;
dev.putc = s->putc;
dev.puts = s->puts;
dev.getc = s->getc;
dev.tstc = s->tstc;
stdio_register(&dev);
s = s->next;
}
}
int serial_assign(const char *name)
{
struct serial_device *s;
for (s = serial_devices; s; s = s->next) {
if (strcmp(s->name, name) == 0) {
serial_current = s;
return 0;
}
}
return 1;
}
void serial_reinit_all(void)
{
struct serial_device *s;
for (s = serial_devices; s; s = s->next)
s->init();
}
static struct serial_device *get_current(void)
{
struct serial_device *dev;
if (!(gd->flags & GD_FLG_RELOC) || !serial_current) {
dev = default_serial_console();
/* We must have a console device */
if (!dev)
panic("Cannot find console");
} else
dev = serial_current;
return dev;
}
int serial_init(void)
{
return get_current()->init();
}
void serial_setbrg(void)
{
get_current()->setbrg();
}
int serial_getc(void)
{
return get_current()->getc();
}
int serial_tstc(void)
{
return get_current()->tstc();
}
void serial_putc(const char c)
{
get_current()->putc(c);
}
void serial_puts(const char *s)
{
get_current()->puts(s);
}
#if CONFIG_POST & CONFIG_SYS_POST_UART
static const int bauds[] = CONFIG_SYS_BAUDRATE_TABLE;
/* Mark weak until post/cpu/.../uart.c migrate over */
__weak
int uart_post_test(int flags)
{
unsigned char c;
int ret, saved_baud, b;
struct serial_device *saved_dev, *s;
bd_t *bd = gd->bd;
/* Save current serial state */
ret = 0;
saved_dev = serial_current;
saved_baud = bd->bi_baudrate;
for (s = serial_devices; s; s = s->next) {
/* If this driver doesn't support loop back, skip it */
if (!s->loop)
continue;
/* Test the next device */
serial_current = s;
ret = serial_init();
if (ret)
goto done;
/* Consume anything that happens to be queued */
while (serial_tstc())
serial_getc();
/* Enable loop back */
s->loop(1);
/* Test every available baud rate */
for (b = 0; b < ARRAY_SIZE(bauds); ++b) {
bd->bi_baudrate = bauds[b];
serial_setbrg();
/*
* Stick to printable chars to avoid issues:
* - terminal corruption
* - serial program reacting to sequences and sending
* back random extra data
* - most serial drivers add in extra chars (like \r\n)
*/
for (c = 0x20; c < 0x7f; ++c) {
/* Send it out */
serial_putc(c);
/* Make sure it's the same one */
ret = (c != serial_getc());
if (ret) {
s->loop(0);
goto done;
}
/* Clean up the output in case it was sent */
serial_putc('\b');
ret = ('\b' != serial_getc());
if (ret) {
s->loop(0);
goto done;
}
}
}
/* Disable loop back */
s->loop(0);
/* XXX: There is no serial_uninit() !? */
if (s->uninit)
s->uninit();
}
done:
/* Restore previous serial state */
serial_current = saved_dev;
bd->bi_baudrate = saved_baud;
serial_reinit_all();
serial_setbrg();
return ret;
}
#endif
|
1001-study-uboot
|
common/serial.c
|
C
|
gpl3
| 6,890
|
/*
* (C) Copyright 2000, 2001
* Rich Ireland, Enterasys Networks, rireland@enterasys.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
*
*/
/*
* FPGA support
*/
#include <common.h>
#include <command.h>
#if defined(CONFIG_CMD_NET)
#include <net.h>
#endif
#include <fpga.h>
#include <malloc.h>
#if 0
#define FPGA_DEBUG
#endif
#ifdef FPGA_DEBUG
#define PRINTF(fmt,args...) printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif
/* Local functions */
static int fpga_get_op (char *opstr);
/* Local defines */
#define FPGA_NONE -1
#define FPGA_INFO 0
#define FPGA_LOAD 1
#define FPGA_LOADB 2
#define FPGA_DUMP 3
#define FPGA_LOADMK 4
/* Convert bitstream data and load into the fpga */
int fpga_loadbitstream(unsigned long dev, char* fpgadata, size_t size)
{
#if defined(CONFIG_FPGA_XILINX)
unsigned int length;
unsigned int swapsize;
char buffer[80];
unsigned char *dataptr;
unsigned int i;
int rc;
dataptr = (unsigned char *)fpgadata;
/* skip the first bytes of the bitsteam, their meaning is unknown */
length = (*dataptr << 8) + *(dataptr+1);
dataptr+=2;
dataptr+=length;
/* get design name (identifier, length, string) */
length = (*dataptr << 8) + *(dataptr+1);
dataptr+=2;
if (*dataptr++ != 0x61) {
PRINTF ("%s: Design name identifier not recognized in bitstream\n",
__FUNCTION__ );
return FPGA_FAIL;
}
length = (*dataptr << 8) + *(dataptr+1);
dataptr+=2;
for(i=0;i<length;i++)
buffer[i] = *dataptr++;
printf(" design filename = \"%s\"\n", buffer);
/* get part number (identifier, length, string) */
if (*dataptr++ != 0x62) {
printf("%s: Part number identifier not recognized in bitstream\n",
__FUNCTION__ );
return FPGA_FAIL;
}
length = (*dataptr << 8) + *(dataptr+1);
dataptr+=2;
for(i=0;i<length;i++)
buffer[i] = *dataptr++;
printf(" part number = \"%s\"\n", buffer);
/* get date (identifier, length, string) */
if (*dataptr++ != 0x63) {
printf("%s: Date identifier not recognized in bitstream\n",
__FUNCTION__);
return FPGA_FAIL;
}
length = (*dataptr << 8) + *(dataptr+1);
dataptr+=2;
for(i=0;i<length;i++)
buffer[i] = *dataptr++;
printf(" date = \"%s\"\n", buffer);
/* get time (identifier, length, string) */
if (*dataptr++ != 0x64) {
printf("%s: Time identifier not recognized in bitstream\n",__FUNCTION__);
return FPGA_FAIL;
}
length = (*dataptr << 8) + *(dataptr+1);
dataptr+=2;
for(i=0;i<length;i++)
buffer[i] = *dataptr++;
printf(" time = \"%s\"\n", buffer);
/* get fpga data length (identifier, length) */
if (*dataptr++ != 0x65) {
printf("%s: Data length identifier not recognized in bitstream\n",
__FUNCTION__);
return FPGA_FAIL;
}
swapsize = ((unsigned int) *dataptr <<24) +
((unsigned int) *(dataptr+1) <<16) +
((unsigned int) *(dataptr+2) <<8 ) +
((unsigned int) *(dataptr+3) ) ;
dataptr+=4;
printf(" bytes in bitstream = %d\n", swapsize);
rc = fpga_load(dev, dataptr, swapsize);
return rc;
#else
printf("Bitstream support only for Xilinx devices\n");
return FPGA_FAIL;
#endif
}
/* ------------------------------------------------------------------------- */
/* command form:
* fpga <op> <device number> <data addr> <datasize>
* where op is 'load', 'dump', or 'info'
* If there is no device number field, the fpga environment variable is used.
* If there is no data addr field, the fpgadata environment variable is used.
* The info command requires no data address field.
*/
int do_fpga (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
int op, dev = FPGA_INVALID_DEVICE;
size_t data_size = 0;
void *fpga_data = NULL;
char *devstr = getenv ("fpga");
char *datastr = getenv ("fpgadata");
int rc = FPGA_FAIL;
int wrong_parms = 0;
#if defined (CONFIG_FIT)
const char *fit_uname = NULL;
ulong fit_addr;
#endif
if (devstr)
dev = (int) simple_strtoul (devstr, NULL, 16);
if (datastr)
fpga_data = (void *) simple_strtoul (datastr, NULL, 16);
switch (argc) {
case 5: /* fpga <op> <dev> <data> <datasize> */
data_size = simple_strtoul (argv[4], NULL, 16);
case 4: /* fpga <op> <dev> <data> */
#if defined(CONFIG_FIT)
if (fit_parse_subimage (argv[3], (ulong)fpga_data,
&fit_addr, &fit_uname)) {
fpga_data = (void *)fit_addr;
debug ("* fpga: subimage '%s' from FIT image at 0x%08lx\n",
fit_uname, fit_addr);
} else
#endif
{
fpga_data = (void *) simple_strtoul (argv[3], NULL, 16);
debug ("* fpga: cmdline image address = 0x%08lx\n", (ulong)fpga_data);
}
PRINTF ("%s: fpga_data = 0x%x\n", __FUNCTION__, (uint) fpga_data);
case 3: /* fpga <op> <dev | data addr> */
dev = (int) simple_strtoul (argv[2], NULL, 16);
PRINTF ("%s: device = %d\n", __FUNCTION__, dev);
/* FIXME - this is a really weak test */
if ((argc == 3) && (dev > fpga_count ())) { /* must be buffer ptr */
PRINTF ("%s: Assuming buffer pointer in arg 3\n",
__FUNCTION__);
#if defined(CONFIG_FIT)
if (fit_parse_subimage (argv[2], (ulong)fpga_data,
&fit_addr, &fit_uname)) {
fpga_data = (void *)fit_addr;
debug ("* fpga: subimage '%s' from FIT image at 0x%08lx\n",
fit_uname, fit_addr);
} else
#endif
{
fpga_data = (void *) dev;
debug ("* fpga: cmdline image address = 0x%08lx\n", (ulong)fpga_data);
}
PRINTF ("%s: fpga_data = 0x%x\n",
__FUNCTION__, (uint) fpga_data);
dev = FPGA_INVALID_DEVICE; /* reset device num */
}
case 2: /* fpga <op> */
op = (int) fpga_get_op (argv[1]);
break;
default:
PRINTF ("%s: Too many or too few args (%d)\n",
__FUNCTION__, argc);
op = FPGA_NONE; /* force usage display */
break;
}
if (dev == FPGA_INVALID_DEVICE) {
puts("FPGA device not specified\n");
op = FPGA_NONE;
}
switch (op) {
case FPGA_NONE:
case FPGA_INFO:
break;
case FPGA_LOAD:
case FPGA_LOADB:
case FPGA_DUMP:
if (!fpga_data || !data_size)
wrong_parms = 1;
break;
case FPGA_LOADMK:
if (!fpga_data)
wrong_parms = 1;
break;
}
if (wrong_parms) {
puts("Wrong parameters for FPGA request\n");
op = FPGA_NONE;
}
switch (op) {
case FPGA_NONE:
return cmd_usage(cmdtp);
case FPGA_INFO:
rc = fpga_info (dev);
break;
case FPGA_LOAD:
rc = fpga_load (dev, fpga_data, data_size);
break;
case FPGA_LOADB:
rc = fpga_loadbitstream(dev, fpga_data, data_size);
break;
case FPGA_LOADMK:
switch (genimg_get_format (fpga_data)) {
case IMAGE_FORMAT_LEGACY:
{
image_header_t *hdr = (image_header_t *)fpga_data;
ulong data;
data = (ulong)image_get_data (hdr);
data_size = image_get_data_size (hdr);
rc = fpga_load (dev, (void *)data, data_size);
}
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
{
const void *fit_hdr = (const void *)fpga_data;
int noffset;
const void *fit_data;
if (fit_uname == NULL) {
puts ("No FIT subimage unit name\n");
return 1;
}
if (!fit_check_format (fit_hdr)) {
puts ("Bad FIT image format\n");
return 1;
}
/* get fpga component image node offset */
noffset = fit_image_get_node (fit_hdr, fit_uname);
if (noffset < 0) {
printf ("Can't find '%s' FIT subimage\n", fit_uname);
return 1;
}
/* verify integrity */
if (!fit_image_check_hashes (fit_hdr, noffset)) {
puts ("Bad Data Hash\n");
return 1;
}
/* get fpga subimage data address and length */
if (fit_image_get_data (fit_hdr, noffset, &fit_data, &data_size)) {
puts ("Could not find fpga subimage data\n");
return 1;
}
rc = fpga_load (dev, fit_data, data_size);
}
break;
#endif
default:
puts ("** Unknown image type\n");
rc = FPGA_FAIL;
break;
}
break;
case FPGA_DUMP:
rc = fpga_dump (dev, fpga_data, data_size);
break;
default:
printf ("Unknown operation\n");
return cmd_usage(cmdtp);
}
return (rc);
}
/*
* Map op to supported operations. We don't use a table since we
* would just have to relocate it from flash anyway.
*/
static int fpga_get_op (char *opstr)
{
int op = FPGA_NONE;
if (!strcmp ("info", opstr)) {
op = FPGA_INFO;
} else if (!strcmp ("loadb", opstr)) {
op = FPGA_LOADB;
} else if (!strcmp ("load", opstr)) {
op = FPGA_LOAD;
} else if (!strcmp ("loadmk", opstr)) {
op = FPGA_LOADMK;
} else if (!strcmp ("dump", opstr)) {
op = FPGA_DUMP;
}
if (op == FPGA_NONE) {
printf ("Unknown fpga operation \"%s\"\n", opstr);
}
return op;
}
U_BOOT_CMD (fpga, 6, 1, do_fpga,
"loadable FPGA image support",
"[operation type] [device number] [image address] [image size]\n"
"fpga operations:\n"
" dump\t[dev]\t\t\tLoad device to memory buffer\n"
" info\t[dev]\t\t\tlist known device information\n"
" load\t[dev] [address] [size]\tLoad device from memory buffer\n"
" loadb\t[dev] [address] [size]\t"
"Load device from bitstream buffer (Xilinx only)\n"
" loadmk [dev] [address]\tLoad device generated with mkimage"
#if defined(CONFIG_FIT)
"\n"
"\tFor loadmk operating on FIT format uImage address must include\n"
"\tsubimage unit name in the form of addr:<subimg_uname>"
#endif
);
|
1001-study-uboot
|
common/cmd_fpga.c
|
C
|
gpl3
| 9,829
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* Boot support
*/
#include <common.h>
#include <command.h>
#include <net.h>
static int netboot_common(enum proto_t, cmd_tbl_t *, int, char * const []);
int do_bootp (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return netboot_common (BOOTP, cmdtp, argc, argv);
}
U_BOOT_CMD(
bootp, 3, 1, do_bootp,
"boot image via network using BOOTP/TFTP protocol",
"[loadAddress] [[hostIPaddr:]bootfilename]"
);
int do_tftpb (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return netboot_common(TFTPGET, cmdtp, argc, argv);
}
U_BOOT_CMD(
tftpboot, 3, 1, do_tftpb,
"boot image via network using TFTP protocol",
"[loadAddress] [[hostIPaddr:]bootfilename]"
);
#ifdef CONFIG_CMD_TFTPPUT
int do_tftpput(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int ret;
ret = netboot_common(TFTPPUT, cmdtp, argc, argv);
return ret;
}
U_BOOT_CMD(
tftpput, 4, 1, do_tftpput,
"TFTP put command, for uploading files to a server",
"Address Size [[hostIPaddr:]filename]"
);
#endif
#ifdef CONFIG_CMD_TFTPSRV
static int do_tftpsrv(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
{
return netboot_common(TFTPSRV, cmdtp, argc, argv);
}
U_BOOT_CMD(
tftpsrv, 2, 1, do_tftpsrv,
"act as a TFTP server and boot the first received file",
"[loadAddress]\n"
"Listen for an incoming TFTP transfer, receive a file and boot it.\n"
"The transfer is aborted if a transfer has not been started after\n"
"about 50 seconds or if Ctrl-C is pressed."
);
#endif
#ifdef CONFIG_CMD_RARP
int do_rarpb (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return netboot_common (RARP, cmdtp, argc, argv);
}
U_BOOT_CMD(
rarpboot, 3, 1, do_rarpb,
"boot image via network using RARP/TFTP protocol",
"[loadAddress] [[hostIPaddr:]bootfilename]"
);
#endif
#if defined(CONFIG_CMD_DHCP)
int do_dhcp (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return netboot_common(DHCP, cmdtp, argc, argv);
}
U_BOOT_CMD(
dhcp, 3, 1, do_dhcp,
"boot image via network using DHCP/TFTP protocol",
"[loadAddress] [[hostIPaddr:]bootfilename]"
);
#endif
#if defined(CONFIG_CMD_NFS)
int do_nfs (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return netboot_common(NFS, cmdtp, argc, argv);
}
U_BOOT_CMD(
nfs, 3, 1, do_nfs,
"boot image via network using NFS protocol",
"[loadAddress] [[hostIPaddr:]bootfilename]"
);
#endif
static void netboot_update_env (void)
{
char tmp[22];
if (NetOurGatewayIP) {
ip_to_string (NetOurGatewayIP, tmp);
setenv ("gatewayip", tmp);
}
if (NetOurSubnetMask) {
ip_to_string (NetOurSubnetMask, tmp);
setenv ("netmask", tmp);
}
if (NetOurHostName[0])
setenv ("hostname", NetOurHostName);
if (NetOurRootPath[0])
setenv ("rootpath", NetOurRootPath);
if (NetOurIP) {
ip_to_string (NetOurIP, tmp);
setenv ("ipaddr", tmp);
}
if (NetServerIP) {
ip_to_string (NetServerIP, tmp);
setenv ("serverip", tmp);
}
if (NetOurDNSIP) {
ip_to_string (NetOurDNSIP, tmp);
setenv ("dnsip", tmp);
}
#if defined(CONFIG_BOOTP_DNS2)
if (NetOurDNS2IP) {
ip_to_string (NetOurDNS2IP, tmp);
setenv ("dnsip2", tmp);
}
#endif
if (NetOurNISDomain[0])
setenv ("domain", NetOurNISDomain);
#if defined(CONFIG_CMD_SNTP) \
&& defined(CONFIG_BOOTP_TIMEOFFSET)
if (NetTimeOffset) {
sprintf (tmp, "%d", NetTimeOffset);
setenv ("timeoffset", tmp);
}
#endif
#if defined(CONFIG_CMD_SNTP) \
&& defined(CONFIG_BOOTP_NTPSERVER)
if (NetNtpServerIP) {
ip_to_string (NetNtpServerIP, tmp);
setenv ("ntpserverip", tmp);
}
#endif
}
static int netboot_common(enum proto_t proto, cmd_tbl_t *cmdtp, int argc,
char * const argv[])
{
char *s;
char *end;
int rcode = 0;
int size;
ulong addr;
/* pre-set load_addr */
if ((s = getenv("loadaddr")) != NULL) {
load_addr = simple_strtoul(s, NULL, 16);
}
switch (argc) {
case 1:
break;
case 2: /*
* Only one arg - accept two forms:
* Just load address, or just boot file name. The latter
* form must be written in a format which can not be
* mis-interpreted as a valid number.
*/
addr = simple_strtoul(argv[1], &end, 16);
if (end == (argv[1] + strlen(argv[1])))
load_addr = addr;
else
copy_filename(BootFile, argv[1], sizeof(BootFile));
break;
case 3: load_addr = simple_strtoul(argv[1], NULL, 16);
copy_filename (BootFile, argv[2], sizeof(BootFile));
break;
#ifdef CONFIG_CMD_TFTPPUT
case 4:
if (strict_strtoul(argv[1], 16, &save_addr) < 0 ||
strict_strtoul(argv[2], 16, &save_size) < 0) {
printf("Invalid address/size\n");
return cmd_usage(cmdtp);
}
copy_filename(BootFile, argv[3], sizeof(BootFile));
break;
#endif
default:
show_boot_progress (-80);
return cmd_usage(cmdtp);
}
show_boot_progress (80);
if ((size = NetLoop(proto)) < 0) {
show_boot_progress (-81);
return 1;
}
show_boot_progress (81);
/* NetLoop ok, update environment */
netboot_update_env();
/* done if no file was loaded (no errors though) */
if (size == 0) {
show_boot_progress (-82);
return 0;
}
/* flush cache */
flush_cache(load_addr, size);
show_boot_progress(82);
rcode = bootm_maybe_autostart(cmdtp, argv[0]);
if (rcode < 0)
show_boot_progress (-83);
else
show_boot_progress (84);
return rcode;
}
#if defined(CONFIG_CMD_PING)
int do_ping (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc < 2)
return -1;
NetPingIP = string_to_ip(argv[1]);
if (NetPingIP == 0)
return cmd_usage(cmdtp);
if (NetLoop(PING) < 0) {
printf("ping failed; host %s is not alive\n", argv[1]);
return 1;
}
printf("host %s is alive\n", argv[1]);
return 0;
}
U_BOOT_CMD(
ping, 2, 1, do_ping,
"send ICMP ECHO_REQUEST to network host",
"pingAddress"
);
#endif
#if defined(CONFIG_CMD_CDP)
static void cdp_update_env(void)
{
char tmp[16];
if (CDPApplianceVLAN != htons(-1)) {
printf("CDP offered appliance VLAN %d\n", ntohs(CDPApplianceVLAN));
VLAN_to_string(CDPApplianceVLAN, tmp);
setenv("vlan", tmp);
NetOurVLAN = CDPApplianceVLAN;
}
if (CDPNativeVLAN != htons(-1)) {
printf("CDP offered native VLAN %d\n", ntohs(CDPNativeVLAN));
VLAN_to_string(CDPNativeVLAN, tmp);
setenv("nvlan", tmp);
NetOurNativeVLAN = CDPNativeVLAN;
}
}
int do_cdp (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int r;
r = NetLoop(CDP);
if (r < 0) {
printf("cdp failed; perhaps not a CISCO switch?\n");
return 1;
}
cdp_update_env();
return 0;
}
U_BOOT_CMD(
cdp, 1, 1, do_cdp,
"Perform CDP network configuration",
"\n"
);
#endif
#if defined(CONFIG_CMD_SNTP)
int do_sntp (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *toff;
if (argc < 2) {
NetNtpServerIP = getenv_IPaddr ("ntpserverip");
if (NetNtpServerIP == 0) {
printf ("ntpserverip not set\n");
return (1);
}
} else {
NetNtpServerIP = string_to_ip(argv[1]);
if (NetNtpServerIP == 0) {
printf ("Bad NTP server IP address\n");
return (1);
}
}
toff = getenv ("timeoffset");
if (toff == NULL) NetTimeOffset = 0;
else NetTimeOffset = simple_strtol (toff, NULL, 10);
if (NetLoop(SNTP) < 0) {
printf("SNTP failed: host %pI4 not responding\n",
&NetNtpServerIP);
return 1;
}
return 0;
}
U_BOOT_CMD(
sntp, 2, 1, do_sntp,
"synchronize RTC via network",
"[NTP server IP]\n"
);
#endif
#if defined(CONFIG_CMD_DNS)
int do_dns(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc == 1)
return cmd_usage(cmdtp);
/*
* We should check for a valid hostname:
* - Each label must be between 1 and 63 characters long
* - the entire hostname has a maximum of 255 characters
* - only the ASCII letters 'a' through 'z' (case-insensitive),
* the digits '0' through '9', and the hyphen
* - cannot begin or end with a hyphen
* - no other symbols, punctuation characters, or blank spaces are
* permitted
* but hey - this is a minimalist implmentation, so only check length
* and let the name server deal with things.
*/
if (strlen(argv[1]) >= 255) {
printf("dns error: hostname too long\n");
return 1;
}
NetDNSResolve = argv[1];
if (argc == 3)
NetDNSenvvar = argv[2];
else
NetDNSenvvar = NULL;
if (NetLoop(DNS) < 0) {
printf("dns lookup of %s failed, check setup\n", argv[1]);
return 1;
}
return 0;
}
U_BOOT_CMD(
dns, 3, 1, do_dns,
"lookup the IP of a hostname",
"hostname [envvar]"
);
#endif /* CONFIG_CMD_DNS */
|
1001-study-uboot
|
common/cmd_net.c
|
C
|
gpl3
| 9,248
|
/*
* LowLevel function for DataFlash environment support
* Author : Gilles Gastaldi (Atmel)
*
* 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 <environment.h>
#include <linux/stddef.h>
#include <dataflash.h>
#include <search.h>
#include <errno.h>
DECLARE_GLOBAL_DATA_PTR;
env_t *env_ptr;
char *env_name_spec = "dataflash";
uchar env_get_char_spec(int index)
{
uchar c;
read_dataflash(CONFIG_ENV_ADDR + index + offsetof(env_t, data),
1, (char *)&c);
return c;
}
void env_relocate_spec(void)
{
char buf[CONFIG_ENV_SIZE];
read_dataflash(CONFIG_ENV_ADDR, CONFIG_ENV_SIZE, buf);
env_import(buf, 1);
}
#ifdef CONFIG_ENV_OFFSET_REDUND
#error No support for redundant environment on dataflash yet!
#endif
int saveenv(void)
{
env_t env_new;
ssize_t len;
char *res;
res = (char *)&env_new.data;
len = hexport_r(&env_htab, '\0', &res, ENV_SIZE, 0, NULL);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
return 1;
}
env_new.crc = crc32(0, env_new.data, ENV_SIZE);
return write_dataflash(CONFIG_ENV_ADDR,
(unsigned long)&env_new,
CONFIG_ENV_SIZE);
}
/*
* Initialize environment use
*
* We are still running from ROM, so data use is limited.
* Use a (moderately small) buffer on the stack
*/
int env_init(void)
{
ulong crc, len = ENV_SIZE, new = 0;
unsigned off;
uchar buf[64];
if (gd->env_valid)
return 0;
AT91F_DataflashInit(); /* prepare for DATAFLASH read/write */
/* read old CRC */
read_dataflash(CONFIG_ENV_ADDR + offsetof(env_t, crc),
sizeof(ulong), (char *)&crc);
off = offsetof(env_t, data);
while (len > 0) {
int n = (len > sizeof(buf)) ? sizeof(buf) : len;
read_dataflash(CONFIG_ENV_ADDR + off, n, (char *)buf);
new = crc32(new, buf, n);
len -= n;
off += n;
}
if (crc == new) {
gd->env_addr = offsetof(env_t, data);
gd->env_valid = 1;
} else {
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 0;
}
return 0;
}
|
1001-study-uboot
|
common/env_dataflash.c
|
C
|
gpl3
| 2,660
|
/*
* An inteface for configuring a hardware via u-boot environment.
*
* Copyright (c) 2009 MontaVista Software, Inc.
* Copyright 2011 Freescale Semiconductor, Inc.
*
* Author: Anton Vorontsov <avorontsov@ru.mvista.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.
*/
#ifndef HWCONFIG_TEST
#include <config.h>
#include <common.h>
#include <exports.h>
#include <hwconfig.h>
#include <linux/types.h>
#include <linux/string.h>
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define min(a, b) (((a) < (b)) ? (a) : (b))
#endif /* HWCONFIG_TEST */
DECLARE_GLOBAL_DATA_PTR;
static const char *hwconfig_parse(const char *opts, size_t maxlen,
const char *opt, char *stopchs, char eqch,
size_t *arglen)
{
size_t optlen = strlen(opt);
char *str;
const char *start = opts;
const char *end;
next:
str = strstr(opts, opt);
end = str + optlen;
if (end - start > maxlen)
return NULL;
if (str && (str == opts || strpbrk(str - 1, stopchs) == str - 1) &&
(strpbrk(end, stopchs) == end || *end == eqch ||
*end == '\0')) {
const char *arg_end;
if (!arglen)
return str;
if (*end != eqch)
return NULL;
arg_end = strpbrk(str, stopchs);
if (!arg_end)
*arglen = min(maxlen, strlen(str)) - optlen - 1;
else
*arglen = arg_end - end - 1;
return end + 1;
} else if (str) {
opts = end;
goto next;
}
return NULL;
}
const char cpu_hwconfig[] __attribute__((weak)) = "";
const char board_hwconfig[] __attribute__((weak)) = "";
static const char *__hwconfig(const char *opt, size_t *arglen,
const char *env_hwconfig)
{
const char *ret;
/* if we are passed a buffer use it, otherwise try the environment */
if (!env_hwconfig) {
if (!(gd->flags & GD_FLG_ENV_READY)) {
printf("WARNING: Calling __hwconfig without a buffer "
"and before environment is ready\n");
return NULL;
}
env_hwconfig = getenv("hwconfig");
}
if (env_hwconfig) {
ret = hwconfig_parse(env_hwconfig, strlen(env_hwconfig),
opt, ";", ':', arglen);
if (ret)
return ret;
}
ret = hwconfig_parse(board_hwconfig, strlen(board_hwconfig),
opt, ";", ':', arglen);
if (ret)
return ret;
return hwconfig_parse(cpu_hwconfig, strlen(cpu_hwconfig),
opt, ";", ':', arglen);
}
/*
* hwconfig_f - query if a particular hwconfig option is specified
* @opt: a string representing an option
* @buf: if non-NULL use this buffer to parse, otherwise try env
*
* This call can be used to find out whether U-Boot should configure
* a particular hardware option.
*
* Returns non-zero value if the hardware option can be used and thus
* should be configured, 0 otherwise.
*
* This function also returns non-zero value if CONFIG_HWCONFIG is
* undefined.
*
* Returning non-zero value without CONFIG_HWCONFIG has its crucial
* purpose: the hwconfig() call should be a "transparent" interface,
* e.g. if a board doesn't need hwconfig facility, then we assume
* that the board file only calls things that are actually used, so
* hwconfig() will always return true result.
*/
int hwconfig_f(const char *opt, char *buf)
{
return !!__hwconfig(opt, NULL, buf);
}
/*
* hwconfig_arg_f - get hwconfig option's argument
* @opt: a string representing an option
* @arglen: a pointer to an allocated size_t variable
* @buf: if non-NULL use this buffer to parse, otherwise try env
*
* Unlike hwconfig_f() function, this function returns a pointer to the
* start of the hwconfig arguments, if option is not found or it has
* no specified arguments, the function returns NULL pointer.
*
* If CONFIG_HWCONFIG is undefined, the function returns "", and
* arglen is set to 0.
*/
const char *hwconfig_arg_f(const char *opt, size_t *arglen, char *buf)
{
return __hwconfig(opt, arglen, buf);
}
/*
* hwconfig_arg_cmp_f - compare hwconfig option's argument
* @opt: a string representing an option
* @arg: a string for comparing an option's argument
* @buf: if non-NULL use this buffer to parse, otherwise try env
*
* This call is similar to hwconfig_arg_f, but instead of returning
* hwconfig argument and its length, it is comparing it to @arg.
*
* Returns non-zero value if @arg matches, 0 otherwise.
*
* If CONFIG_HWCONFIG is undefined, the function returns a non-zero
* value, i.e. the argument matches.
*/
int hwconfig_arg_cmp_f(const char *opt, const char *arg, char *buf)
{
const char *argstr;
size_t arglen;
argstr = hwconfig_arg_f(opt, &arglen, buf);
if (!argstr || arglen != strlen(arg))
return 0;
return !strncmp(argstr, arg, arglen);
}
/*
* hwconfig_sub_f - query if a particular hwconfig sub-option is specified
* @opt: a string representing an option
* @subopt: a string representing a sub-option
* @buf: if non-NULL use this buffer to parse, otherwise try env
*
* This call is similar to hwconfig_f(), except that it takes additional
* argument @subopt. In this example:
* "dr_usb:mode=peripheral"
* "dr_usb" is an option, "mode" is a sub-option, and "peripheral" is its
* argument.
*/
int hwconfig_sub_f(const char *opt, const char *subopt, char *buf)
{
size_t arglen;
const char *arg;
arg = __hwconfig(opt, &arglen, buf);
if (!arg)
return 0;
return !!hwconfig_parse(arg, arglen, subopt, ",;", '=', NULL);
}
/*
* hwconfig_subarg_f - get hwconfig sub-option's argument
* @opt: a string representing an option
* @subopt: a string representing a sub-option
* @subarglen: a pointer to an allocated size_t variable
* @buf: if non-NULL use this buffer to parse, otherwise try env
*
* This call is similar to hwconfig_arg_f(), except that it takes an
* additional argument @subopt, and so works with sub-options.
*/
const char *hwconfig_subarg_f(const char *opt, const char *subopt,
size_t *subarglen, char *buf)
{
size_t arglen;
const char *arg;
arg = __hwconfig(opt, &arglen, buf);
if (!arg)
return NULL;
return hwconfig_parse(arg, arglen, subopt, ",;", '=', subarglen);
}
/*
* hwconfig_arg_cmp_f - compare hwconfig sub-option's argument
* @opt: a string representing an option
* @subopt: a string representing a sub-option
* @subarg: a string for comparing an sub-option's argument
* @buf: if non-NULL use this buffer to parse, otherwise try env
*
* This call is similar to hwconfig_arg_cmp_f, except that it takes an
* additional argument @subopt, and so works with sub-options.
*/
int hwconfig_subarg_cmp_f(const char *opt, const char *subopt,
const char *subarg, char *buf)
{
const char *argstr;
size_t arglen;
argstr = hwconfig_subarg_f(opt, subopt, &arglen, buf);
if (!argstr || arglen != strlen(subarg))
return 0;
return !strncmp(argstr, subarg, arglen);
}
#ifdef HWCONFIG_TEST
int main()
{
const char *ret;
size_t len;
setenv("hwconfig", "key1:subkey1=value1,subkey2=value2;key2:value3;;;;"
"key3;:,:=;key4", 1);
ret = hwconfig_arg("key1", &len);
printf("%zd %.*s\n", len, (int)len, ret);
assert(len == 29);
assert(hwconfig_arg_cmp("key1", "subkey1=value1,subkey2=value2"));
assert(!strncmp(ret, "subkey1=value1,subkey2=value2", len));
ret = hwconfig_subarg("key1", "subkey1", &len);
printf("%zd %.*s\n", len, (int)len, ret);
assert(len == 6);
assert(hwconfig_subarg_cmp("key1", "subkey1", "value1"));
assert(!strncmp(ret, "value1", len));
ret = hwconfig_subarg("key1", "subkey2", &len);
printf("%zd %.*s\n", len, (int)len, ret);
assert(len == 6);
assert(hwconfig_subarg_cmp("key1", "subkey2", "value2"));
assert(!strncmp(ret, "value2", len));
ret = hwconfig_arg("key2", &len);
printf("%zd %.*s\n", len, (int)len, ret);
assert(len == 6);
assert(hwconfig_arg_cmp("key2", "value3"));
assert(!strncmp(ret, "value3", len));
assert(hwconfig("key3"));
assert(hwconfig_arg("key4", &len) == NULL);
assert(hwconfig_arg("bogus", &len) == NULL);
unsetenv("hwconfig");
assert(hwconfig(NULL) == 0);
assert(hwconfig("") == 0);
assert(hwconfig("key3") == 0);
return 0;
}
#endif /* HWCONFIG_TEST */
|
1001-study-uboot
|
common/hwconfig.c
|
C
|
gpl3
| 8,145
|
/*
* (C) Copyright 2000-2009
* 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
*/
/*
* Command Processor Table
*/
#include <common.h>
#include <command.h>
#include <linux/ctype.h>
/*
* Use puts() instead of printf() to avoid printf buffer overflow
* for long help messages
*/
int _do_help (cmd_tbl_t *cmd_start, int cmd_items, cmd_tbl_t * cmdtp, int
flag, int argc, char * const argv[])
{
int i;
int rcode = 0;
if (argc == 1) { /*show list of commands */
cmd_tbl_t *cmd_array[cmd_items];
int i, j, swaps;
/* Make array of commands from .uboot_cmd section */
cmdtp = cmd_start;
for (i = 0; i < cmd_items; i++) {
cmd_array[i] = cmdtp++;
}
/* Sort command list (trivial bubble sort) */
for (i = cmd_items - 1; i > 0; --i) {
swaps = 0;
for (j = 0; j < i; ++j) {
if (strcmp (cmd_array[j]->name,
cmd_array[j + 1]->name) > 0) {
cmd_tbl_t *tmp;
tmp = cmd_array[j];
cmd_array[j] = cmd_array[j + 1];
cmd_array[j + 1] = tmp;
++swaps;
}
}
if (!swaps)
break;
}
/* print short help (usage) */
for (i = 0; i < cmd_items; i++) {
const char *usage = cmd_array[i]->usage;
/* allow user abort */
if (ctrlc ())
return 1;
if (usage == NULL)
continue;
printf("%-*s- %s\n", CONFIG_SYS_HELP_CMD_WIDTH,
cmd_array[i]->name, usage);
}
return 0;
}
/*
* command help (long version)
*/
for (i = 1; i < argc; ++i) {
if ((cmdtp = find_cmd_tbl (argv[i], cmd_start, cmd_items )) != NULL) {
rcode |= cmd_usage(cmdtp);
} else {
printf ("Unknown command '%s' - try 'help'"
" without arguments for list of all"
" known commands\n\n", argv[i]
);
rcode = 1;
}
}
return rcode;
}
/***************************************************************************
* find command table entry for a command
*/
cmd_tbl_t *find_cmd_tbl (const char *cmd, cmd_tbl_t *table, int table_len)
{
cmd_tbl_t *cmdtp;
cmd_tbl_t *cmdtp_temp = table; /*Init value */
const char *p;
int len;
int n_found = 0;
if (!cmd)
return NULL;
/*
* Some commands allow length modifiers (like "cp.b");
* compare command name only until first dot.
*/
len = ((p = strchr(cmd, '.')) == NULL) ? strlen (cmd) : (p - cmd);
for (cmdtp = table;
cmdtp != table + table_len;
cmdtp++) {
if (strncmp (cmd, cmdtp->name, len) == 0) {
if (len == strlen (cmdtp->name))
return cmdtp; /* full match */
cmdtp_temp = cmdtp; /* abbreviated command ? */
n_found++;
}
}
if (n_found == 1) { /* exactly one match */
return cmdtp_temp;
}
return NULL; /* not found or ambiguous command */
}
cmd_tbl_t *find_cmd (const char *cmd)
{
int len = &__u_boot_cmd_end - &__u_boot_cmd_start;
return find_cmd_tbl(cmd, &__u_boot_cmd_start, len);
}
int cmd_usage(const cmd_tbl_t *cmdtp)
{
printf("%s - %s\n\n", cmdtp->name, cmdtp->usage);
#ifdef CONFIG_SYS_LONGHELP
printf("Usage:\n%s ", cmdtp->name);
if (!cmdtp->help) {
puts ("- No additional help available.\n");
return 1;
}
puts (cmdtp->help);
putc ('\n');
#endif /* CONFIG_SYS_LONGHELP */
return 1;
}
#ifdef CONFIG_AUTO_COMPLETE
int var_complete(int argc, char * const argv[], char last_char, int maxv, char *cmdv[])
{
static char tmp_buf[512];
int space;
space = last_char == '\0' || isblank(last_char);
if (space && argc == 1)
return env_complete("", maxv, cmdv, sizeof(tmp_buf), tmp_buf);
if (!space && argc == 2)
return env_complete(argv[1], maxv, cmdv, sizeof(tmp_buf), tmp_buf);
return 0;
}
/*************************************************************************************/
static int complete_cmdv(int argc, char * const argv[], char last_char, int maxv, char *cmdv[])
{
cmd_tbl_t *cmdtp;
const char *p;
int len, clen;
int n_found = 0;
const char *cmd;
/* sanity? */
if (maxv < 2)
return -2;
cmdv[0] = NULL;
if (argc == 0) {
/* output full list of commands */
for (cmdtp = &__u_boot_cmd_start; cmdtp != &__u_boot_cmd_end; cmdtp++) {
if (n_found >= maxv - 2) {
cmdv[n_found++] = "...";
break;
}
cmdv[n_found++] = cmdtp->name;
}
cmdv[n_found] = NULL;
return n_found;
}
/* more than one arg or one but the start of the next */
if (argc > 1 || (last_char == '\0' || isblank(last_char))) {
cmdtp = find_cmd(argv[0]);
if (cmdtp == NULL || cmdtp->complete == NULL) {
cmdv[0] = NULL;
return 0;
}
return (*cmdtp->complete)(argc, argv, last_char, maxv, cmdv);
}
cmd = argv[0];
/*
* Some commands allow length modifiers (like "cp.b");
* compare command name only until first dot.
*/
p = strchr(cmd, '.');
if (p == NULL)
len = strlen(cmd);
else
len = p - cmd;
/* return the partial matches */
for (cmdtp = &__u_boot_cmd_start; cmdtp != &__u_boot_cmd_end; cmdtp++) {
clen = strlen(cmdtp->name);
if (clen < len)
continue;
if (memcmp(cmd, cmdtp->name, len) != 0)
continue;
/* too many! */
if (n_found >= maxv - 2) {
cmdv[n_found++] = "...";
break;
}
cmdv[n_found++] = cmdtp->name;
}
cmdv[n_found] = NULL;
return n_found;
}
static int make_argv(char *s, int argvsz, char *argv[])
{
int argc = 0;
/* split into argv */
while (argc < argvsz - 1) {
/* skip any white space */
while (isblank(*s))
++s;
if (*s == '\0') /* end of s, no more args */
break;
argv[argc++] = s; /* begin of argument string */
/* find end of string */
while (*s && !isblank(*s))
++s;
if (*s == '\0') /* end of s, no more args */
break;
*s++ = '\0'; /* terminate current arg */
}
argv[argc] = NULL;
return argc;
}
static void print_argv(const char *banner, const char *leader, const char *sep, int linemax, char * const argv[])
{
int ll = leader != NULL ? strlen(leader) : 0;
int sl = sep != NULL ? strlen(sep) : 0;
int len, i;
if (banner) {
puts("\n");
puts(banner);
}
i = linemax; /* force leader and newline */
while (*argv != NULL) {
len = strlen(*argv) + sl;
if (i + len >= linemax) {
puts("\n");
if (leader)
puts(leader);
i = ll - sl;
} else if (sep)
puts(sep);
puts(*argv++);
i += len;
}
printf("\n");
}
static int find_common_prefix(char * const argv[])
{
int i, len;
char *anchor, *s, *t;
if (*argv == NULL)
return 0;
/* begin with max */
anchor = *argv++;
len = strlen(anchor);
while ((t = *argv++) != NULL) {
s = anchor;
for (i = 0; i < len; i++, t++, s++) {
if (*t != *s)
break;
}
len = s - anchor;
}
return len;
}
static char tmp_buf[CONFIG_SYS_CBSIZE]; /* copy of console I/O buffer */
int cmd_auto_complete(const char *const prompt, char *buf, int *np, int *colp)
{
int n = *np, col = *colp;
char *argv[CONFIG_SYS_MAXARGS + 1]; /* NULL terminated */
char *cmdv[20];
char *s, *t;
const char *sep;
int i, j, k, len, seplen, argc;
int cnt;
char last_char;
if (strcmp(prompt, CONFIG_SYS_PROMPT) != 0)
return 0; /* not in normal console */
cnt = strlen(buf);
if (cnt >= 1)
last_char = buf[cnt - 1];
else
last_char = '\0';
/* copy to secondary buffer which will be affected */
strcpy(tmp_buf, buf);
/* separate into argv */
argc = make_argv(tmp_buf, sizeof(argv)/sizeof(argv[0]), argv);
/* do the completion and return the possible completions */
i = complete_cmdv(argc, argv, last_char, sizeof(cmdv)/sizeof(cmdv[0]), cmdv);
/* no match; bell and out */
if (i == 0) {
if (argc > 1) /* allow tab for non command */
return 0;
putc('\a');
return 1;
}
s = NULL;
len = 0;
sep = NULL;
seplen = 0;
if (i == 1) { /* one match; perfect */
k = strlen(argv[argc - 1]);
s = cmdv[0] + k;
len = strlen(s);
sep = " ";
seplen = 1;
} else if (i > 1 && (j = find_common_prefix(cmdv)) != 0) { /* more */
k = strlen(argv[argc - 1]);
j -= k;
if (j > 0) {
s = cmdv[0] + k;
len = j;
}
}
if (s != NULL) {
k = len + seplen;
/* make sure it fits */
if (n + k >= CONFIG_SYS_CBSIZE - 2) {
putc('\a');
return 1;
}
t = buf + cnt;
for (i = 0; i < len; i++)
*t++ = *s++;
if (sep != NULL)
for (i = 0; i < seplen; i++)
*t++ = sep[i];
*t = '\0';
n += k;
col += k;
puts(t - k);
if (sep == NULL)
putc('\a');
*np = n;
*colp = col;
} else {
print_argv(NULL, " ", " ", 78, cmdv);
puts(prompt);
puts(buf);
}
return 1;
}
#endif
#ifdef CMD_DATA_SIZE
int cmd_get_data_size(char* arg, int default_size)
{
/* Check for a size specification .b, .w or .l.
*/
int len = strlen(arg);
if (len > 2 && arg[len-2] == '.') {
switch(arg[len-1]) {
case 'b':
return 1;
case 'w':
return 2;
case 'l':
return 4;
case 's':
return -2;
default:
return -1;
}
}
return default_size;
}
#endif
#if defined(CONFIG_NEEDS_MANUAL_RELOC)
DECLARE_GLOBAL_DATA_PTR;
void fixup_cmdtable(cmd_tbl_t *cmdtp, int size)
{
int i;
if (gd->reloc_off == 0)
return;
for (i = 0; i < size; i++) {
ulong addr;
addr = (ulong) (cmdtp->cmd) + gd->reloc_off;
#if DEBUG_COMMANDS
printf("Command \"%s\": 0x%08lx => 0x%08lx\n",
cmdtp->name, (ulong) (cmdtp->cmd), addr);
#endif
cmdtp->cmd =
(int (*)(struct cmd_tbl_s *, int, int, char * const []))addr;
addr = (ulong)(cmdtp->name) + gd->reloc_off;
cmdtp->name = (char *)addr;
if (cmdtp->usage) {
addr = (ulong)(cmdtp->usage) + gd->reloc_off;
cmdtp->usage = (char *)addr;
}
#ifdef CONFIG_SYS_LONGHELP
if (cmdtp->help) {
addr = (ulong)(cmdtp->help) + gd->reloc_off;
cmdtp->help = (char *)addr;
}
#endif
#ifdef CONFIG_AUTO_COMPLETE
if (cmdtp->complete) {
addr = (ulong)(cmdtp->complete) + gd->reloc_off;
cmdtp->complete =
(int (*)(int, char * const [], char, int, char * []))addr;
}
#endif
cmdtp++;
}
}
#endif
|
1001-study-uboot
|
common/command.c
|
C
|
gpl3
| 10,430
|
/*
* (C) Copyright 2005
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <led-display.h>
#undef DEBUG_DISP
int do_display (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
/* Clear display */
display_set(DISPLAY_CLEAR | DISPLAY_HOME);
if (argc < 2)
return (0);
for (i = 1; i < argc; i++) {
char *p = argv[i];
if (i > 1) { /* Insert a space between strings */
display_putc(' ');
}
while ((*p)) {
#ifdef DEBUG_DISP
putc(*p);
#endif
display_putc(*p++);
}
}
#ifdef DEBUG_DISP
putc('\n');
#endif
return (0);
}
/***************************************************/
U_BOOT_CMD(
display, CONFIG_SYS_MAXARGS, 1, do_display,
"display string on dot matrix display",
"[<string>]\n"
" - with <string> argument: display <string> on dot matrix display\n"
" - without arguments: clear dot matrix display"
);
|
1001-study-uboot
|
common/cmd_display.c
|
C
|
gpl3
| 1,721
|
/*
* (C) Copyright 2009 mGine co.
* unsik Kim <donari75@gmail.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 <command.h>
#include <mg_disk.h>
int do_mg_disk_cmd (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
u32 from, to, size;
switch (argc) {
case 2:
if (!strcmp(argv[1], "init"))
mg_disk_init();
else
return 1;
break;
case 5:
from = simple_strtoul(argv[2], NULL, 0);
to = simple_strtoul(argv[3], NULL, 0);
size = simple_strtoul(argv[4], NULL, 0);
if (!strcmp(argv[1], "read"))
mg_disk_read(from, (u8 *)to, size);
else if (!strcmp(argv[1], "write"))
mg_disk_write(to, (u8 *)from, size);
else if (!strcmp(argv[1], "readsec"))
mg_disk_read_sects((void *)to, from, size);
else if (!strcmp(argv[1], "writesec"))
mg_disk_write_sects((void *)from, to, size);
else
return 1;
break;
default:
return cmd_usage(cmdtp);
}
return 0;
}
U_BOOT_CMD(
mgd, 5, 0, do_mg_disk_cmd,
"mgine m[g]flash command\n",
": mgine mflash IO mode (disk) command\n"
" - initialize : mgd init\n"
" - random read : mgd read [from] [to] [size]\n"
" - random write : mgd write [from] [to] [size]\n"
" - sector read : mgd readsec [sector] [to] [counts]\n"
" - sector write : mgd writesec [from] [sector] [counts]"
);
|
1001-study-uboot
|
common/cmd_mgdisk.c
|
C
|
gpl3
| 2,066
|
/*
* (C) Copyright 2000-2010
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Andreas Heppel <aheppel@sysgo.de>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <environment.h>
#include <linux/stddef.h>
#if defined(CONFIG_I2C_ENV_EEPROM_BUS)
#include <i2c.h>
#endif
#include <search.h>
#include <errno.h>
#include <linux/compiler.h> /* for BUG_ON */
DECLARE_GLOBAL_DATA_PTR;
env_t *env_ptr;
char *env_name_spec = "EEPROM";
int env_eeprom_bus = -1;
static int eeprom_bus_read(unsigned dev_addr, unsigned offset,
uchar *buffer, unsigned cnt)
{
int rcode;
#if defined(CONFIG_I2C_ENV_EEPROM_BUS)
int old_bus = i2c_get_bus_num();
if (gd->flags & GD_FLG_RELOC) {
if (env_eeprom_bus == -1) {
I2C_MUX_DEVICE *dev = NULL;
dev = i2c_mux_ident_muxstring(
(uchar *)CONFIG_I2C_ENV_EEPROM_BUS);
if (dev != NULL)
env_eeprom_bus = dev->busid;
else
printf("error adding env eeprom bus.\n");
}
if (old_bus != env_eeprom_bus) {
i2c_set_bus_num(env_eeprom_bus);
old_bus = env_eeprom_bus;
}
} else {
rcode = i2c_mux_ident_muxstring_f(
(uchar *)CONFIG_I2C_ENV_EEPROM_BUS);
}
#endif
rcode = eeprom_read(dev_addr, offset, buffer, cnt);
#if defined(CONFIG_I2C_ENV_EEPROM_BUS)
if (old_bus != env_eeprom_bus)
i2c_set_bus_num(old_bus);
#endif
return rcode;
}
static int eeprom_bus_write(unsigned dev_addr, unsigned offset,
uchar *buffer, unsigned cnt)
{
int rcode;
#if defined(CONFIG_I2C_ENV_EEPROM_BUS)
int old_bus = i2c_get_bus_num();
rcode = i2c_mux_ident_muxstring_f((uchar *)CONFIG_I2C_ENV_EEPROM_BUS);
#endif
rcode = eeprom_write(dev_addr, offset, buffer, cnt);
#if defined(CONFIG_I2C_ENV_EEPROM_BUS)
i2c_set_bus_num(old_bus);
#endif
return rcode;
}
uchar env_get_char_spec(int index)
{
uchar c;
unsigned int off = CONFIG_ENV_OFFSET;
#ifdef CONFIG_ENV_OFFSET_REDUND
if (gd->env_valid == 2)
off = CONFIG_ENV_OFFSET_REDUND;
#endif
eeprom_bus_read(CONFIG_SYS_DEF_EEPROM_ADDR,
off + index + offsetof(env_t, data), &c, 1);
return c;
}
void env_relocate_spec(void)
{
char buf[CONFIG_ENV_SIZE];
unsigned int off = CONFIG_ENV_OFFSET;
#ifdef CONFIG_ENV_OFFSET_REDUND
if (gd->env_valid == 2)
off = CONFIG_ENV_OFFSET_REDUND;
#endif
eeprom_bus_read(CONFIG_SYS_DEF_EEPROM_ADDR,
off, (uchar *)buf, CONFIG_ENV_SIZE);
env_import(buf, 1);
}
int saveenv(void)
{
env_t env_new;
ssize_t len;
char *res;
int rc;
unsigned int off = CONFIG_ENV_OFFSET;
#ifdef CONFIG_ENV_OFFSET_REDUND
unsigned int off_red = CONFIG_ENV_OFFSET_REDUND;
char flag_obsolete = OBSOLETE_FLAG;
#endif
BUG_ON(env_ptr != NULL);
res = (char *)&env_new.data;
len = hexport_r(&env_htab, '\0', &res, ENV_SIZE, 0, NULL);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
return 1;
}
env_new.crc = crc32(0, env_new.data, ENV_SIZE);
#ifdef CONFIG_ENV_OFFSET_REDUND
if (gd->env_valid == 1) {
off = CONFIG_ENV_OFFSET_REDUND;
off_red = CONFIG_ENV_OFFSET;
}
env_new.flags = ACTIVE_FLAG;
#endif
rc = eeprom_bus_write(CONFIG_SYS_DEF_EEPROM_ADDR,
off, (uchar *)&env_new, CONFIG_ENV_SIZE);
#ifdef CONFIG_ENV_OFFSET_REDUND
if (rc == 0) {
eeprom_bus_write(CONFIG_SYS_DEF_EEPROM_ADDR,
off_red + offsetof(env_t, flags),
(uchar *)&flag_obsolete, 1);
if (gd->env_valid == 1)
gd->env_valid = 2;
else
gd->env_valid = 1;
}
#endif
return rc;
}
/*
* Initialize Environment use
*
* We are still running from ROM, so data use is limited.
* Use a (moderately small) buffer on the stack
*/
#ifdef CONFIG_ENV_OFFSET_REDUND
int env_init(void)
{
ulong len, crc[2], crc_tmp;
unsigned int off, off_env[2];
uchar buf[64], flags[2];
int i, crc_ok[2] = {0, 0};
eeprom_init(); /* prepare for EEPROM read/write */
off_env[0] = CONFIG_ENV_OFFSET;
off_env[1] = CONFIG_ENV_OFFSET_REDUND;
for (i = 0; i < 2; i++) {
/* read CRC */
eeprom_bus_read(CONFIG_SYS_DEF_EEPROM_ADDR,
off_env[i] + offsetof(env_t, crc),
(uchar *)&crc[i], sizeof(ulong));
/* read FLAGS */
eeprom_bus_read(CONFIG_SYS_DEF_EEPROM_ADDR,
off_env[i] + offsetof(env_t, flags),
(uchar *)&flags[i], sizeof(uchar));
crc_tmp = 0;
len = ENV_SIZE;
off = off_env[i] + offsetof(env_t, data);
while (len > 0) {
int n = (len > sizeof(buf)) ? sizeof(buf) : len;
eeprom_bus_read(CONFIG_SYS_DEF_EEPROM_ADDR, off,
buf, n);
crc_tmp = crc32(crc_tmp, buf, n);
len -= n;
off += n;
}
if (crc_tmp == crc[i])
crc_ok[i] = 1;
}
if (!crc_ok[0] && !crc_ok[1]) {
gd->env_addr = 0;
gd->env_valid = 0;
return 0;
} else if (crc_ok[0] && !crc_ok[1]) {
gd->env_valid = 1;
} else if (!crc_ok[0] && crc_ok[1]) {
gd->env_valid = 2;
} else {
/* both ok - check serial */
if (flags[0] == ACTIVE_FLAG && flags[1] == OBSOLETE_FLAG)
gd->env_valid = 1;
else if (flags[0] == OBSOLETE_FLAG && flags[1] == ACTIVE_FLAG)
gd->env_valid = 2;
else if (flags[0] == 0xFF && flags[1] == 0)
gd->env_valid = 2;
else if (flags[1] == 0xFF && flags[0] == 0)
gd->env_valid = 1;
else /* flags are equal - almost impossible */
gd->env_valid = 1;
}
if (gd->env_valid == 2)
gd->env_addr = off_env[1] + offsetof(env_t, data);
else if (gd->env_valid == 1)
gd->env_addr = off_env[0] + offsetof(env_t, data);
return 0;
}
#else
int env_init(void)
{
ulong crc, len, new;
unsigned off;
uchar buf[64];
eeprom_init(); /* prepare for EEPROM read/write */
/* read old CRC */
eeprom_bus_read(CONFIG_SYS_DEF_EEPROM_ADDR,
CONFIG_ENV_OFFSET + offsetof(env_t, crc),
(uchar *)&crc, sizeof(ulong));
new = 0;
len = ENV_SIZE;
off = offsetof(env_t, data);
while (len > 0) {
int n = (len > sizeof(buf)) ? sizeof(buf) : len;
eeprom_bus_read(CONFIG_SYS_DEF_EEPROM_ADDR,
CONFIG_ENV_OFFSET + off, buf, n);
new = crc32(new, buf, n);
len -= n;
off += n;
}
if (crc == new) {
gd->env_addr = offsetof(env_t, data);
gd->env_valid = 1;
} else {
gd->env_addr = 0;
gd->env_valid = 0;
}
return 0;
}
#endif
|
1001-study-uboot
|
common/env_eeprom.c
|
C
|
gpl3
| 6,825
|
/*
* (C) Copyright 2002-2009
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
/* 'inline' - We have to do it fast */
static inline void mdm_readline(char *buf, int bufsiz)
{
char c;
char *p;
int n;
n = 0;
p = buf;
for(;;) {
c = serial_getc();
/* dbg("(%c)", c); */
switch(c) {
case '\r':
break;
case '\n':
*p = '\0';
return;
default:
if(n++ > bufsiz) {
*p = '\0';
return; /* sanity check */
}
*p = c;
p++;
break;
}
}
}
extern void dbg(const char *fmt, ...);
int mdm_init (void)
{
char env_str[16];
char *init_str;
int i;
extern void enable_putc(void);
extern int hwflow_onoff(int);
enable_putc(); /* enable serial_putc() */
#ifdef CONFIG_HWFLOW
init_str = getenv("mdm_flow_control");
if (init_str && (strcmp(init_str, "rts/cts") == 0))
hwflow_onoff (1);
else
hwflow_onoff(-1);
#endif
for (i = 1;;i++) {
sprintf(env_str, "mdm_init%d", i);
if ((init_str = getenv(env_str)) != NULL) {
serial_puts(init_str);
serial_puts("\n");
for(;;) {
mdm_readline(console_buffer, CONFIG_SYS_CBSIZE);
dbg("ini%d: [%s]", i, console_buffer);
if ((strcmp(console_buffer, "OK") == 0) ||
(strcmp(console_buffer, "ERROR") == 0)) {
dbg("ini%d: cmd done", i);
break;
} else /* in case we are originating call ... */
if (strncmp(console_buffer, "CONNECT", 7) == 0) {
dbg("ini%d: connect", i);
return 0;
}
}
} else
break; /* no init string - stop modem init */
udelay(100000);
}
udelay(100000);
/* final stage - wait for connect */
for(;i > 1;) { /* if 'i' > 1 - wait for connection
message from modem */
mdm_readline(console_buffer, CONFIG_SYS_CBSIZE);
dbg("ini_f: [%s]", console_buffer);
if (strncmp(console_buffer, "CONNECT", 7) == 0) {
dbg("ini_f: connected");
return 0;
}
}
return 0;
}
|
1001-study-uboot
|
common/modem.c
|
C
|
gpl3
| 2,677
|
/*
* The builtin symbol table for use with kallsyms
*
* Copyright (c) 2008-2009 Analog Devices Inc.
* Licensed under the GPL-2 or later.
*/
const char const system_map[] = SYSTEM_MAP;
|
1001-study-uboot
|
common/system_map.c
|
C
|
gpl3
| 190
|
/*
* Most of this source has been derived from the Linux USB
* project:
* (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
* (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
* (c) 1999 Michael Gee (michael@linuxspecific.com)
* (c) 2000 Yggdrasil Computing, Inc.
*
*
* Adapted for U-Boot:
* (C) Copyright 2001 Denis Peter, MPL AG Switzerland
*
* For BBB support (C) Copyright 2003
* Gary Jennejohn, DENX Software Engineering <garyj@denx.de>
*
* BBB support based on /sys/dev/usb/umass.c from
* FreeBSD.
*
* 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
*
*/
/* Note:
* Currently only the CBI transport protocoll has been implemented, and it
* is only tested with a TEAC USB Floppy. Other Massstorages with CBI or CB
* transport protocoll may work as well.
*/
/*
* New Note:
* Support for USB Mass Storage Devices (BBB) has been added. It has
* only been tested with USB memory sticks.
*/
#include <common.h>
#include <command.h>
#include <asm/byteorder.h>
#include <asm/processor.h>
#include <part.h>
#include <usb.h>
#undef BBB_COMDAT_TRACE
#undef BBB_XPORT_TRACE
#ifdef USB_STOR_DEBUG
#define USB_BLK_DEBUG 1
#else
#define USB_BLK_DEBUG 0
#endif
#define USB_STOR_PRINTF(fmt, args...) debug_cond(USB_BLK_DEBUG, fmt, ##args)
#include <scsi.h>
/* direction table -- this indicates the direction of the data
* transfer for each command code -- a 1 indicates input
*/
static const unsigned char us_direction[256/8] = {
0x28, 0x81, 0x14, 0x14, 0x20, 0x01, 0x90, 0x77,
0x0C, 0x20, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
#define US_DIRECTION(x) ((us_direction[x>>3] >> (x & 7)) & 1)
static unsigned char usb_stor_buf[512];
static ccb usb_ccb;
/*
* CBI style
*/
#define US_CBI_ADSC 0
/*
* BULK only
*/
#define US_BBB_RESET 0xff
#define US_BBB_GET_MAX_LUN 0xfe
/* Command Block Wrapper */
typedef struct {
__u32 dCBWSignature;
# define CBWSIGNATURE 0x43425355
__u32 dCBWTag;
__u32 dCBWDataTransferLength;
__u8 bCBWFlags;
# define CBWFLAGS_OUT 0x00
# define CBWFLAGS_IN 0x80
__u8 bCBWLUN;
__u8 bCDBLength;
# define CBWCDBLENGTH 16
__u8 CBWCDB[CBWCDBLENGTH];
} umass_bbb_cbw_t;
#define UMASS_BBB_CBW_SIZE 31
static __u32 CBWTag;
/* Command Status Wrapper */
typedef struct {
__u32 dCSWSignature;
# define CSWSIGNATURE 0x53425355
__u32 dCSWTag;
__u32 dCSWDataResidue;
__u8 bCSWStatus;
# define CSWSTATUS_GOOD 0x0
# define CSWSTATUS_FAILED 0x1
# define CSWSTATUS_PHASE 0x2
} umass_bbb_csw_t;
#define UMASS_BBB_CSW_SIZE 13
#define USB_MAX_STOR_DEV 5
static int usb_max_devs; /* number of highest available usb device */
static block_dev_desc_t usb_dev_desc[USB_MAX_STOR_DEV];
struct us_data;
typedef int (*trans_cmnd)(ccb *cb, struct us_data *data);
typedef int (*trans_reset)(struct us_data *data);
struct us_data {
struct usb_device *pusb_dev; /* this usb_device */
unsigned int flags; /* from filter initially */
unsigned char ifnum; /* interface number */
unsigned char ep_in; /* in endpoint */
unsigned char ep_out; /* out ....... */
unsigned char ep_int; /* interrupt . */
unsigned char subclass; /* as in overview */
unsigned char protocol; /* .............. */
unsigned char attention_done; /* force attn on first cmd */
unsigned short ip_data; /* interrupt data */
int action; /* what to do */
int ip_wanted; /* needed */
int *irq_handle; /* for USB int requests */
unsigned int irqpipe; /* pipe for release_irq */
unsigned char irqmaxp; /* max packed for irq Pipe */
unsigned char irqinterval; /* Intervall for IRQ Pipe */
ccb *srb; /* current srb */
trans_reset transport_reset; /* reset routine */
trans_cmnd transport; /* transport routine */
};
static struct us_data usb_stor[USB_MAX_STOR_DEV];
#define USB_STOR_TRANSPORT_GOOD 0
#define USB_STOR_TRANSPORT_FAILED -1
#define USB_STOR_TRANSPORT_ERROR -2
int usb_stor_get_info(struct usb_device *dev, struct us_data *us,
block_dev_desc_t *dev_desc);
int usb_storage_probe(struct usb_device *dev, unsigned int ifnum,
struct us_data *ss);
unsigned long usb_stor_read(int device, unsigned long blknr,
unsigned long blkcnt, void *buffer);
unsigned long usb_stor_write(int device, unsigned long blknr,
unsigned long blkcnt, const void *buffer);
struct usb_device * usb_get_dev_index(int index);
void uhci_show_temp_int_td(void);
#ifdef CONFIG_PARTITIONS
block_dev_desc_t *usb_stor_get_dev(int index)
{
return (index < usb_max_devs) ? &usb_dev_desc[index] : NULL;
}
#endif
void usb_show_progress(void)
{
debug(".");
}
/*******************************************************************************
* show info on storage devices; 'usb start/init' must be invoked earlier
* as we only retrieve structures populated during devices initialization
*/
int usb_stor_info(void)
{
int i;
if (usb_max_devs > 0) {
for (i = 0; i < usb_max_devs; i++) {
printf(" Device %d: ", i);
dev_print(&usb_dev_desc[i]);
}
return 0;
}
printf("No storage devices, perhaps not 'usb start'ed..?\n");
return 1;
}
static unsigned int usb_get_max_lun(struct us_data *us)
{
int len;
unsigned char result;
len = usb_control_msg(us->pusb_dev,
usb_rcvctrlpipe(us->pusb_dev, 0),
US_BBB_GET_MAX_LUN,
USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
0, us->ifnum,
&result, sizeof(result),
USB_CNTL_TIMEOUT * 5);
USB_STOR_PRINTF("Get Max LUN -> len = %i, result = %i\n",
len, (int) result);
return (len > 0) ? result : 0;
}
/*******************************************************************************
* scan the usb and reports device info
* to the user if mode = 1
* returns current device or -1 if no
*/
int usb_stor_scan(int mode)
{
unsigned char i;
struct usb_device *dev;
/* GJ */
memset(usb_stor_buf, 0, sizeof(usb_stor_buf));
if (mode == 1)
printf(" scanning bus for storage devices... ");
usb_disable_asynch(1); /* asynch transfer not allowed */
for (i = 0; i < USB_MAX_STOR_DEV; i++) {
memset(&usb_dev_desc[i], 0, sizeof(block_dev_desc_t));
usb_dev_desc[i].if_type = IF_TYPE_USB;
usb_dev_desc[i].dev = i;
usb_dev_desc[i].part_type = PART_TYPE_UNKNOWN;
usb_dev_desc[i].target = 0xff;
usb_dev_desc[i].type = DEV_TYPE_UNKNOWN;
usb_dev_desc[i].block_read = usb_stor_read;
usb_dev_desc[i].block_write = usb_stor_write;
}
usb_max_devs = 0;
for (i = 0; i < USB_MAX_DEVICE; i++) {
dev = usb_get_dev_index(i); /* get device */
USB_STOR_PRINTF("i=%d\n", i);
if (dev == NULL)
break; /* no more devices available */
if (usb_storage_probe(dev, 0, &usb_stor[usb_max_devs])) {
/* OK, it's a storage device. Iterate over its LUNs
* and populate `usb_dev_desc'.
*/
int lun, max_lun, start = usb_max_devs;
max_lun = usb_get_max_lun(&usb_stor[usb_max_devs]);
for (lun = 0;
lun <= max_lun && usb_max_devs < USB_MAX_STOR_DEV;
lun++) {
usb_dev_desc[usb_max_devs].lun = lun;
if (usb_stor_get_info(dev, &usb_stor[start],
&usb_dev_desc[usb_max_devs]) == 1) {
usb_max_devs++;
}
}
}
/* if storage device */
if (usb_max_devs == USB_MAX_STOR_DEV) {
printf("max USB Storage Device reached: %d stopping\n",
usb_max_devs);
break;
}
} /* for */
usb_disable_asynch(0); /* asynch transfer allowed */
printf("%d Storage Device(s) found\n", usb_max_devs);
if (usb_max_devs > 0)
return 0;
return -1;
}
static int usb_stor_irq(struct usb_device *dev)
{
struct us_data *us;
us = (struct us_data *)dev->privptr;
if (us->ip_wanted)
us->ip_wanted = 0;
return 0;
}
#ifdef USB_STOR_DEBUG
static void usb_show_srb(ccb *pccb)
{
int i;
printf("SRB: len %d datalen 0x%lX\n ", pccb->cmdlen, pccb->datalen);
for (i = 0; i < 12; i++)
printf("%02X ", pccb->cmd[i]);
printf("\n");
}
static void display_int_status(unsigned long tmp)
{
printf("Status: %s %s %s %s %s %s %s\n",
(tmp & USB_ST_ACTIVE) ? "Active" : "",
(tmp & USB_ST_STALLED) ? "Stalled" : "",
(tmp & USB_ST_BUF_ERR) ? "Buffer Error" : "",
(tmp & USB_ST_BABBLE_DET) ? "Babble Det" : "",
(tmp & USB_ST_NAK_REC) ? "NAKed" : "",
(tmp & USB_ST_CRC_ERR) ? "CRC Error" : "",
(tmp & USB_ST_BIT_ERR) ? "Bitstuff Error" : "");
}
#endif
/***********************************************************************
* Data transfer routines
***********************************************************************/
static int us_one_transfer(struct us_data *us, int pipe, char *buf, int length)
{
int max_size;
int this_xfer;
int result;
int partial;
int maxtry;
int stat;
/* determine the maximum packet size for these transfers */
max_size = usb_maxpacket(us->pusb_dev, pipe) * 16;
/* while we have data left to transfer */
while (length) {
/* calculate how long this will be -- maximum or a remainder */
this_xfer = length > max_size ? max_size : length;
length -= this_xfer;
/* setup the retry counter */
maxtry = 10;
/* set up the transfer loop */
do {
/* transfer the data */
USB_STOR_PRINTF("Bulk xfer 0x%x(%d) try #%d\n",
(unsigned int)buf, this_xfer, 11 - maxtry);
result = usb_bulk_msg(us->pusb_dev, pipe, buf,
this_xfer, &partial,
USB_CNTL_TIMEOUT * 5);
USB_STOR_PRINTF("bulk_msg returned %d xferred %d/%d\n",
result, partial, this_xfer);
if (us->pusb_dev->status != 0) {
/* if we stall, we need to clear it before
* we go on
*/
#ifdef USB_STOR_DEBUG
display_int_status(us->pusb_dev->status);
#endif
if (us->pusb_dev->status & USB_ST_STALLED) {
USB_STOR_PRINTF("stalled ->clearing endpoint halt for pipe 0x%x\n", pipe);
stat = us->pusb_dev->status;
usb_clear_halt(us->pusb_dev, pipe);
us->pusb_dev->status = stat;
if (this_xfer == partial) {
USB_STOR_PRINTF("bulk transferred with error %lX, but data ok\n", us->pusb_dev->status);
return 0;
}
else
return result;
}
if (us->pusb_dev->status & USB_ST_NAK_REC) {
USB_STOR_PRINTF("Device NAKed bulk_msg\n");
return result;
}
USB_STOR_PRINTF("bulk transferred with error");
if (this_xfer == partial) {
USB_STOR_PRINTF(" %ld, but data ok\n",
us->pusb_dev->status);
return 0;
}
/* if our try counter reaches 0, bail out */
USB_STOR_PRINTF(" %ld, data %d\n",
us->pusb_dev->status, partial);
if (!maxtry--)
return result;
}
/* update to show what data was transferred */
this_xfer -= partial;
buf += partial;
/* continue until this transfer is done */
} while (this_xfer);
}
/* if we get here, we're done and successful */
return 0;
}
static int usb_stor_BBB_reset(struct us_data *us)
{
int result;
unsigned int pipe;
/*
* Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
*
* For Reset Recovery the host shall issue in the following order:
* a) a Bulk-Only Mass Storage Reset
* b) a Clear Feature HALT to the Bulk-In endpoint
* c) a Clear Feature HALT to the Bulk-Out endpoint
*
* This is done in 3 steps.
*
* If the reset doesn't succeed, the device should be port reset.
*
* This comment stolen from FreeBSD's /sys/dev/usb/umass.c.
*/
USB_STOR_PRINTF("BBB_reset\n");
result = usb_control_msg(us->pusb_dev, usb_sndctrlpipe(us->pusb_dev, 0),
US_BBB_RESET,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, us->ifnum, 0, 0, USB_CNTL_TIMEOUT * 5);
if ((result < 0) && (us->pusb_dev->status & USB_ST_STALLED)) {
USB_STOR_PRINTF("RESET:stall\n");
return -1;
}
/* long wait for reset */
wait_ms(150);
USB_STOR_PRINTF("BBB_reset result %d: status %lX reset\n", result,
us->pusb_dev->status);
pipe = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
result = usb_clear_halt(us->pusb_dev, pipe);
/* long wait for reset */
wait_ms(150);
USB_STOR_PRINTF("BBB_reset result %d: status %lX clearing IN endpoint\n",
result, us->pusb_dev->status);
/* long wait for reset */
pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
result = usb_clear_halt(us->pusb_dev, pipe);
wait_ms(150);
USB_STOR_PRINTF("BBB_reset result %d: status %lX"
" clearing OUT endpoint\n", result,
us->pusb_dev->status);
USB_STOR_PRINTF("BBB_reset done\n");
return 0;
}
/* FIXME: this reset function doesn't really reset the port, and it
* should. Actually it should probably do what it's doing here, and
* reset the port physically
*/
static int usb_stor_CB_reset(struct us_data *us)
{
unsigned char cmd[12];
int result;
USB_STOR_PRINTF("CB_reset\n");
memset(cmd, 0xff, sizeof(cmd));
cmd[0] = SCSI_SEND_DIAG;
cmd[1] = 4;
result = usb_control_msg(us->pusb_dev, usb_sndctrlpipe(us->pusb_dev, 0),
US_CBI_ADSC,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, us->ifnum, cmd, sizeof(cmd),
USB_CNTL_TIMEOUT * 5);
/* long wait for reset */
wait_ms(1500);
USB_STOR_PRINTF("CB_reset result %d: status %lX"
" clearing endpoint halt\n", result,
us->pusb_dev->status);
usb_clear_halt(us->pusb_dev, usb_rcvbulkpipe(us->pusb_dev, us->ep_in));
usb_clear_halt(us->pusb_dev, usb_rcvbulkpipe(us->pusb_dev, us->ep_out));
USB_STOR_PRINTF("CB_reset done\n");
return 0;
}
/*
* Set up the command for a BBB device. Note that the actual SCSI
* command is copied into cbw.CBWCDB.
*/
int usb_stor_BBB_comdat(ccb *srb, struct us_data *us)
{
int result;
int actlen;
int dir_in;
unsigned int pipe;
umass_bbb_cbw_t cbw;
dir_in = US_DIRECTION(srb->cmd[0]);
#ifdef BBB_COMDAT_TRACE
printf("dir %d lun %d cmdlen %d cmd %p datalen %d pdata %p\n",
dir_in, srb->lun, srb->cmdlen, srb->cmd, srb->datalen,
srb->pdata);
if (srb->cmdlen) {
for (result = 0; result < srb->cmdlen; result++)
printf("cmd[%d] %#x ", result, srb->cmd[result]);
printf("\n");
}
#endif
/* sanity checks */
if (!(srb->cmdlen <= CBWCDBLENGTH)) {
USB_STOR_PRINTF("usb_stor_BBB_comdat:cmdlen too large\n");
return -1;
}
/* always OUT to the ep */
pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
cbw.dCBWSignature = cpu_to_le32(CBWSIGNATURE);
cbw.dCBWTag = cpu_to_le32(CBWTag++);
cbw.dCBWDataTransferLength = cpu_to_le32(srb->datalen);
cbw.bCBWFlags = (dir_in ? CBWFLAGS_IN : CBWFLAGS_OUT);
cbw.bCBWLUN = srb->lun;
cbw.bCDBLength = srb->cmdlen;
/* copy the command data into the CBW command data buffer */
/* DST SRC LEN!!! */
memcpy(cbw.CBWCDB, srb->cmd, srb->cmdlen);
result = usb_bulk_msg(us->pusb_dev, pipe, &cbw, UMASS_BBB_CBW_SIZE,
&actlen, USB_CNTL_TIMEOUT * 5);
if (result < 0)
USB_STOR_PRINTF("usb_stor_BBB_comdat:usb_bulk_msg error\n");
return result;
}
/* FIXME: we also need a CBI_command which sets up the completion
* interrupt, and waits for it
*/
int usb_stor_CB_comdat(ccb *srb, struct us_data *us)
{
int result = 0;
int dir_in, retry;
unsigned int pipe;
unsigned long status;
retry = 5;
dir_in = US_DIRECTION(srb->cmd[0]);
if (dir_in)
pipe = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
else
pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
while (retry--) {
USB_STOR_PRINTF("CBI gets a command: Try %d\n", 5 - retry);
#ifdef USB_STOR_DEBUG
usb_show_srb(srb);
#endif
/* let's send the command via the control pipe */
result = usb_control_msg(us->pusb_dev,
usb_sndctrlpipe(us->pusb_dev , 0),
US_CBI_ADSC,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, us->ifnum,
srb->cmd, srb->cmdlen,
USB_CNTL_TIMEOUT * 5);
USB_STOR_PRINTF("CB_transport: control msg returned %d,"
" status %lX\n", result, us->pusb_dev->status);
/* check the return code for the command */
if (result < 0) {
if (us->pusb_dev->status & USB_ST_STALLED) {
status = us->pusb_dev->status;
USB_STOR_PRINTF(" stall during command found,"
" clear pipe\n");
usb_clear_halt(us->pusb_dev,
usb_sndctrlpipe(us->pusb_dev, 0));
us->pusb_dev->status = status;
}
USB_STOR_PRINTF(" error during command %02X"
" Stat = %lX\n", srb->cmd[0],
us->pusb_dev->status);
return result;
}
/* transfer the data payload for this command, if one exists*/
USB_STOR_PRINTF("CB_transport: control msg returned %d,"
" direction is %s to go 0x%lx\n", result,
dir_in ? "IN" : "OUT", srb->datalen);
if (srb->datalen) {
result = us_one_transfer(us, pipe, (char *)srb->pdata,
srb->datalen);
USB_STOR_PRINTF("CBI attempted to transfer data,"
" result is %d status %lX, len %d\n",
result, us->pusb_dev->status,
us->pusb_dev->act_len);
if (!(us->pusb_dev->status & USB_ST_NAK_REC))
break;
} /* if (srb->datalen) */
else
break;
}
/* return result */
return result;
}
int usb_stor_CBI_get_status(ccb *srb, struct us_data *us)
{
int timeout;
us->ip_wanted = 1;
submit_int_msg(us->pusb_dev, us->irqpipe,
(void *) &us->ip_data, us->irqmaxp, us->irqinterval);
timeout = 1000;
while (timeout--) {
if ((volatile int *) us->ip_wanted == 0)
break;
wait_ms(10);
}
if (us->ip_wanted) {
printf(" Did not get interrupt on CBI\n");
us->ip_wanted = 0;
return USB_STOR_TRANSPORT_ERROR;
}
USB_STOR_PRINTF
("Got interrupt data 0x%x, transfered %d status 0x%lX\n",
us->ip_data, us->pusb_dev->irq_act_len,
us->pusb_dev->irq_status);
/* UFI gives us ASC and ASCQ, like a request sense */
if (us->subclass == US_SC_UFI) {
if (srb->cmd[0] == SCSI_REQ_SENSE ||
srb->cmd[0] == SCSI_INQUIRY)
return USB_STOR_TRANSPORT_GOOD; /* Good */
else if (us->ip_data)
return USB_STOR_TRANSPORT_FAILED;
else
return USB_STOR_TRANSPORT_GOOD;
}
/* otherwise, we interpret the data normally */
switch (us->ip_data) {
case 0x0001:
return USB_STOR_TRANSPORT_GOOD;
case 0x0002:
return USB_STOR_TRANSPORT_FAILED;
default:
return USB_STOR_TRANSPORT_ERROR;
} /* switch */
return USB_STOR_TRANSPORT_ERROR;
}
#define USB_TRANSPORT_UNKNOWN_RETRY 5
#define USB_TRANSPORT_NOT_READY_RETRY 10
/* clear a stall on an endpoint - special for BBB devices */
int usb_stor_BBB_clear_endpt_stall(struct us_data *us, __u8 endpt)
{
int result;
/* ENDPOINT_HALT = 0, so set value to 0 */
result = usb_control_msg(us->pusb_dev, usb_sndctrlpipe(us->pusb_dev, 0),
USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
0, endpt, 0, 0, USB_CNTL_TIMEOUT * 5);
return result;
}
int usb_stor_BBB_transport(ccb *srb, struct us_data *us)
{
int result, retry;
int dir_in;
int actlen, data_actlen;
unsigned int pipe, pipein, pipeout;
umass_bbb_csw_t csw;
#ifdef BBB_XPORT_TRACE
unsigned char *ptr;
int index;
#endif
dir_in = US_DIRECTION(srb->cmd[0]);
/* COMMAND phase */
USB_STOR_PRINTF("COMMAND phase\n");
result = usb_stor_BBB_comdat(srb, us);
if (result < 0) {
USB_STOR_PRINTF("failed to send CBW status %ld\n",
us->pusb_dev->status);
usb_stor_BBB_reset(us);
return USB_STOR_TRANSPORT_FAILED;
}
wait_ms(5);
pipein = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
pipeout = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
/* DATA phase + error handling */
data_actlen = 0;
/* no data, go immediately to the STATUS phase */
if (srb->datalen == 0)
goto st;
USB_STOR_PRINTF("DATA phase\n");
if (dir_in)
pipe = pipein;
else
pipe = pipeout;
result = usb_bulk_msg(us->pusb_dev, pipe, srb->pdata, srb->datalen,
&data_actlen, USB_CNTL_TIMEOUT * 5);
/* special handling of STALL in DATA phase */
if ((result < 0) && (us->pusb_dev->status & USB_ST_STALLED)) {
USB_STOR_PRINTF("DATA:stall\n");
/* clear the STALL on the endpoint */
result = usb_stor_BBB_clear_endpt_stall(us,
dir_in ? us->ep_in : us->ep_out);
if (result >= 0)
/* continue on to STATUS phase */
goto st;
}
if (result < 0) {
USB_STOR_PRINTF("usb_bulk_msg error status %ld\n",
us->pusb_dev->status);
usb_stor_BBB_reset(us);
return USB_STOR_TRANSPORT_FAILED;
}
#ifdef BBB_XPORT_TRACE
for (index = 0; index < data_actlen; index++)
printf("pdata[%d] %#x ", index, srb->pdata[index]);
printf("\n");
#endif
/* STATUS phase + error handling */
st:
retry = 0;
again:
USB_STOR_PRINTF("STATUS phase\n");
result = usb_bulk_msg(us->pusb_dev, pipein, &csw, UMASS_BBB_CSW_SIZE,
&actlen, USB_CNTL_TIMEOUT*5);
/* special handling of STALL in STATUS phase */
if ((result < 0) && (retry < 1) &&
(us->pusb_dev->status & USB_ST_STALLED)) {
USB_STOR_PRINTF("STATUS:stall\n");
/* clear the STALL on the endpoint */
result = usb_stor_BBB_clear_endpt_stall(us, us->ep_in);
if (result >= 0 && (retry++ < 1))
/* do a retry */
goto again;
}
if (result < 0) {
USB_STOR_PRINTF("usb_bulk_msg error status %ld\n",
us->pusb_dev->status);
usb_stor_BBB_reset(us);
return USB_STOR_TRANSPORT_FAILED;
}
#ifdef BBB_XPORT_TRACE
ptr = (unsigned char *)&csw;
for (index = 0; index < UMASS_BBB_CSW_SIZE; index++)
printf("ptr[%d] %#x ", index, ptr[index]);
printf("\n");
#endif
/* misuse pipe to get the residue */
pipe = le32_to_cpu(csw.dCSWDataResidue);
if (pipe == 0 && srb->datalen != 0 && srb->datalen - data_actlen != 0)
pipe = srb->datalen - data_actlen;
if (CSWSIGNATURE != le32_to_cpu(csw.dCSWSignature)) {
USB_STOR_PRINTF("!CSWSIGNATURE\n");
usb_stor_BBB_reset(us);
return USB_STOR_TRANSPORT_FAILED;
} else if ((CBWTag - 1) != le32_to_cpu(csw.dCSWTag)) {
USB_STOR_PRINTF("!Tag\n");
usb_stor_BBB_reset(us);
return USB_STOR_TRANSPORT_FAILED;
} else if (csw.bCSWStatus > CSWSTATUS_PHASE) {
USB_STOR_PRINTF(">PHASE\n");
usb_stor_BBB_reset(us);
return USB_STOR_TRANSPORT_FAILED;
} else if (csw.bCSWStatus == CSWSTATUS_PHASE) {
USB_STOR_PRINTF("=PHASE\n");
usb_stor_BBB_reset(us);
return USB_STOR_TRANSPORT_FAILED;
} else if (data_actlen > srb->datalen) {
USB_STOR_PRINTF("transferred %dB instead of %ldB\n",
data_actlen, srb->datalen);
return USB_STOR_TRANSPORT_FAILED;
} else if (csw.bCSWStatus == CSWSTATUS_FAILED) {
USB_STOR_PRINTF("FAILED\n");
return USB_STOR_TRANSPORT_FAILED;
}
return result;
}
int usb_stor_CB_transport(ccb *srb, struct us_data *us)
{
int result, status;
ccb *psrb;
ccb reqsrb;
int retry, notready;
psrb = &reqsrb;
status = USB_STOR_TRANSPORT_GOOD;
retry = 0;
notready = 0;
/* issue the command */
do_retry:
result = usb_stor_CB_comdat(srb, us);
USB_STOR_PRINTF("command / Data returned %d, status %lX\n",
result, us->pusb_dev->status);
/* if this is an CBI Protocol, get IRQ */
if (us->protocol == US_PR_CBI) {
status = usb_stor_CBI_get_status(srb, us);
/* if the status is error, report it */
if (status == USB_STOR_TRANSPORT_ERROR) {
USB_STOR_PRINTF(" USB CBI Command Error\n");
return status;
}
srb->sense_buf[12] = (unsigned char)(us->ip_data >> 8);
srb->sense_buf[13] = (unsigned char)(us->ip_data & 0xff);
if (!us->ip_data) {
/* if the status is good, report it */
if (status == USB_STOR_TRANSPORT_GOOD) {
USB_STOR_PRINTF(" USB CBI Command Good\n");
return status;
}
}
}
/* do we have to issue an auto request? */
/* HERE we have to check the result */
if ((result < 0) && !(us->pusb_dev->status & USB_ST_STALLED)) {
USB_STOR_PRINTF("ERROR %lX\n", us->pusb_dev->status);
us->transport_reset(us);
return USB_STOR_TRANSPORT_ERROR;
}
if ((us->protocol == US_PR_CBI) &&
((srb->cmd[0] == SCSI_REQ_SENSE) ||
(srb->cmd[0] == SCSI_INQUIRY))) {
/* do not issue an autorequest after request sense */
USB_STOR_PRINTF("No auto request and good\n");
return USB_STOR_TRANSPORT_GOOD;
}
/* issue an request_sense */
memset(&psrb->cmd[0], 0, 12);
psrb->cmd[0] = SCSI_REQ_SENSE;
psrb->cmd[1] = srb->lun << 5;
psrb->cmd[4] = 18;
psrb->datalen = 18;
psrb->pdata = &srb->sense_buf[0];
psrb->cmdlen = 12;
/* issue the command */
result = usb_stor_CB_comdat(psrb, us);
USB_STOR_PRINTF("auto request returned %d\n", result);
/* if this is an CBI Protocol, get IRQ */
if (us->protocol == US_PR_CBI)
status = usb_stor_CBI_get_status(psrb, us);
if ((result < 0) && !(us->pusb_dev->status & USB_ST_STALLED)) {
USB_STOR_PRINTF(" AUTO REQUEST ERROR %ld\n",
us->pusb_dev->status);
return USB_STOR_TRANSPORT_ERROR;
}
USB_STOR_PRINTF("autorequest returned 0x%02X 0x%02X 0x%02X 0x%02X\n",
srb->sense_buf[0], srb->sense_buf[2],
srb->sense_buf[12], srb->sense_buf[13]);
/* Check the auto request result */
if ((srb->sense_buf[2] == 0) &&
(srb->sense_buf[12] == 0) &&
(srb->sense_buf[13] == 0)) {
/* ok, no sense */
return USB_STOR_TRANSPORT_GOOD;
}
/* Check the auto request result */
switch (srb->sense_buf[2]) {
case 0x01:
/* Recovered Error */
return USB_STOR_TRANSPORT_GOOD;
break;
case 0x02:
/* Not Ready */
if (notready++ > USB_TRANSPORT_NOT_READY_RETRY) {
printf("cmd 0x%02X returned 0x%02X 0x%02X 0x%02X"
" 0x%02X (NOT READY)\n", srb->cmd[0],
srb->sense_buf[0], srb->sense_buf[2],
srb->sense_buf[12], srb->sense_buf[13]);
return USB_STOR_TRANSPORT_FAILED;
} else {
wait_ms(100);
goto do_retry;
}
break;
default:
if (retry++ > USB_TRANSPORT_UNKNOWN_RETRY) {
printf("cmd 0x%02X returned 0x%02X 0x%02X 0x%02X"
" 0x%02X\n", srb->cmd[0], srb->sense_buf[0],
srb->sense_buf[2], srb->sense_buf[12],
srb->sense_buf[13]);
return USB_STOR_TRANSPORT_FAILED;
} else
goto do_retry;
break;
}
return USB_STOR_TRANSPORT_FAILED;
}
static int usb_inquiry(ccb *srb, struct us_data *ss)
{
int retry, i;
retry = 5;
do {
memset(&srb->cmd[0], 0, 12);
srb->cmd[0] = SCSI_INQUIRY;
srb->cmd[1] = srb->lun << 5;
srb->cmd[4] = 36;
srb->datalen = 36;
srb->cmdlen = 12;
i = ss->transport(srb, ss);
USB_STOR_PRINTF("inquiry returns %d\n", i);
if (i == 0)
break;
} while (--retry);
if (!retry) {
printf("error in inquiry\n");
return -1;
}
return 0;
}
static int usb_request_sense(ccb *srb, struct us_data *ss)
{
char *ptr;
ptr = (char *)srb->pdata;
memset(&srb->cmd[0], 0, 12);
srb->cmd[0] = SCSI_REQ_SENSE;
srb->cmd[1] = srb->lun << 5;
srb->cmd[4] = 18;
srb->datalen = 18;
srb->pdata = &srb->sense_buf[0];
srb->cmdlen = 12;
ss->transport(srb, ss);
USB_STOR_PRINTF("Request Sense returned %02X %02X %02X\n",
srb->sense_buf[2], srb->sense_buf[12],
srb->sense_buf[13]);
srb->pdata = (uchar *)ptr;
return 0;
}
static int usb_test_unit_ready(ccb *srb, struct us_data *ss)
{
int retries = 10;
do {
memset(&srb->cmd[0], 0, 12);
srb->cmd[0] = SCSI_TST_U_RDY;
srb->cmd[1] = srb->lun << 5;
srb->datalen = 0;
srb->cmdlen = 12;
if (ss->transport(srb, ss) == USB_STOR_TRANSPORT_GOOD)
return 0;
usb_request_sense(srb, ss);
wait_ms(100);
} while (retries--);
return -1;
}
static int usb_read_capacity(ccb *srb, struct us_data *ss)
{
int retry;
/* XXX retries */
retry = 3;
do {
memset(&srb->cmd[0], 0, 12);
srb->cmd[0] = SCSI_RD_CAPAC;
srb->cmd[1] = srb->lun << 5;
srb->datalen = 8;
srb->cmdlen = 12;
if (ss->transport(srb, ss) == USB_STOR_TRANSPORT_GOOD)
return 0;
} while (retry--);
return -1;
}
static int usb_read_10(ccb *srb, struct us_data *ss, unsigned long start,
unsigned short blocks)
{
memset(&srb->cmd[0], 0, 12);
srb->cmd[0] = SCSI_READ10;
srb->cmd[1] = srb->lun << 5;
srb->cmd[2] = ((unsigned char) (start >> 24)) & 0xff;
srb->cmd[3] = ((unsigned char) (start >> 16)) & 0xff;
srb->cmd[4] = ((unsigned char) (start >> 8)) & 0xff;
srb->cmd[5] = ((unsigned char) (start)) & 0xff;
srb->cmd[7] = ((unsigned char) (blocks >> 8)) & 0xff;
srb->cmd[8] = (unsigned char) blocks & 0xff;
srb->cmdlen = 12;
USB_STOR_PRINTF("read10: start %lx blocks %x\n", start, blocks);
return ss->transport(srb, ss);
}
static int usb_write_10(ccb *srb, struct us_data *ss, unsigned long start,
unsigned short blocks)
{
memset(&srb->cmd[0], 0, 12);
srb->cmd[0] = SCSI_WRITE10;
srb->cmd[1] = srb->lun << 5;
srb->cmd[2] = ((unsigned char) (start >> 24)) & 0xff;
srb->cmd[3] = ((unsigned char) (start >> 16)) & 0xff;
srb->cmd[4] = ((unsigned char) (start >> 8)) & 0xff;
srb->cmd[5] = ((unsigned char) (start)) & 0xff;
srb->cmd[7] = ((unsigned char) (blocks >> 8)) & 0xff;
srb->cmd[8] = (unsigned char) blocks & 0xff;
srb->cmdlen = 12;
USB_STOR_PRINTF("write10: start %lx blocks %x\n", start, blocks);
return ss->transport(srb, ss);
}
#ifdef CONFIG_USB_BIN_FIXUP
/*
* Some USB storage devices queried for SCSI identification data respond with
* binary strings, which if output to the console freeze the terminal. The
* workaround is to modify the vendor and product strings read from such
* device with proper values (as reported by 'usb info').
*
* Vendor and product length limits are taken from the definition of
* block_dev_desc_t in include/part.h.
*/
static void usb_bin_fixup(struct usb_device_descriptor descriptor,
unsigned char vendor[],
unsigned char product[]) {
const unsigned char max_vendor_len = 40;
const unsigned char max_product_len = 20;
if (descriptor.idVendor == 0x0424 && descriptor.idProduct == 0x223a) {
strncpy((char *)vendor, "SMSC", max_vendor_len);
strncpy((char *)product, "Flash Media Cntrller",
max_product_len);
}
}
#endif /* CONFIG_USB_BIN_FIXUP */
#define USB_MAX_READ_BLK 20
unsigned long usb_stor_read(int device, unsigned long blknr,
unsigned long blkcnt, void *buffer)
{
unsigned long start, blks, buf_addr;
unsigned short smallblks;
struct usb_device *dev;
int retry, i;
ccb *srb = &usb_ccb;
if (blkcnt == 0)
return 0;
device &= 0xff;
/* Setup device */
USB_STOR_PRINTF("\nusb_read: dev %d \n", device);
dev = NULL;
for (i = 0; i < USB_MAX_DEVICE; i++) {
dev = usb_get_dev_index(i);
if (dev == NULL)
return 0;
if (dev->devnum == usb_dev_desc[device].target)
break;
}
usb_disable_asynch(1); /* asynch transfer not allowed */
srb->lun = usb_dev_desc[device].lun;
buf_addr = (unsigned long)buffer;
start = blknr;
blks = blkcnt;
if (usb_test_unit_ready(srb, (struct us_data *)dev->privptr)) {
printf("Device NOT ready\n Request Sense returned %02X %02X"
" %02X\n", srb->sense_buf[2], srb->sense_buf[12],
srb->sense_buf[13]);
return 0;
}
USB_STOR_PRINTF("\nusb_read: dev %d startblk %lx, blccnt %lx"
" buffer %lx\n", device, start, blks, buf_addr);
do {
/* XXX need some comment here */
retry = 2;
srb->pdata = (unsigned char *)buf_addr;
if (blks > USB_MAX_READ_BLK)
smallblks = USB_MAX_READ_BLK;
else
smallblks = (unsigned short) blks;
retry_it:
if (smallblks == USB_MAX_READ_BLK)
usb_show_progress();
srb->datalen = usb_dev_desc[device].blksz * smallblks;
srb->pdata = (unsigned char *)buf_addr;
if (usb_read_10(srb, (struct us_data *)dev->privptr, start,
smallblks)) {
USB_STOR_PRINTF("Read ERROR\n");
usb_request_sense(srb, (struct us_data *)dev->privptr);
if (retry--)
goto retry_it;
blkcnt -= blks;
break;
}
start += smallblks;
blks -= smallblks;
buf_addr += srb->datalen;
} while (blks != 0);
USB_STOR_PRINTF("usb_read: end startblk %lx, blccnt %x buffer %lx\n",
start, smallblks, buf_addr);
usb_disable_asynch(0); /* asynch transfer allowed */
if (blkcnt >= USB_MAX_READ_BLK)
debug("\n");
return blkcnt;
}
#define USB_MAX_WRITE_BLK 20
unsigned long usb_stor_write(int device, unsigned long blknr,
unsigned long blkcnt, const void *buffer)
{
unsigned long start, blks, buf_addr;
unsigned short smallblks;
struct usb_device *dev;
int retry, i;
ccb *srb = &usb_ccb;
if (blkcnt == 0)
return 0;
device &= 0xff;
/* Setup device */
USB_STOR_PRINTF("\nusb_write: dev %d \n", device);
dev = NULL;
for (i = 0; i < USB_MAX_DEVICE; i++) {
dev = usb_get_dev_index(i);
if (dev == NULL)
return 0;
if (dev->devnum == usb_dev_desc[device].target)
break;
}
usb_disable_asynch(1); /* asynch transfer not allowed */
srb->lun = usb_dev_desc[device].lun;
buf_addr = (unsigned long)buffer;
start = blknr;
blks = blkcnt;
if (usb_test_unit_ready(srb, (struct us_data *)dev->privptr)) {
printf("Device NOT ready\n Request Sense returned %02X %02X"
" %02X\n", srb->sense_buf[2], srb->sense_buf[12],
srb->sense_buf[13]);
return 0;
}
USB_STOR_PRINTF("\nusb_write: dev %d startblk %lx, blccnt %lx"
" buffer %lx\n", device, start, blks, buf_addr);
do {
/* If write fails retry for max retry count else
* return with number of blocks written successfully.
*/
retry = 2;
srb->pdata = (unsigned char *)buf_addr;
if (blks > USB_MAX_WRITE_BLK)
smallblks = USB_MAX_WRITE_BLK;
else
smallblks = (unsigned short) blks;
retry_it:
if (smallblks == USB_MAX_WRITE_BLK)
usb_show_progress();
srb->datalen = usb_dev_desc[device].blksz * smallblks;
srb->pdata = (unsigned char *)buf_addr;
if (usb_write_10(srb, (struct us_data *)dev->privptr, start,
smallblks)) {
USB_STOR_PRINTF("Write ERROR\n");
usb_request_sense(srb, (struct us_data *)dev->privptr);
if (retry--)
goto retry_it;
blkcnt -= blks;
break;
}
start += smallblks;
blks -= smallblks;
buf_addr += srb->datalen;
} while (blks != 0);
USB_STOR_PRINTF("usb_write: end startblk %lx, blccnt %x buffer %lx\n",
start, smallblks, buf_addr);
usb_disable_asynch(0); /* asynch transfer allowed */
if (blkcnt >= USB_MAX_WRITE_BLK)
debug("\n");
return blkcnt;
}
/* Probe to see if a new device is actually a Storage device */
int usb_storage_probe(struct usb_device *dev, unsigned int ifnum,
struct us_data *ss)
{
struct usb_interface *iface;
int i;
unsigned int flags = 0;
int protocol = 0;
int subclass = 0;
/* let's examine the device now */
iface = &dev->config.if_desc[ifnum];
#if 0
/* this is the place to patch some storage devices */
USB_STOR_PRINTF("iVendor %X iProduct %X\n", dev->descriptor.idVendor,
dev->descriptor.idProduct);
if ((dev->descriptor.idVendor) == 0x066b &&
(dev->descriptor.idProduct) == 0x0103) {
USB_STOR_PRINTF("patched for E-USB\n");
protocol = US_PR_CB;
subclass = US_SC_UFI; /* an assumption */
}
#endif
if (dev->descriptor.bDeviceClass != 0 ||
iface->desc.bInterfaceClass != USB_CLASS_MASS_STORAGE ||
iface->desc.bInterfaceSubClass < US_SC_MIN ||
iface->desc.bInterfaceSubClass > US_SC_MAX) {
/* if it's not a mass storage, we go no further */
return 0;
}
memset(ss, 0, sizeof(struct us_data));
/* At this point, we know we've got a live one */
USB_STOR_PRINTF("\n\nUSB Mass Storage device detected\n");
/* Initialize the us_data structure with some useful info */
ss->flags = flags;
ss->ifnum = ifnum;
ss->pusb_dev = dev;
ss->attention_done = 0;
/* If the device has subclass and protocol, then use that. Otherwise,
* take data from the specific interface.
*/
if (subclass) {
ss->subclass = subclass;
ss->protocol = protocol;
} else {
ss->subclass = iface->desc.bInterfaceSubClass;
ss->protocol = iface->desc.bInterfaceProtocol;
}
/* set the handler pointers based on the protocol */
USB_STOR_PRINTF("Transport: ");
switch (ss->protocol) {
case US_PR_CB:
USB_STOR_PRINTF("Control/Bulk\n");
ss->transport = usb_stor_CB_transport;
ss->transport_reset = usb_stor_CB_reset;
break;
case US_PR_CBI:
USB_STOR_PRINTF("Control/Bulk/Interrupt\n");
ss->transport = usb_stor_CB_transport;
ss->transport_reset = usb_stor_CB_reset;
break;
case US_PR_BULK:
USB_STOR_PRINTF("Bulk/Bulk/Bulk\n");
ss->transport = usb_stor_BBB_transport;
ss->transport_reset = usb_stor_BBB_reset;
break;
default:
printf("USB Storage Transport unknown / not yet implemented\n");
return 0;
break;
}
/*
* We are expecting a minimum of 2 endpoints - in and out (bulk).
* An optional interrupt is OK (necessary for CBI protocol).
* We will ignore any others.
*/
for (i = 0; i < iface->desc.bNumEndpoints; i++) {
/* is it an BULK endpoint? */
if ((iface->ep_desc[i].bmAttributes &
USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK) {
if (iface->ep_desc[i].bEndpointAddress & USB_DIR_IN)
ss->ep_in = iface->ep_desc[i].bEndpointAddress &
USB_ENDPOINT_NUMBER_MASK;
else
ss->ep_out =
iface->ep_desc[i].bEndpointAddress &
USB_ENDPOINT_NUMBER_MASK;
}
/* is it an interrupt endpoint? */
if ((iface->ep_desc[i].bmAttributes &
USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT) {
ss->ep_int = iface->ep_desc[i].bEndpointAddress &
USB_ENDPOINT_NUMBER_MASK;
ss->irqinterval = iface->ep_desc[i].bInterval;
}
}
USB_STOR_PRINTF("Endpoints In %d Out %d Int %d\n",
ss->ep_in, ss->ep_out, ss->ep_int);
/* Do some basic sanity checks, and bail if we find a problem */
if (usb_set_interface(dev, iface->desc.bInterfaceNumber, 0) ||
!ss->ep_in || !ss->ep_out ||
(ss->protocol == US_PR_CBI && ss->ep_int == 0)) {
USB_STOR_PRINTF("Problems with device\n");
return 0;
}
/* set class specific stuff */
/* We only handle certain protocols. Currently, these are
* the only ones.
* The SFF8070 accepts the requests used in u-boot
*/
if (ss->subclass != US_SC_UFI && ss->subclass != US_SC_SCSI &&
ss->subclass != US_SC_8070) {
printf("Sorry, protocol %d not yet supported.\n", ss->subclass);
return 0;
}
if (ss->ep_int) {
/* we had found an interrupt endpoint, prepare irq pipe
* set up the IRQ pipe and handler
*/
ss->irqinterval = (ss->irqinterval > 0) ? ss->irqinterval : 255;
ss->irqpipe = usb_rcvintpipe(ss->pusb_dev, ss->ep_int);
ss->irqmaxp = usb_maxpacket(dev, ss->irqpipe);
dev->irq_handle = usb_stor_irq;
}
dev->privptr = (void *)ss;
return 1;
}
int usb_stor_get_info(struct usb_device *dev, struct us_data *ss,
block_dev_desc_t *dev_desc)
{
unsigned char perq, modi;
unsigned long cap[2];
unsigned long *capacity, *blksz;
ccb *pccb = &usb_ccb;
pccb->pdata = usb_stor_buf;
dev_desc->target = dev->devnum;
pccb->lun = dev_desc->lun;
USB_STOR_PRINTF(" address %d\n", dev_desc->target);
if (usb_inquiry(pccb, ss))
return -1;
perq = usb_stor_buf[0];
modi = usb_stor_buf[1];
if ((perq & 0x1f) == 0x1f) {
/* skip unknown devices */
return 0;
}
if ((modi&0x80) == 0x80) {
/* drive is removable */
dev_desc->removable = 1;
}
memcpy(&dev_desc->vendor[0], &usb_stor_buf[8], 8);
memcpy(&dev_desc->product[0], &usb_stor_buf[16], 16);
memcpy(&dev_desc->revision[0], &usb_stor_buf[32], 4);
dev_desc->vendor[8] = 0;
dev_desc->product[16] = 0;
dev_desc->revision[4] = 0;
#ifdef CONFIG_USB_BIN_FIXUP
usb_bin_fixup(dev->descriptor, (uchar *)dev_desc->vendor,
(uchar *)dev_desc->product);
#endif /* CONFIG_USB_BIN_FIXUP */
USB_STOR_PRINTF("ISO Vers %X, Response Data %X\n", usb_stor_buf[2],
usb_stor_buf[3]);
if (usb_test_unit_ready(pccb, ss)) {
printf("Device NOT ready\n"
" Request Sense returned %02X %02X %02X\n",
pccb->sense_buf[2], pccb->sense_buf[12],
pccb->sense_buf[13]);
if (dev_desc->removable == 1) {
dev_desc->type = perq;
return 1;
}
return 0;
}
pccb->pdata = (unsigned char *)&cap[0];
memset(pccb->pdata, 0, 8);
if (usb_read_capacity(pccb, ss) != 0) {
printf("READ_CAP ERROR\n");
cap[0] = 2880;
cap[1] = 0x200;
}
USB_STOR_PRINTF("Read Capacity returns: 0x%lx, 0x%lx\n", cap[0],
cap[1]);
#if 0
if (cap[0] > (0x200000 * 10)) /* greater than 10 GByte */
cap[0] >>= 16;
#endif
cap[0] = cpu_to_be32(cap[0]);
cap[1] = cpu_to_be32(cap[1]);
/* this assumes bigendian! */
cap[0] += 1;
capacity = &cap[0];
blksz = &cap[1];
USB_STOR_PRINTF("Capacity = 0x%lx, blocksz = 0x%lx\n",
*capacity, *blksz);
dev_desc->lba = *capacity;
dev_desc->blksz = *blksz;
dev_desc->type = perq;
USB_STOR_PRINTF(" address %d\n", dev_desc->target);
USB_STOR_PRINTF("partype: %d\n", dev_desc->part_type);
init_part(dev_desc);
USB_STOR_PRINTF("partype: %d\n", dev_desc->part_type);
return 1;
}
|
1001-study-uboot
|
common/usb_storage.c
|
C
|
gpl3
| 40,330
|
/*
* (C) Copyright 2000-2004
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2003
* Kai-Uwe Bloem, Auerswald GmbH & Co KG, <linux-development@auerswald.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
*/
/*
* Multi Image extract
*/
#include <common.h>
#include <command.h>
#include <image.h>
#include <watchdog.h>
#if defined(CONFIG_BZIP2)
#include <bzlib.h>
#endif
#include <asm/byteorder.h>
#ifndef CONFIG_SYS_XIMG_LEN
/* use 8MByte as default max gunzip size */
#define CONFIG_SYS_XIMG_LEN 0x800000
#endif
int
do_imgextract(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong addr = load_addr;
ulong dest = 0;
ulong data, len, count;
int verify;
int part = 0;
char pbuf[10];
image_header_t *hdr;
#if defined(CONFIG_FIT)
const char *uname = NULL;
const void* fit_hdr;
int noffset;
const void *fit_data;
size_t fit_len;
#endif
uint unc_len = CONFIG_SYS_XIMG_LEN;
uint8_t comp;
verify = getenv_yesno("verify");
if (argc > 1) {
addr = simple_strtoul(argv[1], NULL, 16);
}
if (argc > 2) {
part = simple_strtoul(argv[2], NULL, 16);
#if defined(CONFIG_FIT)
uname = argv[2];
#endif
}
if (argc > 3) {
dest = simple_strtoul(argv[3], NULL, 16);
}
switch (genimg_get_format((void *)addr)) {
case IMAGE_FORMAT_LEGACY:
printf("## Copying part %d from legacy image "
"at %08lx ...\n", part, addr);
hdr = (image_header_t *)addr;
if (!image_check_magic(hdr)) {
printf("Bad Magic Number\n");
return 1;
}
if (!image_check_hcrc(hdr)) {
printf("Bad Header Checksum\n");
return 1;
}
#ifdef DEBUG
image_print_contents(hdr);
#endif
if (!image_check_type(hdr, IH_TYPE_MULTI)) {
printf("Wrong Image Type for %s command\n",
cmdtp->name);
return 1;
}
comp = image_get_comp(hdr);
if ((comp != IH_COMP_NONE) && (argc < 4)) {
printf("Must specify load address for %s command "
"with compressed image\n",
cmdtp->name);
return 1;
}
if (verify) {
printf(" Verifying Checksum ... ");
if (!image_check_dcrc(hdr)) {
printf("Bad Data CRC\n");
return 1;
}
printf("OK\n");
}
count = image_multi_count(hdr);
if (part >= count) {
printf("Bad Image Part\n");
return 1;
}
image_multi_getimg(hdr, part, &data, &len);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
if (uname == NULL) {
puts("No FIT subimage unit name\n");
return 1;
}
printf("## Copying '%s' subimage from FIT image "
"at %08lx ...\n", uname, addr);
fit_hdr = (const void *)addr;
if (!fit_check_format(fit_hdr)) {
puts("Bad FIT image format\n");
return 1;
}
/* get subimage node offset */
noffset = fit_image_get_node(fit_hdr, uname);
if (noffset < 0) {
printf("Can't find '%s' FIT subimage\n", uname);
return 1;
}
if (fit_image_check_comp(fit_hdr, noffset, IH_COMP_NONE)
&& (argc < 4)) {
printf("Must specify load address for %s command "
"with compressed image\n",
cmdtp->name);
return 1;
}
/* verify integrity */
if (verify) {
if (!fit_image_check_hashes(fit_hdr, noffset)) {
puts("Bad Data Hash\n");
return 1;
}
}
/* get subimage data address and length */
if (fit_image_get_data(fit_hdr, noffset,
&fit_data, &fit_len)) {
puts("Could not find script subimage data\n");
return 1;
}
if (fit_image_get_comp(fit_hdr, noffset, &comp)) {
puts("Could not find script subimage "
"compression type\n");
return 1;
}
data = (ulong)fit_data;
len = (ulong)fit_len;
break;
#endif
default:
puts("Invalid image type for imxtract\n");
return 1;
}
if (argc > 3) {
switch (comp) {
case IH_COMP_NONE:
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
{
size_t l = len;
size_t tail;
void *to = (void *) dest;
void *from = (void *)data;
printf(" Loading part %d ... ", part);
while (l > 0) {
tail = (l > CHUNKSZ) ? CHUNKSZ : l;
WATCHDOG_RESET();
memmove(to, from, tail);
to += tail;
from += tail;
l -= tail;
}
}
#else /* !(CONFIG_HW_WATCHDOG || CONFIG_WATCHDOG) */
printf(" Loading part %d ... ", part);
memmove((char *) dest, (char *)data, len);
#endif /* CONFIG_HW_WATCHDOG || CONFIG_WATCHDOG */
break;
#ifdef CONFIG_GZIP
case IH_COMP_GZIP:
printf(" Uncompressing part %d ... ", part);
if (gunzip((void *) dest, unc_len,
(uchar *) data, &len) != 0) {
puts("GUNZIP ERROR - image not loaded\n");
return 1;
}
break;
#endif
#if defined(CONFIG_BZIP2)
case IH_COMP_BZIP2:
{
int i;
printf(" Uncompressing part %d ... ", part);
/*
* If we've got less than 4 MB of malloc()
* space, use slower decompression algorithm
* which requires at most 2300 KB of memory.
*/
i = BZ2_bzBuffToBuffDecompress(
(char *)ntohl(hdr->ih_load),
&unc_len, (char *)data, len,
CONFIG_SYS_MALLOC_LEN < (4096 * 1024),
0);
if (i != BZ_OK) {
printf("BUNZIP2 ERROR %d - "
"image not loaded\n", i);
return 1;
}
}
break;
#endif /* CONFIG_BZIP2 */
default:
printf("Unimplemented compression type %d\n", comp);
return 1;
}
puts("OK\n");
}
sprintf(pbuf, "%8lx", data);
setenv("fileaddr", pbuf);
sprintf(pbuf, "%8lx", len);
setenv("filesize", pbuf);
return 0;
}
U_BOOT_CMD(
imxtract, 4, 1, do_imgextract,
"extract a part of a multi-image",
"addr part [dest]\n"
" - extract <part> from legacy image at <addr> and copy to <dest>"
#if defined(CONFIG_FIT)
"\n"
"addr uname [dest]\n"
" - extract <uname> subimage from FIT image at <addr> and copy to <dest>"
#endif
);
|
1001-study-uboot
|
common/cmd_ximg.c
|
C
|
gpl3
| 6,391
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <u-boot/md5.h>
static int do_md5sum(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unsigned long addr, len;
unsigned int i;
u8 output[16];
if (argc < 3)
return cmd_usage(cmdtp);
addr = simple_strtoul(argv[1], NULL, 16);
len = simple_strtoul(argv[2], NULL, 16);
md5_wd((unsigned char *) addr, len, output, CHUNKSZ_MD5);
printf("md5 for %08lx ... %08lx ==> ", addr, addr + len - 1);
for (i = 0; i < 16; i++)
printf("%02x", output[i]);
printf("\n");
return 0;
}
U_BOOT_CMD(
md5sum, 3, 1, do_md5sum,
"compute MD5 message digest",
"address count"
);
|
1001-study-uboot
|
common/cmd_md5sum.c
|
C
|
gpl3
| 1,515
|
/*
* Driver for NAND support, Rick Bronson
* borrowed heavily from:
* (c) 1999 Machine Vision Holdings, Inc.
* (c) 1999, 2000 David Woodhouse <dwmw2@infradead.org>
*
* Ported 'dynenv' to 'nand env.oob' command
* (C) 2010 Nanometrics, Inc.
* 'dynenv' -- Dynamic environment offset in NAND OOB
* (C) Copyright 2006-2007 OpenMoko, Inc.
* Added 16-bit nand support
* (C) 2004 Texas Instruments
*
* Copyright 2010 Freescale Semiconductor
* The portions of this file whose copyright is held by Freescale and which
* are not considered a derived work of GPL v2-only code may be distributed
* and/or modified under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*/
#include <common.h>
#include <linux/mtd/mtd.h>
#include <command.h>
#include <watchdog.h>
#include <malloc.h>
#include <asm/byteorder.h>
#include <jffs2/jffs2.h>
#include <nand.h>
#if defined(CONFIG_CMD_MTDPARTS)
/* partition handling routines */
int mtdparts_init(void);
int id_parse(const char *id, const char **ret_id, u8 *dev_type, u8 *dev_num);
int find_dev_and_part(const char *id, struct mtd_device **dev,
u8 *part_num, struct part_info **part);
#endif
static int nand_dump(nand_info_t *nand, ulong off, int only_oob, int repeat)
{
int i;
u_char *datbuf, *oobbuf, *p;
static loff_t last;
if (repeat)
off = last + nand->writesize;
last = off;
datbuf = malloc(nand->writesize + nand->oobsize);
oobbuf = malloc(nand->oobsize);
if (!datbuf || !oobbuf) {
puts("No memory for page buffer\n");
return 1;
}
off &= ~(nand->writesize - 1);
loff_t addr = (loff_t) off;
struct mtd_oob_ops ops;
memset(&ops, 0, sizeof(ops));
ops.datbuf = datbuf;
ops.oobbuf = oobbuf; /* must exist, but oob data will be appended to ops.datbuf */
ops.len = nand->writesize;
ops.ooblen = nand->oobsize;
ops.mode = MTD_OOB_RAW;
i = nand->read_oob(nand, addr, &ops);
if (i < 0) {
printf("Error (%d) reading page %08lx\n", i, off);
free(datbuf);
free(oobbuf);
return 1;
}
printf("Page %08lx dump:\n", off);
i = nand->writesize >> 4;
p = datbuf;
while (i--) {
if (!only_oob)
printf("\t%02x %02x %02x %02x %02x %02x %02x %02x"
" %02x %02x %02x %02x %02x %02x %02x %02x\n",
p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
p[8], p[9], p[10], p[11], p[12], p[13], p[14],
p[15]);
p += 16;
}
puts("OOB:\n");
i = nand->oobsize >> 3;
while (i--) {
printf("\t%02x %02x %02x %02x %02x %02x %02x %02x\n",
p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
p += 8;
}
free(datbuf);
free(oobbuf);
return 0;
}
/* ------------------------------------------------------------------------- */
static int set_dev(int dev)
{
if (dev < 0 || dev >= CONFIG_SYS_MAX_NAND_DEVICE ||
!nand_info[dev].name) {
puts("No such device\n");
return -1;
}
if (nand_curr_device == dev)
return 0;
printf("Device %d: %s", dev, nand_info[dev].name);
puts("... is now current device\n");
nand_curr_device = dev;
#ifdef CONFIG_SYS_NAND_SELECT_DEVICE
board_nand_select_device(nand_info[dev].priv, dev);
#endif
return 0;
}
static inline int str2off(const char *p, loff_t *num)
{
char *endptr;
*num = simple_strtoull(p, &endptr, 16);
return *p != '\0' && *endptr == '\0';
}
static inline int str2long(const char *p, ulong *num)
{
char *endptr;
*num = simple_strtoul(p, &endptr, 16);
return *p != '\0' && *endptr == '\0';
}
static int get_part(const char *partname, int *idx, loff_t *off, loff_t *size)
{
#ifdef CONFIG_CMD_MTDPARTS
struct mtd_device *dev;
struct part_info *part;
u8 pnum;
int ret;
ret = mtdparts_init();
if (ret)
return ret;
ret = find_dev_and_part(partname, &dev, &pnum, &part);
if (ret)
return ret;
if (dev->id->type != MTD_DEV_TYPE_NAND) {
puts("not a NAND device\n");
return -1;
}
*off = part->offset;
*size = part->size;
*idx = dev->id->num;
ret = set_dev(*idx);
if (ret)
return ret;
return 0;
#else
puts("offset is not a number\n");
return -1;
#endif
}
static int arg_off(const char *arg, int *idx, loff_t *off, loff_t *maxsize)
{
if (!str2off(arg, off))
return get_part(arg, idx, off, maxsize);
if (*off >= nand_info[*idx].size) {
puts("Offset exceeds device limit\n");
return -1;
}
*maxsize = nand_info[*idx].size - *off;
return 0;
}
static int arg_off_size(int argc, char *const argv[], int *idx,
loff_t *off, loff_t *size)
{
int ret;
loff_t maxsize;
if (argc == 0) {
*off = 0;
*size = nand_info[*idx].size;
goto print;
}
ret = arg_off(argv[0], idx, off, &maxsize);
if (ret)
return ret;
if (argc == 1) {
*size = maxsize;
goto print;
}
if (!str2off(argv[1], size)) {
printf("'%s' is not a number\n", argv[1]);
return -1;
}
if (*size > maxsize) {
puts("Size exceeds partition or device limit\n");
return -1;
}
print:
printf("device %d ", *idx);
if (*size == nand_info[*idx].size)
puts("whole chip\n");
else
printf("offset 0x%llx, size 0x%llx\n",
(unsigned long long)*off, (unsigned long long)*size);
return 0;
}
#ifdef CONFIG_CMD_NAND_LOCK_UNLOCK
static void print_status(ulong start, ulong end, ulong erasesize, int status)
{
printf("%08lx - %08lx: %08lx blocks %s%s%s\n",
start,
end - 1,
(end - start) / erasesize,
((status & NAND_LOCK_STATUS_TIGHT) ? "TIGHT " : ""),
((status & NAND_LOCK_STATUS_LOCK) ? "LOCK " : ""),
((status & NAND_LOCK_STATUS_UNLOCK) ? "UNLOCK " : ""));
}
static void do_nand_status(nand_info_t *nand)
{
ulong block_start = 0;
ulong off;
int last_status = -1;
struct nand_chip *nand_chip = nand->priv;
/* check the WP bit */
nand_chip->cmdfunc(nand, NAND_CMD_STATUS, -1, -1);
printf("device is %swrite protected\n",
(nand_chip->read_byte(nand) & 0x80 ?
"NOT " : ""));
for (off = 0; off < nand->size; off += nand->erasesize) {
int s = nand_get_lock_status(nand, off);
/* print message only if status has changed */
if (s != last_status && off != 0) {
print_status(block_start, off, nand->erasesize,
last_status);
block_start = off;
}
last_status = s;
}
/* Print the last block info */
print_status(block_start, off, nand->erasesize, last_status);
}
#endif
#ifdef CONFIG_ENV_OFFSET_OOB
unsigned long nand_env_oob_offset;
int do_nand_env_oob(cmd_tbl_t *cmdtp, int argc, char *const argv[])
{
int ret;
uint32_t oob_buf[ENV_OFFSET_SIZE/sizeof(uint32_t)];
nand_info_t *nand = &nand_info[0];
char *cmd = argv[1];
if (CONFIG_SYS_MAX_NAND_DEVICE == 0 || !nand->name) {
puts("no devices available\n");
return 1;
}
set_dev(0);
if (!strcmp(cmd, "get")) {
ret = get_nand_env_oob(nand, &nand_env_oob_offset);
if (ret)
return 1;
printf("0x%08lx\n", nand_env_oob_offset);
} else if (!strcmp(cmd, "set")) {
loff_t addr;
loff_t maxsize;
struct mtd_oob_ops ops;
int idx = 0;
if (argc < 3)
goto usage;
if (arg_off(argv[2], &idx, &addr, &maxsize)) {
puts("Offset or partition name expected\n");
return 1;
}
if (idx != 0) {
puts("Partition not on first NAND device\n");
return 1;
}
if (nand->oobavail < ENV_OFFSET_SIZE) {
printf("Insufficient available OOB bytes:\n"
"%d OOB bytes available but %d required for "
"env.oob support\n",
nand->oobavail, ENV_OFFSET_SIZE);
return 1;
}
if ((addr & (nand->erasesize - 1)) != 0) {
printf("Environment offset must be block-aligned\n");
return 1;
}
ops.datbuf = NULL;
ops.mode = MTD_OOB_AUTO;
ops.ooboffs = 0;
ops.ooblen = ENV_OFFSET_SIZE;
ops.oobbuf = (void *) oob_buf;
oob_buf[0] = ENV_OOB_MARKER;
oob_buf[1] = addr / nand->erasesize;
ret = nand->write_oob(nand, ENV_OFFSET_SIZE, &ops);
if (ret) {
printf("Error writing OOB block 0\n");
return ret;
}
ret = get_nand_env_oob(nand, &nand_env_oob_offset);
if (ret) {
printf("Error reading env offset in OOB\n");
return ret;
}
if (addr != nand_env_oob_offset) {
printf("Verification of env offset in OOB failed: "
"0x%08llx expected but got 0x%08lx\n",
(unsigned long long)addr, nand_env_oob_offset);
return 1;
}
} else {
goto usage;
}
return ret;
usage:
return cmd_usage(cmdtp);
}
#endif
static void nand_print_and_set_info(int idx)
{
nand_info_t *nand = &nand_info[idx];
struct nand_chip *chip = nand->priv;
const int bufsz = 32;
char buf[bufsz];
printf("Device %d: ", idx);
if (chip->numchips > 1)
printf("%dx ", chip->numchips);
printf("%s, sector size %u KiB\n",
nand->name, nand->erasesize >> 10);
printf(" Page size %8d b\n", nand->writesize);
printf(" OOB size %8d b\n", nand->oobsize);
printf(" Erase size %8d b\n", nand->erasesize);
/* Set geometry info */
sprintf(buf, "%x", nand->writesize);
setenv("nand_writesize", buf);
sprintf(buf, "%x", nand->oobsize);
setenv("nand_oobsize", buf);
sprintf(buf, "%x", nand->erasesize);
setenv("nand_erasesize", buf);
}
int do_nand(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
int i, ret = 0;
ulong addr;
loff_t off, size;
char *cmd, *s;
nand_info_t *nand;
#ifdef CONFIG_SYS_NAND_QUIET
int quiet = CONFIG_SYS_NAND_QUIET;
#else
int quiet = 0;
#endif
const char *quiet_str = getenv("quiet");
int dev = nand_curr_device;
int repeat = flag & CMD_FLAG_REPEAT;
/* at least two arguments please */
if (argc < 2)
goto usage;
if (quiet_str)
quiet = simple_strtoul(quiet_str, NULL, 0) != 0;
cmd = argv[1];
/* Only "dump" is repeatable. */
if (repeat && strcmp(cmd, "dump"))
return 0;
if (strcmp(cmd, "info") == 0) {
putc('\n');
for (i = 0; i < CONFIG_SYS_MAX_NAND_DEVICE; i++) {
if (nand_info[i].name)
nand_print_and_set_info(i);
}
return 0;
}
if (strcmp(cmd, "device") == 0) {
if (argc < 3) {
putc('\n');
if (dev < 0 || dev >= CONFIG_SYS_MAX_NAND_DEVICE)
puts("no devices available\n");
else
nand_print_and_set_info(dev);
return 0;
}
dev = (int)simple_strtoul(argv[2], NULL, 10);
set_dev(dev);
return 0;
}
#ifdef CONFIG_ENV_OFFSET_OOB
/* this command operates only on the first nand device */
if (strcmp(cmd, "env.oob") == 0)
return do_nand_env_oob(cmdtp, argc - 1, argv + 1);
#endif
/* The following commands operate on the current device, unless
* overridden by a partition specifier. Note that if somehow the
* current device is invalid, it will have to be changed to a valid
* one before these commands can run, even if a partition specifier
* for another device is to be used.
*/
if (dev < 0 || dev >= CONFIG_SYS_MAX_NAND_DEVICE ||
!nand_info[dev].name) {
puts("\nno devices available\n");
return 1;
}
nand = &nand_info[dev];
if (strcmp(cmd, "bad") == 0) {
printf("\nDevice %d bad blocks:\n", dev);
for (off = 0; off < nand->size; off += nand->erasesize)
if (nand_block_isbad(nand, off))
printf(" %08llx\n", (unsigned long long)off);
return 0;
}
/*
* Syntax is:
* 0 1 2 3 4
* nand erase [clean] [off size]
*/
if (strncmp(cmd, "erase", 5) == 0 || strncmp(cmd, "scrub", 5) == 0) {
nand_erase_options_t opts;
/* "clean" at index 2 means request to write cleanmarker */
int clean = argc > 2 && !strcmp("clean", argv[2]);
int scrub_yes = argc > 2 && !strcmp("-y", argv[2]);
int o = (clean || scrub_yes) ? 3 : 2;
int scrub = !strncmp(cmd, "scrub", 5);
int spread = 0;
int args = 2;
const char *scrub_warn =
"Warning: "
"scrub option will erase all factory set bad blocks!\n"
" "
"There is no reliable way to recover them.\n"
" "
"Use this command only for testing purposes if you\n"
" "
"are sure of what you are doing!\n"
"\nReally scrub this NAND flash? <y/N>\n";
if (cmd[5] != 0) {
if (!strcmp(&cmd[5], ".spread")) {
spread = 1;
} else if (!strcmp(&cmd[5], ".part")) {
args = 1;
} else if (!strcmp(&cmd[5], ".chip")) {
args = 0;
} else {
goto usage;
}
}
/*
* Don't allow missing arguments to cause full chip/partition
* erases -- easy to do accidentally, e.g. with a misspelled
* variable name.
*/
if (argc != o + args)
goto usage;
printf("\nNAND %s: ", cmd);
/* skip first two or three arguments, look for offset and size */
if (arg_off_size(argc - o, argv + o, &dev, &off, &size) != 0)
return 1;
nand = &nand_info[dev];
memset(&opts, 0, sizeof(opts));
opts.offset = off;
opts.length = size;
opts.jffs2 = clean;
opts.quiet = quiet;
opts.spread = spread;
if (scrub) {
if (!scrub_yes)
puts(scrub_warn);
if (scrub_yes)
opts.scrub = 1;
else if (getc() == 'y') {
puts("y");
if (getc() == '\r')
opts.scrub = 1;
else {
puts("scrub aborted\n");
return -1;
}
} else {
puts("scrub aborted\n");
return -1;
}
}
ret = nand_erase_opts(nand, &opts);
printf("%s\n", ret ? "ERROR" : "OK");
return ret == 0 ? 0 : 1;
}
if (strncmp(cmd, "dump", 4) == 0) {
if (argc < 3)
goto usage;
off = (int)simple_strtoul(argv[2], NULL, 16);
ret = nand_dump(nand, off, !strcmp(&cmd[4], ".oob"), repeat);
return ret == 0 ? 1 : 0;
}
if (strncmp(cmd, "read", 4) == 0 || strncmp(cmd, "write", 5) == 0) {
size_t rwsize;
int read;
if (argc < 4)
goto usage;
addr = (ulong)simple_strtoul(argv[2], NULL, 16);
read = strncmp(cmd, "read", 4) == 0; /* 1 = read, 0 = write */
printf("\nNAND %s: ", read ? "read" : "write");
if (arg_off_size(argc - 3, argv + 3, &dev, &off, &size) != 0)
return 1;
nand = &nand_info[dev];
rwsize = size;
printf("\n%s, size:%ld(erase), %ld(write), %ld(oob)\n",
nand->name, nand->erasesize, nand->writesize, nand->oobsize);
s = strchr(cmd, '.');
if (!s || !strcmp(s, ".jffs2") ||
!strcmp(s, ".e") || !strcmp(s, ".i")) {
if (read)
ret = nand_read_skip_bad(nand, off, &rwsize,
(u_char *)addr);
else
ret = nand_write_skip_bad(nand, off, &rwsize,
(u_char *)addr, 0);
#ifdef CONFIG_CMD_NAND_TRIMFFS
} else if (!strcmp(s, ".trimffs")) {
if (read) {
printf("Unknown nand command suffix '%s'\n", s);
return 1;
}
ret = nand_write_skip_bad(nand, off, &rwsize,
(u_char *)addr,
WITH_DROP_FFS);
#endif
#ifdef CONFIG_CMD_NAND_YAFFS
} else if (!strcmp(s, ".yaffs")) {
if (read) {
printf("Unknown nand command suffix '%s'.\n", s);
return 1;
}
ret = nand_write_skip_bad(nand, off, &rwsize,
(u_char *)addr, WITH_YAFFS_OOB);
#endif
} else if (!strcmp(s, ".oob")) {
/* out-of-band data */
mtd_oob_ops_t ops = {
.oobbuf = (u8 *)addr,
.ooblen = rwsize,
.mode = MTD_OOB_RAW
};
if (read)
ret = nand->read_oob(nand, off, &ops);
else
ret = nand->write_oob(nand, off, &ops);
} else if (!strcmp(s, ".raw")) {
/* Raw access */
mtd_oob_ops_t ops = {
.datbuf = (u8 *)addr,
.oobbuf = ((u8 *)addr) + nand->writesize,
.len = nand->writesize,
.ooblen = nand->oobsize,
.mode = MTD_OOB_RAW
};
rwsize = nand->writesize + nand->oobsize;
if (read)
ret = nand->read_oob(nand, off, &ops);
else
ret = nand->write_oob(nand, off, &ops);
} else {
printf("Unknown nand command suffix '%s'.\n", s);
return 1;
}
printf(" %zu bytes %s: %s\n", rwsize,
read ? "read" : "written", ret ? "ERROR" : "OK");
return ret == 0 ? 0 : 1;
}
if (strcmp(cmd, "markbad") == 0) {
argc -= 2;
argv += 2;
if (argc <= 0)
goto usage;
while (argc > 0) {
addr = simple_strtoul(*argv, NULL, 16);
if (nand->block_markbad(nand, addr)) {
printf("block 0x%08lx NOT marked "
"as bad! ERROR %d\n",
addr, ret);
ret = 1;
} else {
printf("block 0x%08lx successfully "
"marked as bad\n",
addr);
}
--argc;
++argv;
}
return ret;
}
if (strcmp(cmd, "biterr") == 0) {
/* todo */
return 1;
}
#ifdef CONFIG_CMD_NAND_LOCK_UNLOCK
if (strcmp(cmd, "lock") == 0) {
int tight = 0;
int status = 0;
if (argc == 3) {
if (!strcmp("tight", argv[2]))
tight = 1;
if (!strcmp("status", argv[2]))
status = 1;
}
if (status) {
do_nand_status(nand);
} else {
if (!nand_lock(nand, tight)) {
puts("NAND flash successfully locked\n");
} else {
puts("Error locking NAND flash\n");
return 1;
}
}
return 0;
}
if (strcmp(cmd, "unlock") == 0) {
if (arg_off_size(argc - 2, argv + 2, &dev, &off, &size) < 0)
return 1;
if (!nand_unlock(&nand_info[dev], off, size)) {
puts("NAND flash successfully unlocked\n");
} else {
puts("Error unlocking NAND flash, "
"write and erase will probably fail\n");
return 1;
}
return 0;
}
#endif
usage:
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
nand, CONFIG_SYS_MAXARGS, 1, do_nand,
"NAND sub-system",
"info - show available NAND devices\n"
"nand device [dev] - show or set current device\n"
"nand read - addr off|partition size\n"
"nand write - addr off|partition size\n"
" read/write 'size' bytes starting at offset 'off'\n"
" to/from memory address 'addr', skipping bad blocks.\n"
"nand read.raw - addr off|partition\n"
"nand write.raw - addr off|partition\n"
" Use read.raw/write.raw to avoid ECC and access the page as-is.\n"
#ifdef CONFIG_CMD_NAND_TRIMFFS
"nand write.trimffs - addr off|partition size\n"
" write 'size' bytes starting at offset 'off' from memory address\n"
" 'addr', skipping bad blocks and dropping any pages at the end\n"
" of eraseblocks that contain only 0xFF\n"
#endif
#ifdef CONFIG_CMD_NAND_YAFFS
"nand write.yaffs - addr off|partition size\n"
" write 'size' bytes starting at offset 'off' with yaffs format\n"
" from memory address 'addr', skipping bad blocks.\n"
#endif
"nand erase[.spread] [clean] off size - erase 'size' bytes "
"from offset 'off'\n"
" With '.spread', erase enough for given file size, otherwise,\n"
" 'size' includes skipped bad blocks.\n"
"nand erase.part [clean] partition - erase entire mtd partition'\n"
"nand erase.chip [clean] - erase entire chip'\n"
"nand bad - show bad blocks\n"
"nand dump[.oob] off - dump page\n"
"nand scrub [-y] off size | scrub.part partition | scrub.chip\n"
" really clean NAND erasing bad blocks (UNSAFE)\n"
"nand markbad off [...] - mark bad block(s) at offset (UNSAFE)\n"
"nand biterr off - make a bit error at offset (UNSAFE)"
#ifdef CONFIG_CMD_NAND_LOCK_UNLOCK
"\n"
"nand lock [tight] [status]\n"
" bring nand to lock state or display locked pages\n"
"nand unlock [offset] [size] - unlock section"
#endif
#ifdef CONFIG_ENV_OFFSET_OOB
"\n"
"nand env.oob - environment offset in OOB of block 0 of"
" first device.\n"
"nand env.oob set off|partition - set enviromnent offset\n"
"nand env.oob get - get environment offset"
#endif
);
static int nand_load_image(cmd_tbl_t *cmdtp, nand_info_t *nand,
ulong offset, ulong addr, char *cmd)
{
int r;
char *s;
size_t cnt;
image_header_t *hdr;
#if defined(CONFIG_FIT)
const void *fit_hdr = NULL;
#endif
s = strchr(cmd, '.');
if (s != NULL &&
(strcmp(s, ".jffs2") && strcmp(s, ".e") && strcmp(s, ".i"))) {
printf("Unknown nand load suffix '%s'\n", s);
show_boot_progress(-53);
return 1;
}
printf("\nLoading from %s, offset 0x%lx\n", nand->name, offset);
cnt = nand->writesize;
r = nand_read_skip_bad(nand, offset, &cnt, (u_char *) addr);
if (r) {
puts("** Read error\n");
show_boot_progress (-56);
return 1;
}
show_boot_progress (56);
switch (genimg_get_format ((void *)addr)) {
case IMAGE_FORMAT_LEGACY:
hdr = (image_header_t *)addr;
show_boot_progress (57);
image_print_contents (hdr);
cnt = image_get_image_size (hdr);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
fit_hdr = (const void *)addr;
puts ("Fit image detected...\n");
cnt = fit_get_size (fit_hdr);
break;
#endif
default:
show_boot_progress (-57);
puts ("** Unknown image type\n");
return 1;
}
show_boot_progress (57);
r = nand_read_skip_bad(nand, offset, &cnt, (u_char *) addr);
if (r) {
puts("** Read error\n");
show_boot_progress (-58);
return 1;
}
show_boot_progress (58);
#if defined(CONFIG_FIT)
/* This cannot be done earlier, we need complete FIT image in RAM first */
if (genimg_get_format ((void *)addr) == IMAGE_FORMAT_FIT) {
if (!fit_check_format (fit_hdr)) {
show_boot_progress (-150);
puts ("** Bad FIT image format\n");
return 1;
}
show_boot_progress (151);
fit_print_contents (fit_hdr);
}
#endif
/* Loading ok, update default load address */
load_addr = addr;
return bootm_maybe_autostart(cmdtp, cmd);
}
int do_nandboot(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
char *boot_device = NULL;
int idx;
ulong addr, offset = 0;
#if defined(CONFIG_CMD_MTDPARTS)
struct mtd_device *dev;
struct part_info *part;
u8 pnum;
if (argc >= 2) {
char *p = (argc == 2) ? argv[1] : argv[2];
if (!(str2long(p, &addr)) && (mtdparts_init() == 0) &&
(find_dev_and_part(p, &dev, &pnum, &part) == 0)) {
if (dev->id->type != MTD_DEV_TYPE_NAND) {
puts("Not a NAND device\n");
return 1;
}
if (argc > 3)
goto usage;
if (argc == 3)
addr = simple_strtoul(argv[1], NULL, 16);
else
addr = CONFIG_SYS_LOAD_ADDR;
return nand_load_image(cmdtp, &nand_info[dev->id->num],
part->offset, addr, argv[0]);
}
}
#endif
show_boot_progress(52);
switch (argc) {
case 1:
addr = CONFIG_SYS_LOAD_ADDR;
boot_device = getenv("bootdevice");
break;
case 2:
addr = simple_strtoul(argv[1], NULL, 16);
boot_device = getenv("bootdevice");
break;
case 3:
addr = simple_strtoul(argv[1], NULL, 16);
boot_device = argv[2];
break;
case 4:
addr = simple_strtoul(argv[1], NULL, 16);
boot_device = argv[2];
offset = simple_strtoul(argv[3], NULL, 16);
break;
default:
#if defined(CONFIG_CMD_MTDPARTS)
usage:
#endif
show_boot_progress(-53);
return cmd_usage(cmdtp);
}
show_boot_progress(53);
if (!boot_device) {
puts("\n** No boot device **\n");
show_boot_progress(-54);
return 1;
}
show_boot_progress(54);
idx = simple_strtoul(boot_device, NULL, 16);
if (idx < 0 || idx >= CONFIG_SYS_MAX_NAND_DEVICE || !nand_info[idx].name) {
printf("\n** Device %d not available\n", idx);
show_boot_progress(-55);
return 1;
}
show_boot_progress(55);
return nand_load_image(cmdtp, &nand_info[idx], offset, addr, argv[0]);
}
U_BOOT_CMD(nboot, 4, 1, do_nandboot,
"boot from NAND device",
"[partition] | [[[loadAddr] dev] offset]"
);
|
1001-study-uboot
|
common/cmd_nand.c
|
C
|
gpl3
| 22,496
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <sha1.h>
static int do_sha1sum(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unsigned long addr, len;
unsigned int i;
u8 output[20];
if (argc < 3)
return cmd_usage(cmdtp);
addr = simple_strtoul(argv[1], NULL, 16);
len = simple_strtoul(argv[2], NULL, 16);
sha1_csum_wd((unsigned char *) addr, len, output, CHUNKSZ_SHA1);
printf("SHA1 for %08lx ... %08lx ==> ", addr, addr + len - 1);
for (i = 0; i < 20; i++)
printf("%02x", output[i]);
printf("\n");
return 0;
}
U_BOOT_CMD(
sha1sum, 3, 1, do_sha1sum,
"compute SHA1 message digest",
"address count"
);
|
1001-study-uboot
|
common/cmd_sha1sum.c
|
C
|
gpl3
| 1,521
|
/*
* 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 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 <tpm.h>
#define MAX_TRANSACTION_SIZE 30
/*
* tpm_write() expects a variable number of parameters: the internal address
* followed by data to write, byte by byte.
*
* Returns 0 on success or -1 on errors (wrong arguments or TPM failure).
*/
static int tpm_process(int argc, char * const argv[], cmd_tbl_t *cmdtp)
{
u8 tpm_buffer[MAX_TRANSACTION_SIZE];
u32 write_size, read_size;
char *p;
int rv = -1;
for (write_size = 0; write_size < argc; write_size++) {
u32 datum = simple_strtoul(argv[write_size], &p, 0);
if (*p || (datum > 0xff)) {
printf("\n%s: bad data value\n\n", argv[write_size]);
cmd_usage(cmdtp);
return rv;
}
tpm_buffer[write_size] = (u8)datum;
}
read_size = sizeof(tpm_buffer);
if (!tis_sendrecv(tpm_buffer, write_size, tpm_buffer, &read_size)) {
int i;
puts("Got TPM response:\n");
for (i = 0; i < read_size; i++)
printf(" %2.2x", tpm_buffer[i]);
puts("\n");
rv = 0;
} else {
puts("tpm command failed\n");
}
return rv;
}
static int do_tpm(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int rv = 0;
/*
* Verify that in case it is present, the first argument, it is
* exactly one character in size.
*/
if (argc < 7) {
puts("command should be at least six bytes in size\n");
return -1;
}
if (tis_init()) {
puts("tis_init() failed!\n");
return -1;
}
if (tis_open()) {
puts("tis_open() failed!\n");
return -1;
}
rv = tpm_process(argc - 1, argv + 1, cmdtp);
if (tis_close()) {
puts("tis_close() failed!\n");
rv = -1;
}
return rv;
}
U_BOOT_CMD(tpm, MAX_TRANSACTION_SIZE, 1, do_tpm,
"<byte> [<byte> ...] - write data and read response",
"send arbitrary data (at least 6 bytes) to the TPM "
"device and read the response"
);
|
1001-study-uboot
|
common/cmd_tpm.c
|
C
|
gpl3
| 2,653
|
/*
* Copyright 2000-2009
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
int do_exit(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int r;
r = 0;
if (argc > 1)
r = simple_strtoul(argv[1], NULL, 10);
return -r - 2;
}
U_BOOT_CMD(
exit, 2, 1, do_exit,
"exit script",
""
);
|
1001-study-uboot
|
common/cmd_exit.c
|
C
|
gpl3
| 1,148
|
/*
* (C) Copyright 2001
* Denis Peter, MPL AG Switzerland
*
* Most of this source has been derived from the Linux USB
* project.
*
* 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/byteorder.h>
#include <asm/unaligned.h>
#include <part.h>
#include <usb.h>
#ifdef CONFIG_USB_STORAGE
static int usb_stor_curr_dev = -1; /* current device */
#endif
#ifdef CONFIG_USB_HOST_ETHER
static int usb_ether_curr_dev = -1; /* current ethernet device */
#endif
/* some display routines (info command) */
char *usb_get_class_desc(unsigned char dclass)
{
switch (dclass) {
case USB_CLASS_PER_INTERFACE:
return "See Interface";
case USB_CLASS_AUDIO:
return "Audio";
case USB_CLASS_COMM:
return "Communication";
case USB_CLASS_HID:
return "Human Interface";
case USB_CLASS_PRINTER:
return "Printer";
case USB_CLASS_MASS_STORAGE:
return "Mass Storage";
case USB_CLASS_HUB:
return "Hub";
case USB_CLASS_DATA:
return "CDC Data";
case USB_CLASS_VENDOR_SPEC:
return "Vendor specific";
default:
return "";
}
}
void usb_display_class_sub(unsigned char dclass, unsigned char subclass,
unsigned char proto)
{
switch (dclass) {
case USB_CLASS_PER_INTERFACE:
printf("See Interface");
break;
case USB_CLASS_HID:
printf("Human Interface, Subclass: ");
switch (subclass) {
case USB_SUB_HID_NONE:
printf("None");
break;
case USB_SUB_HID_BOOT:
printf("Boot ");
switch (proto) {
case USB_PROT_HID_NONE:
printf("None");
break;
case USB_PROT_HID_KEYBOARD:
printf("Keyboard");
break;
case USB_PROT_HID_MOUSE:
printf("Mouse");
break;
default:
printf("reserved");
break;
}
break;
default:
printf("reserved");
break;
}
break;
case USB_CLASS_MASS_STORAGE:
printf("Mass Storage, ");
switch (subclass) {
case US_SC_RBC:
printf("RBC ");
break;
case US_SC_8020:
printf("SFF-8020i (ATAPI)");
break;
case US_SC_QIC:
printf("QIC-157 (Tape)");
break;
case US_SC_UFI:
printf("UFI");
break;
case US_SC_8070:
printf("SFF-8070");
break;
case US_SC_SCSI:
printf("Transp. SCSI");
break;
default:
printf("reserved");
break;
}
printf(", ");
switch (proto) {
case US_PR_CB:
printf("Command/Bulk");
break;
case US_PR_CBI:
printf("Command/Bulk/Int");
break;
case US_PR_BULK:
printf("Bulk only");
break;
default:
printf("reserved");
break;
}
break;
default:
printf("%s", usb_get_class_desc(dclass));
break;
}
}
void usb_display_string(struct usb_device *dev, int index)
{
char buffer[256];
if (index != 0) {
if (usb_string(dev, index, &buffer[0], 256) > 0)
printf("String: \"%s\"", buffer);
}
}
void usb_display_desc(struct usb_device *dev)
{
if (dev->descriptor.bDescriptorType == USB_DT_DEVICE) {
printf("%d: %s, USB Revision %x.%x\n", dev->devnum,
usb_get_class_desc(dev->config.if_desc[0].desc.bInterfaceClass),
(dev->descriptor.bcdUSB>>8) & 0xff,
dev->descriptor.bcdUSB & 0xff);
if (strlen(dev->mf) || strlen(dev->prod) ||
strlen(dev->serial))
printf(" - %s %s %s\n", dev->mf, dev->prod,
dev->serial);
if (dev->descriptor.bDeviceClass) {
printf(" - Class: ");
usb_display_class_sub(dev->descriptor.bDeviceClass,
dev->descriptor.bDeviceSubClass,
dev->descriptor.bDeviceProtocol);
printf("\n");
} else {
printf(" - Class: (from Interface) %s\n",
usb_get_class_desc(
dev->config.if_desc[0].desc.bInterfaceClass));
}
printf(" - PacketSize: %d Configurations: %d\n",
dev->descriptor.bMaxPacketSize0,
dev->descriptor.bNumConfigurations);
printf(" - Vendor: 0x%04x Product 0x%04x Version %d.%d\n",
dev->descriptor.idVendor, dev->descriptor.idProduct,
(dev->descriptor.bcdDevice>>8) & 0xff,
dev->descriptor.bcdDevice & 0xff);
}
}
void usb_display_conf_desc(struct usb_configuration_descriptor *config,
struct usb_device *dev)
{
printf(" Configuration: %d\n", config->bConfigurationValue);
printf(" - Interfaces: %d %s%s%dmA\n", config->bNumInterfaces,
(config->bmAttributes & 0x40) ? "Self Powered " : "Bus Powered ",
(config->bmAttributes & 0x20) ? "Remote Wakeup " : "",
config->bMaxPower*2);
if (config->iConfiguration) {
printf(" - ");
usb_display_string(dev, config->iConfiguration);
printf("\n");
}
}
void usb_display_if_desc(struct usb_interface_descriptor *ifdesc,
struct usb_device *dev)
{
printf(" Interface: %d\n", ifdesc->bInterfaceNumber);
printf(" - Alternate Setting %d, Endpoints: %d\n",
ifdesc->bAlternateSetting, ifdesc->bNumEndpoints);
printf(" - Class ");
usb_display_class_sub(ifdesc->bInterfaceClass,
ifdesc->bInterfaceSubClass, ifdesc->bInterfaceProtocol);
printf("\n");
if (ifdesc->iInterface) {
printf(" - ");
usb_display_string(dev, ifdesc->iInterface);
printf("\n");
}
}
void usb_display_ep_desc(struct usb_endpoint_descriptor *epdesc)
{
printf(" - Endpoint %d %s ", epdesc->bEndpointAddress & 0xf,
(epdesc->bEndpointAddress & 0x80) ? "In" : "Out");
switch ((epdesc->bmAttributes & 0x03)) {
case 0:
printf("Control");
break;
case 1:
printf("Isochronous");
break;
case 2:
printf("Bulk");
break;
case 3:
printf("Interrupt");
break;
}
printf(" MaxPacket %d", get_unaligned(&epdesc->wMaxPacketSize));
if ((epdesc->bmAttributes & 0x03) == 0x3)
printf(" Interval %dms", epdesc->bInterval);
printf("\n");
}
/* main routine to diasplay the configs, interfaces and endpoints */
void usb_display_config(struct usb_device *dev)
{
struct usb_config *config;
struct usb_interface *ifdesc;
struct usb_endpoint_descriptor *epdesc;
int i, ii;
config = &dev->config;
usb_display_conf_desc(&config->desc, dev);
for (i = 0; i < config->no_of_if; i++) {
ifdesc = &config->if_desc[i];
usb_display_if_desc(&ifdesc->desc, dev);
for (ii = 0; ii < ifdesc->no_of_ep; ii++) {
epdesc = &ifdesc->ep_desc[ii];
usb_display_ep_desc(epdesc);
}
}
printf("\n");
}
static inline char *portspeed(int speed)
{
if (speed == USB_SPEED_HIGH)
return "480 Mb/s";
else if (speed == USB_SPEED_LOW)
return "1.5 Mb/s";
else
return "12 Mb/s";
}
/* shows the device tree recursively */
void usb_show_tree_graph(struct usb_device *dev, char *pre)
{
int i, index;
int has_child, last_child;
index = strlen(pre);
printf(" %s", pre);
/* check if the device has connected children */
has_child = 0;
for (i = 0; i < dev->maxchild; i++) {
if (dev->children[i] != NULL)
has_child = 1;
}
/* check if we are the last one */
last_child = 1;
if (dev->parent != NULL) {
for (i = 0; i < dev->parent->maxchild; i++) {
/* search for children */
if (dev->parent->children[i] == dev) {
/* found our pointer, see if we have a
* little sister
*/
while (i++ < dev->parent->maxchild) {
if (dev->parent->children[i] != NULL) {
/* found a sister */
last_child = 0;
break;
} /* if */
} /* while */
} /* device found */
} /* for all children of the parent */
printf("\b+-");
/* correct last child */
if (last_child)
pre[index-1] = ' ';
} /* if not root hub */
else
printf(" ");
printf("%d ", dev->devnum);
pre[index++] = ' ';
pre[index++] = has_child ? '|' : ' ';
pre[index] = 0;
printf(" %s (%s, %dmA)\n", usb_get_class_desc(
dev->config.if_desc[0].desc.bInterfaceClass),
portspeed(dev->speed),
dev->config.desc.bMaxPower * 2);
if (strlen(dev->mf) || strlen(dev->prod) || strlen(dev->serial))
printf(" %s %s %s %s\n", pre, dev->mf, dev->prod, dev->serial);
printf(" %s\n", pre);
if (dev->maxchild > 0) {
for (i = 0; i < dev->maxchild; i++) {
if (dev->children[i] != NULL) {
usb_show_tree_graph(dev->children[i], pre);
pre[index] = 0;
}
}
}
}
/* main routine for the tree command */
void usb_show_tree(struct usb_device *dev)
{
char preamble[32];
memset(preamble, 0, 32);
usb_show_tree_graph(dev, &preamble[0]);
}
/******************************************************************************
* usb boot command intepreter. Derived from diskboot
*/
#ifdef CONFIG_USB_STORAGE
int do_usbboot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *boot_device = NULL;
char *ep;
int dev, part = 1;
ulong addr, cnt;
disk_partition_t info;
image_header_t *hdr;
block_dev_desc_t *stor_dev;
#if defined(CONFIG_FIT)
const void *fit_hdr = NULL;
#endif
switch (argc) {
case 1:
addr = CONFIG_SYS_LOAD_ADDR;
boot_device = getenv("bootdevice");
break;
case 2:
addr = simple_strtoul(argv[1], NULL, 16);
boot_device = getenv("bootdevice");
break;
case 3:
addr = simple_strtoul(argv[1], NULL, 16);
boot_device = argv[2];
break;
default:
return cmd_usage(cmdtp);
}
if (!boot_device) {
puts("\n** No boot device **\n");
return 1;
}
dev = simple_strtoul(boot_device, &ep, 16);
stor_dev = usb_stor_get_dev(dev);
if (stor_dev == NULL || stor_dev->type == DEV_TYPE_UNKNOWN) {
printf("\n** Device %d not available\n", dev);
return 1;
}
if (stor_dev->block_read == NULL) {
printf("storage device not initialized. Use usb scan\n");
return 1;
}
if (*ep) {
if (*ep != ':') {
puts("\n** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = simple_strtoul(++ep, NULL, 16);
}
if (get_partition_info(stor_dev, part, &info)) {
/* try to boot raw .... */
strncpy((char *)&info.type[0], BOOT_PART_TYPE,
sizeof(BOOT_PART_TYPE));
strncpy((char *)&info.name[0], "Raw", 4);
info.start = 0;
info.blksz = 0x200;
info.size = 2880;
printf("error reading partinfo...try to boot raw\n");
}
if ((strncmp((char *)info.type, BOOT_PART_TYPE,
sizeof(info.type)) != 0) &&
(strncmp((char *)info.type, BOOT_PART_COMP,
sizeof(info.type)) != 0)) {
printf("\n** Invalid partition type \"%.32s\""
" (expect \"" BOOT_PART_TYPE "\")\n",
info.type);
return 1;
}
printf("\nLoading from USB device %d, partition %d: "
"Name: %.32s Type: %.32s\n",
dev, part, info.name, info.type);
debug("First Block: %ld, # of blocks: %ld, Block Size: %ld\n",
info.start, info.size, info.blksz);
if (stor_dev->block_read(dev, info.start, 1, (ulong *)addr) != 1) {
printf("** Read error on %d:%d\n", dev, part);
return 1;
}
switch (genimg_get_format((void *)addr)) {
case IMAGE_FORMAT_LEGACY:
hdr = (image_header_t *)addr;
if (!image_check_hcrc(hdr)) {
puts("\n** Bad Header Checksum **\n");
return 1;
}
image_print_contents(hdr);
cnt = image_get_image_size(hdr);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
fit_hdr = (const void *)addr;
puts("Fit image detected...\n");
cnt = fit_get_size(fit_hdr);
break;
#endif
default:
puts("** Unknown image type\n");
return 1;
}
cnt += info.blksz - 1;
cnt /= info.blksz;
cnt -= 1;
if (stor_dev->block_read(dev, info.start+1, cnt,
(ulong *)(addr+info.blksz)) != cnt) {
printf("\n** Read error on %d:%d\n", dev, part);
return 1;
}
#if defined(CONFIG_FIT)
/* This cannot be done earlier, we need complete FIT image in RAM
* first
*/
if (genimg_get_format((void *)addr) == IMAGE_FORMAT_FIT) {
if (!fit_check_format(fit_hdr)) {
puts("** Bad FIT image format\n");
return 1;
}
fit_print_contents(fit_hdr);
}
#endif
/* Loading ok, update default load address */
load_addr = addr;
flush_cache(addr, (cnt+1)*info.blksz);
return bootm_maybe_autostart(cmdtp, argv[0]);
}
#endif /* CONFIG_USB_STORAGE */
/******************************************************************************
* usb command intepreter
*/
int do_usb(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
struct usb_device *dev = NULL;
extern char usb_started;
#ifdef CONFIG_USB_STORAGE
block_dev_desc_t *stor_dev;
#endif
if (argc < 2)
return cmd_usage(cmdtp);
if ((strncmp(argv[1], "reset", 5) == 0) ||
(strncmp(argv[1], "start", 5) == 0)) {
usb_stop();
printf("(Re)start USB...\n");
i = usb_init();
if (i >= 0) {
#ifdef CONFIG_USB_STORAGE
/* try to recognize storage devices immediately */
usb_stor_curr_dev = usb_stor_scan(1);
#endif
#ifdef CONFIG_USB_HOST_ETHER
/* try to recognize ethernet devices immediately */
usb_ether_curr_dev = usb_host_eth_scan(1);
#endif
}
return 0;
}
if (strncmp(argv[1], "stop", 4) == 0) {
#ifdef CONFIG_USB_KEYBOARD
if (argc == 2) {
if (usb_kbd_deregister() != 0) {
printf("USB not stopped: usbkbd still"
" using USB\n");
return 1;
}
} else {
/* forced stop, switch console in to serial */
console_assign(stdin, "serial");
usb_kbd_deregister();
}
#endif
printf("stopping USB..\n");
usb_stop();
return 0;
}
if (!usb_started) {
printf("USB is stopped. Please issue 'usb start' first.\n");
return 1;
}
if (strncmp(argv[1], "tree", 4) == 0) {
printf("\nDevice Tree:\n");
usb_show_tree(usb_get_dev_index(0));
return 0;
}
if (strncmp(argv[1], "inf", 3) == 0) {
int d;
if (argc == 2) {
for (d = 0; d < USB_MAX_DEVICE; d++) {
dev = usb_get_dev_index(d);
if (dev == NULL)
break;
usb_display_desc(dev);
usb_display_config(dev);
}
return 0;
} else {
int d;
i = simple_strtoul(argv[2], NULL, 16);
printf("config for device %d\n", i);
for (d = 0; d < USB_MAX_DEVICE; d++) {
dev = usb_get_dev_index(d);
if (dev == NULL)
break;
if (dev->devnum == i)
break;
}
if (dev == NULL) {
printf("*** No device available ***\n");
return 0;
} else {
usb_display_desc(dev);
usb_display_config(dev);
}
}
return 0;
}
#ifdef CONFIG_USB_STORAGE
if (strncmp(argv[1], "stor", 4) == 0)
return usb_stor_info();
if (strncmp(argv[1], "part", 4) == 0) {
int devno, ok = 0;
if (argc == 2) {
for (devno = 0; ; ++devno) {
stor_dev = usb_stor_get_dev(devno);
if (stor_dev == NULL)
break;
if (stor_dev->type != DEV_TYPE_UNKNOWN) {
ok++;
if (devno)
printf("\n");
debug("print_part of %x\n", devno);
print_part(stor_dev);
}
}
} else {
devno = simple_strtoul(argv[2], NULL, 16);
stor_dev = usb_stor_get_dev(devno);
if (stor_dev != NULL &&
stor_dev->type != DEV_TYPE_UNKNOWN) {
ok++;
debug("print_part of %x\n", devno);
print_part(stor_dev);
}
}
if (!ok) {
printf("\nno USB devices available\n");
return 1;
}
return 0;
}
if (strcmp(argv[1], "read") == 0) {
if (usb_stor_curr_dev < 0) {
printf("no current device selected\n");
return 1;
}
if (argc == 5) {
unsigned long addr = simple_strtoul(argv[2], NULL, 16);
unsigned long blk = simple_strtoul(argv[3], NULL, 16);
unsigned long cnt = simple_strtoul(argv[4], NULL, 16);
unsigned long n;
printf("\nUSB read: device %d block # %ld, count %ld"
" ... ", usb_stor_curr_dev, blk, cnt);
stor_dev = usb_stor_get_dev(usb_stor_curr_dev);
n = stor_dev->block_read(usb_stor_curr_dev, blk, cnt,
(ulong *)addr);
printf("%ld blocks read: %s\n", n,
(n == cnt) ? "OK" : "ERROR");
if (n == cnt)
return 0;
return 1;
}
}
if (strcmp(argv[1], "write") == 0) {
if (usb_stor_curr_dev < 0) {
printf("no current device selected\n");
return 1;
}
if (argc == 5) {
unsigned long addr = simple_strtoul(argv[2], NULL, 16);
unsigned long blk = simple_strtoul(argv[3], NULL, 16);
unsigned long cnt = simple_strtoul(argv[4], NULL, 16);
unsigned long n;
printf("\nUSB write: device %d block # %ld, count %ld"
" ... ", usb_stor_curr_dev, blk, cnt);
stor_dev = usb_stor_get_dev(usb_stor_curr_dev);
n = stor_dev->block_write(usb_stor_curr_dev, blk, cnt,
(ulong *)addr);
printf("%ld blocks write: %s\n", n,
(n == cnt) ? "OK" : "ERROR");
if (n == cnt)
return 0;
return 1;
}
}
if (strncmp(argv[1], "dev", 3) == 0) {
if (argc == 3) {
int dev = (int)simple_strtoul(argv[2], NULL, 10);
printf("\nUSB device %d: ", dev);
stor_dev = usb_stor_get_dev(dev);
if (stor_dev == NULL) {
printf("unknown device\n");
return 1;
}
printf("\n Device %d: ", dev);
dev_print(stor_dev);
if (stor_dev->type == DEV_TYPE_UNKNOWN)
return 1;
usb_stor_curr_dev = dev;
printf("... is now current device\n");
return 0;
} else {
printf("\nUSB device %d: ", usb_stor_curr_dev);
stor_dev = usb_stor_get_dev(usb_stor_curr_dev);
dev_print(stor_dev);
if (stor_dev->type == DEV_TYPE_UNKNOWN)
return 1;
return 0;
}
return 0;
}
#endif /* CONFIG_USB_STORAGE */
return cmd_usage(cmdtp);
}
#ifdef CONFIG_USB_STORAGE
U_BOOT_CMD(
usb, 5, 1, do_usb,
"USB sub-system",
"start - start (scan) USB controller\n"
"usb reset - reset (rescan) USB controller\n"
"usb stop [f] - stop USB [f]=force stop\n"
"usb tree - show USB device tree\n"
"usb info [dev] - show available USB devices\n"
"usb storage - show details of USB storage devices\n"
"usb dev [dev] - show or set current USB storage device\n"
"usb part [dev] - print partition table of one or all USB storage"
" devices\n"
"usb read addr blk# cnt - read `cnt' blocks starting at block `blk#'\n"
" to memory address `addr'\n"
"usb write addr blk# cnt - write `cnt' blocks starting at block `blk#'\n"
" from memory address `addr'"
);
U_BOOT_CMD(
usbboot, 3, 1, do_usbboot,
"boot from USB device",
"loadAddr dev:part"
);
#else
U_BOOT_CMD(
usb, 5, 1, do_usb,
"USB sub-system",
"start - start (scan) USB controller\n"
"usb reset - reset (rescan) USB controller\n"
"usb tree - show USB device tree\n"
"usb info [dev] - show available USB devices"
);
#endif
|
1001-study-uboot
|
common/cmd_usb.c
|
C
|
gpl3
| 18,360
|
/*
* Command for mmc_spi setup.
*
* Copyright (C) 2010 Thomas Chou <thomas@wytron.com.tw>
* Licensed under the GPL-2 or later.
*/
#include <common.h>
#include <mmc.h>
#include <spi.h>
#ifndef CONFIG_MMC_SPI_BUS
# define CONFIG_MMC_SPI_BUS 0
#endif
#ifndef CONFIG_MMC_SPI_CS
# define CONFIG_MMC_SPI_CS 1
#endif
/* in SPI mode, MMC speed limit is 20MHz, while SD speed limit is 25MHz */
#ifndef CONFIG_MMC_SPI_SPEED
# define CONFIG_MMC_SPI_SPEED 25000000
#endif
/* MMC and SD specs only seem to care that sampling is on the
* rising edge ... meaning SPI modes 0 or 3. So either SPI mode
* should be legit. We'll use mode 0 since the steady state is 0,
* which is appropriate for hotplugging, unless the platform data
* specify mode 3 (if hardware is not compatible to mode 0).
*/
#ifndef CONFIG_MMC_SPI_MODE
# define CONFIG_MMC_SPI_MODE SPI_MODE_0
#endif
static int do_mmc_spi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
uint bus = CONFIG_MMC_SPI_BUS;
uint cs = CONFIG_MMC_SPI_CS;
uint speed = CONFIG_MMC_SPI_SPEED;
uint mode = CONFIG_MMC_SPI_MODE;
char *endp;
struct mmc *mmc;
if (argc < 2)
goto usage;
cs = simple_strtoul(argv[1], &endp, 0);
if (*argv[1] == 0 || (*endp != 0 && *endp != ':'))
goto usage;
if (*endp == ':') {
if (endp[1] == 0)
goto usage;
bus = cs;
cs = simple_strtoul(endp + 1, &endp, 0);
if (*endp != 0)
goto usage;
}
if (argc >= 3) {
speed = simple_strtoul(argv[2], &endp, 0);
if (*argv[2] == 0 || *endp != 0)
goto usage;
}
if (argc >= 4) {
mode = simple_strtoul(argv[3], &endp, 16);
if (*argv[3] == 0 || *endp != 0)
goto usage;
}
if (!spi_cs_is_valid(bus, cs)) {
printf("Invalid SPI bus %u cs %u\n", bus, cs);
return 1;
}
mmc = mmc_spi_init(bus, cs, speed, mode);
if (!mmc) {
printf("Failed to create MMC Device\n");
return 1;
}
printf("%s: %d at %u:%u hz %u mode %u\n", mmc->name, mmc->block_dev.dev,
bus, cs, speed, mode);
mmc_init(mmc);
return 0;
usage:
cmd_usage(cmdtp);
return 1;
}
U_BOOT_CMD(
mmc_spi, 4, 0, do_mmc_spi,
"mmc_spi setup",
"[bus:]cs [hz] [mode] - setup mmc_spi device"
);
|
1001-study-uboot
|
common/cmd_mmc_spi.c
|
C
|
gpl3
| 2,125
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <s_record.h>
static int hex1_bin (char c);
static int hex2_bin (char *s);
int srec_decode (char *input, int *count, ulong *addr, char *data)
{
int i;
int v; /* conversion buffer */
int srec_type; /* S-Record type */
unsigned char chksum; /* buffer for checksum */
chksum = 0;
/* skip anything before 'S', and the 'S' itself.
* Return error if not found
*/
for (; *input; ++input) {
if (*input == 'S') { /* skip 'S' */
++input;
break;
}
}
if (*input == '\0') { /* no more data? */
return (SREC_EMPTY);
}
v = *input++; /* record type */
if ((*count = hex2_bin(input)) < 0) {
return (SREC_E_NOSREC);
}
chksum += *count;
input += 2;
switch (v) { /* record type */
case '0': /* start record */
srec_type = SREC_START; /* 2 byte addr field */
*count -= 3; /* - checksum and addr */
break;
case '1':
srec_type = SREC_DATA2; /* 2 byte addr field */
*count -= 3; /* - checksum and addr */
break;
case '2':
srec_type = SREC_DATA3; /* 3 byte addr field */
*count -= 4; /* - checksum and addr */
break;
case '3': /* data record with a */
srec_type = SREC_DATA4; /* 4 byte addr field */
*count -= 5; /* - checksum and addr */
break;
/*** case '4' ***/
case '5': /* count record, addr field contains */
srec_type = SREC_COUNT; /* a 2 byte record counter */
*count = 0; /* no data */
break;
/*** case '6' -- not used ***/
case '7': /* end record with a */
srec_type = SREC_END4; /* 4 byte addr field */
*count -= 5; /* - checksum and addr */
break;
case '8': /* end record with a */
srec_type = SREC_END3; /* 3 byte addr field */
*count -= 4; /* - checksum and addr */
break;
case '9': /* end record with a */
srec_type = SREC_END2; /* 2 byte addr field */
*count -= 3; /* - checksum and addr */
break;
default:
return (SREC_E_BADTYPE);
}
/* read address field */
*addr = 0;
switch (v) {
case '3': /* 4 byte addr field */
case '7':
if ((v = hex2_bin(input)) < 0) {
return (SREC_E_NOSREC);
}
*addr += v;
chksum += v;
input += 2;
/* FALL THRU */
case '2': /* 3 byte addr field */
case '8':
if ((v = hex2_bin(input)) < 0) {
return (SREC_E_NOSREC);
}
*addr <<= 8;
*addr += v;
chksum += v;
input += 2;
/* FALL THRU */
case '0': /* 2 byte addr field */
case '1':
case '5':
case '9':
if ((v = hex2_bin(input)) < 0) {
return (SREC_E_NOSREC);
}
*addr <<= 8;
*addr += v;
chksum += v;
input += 2;
if ((v = hex2_bin(input)) < 0) {
return (SREC_E_NOSREC);
}
*addr <<= 8;
*addr += v;
chksum += v;
input += 2;
break;
default:
return (SREC_E_BADTYPE);
}
/* convert data and calculate checksum */
for (i=0; i < *count; ++i) {
if ((v = hex2_bin(input)) < 0) {
return (SREC_E_NOSREC);
}
data[i] = v;
chksum += v;
input += 2;
}
/* read anc check checksum */
if ((v = hex2_bin(input)) < 0) {
return (SREC_E_NOSREC);
}
if ((unsigned char)v != (unsigned char)~chksum) {
return (SREC_E_BADCHKS);
}
return (srec_type);
}
static int hex1_bin (char c)
{
if (c >= '0' && c <= '9')
return (c - '0');
if (c >= 'a' && c <= 'f')
return (c + 10 - 'a');
if (c >= 'A' && c <= 'F')
return (c + 10 - 'A');
return (-1);
}
static int hex2_bin (char *s)
{
int i, j;
if ((i = hex1_bin(*s++)) < 0) {
return (-1);
}
if ((j = hex1_bin(*s)) < 0) {
return (-1);
}
return ((i<<4) + j);
}
|
1001-study-uboot
|
common/s_record.c
|
C
|
gpl3
| 4,377
|
/*
* (C) Copyright 2003
* Marc Singer, elf@buici.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
*/
/*
* Port I/O Functions
*
* Copied from FADS ROM, Dan Malek (dmalek@jlc.net)
*/
#include <common.h>
#include <command.h>
/* Display values from last command.
* Memory modify remembered values are different from display memory.
*/
static uint in_last_addr, in_last_size;
static uint out_last_addr, out_last_size, out_last_value;
int do_portio_out (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
uint addr = out_last_addr;
uint size = out_last_size;
uint value = out_last_value;
if (argc != 3)
return cmd_usage(cmdtp);
if ((flag & CMD_FLAG_REPEAT) == 0) {
/*
* New command specified. Check for a size specification.
* Defaults to long if no or incorrect specification.
*/
size = cmd_get_data_size (argv[0], 1);
addr = simple_strtoul (argv[1], NULL, 16);
value = simple_strtoul (argv[2], NULL, 16);
}
#if defined (CONFIG_X86)
{
unsigned short port = addr;
switch (size) {
default:
case 1:
{
unsigned char ch = value;
__asm__ volatile ("out %0, %%dx"::"a" (ch), "d" (port));
}
break;
case 2:
{
unsigned short w = value;
__asm__ volatile ("out %0, %%dx"::"a" (w), "d" (port));
}
break;
case 4:
__asm__ volatile ("out %0, %%dx"::"a" (value), "d" (port));
break;
}
}
#endif /* CONFIG_X86 */
out_last_addr = addr;
out_last_size = size;
out_last_value = value;
return 0;
}
U_BOOT_CMD(
out, 3, 1, do_portio_out,
"write datum to IO port",
"[.b, .w, .l] port value\n - output to IO port"
);
int do_portio_in (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
uint addr = in_last_addr;
uint size = in_last_size;
if (argc != 2)
return cmd_usage(cmdtp);
if ((flag & CMD_FLAG_REPEAT) == 0) {
/*
* New command specified. Check for a size specification.
* Defaults to long if no or incorrect specification.
*/
size = cmd_get_data_size (argv[0], 1);
addr = simple_strtoul (argv[1], NULL, 16);
}
#if defined (CONFIG_X86)
{
unsigned short port = addr;
switch (size) {
default:
case 1:
{
unsigned char ch;
__asm__ volatile ("in %%dx, %0":"=a" (ch):"d" (port));
printf (" %02x\n", ch);
}
break;
case 2:
{
unsigned short w;
__asm__ volatile ("in %%dx, %0":"=a" (w):"d" (port));
printf (" %04x\n", w);
}
break;
case 4:
{
unsigned long l;
__asm__ volatile ("in %%dx, %0":"=a" (l):"d" (port));
printf (" %08lx\n", l);
}
break;
}
}
#endif /* CONFIG_X86 */
in_last_addr = addr;
in_last_size = size;
return 0;
}
U_BOOT_CMD(
in, 2, 1, do_portio_in,
"read data from an IO port",
"[.b, .w, .l] port\n"
" - read datum from IO port"
);
|
1001-study-uboot
|
common/cmd_portio.c
|
C
|
gpl3
| 3,540
|
/*
* (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Andreas Heppel <aheppel@sysgo.de>
*
* (C) Copyright 2002
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
* Wolfgang Grandegger, DENX Software Engineering, wg@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
*/
/*
* PCI routines
*/
#include <common.h>
#include <command.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <pci.h>
unsigned char ShortPCIListing = 1;
/*
* Follows routines for the output of infos about devices on PCI bus.
*/
void pci_header_show(pci_dev_t dev);
void pci_header_show_brief(pci_dev_t dev);
/*
* Subroutine: pciinfo
*
* Description: Show information about devices on PCI bus.
* Depending on the define CONFIG_SYS_SHORT_PCI_LISTING
* the output will be more or less exhaustive.
*
* Inputs: bus_no the number of the bus to be scanned.
*
* Return: None
*
*/
void pciinfo(int BusNum, int ShortPCIListing)
{
int Device;
int Function;
unsigned char HeaderType;
unsigned short VendorID;
pci_dev_t dev;
printf("Scanning PCI devices on bus %d\n", BusNum);
if (ShortPCIListing) {
printf("BusDevFun VendorId DeviceId Device Class Sub-Class\n");
printf("_____________________________________________________________\n");
}
for (Device = 0; Device < PCI_MAX_PCI_DEVICES; Device++) {
HeaderType = 0;
VendorID = 0;
for (Function = 0; Function < PCI_MAX_PCI_FUNCTIONS; Function++) {
/*
* If this is not a multi-function device, we skip the rest.
*/
if (Function && !(HeaderType & 0x80))
break;
dev = PCI_BDF(BusNum, Device, Function);
pci_read_config_word(dev, PCI_VENDOR_ID, &VendorID);
if ((VendorID == 0xFFFF) || (VendorID == 0x0000))
continue;
if (!Function) pci_read_config_byte(dev, PCI_HEADER_TYPE, &HeaderType);
if (ShortPCIListing)
{
printf("%02x.%02x.%02x ", BusNum, Device, Function);
pci_header_show_brief(dev);
}
else
{
printf("\nFound PCI device %02x.%02x.%02x:\n",
BusNum, Device, Function);
pci_header_show(dev);
}
}
}
}
/*
* Subroutine: pci_header_show_brief
*
* Description: Reads and prints the header of the
* specified PCI device in short form.
*
* Inputs: dev Bus+Device+Function number
*
* Return: None
*
*/
void pci_header_show_brief(pci_dev_t dev)
{
u16 vendor, device;
u8 class, subclass;
pci_read_config_word(dev, PCI_VENDOR_ID, &vendor);
pci_read_config_word(dev, PCI_DEVICE_ID, &device);
pci_read_config_byte(dev, PCI_CLASS_CODE, &class);
pci_read_config_byte(dev, PCI_CLASS_SUB_CODE, &subclass);
printf("0x%.4x 0x%.4x %-23s 0x%.2x\n",
vendor, device,
pci_class_str(class), subclass);
}
/*
* Subroutine: PCI_Header_Show
*
* Description: Reads the header of the specified PCI device.
*
* Inputs: BusDevFunc Bus+Device+Function number
*
* Return: None
*
*/
void pci_header_show(pci_dev_t dev)
{
u8 _byte, header_type;
u16 _word;
u32 _dword;
#define PRINT(msg, type, reg) \
pci_read_config_##type(dev, reg, &_##type); \
printf(msg, _##type)
#define PRINT2(msg, type, reg, func) \
pci_read_config_##type(dev, reg, &_##type); \
printf(msg, _##type, func(_##type))
pci_read_config_byte(dev, PCI_HEADER_TYPE, &header_type);
PRINT (" vendor ID = 0x%.4x\n", word, PCI_VENDOR_ID);
PRINT (" device ID = 0x%.4x\n", word, PCI_DEVICE_ID);
PRINT (" command register = 0x%.4x\n", word, PCI_COMMAND);
PRINT (" status register = 0x%.4x\n", word, PCI_STATUS);
PRINT (" revision ID = 0x%.2x\n", byte, PCI_REVISION_ID);
PRINT2(" class code = 0x%.2x (%s)\n", byte, PCI_CLASS_CODE,
pci_class_str);
PRINT (" sub class code = 0x%.2x\n", byte, PCI_CLASS_SUB_CODE);
PRINT (" programming interface = 0x%.2x\n", byte, PCI_CLASS_PROG);
PRINT (" cache line = 0x%.2x\n", byte, PCI_CACHE_LINE_SIZE);
PRINT (" latency time = 0x%.2x\n", byte, PCI_LATENCY_TIMER);
PRINT (" header type = 0x%.2x\n", byte, PCI_HEADER_TYPE);
PRINT (" BIST = 0x%.2x\n", byte, PCI_BIST);
PRINT (" base address 0 = 0x%.8x\n", dword, PCI_BASE_ADDRESS_0);
switch (header_type & 0x03) {
case PCI_HEADER_TYPE_NORMAL: /* "normal" PCI device */
PRINT (" base address 1 = 0x%.8x\n", dword, PCI_BASE_ADDRESS_1);
PRINT (" base address 2 = 0x%.8x\n", dword, PCI_BASE_ADDRESS_2);
PRINT (" base address 3 = 0x%.8x\n", dword, PCI_BASE_ADDRESS_3);
PRINT (" base address 4 = 0x%.8x\n", dword, PCI_BASE_ADDRESS_4);
PRINT (" base address 5 = 0x%.8x\n", dword, PCI_BASE_ADDRESS_5);
PRINT (" cardBus CIS pointer = 0x%.8x\n", dword, PCI_CARDBUS_CIS);
PRINT (" sub system vendor ID = 0x%.4x\n", word, PCI_SUBSYSTEM_VENDOR_ID);
PRINT (" sub system ID = 0x%.4x\n", word, PCI_SUBSYSTEM_ID);
PRINT (" expansion ROM base address = 0x%.8x\n", dword, PCI_ROM_ADDRESS);
PRINT (" interrupt line = 0x%.2x\n", byte, PCI_INTERRUPT_LINE);
PRINT (" interrupt pin = 0x%.2x\n", byte, PCI_INTERRUPT_PIN);
PRINT (" min Grant = 0x%.2x\n", byte, PCI_MIN_GNT);
PRINT (" max Latency = 0x%.2x\n", byte, PCI_MAX_LAT);
break;
case PCI_HEADER_TYPE_BRIDGE: /* PCI-to-PCI bridge */
PRINT (" base address 1 = 0x%.8x\n", dword, PCI_BASE_ADDRESS_1);
PRINT (" primary bus number = 0x%.2x\n", byte, PCI_PRIMARY_BUS);
PRINT (" secondary bus number = 0x%.2x\n", byte, PCI_SECONDARY_BUS);
PRINT (" subordinate bus number = 0x%.2x\n", byte, PCI_SUBORDINATE_BUS);
PRINT (" secondary latency timer = 0x%.2x\n", byte, PCI_SEC_LATENCY_TIMER);
PRINT (" IO base = 0x%.2x\n", byte, PCI_IO_BASE);
PRINT (" IO limit = 0x%.2x\n", byte, PCI_IO_LIMIT);
PRINT (" secondary status = 0x%.4x\n", word, PCI_SEC_STATUS);
PRINT (" memory base = 0x%.4x\n", word, PCI_MEMORY_BASE);
PRINT (" memory limit = 0x%.4x\n", word, PCI_MEMORY_LIMIT);
PRINT (" prefetch memory base = 0x%.4x\n", word, PCI_PREF_MEMORY_BASE);
PRINT (" prefetch memory limit = 0x%.4x\n", word, PCI_PREF_MEMORY_LIMIT);
PRINT (" prefetch memory base upper = 0x%.8x\n", dword, PCI_PREF_BASE_UPPER32);
PRINT (" prefetch memory limit upper = 0x%.8x\n", dword, PCI_PREF_LIMIT_UPPER32);
PRINT (" IO base upper 16 bits = 0x%.4x\n", word, PCI_IO_BASE_UPPER16);
PRINT (" IO limit upper 16 bits = 0x%.4x\n", word, PCI_IO_LIMIT_UPPER16);
PRINT (" expansion ROM base address = 0x%.8x\n", dword, PCI_ROM_ADDRESS1);
PRINT (" interrupt line = 0x%.2x\n", byte, PCI_INTERRUPT_LINE);
PRINT (" interrupt pin = 0x%.2x\n", byte, PCI_INTERRUPT_PIN);
PRINT (" bridge control = 0x%.4x\n", word, PCI_BRIDGE_CONTROL);
break;
case PCI_HEADER_TYPE_CARDBUS: /* PCI-to-CardBus bridge */
PRINT (" capabilities = 0x%.2x\n", byte, PCI_CB_CAPABILITY_LIST);
PRINT (" secondary status = 0x%.4x\n", word, PCI_CB_SEC_STATUS);
PRINT (" primary bus number = 0x%.2x\n", byte, PCI_CB_PRIMARY_BUS);
PRINT (" CardBus number = 0x%.2x\n", byte, PCI_CB_CARD_BUS);
PRINT (" subordinate bus number = 0x%.2x\n", byte, PCI_CB_SUBORDINATE_BUS);
PRINT (" CardBus latency timer = 0x%.2x\n", byte, PCI_CB_LATENCY_TIMER);
PRINT (" CardBus memory base 0 = 0x%.8x\n", dword, PCI_CB_MEMORY_BASE_0);
PRINT (" CardBus memory limit 0 = 0x%.8x\n", dword, PCI_CB_MEMORY_LIMIT_0);
PRINT (" CardBus memory base 1 = 0x%.8x\n", dword, PCI_CB_MEMORY_BASE_1);
PRINT (" CardBus memory limit 1 = 0x%.8x\n", dword, PCI_CB_MEMORY_LIMIT_1);
PRINT (" CardBus IO base 0 = 0x%.4x\n", word, PCI_CB_IO_BASE_0);
PRINT (" CardBus IO base high 0 = 0x%.4x\n", word, PCI_CB_IO_BASE_0_HI);
PRINT (" CardBus IO limit 0 = 0x%.4x\n", word, PCI_CB_IO_LIMIT_0);
PRINT (" CardBus IO limit high 0 = 0x%.4x\n", word, PCI_CB_IO_LIMIT_0_HI);
PRINT (" CardBus IO base 1 = 0x%.4x\n", word, PCI_CB_IO_BASE_1);
PRINT (" CardBus IO base high 1 = 0x%.4x\n", word, PCI_CB_IO_BASE_1_HI);
PRINT (" CardBus IO limit 1 = 0x%.4x\n", word, PCI_CB_IO_LIMIT_1);
PRINT (" CardBus IO limit high 1 = 0x%.4x\n", word, PCI_CB_IO_LIMIT_1_HI);
PRINT (" interrupt line = 0x%.2x\n", byte, PCI_INTERRUPT_LINE);
PRINT (" interrupt pin = 0x%.2x\n", byte, PCI_INTERRUPT_PIN);
PRINT (" bridge control = 0x%.4x\n", word, PCI_CB_BRIDGE_CONTROL);
PRINT (" subvendor ID = 0x%.4x\n", word, PCI_CB_SUBSYSTEM_VENDOR_ID);
PRINT (" subdevice ID = 0x%.4x\n", word, PCI_CB_SUBSYSTEM_ID);
PRINT (" PC Card 16bit base address = 0x%.8x\n", dword, PCI_CB_LEGACY_MODE_BASE);
break;
default:
printf("unknown header\n");
break;
}
#undef PRINT
#undef PRINT2
}
/* Convert the "bus.device.function" identifier into a number.
*/
static pci_dev_t get_pci_dev(char* name)
{
char cnum[12];
int len, i, iold, n;
int bdfs[3] = {0,0,0};
len = strlen(name);
if (len > 8)
return -1;
for (i = 0, iold = 0, n = 0; i < len; i++) {
if (name[i] == '.') {
memcpy(cnum, &name[iold], i - iold);
cnum[i - iold] = '\0';
bdfs[n++] = simple_strtoul(cnum, NULL, 16);
iold = i + 1;
}
}
strcpy(cnum, &name[iold]);
if (n == 0)
n = 1;
bdfs[n] = simple_strtoul(cnum, NULL, 16);
return PCI_BDF(bdfs[0], bdfs[1], bdfs[2]);
}
static int pci_cfg_display(pci_dev_t bdf, ulong addr, ulong size, ulong length)
{
#define DISP_LINE_LEN 16
ulong i, nbytes, linebytes;
int rc = 0;
if (length == 0)
length = 0x40 / size; /* Standard PCI configuration space */
/* Print the lines.
* once, and all accesses are with the specified bus width.
*/
nbytes = length * size;
do {
uint val4;
ushort val2;
u_char val1;
printf("%08lx:", addr);
linebytes = (nbytes>DISP_LINE_LEN)?DISP_LINE_LEN:nbytes;
for (i=0; i<linebytes; i+= size) {
if (size == 4) {
pci_read_config_dword(bdf, addr, &val4);
printf(" %08x", val4);
} else if (size == 2) {
pci_read_config_word(bdf, addr, &val2);
printf(" %04x", val2);
} else {
pci_read_config_byte(bdf, addr, &val1);
printf(" %02x", val1);
}
addr += size;
}
printf("\n");
nbytes -= linebytes;
if (ctrlc()) {
rc = 1;
break;
}
} while (nbytes > 0);
return (rc);
}
static int pci_cfg_write (pci_dev_t bdf, ulong addr, ulong size, ulong value)
{
if (size == 4) {
pci_write_config_dword(bdf, addr, value);
}
else if (size == 2) {
ushort val = value & 0xffff;
pci_write_config_word(bdf, addr, val);
}
else {
u_char val = value & 0xff;
pci_write_config_byte(bdf, addr, val);
}
return 0;
}
static int
pci_cfg_modify (pci_dev_t bdf, ulong addr, ulong size, ulong value, int incrflag)
{
ulong i;
int nbytes;
uint val4;
ushort val2;
u_char val1;
/* Print the address, followed by value. Then accept input for
* the next value. A non-converted value exits.
*/
do {
printf("%08lx:", addr);
if (size == 4) {
pci_read_config_dword(bdf, addr, &val4);
printf(" %08x", val4);
}
else if (size == 2) {
pci_read_config_word(bdf, addr, &val2);
printf(" %04x", val2);
}
else {
pci_read_config_byte(bdf, addr, &val1);
printf(" %02x", val1);
}
nbytes = readline (" ? ");
if (nbytes == 0 || (nbytes == 1 && console_buffer[0] == '-')) {
/* <CR> pressed as only input, don't modify current
* location and move to next. "-" pressed will go back.
*/
if (incrflag)
addr += nbytes ? -size : size;
nbytes = 1;
#ifdef CONFIG_BOOT_RETRY_TIME
reset_cmd_timeout(); /* good enough to not time out */
#endif
}
#ifdef CONFIG_BOOT_RETRY_TIME
else if (nbytes == -2) {
break; /* timed out, exit the command */
}
#endif
else {
char *endp;
i = simple_strtoul(console_buffer, &endp, 16);
nbytes = endp - console_buffer;
if (nbytes) {
#ifdef CONFIG_BOOT_RETRY_TIME
/* good enough to not time out
*/
reset_cmd_timeout();
#endif
pci_cfg_write (bdf, addr, size, i);
if (incrflag)
addr += size;
}
}
} while (nbytes);
return 0;
}
/* PCI Configuration Space access commands
*
* Syntax:
* pci display[.b, .w, .l] bus.device.function} [addr] [len]
* pci next[.b, .w, .l] bus.device.function [addr]
* pci modify[.b, .w, .l] bus.device.function [addr]
* pci write[.b, .w, .l] bus.device.function addr value
*/
int do_pci (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr = 0, value = 0, size = 0;
pci_dev_t bdf = 0;
char cmd = 's';
if (argc > 1)
cmd = argv[1][0];
switch (cmd) {
case 'd': /* display */
case 'n': /* next */
case 'm': /* modify */
case 'w': /* write */
/* Check for a size specification. */
size = cmd_get_data_size(argv[1], 4);
if (argc > 3)
addr = simple_strtoul(argv[3], NULL, 16);
if (argc > 4)
value = simple_strtoul(argv[4], NULL, 16);
case 'h': /* header */
if (argc < 3)
goto usage;
if ((bdf = get_pci_dev(argv[2])) == -1)
return 1;
break;
#ifdef CONFIG_CMD_PCI_ENUM
case 'e':
break;
#endif
default: /* scan bus */
value = 1; /* short listing */
bdf = 0; /* bus number */
if (argc > 1) {
if (argv[argc-1][0] == 'l') {
value = 0;
argc--;
}
if (argc > 1)
bdf = simple_strtoul(argv[1], NULL, 16);
}
pciinfo(bdf, value);
return 0;
}
switch (argv[1][0]) {
case 'h': /* header */
pci_header_show(bdf);
return 0;
case 'd': /* display */
return pci_cfg_display(bdf, addr, size, value);
#ifdef CONFIG_CMD_PCI_ENUM
case 'e':
pci_init();
return 0;
#endif
case 'n': /* next */
if (argc < 4)
goto usage;
return pci_cfg_modify(bdf, addr, size, value, 0);
case 'm': /* modify */
if (argc < 4)
goto usage;
return pci_cfg_modify(bdf, addr, size, value, 1);
case 'w': /* write */
if (argc < 5)
goto usage;
return pci_cfg_write(bdf, addr, size, value);
}
return 1;
usage:
return cmd_usage(cmdtp);
}
/***************************************************/
U_BOOT_CMD(
pci, 5, 1, do_pci,
"list and access PCI Configuration Space",
"[bus] [long]\n"
" - short or long list of PCI devices on bus 'bus'\n"
#ifdef CONFIG_CMD_PCI_ENUM
"pci enum\n"
" - re-enumerate PCI buses\n"
#endif
"pci header b.d.f\n"
" - show header of PCI device 'bus.device.function'\n"
"pci display[.b, .w, .l] b.d.f [address] [# of objects]\n"
" - display PCI configuration space (CFG)\n"
"pci next[.b, .w, .l] b.d.f address\n"
" - modify, read and keep CFG address\n"
"pci modify[.b, .w, .l] b.d.f address\n"
" - modify, auto increment CFG address\n"
"pci write[.b, .w, .l] b.d.f address value\n"
" - write to CFG address"
);
|
1001-study-uboot
|
common/cmd_pci.c
|
C
|
gpl3
| 15,822
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* Add to readline cmdline-editing by
* (C) Copyright 2005
* JinHua Luo, GuangDong Linux Center, <luo.jinhua@gd-linux.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
*/
/* #define DEBUG */
#include <common.h>
#include <watchdog.h>
#include <command.h>
#include <version.h>
#ifdef CONFIG_MODEM_SUPPORT
#include <malloc.h> /* for free() prototype */
#endif
#ifdef CONFIG_SYS_HUSH_PARSER
#include <hush.h>
#endif
#include <post.h>
#include <linux/ctype.h>
#if defined(CONFIG_SILENT_CONSOLE) || defined(CONFIG_POST) || defined(CONFIG_CMDLINE_EDITING)
DECLARE_GLOBAL_DATA_PTR;
#endif
/*
* Board-specific Platform code can reimplement show_boot_progress () if needed
*/
void inline __show_boot_progress (int val) {}
void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress")));
#if defined(CONFIG_UPDATE_TFTP)
int update_tftp (ulong addr);
#endif /* CONFIG_UPDATE_TFTP */
#define MAX_DELAY_STOP_STR 32
#undef DEBUG_PARSER
char console_buffer[CONFIG_SYS_CBSIZE + 1]; /* console I/O buffer */
static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen);
static const char erase_seq[] = "\b \b"; /* erase sequence */
static const char tab_seq[] = " "; /* used to expand TABs */
#ifdef CONFIG_BOOT_RETRY_TIME
static uint64_t endtime = 0; /* must be set, default is instant timeout */
static int retry_time = -1; /* -1 so can call readline before main_loop */
#endif
#define endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk())
#ifndef CONFIG_BOOT_RETRY_MIN
#define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME
#endif
#ifdef CONFIG_MODEM_SUPPORT
int do_mdm_init = 0;
extern void mdm_init(void); /* defined in board.c */
#endif
/***************************************************************************
* Watch for 'delay' seconds for autoboot stop or autoboot delay string.
* returns: 0 - no key string, allow autoboot 1 - got key string, abort
*/
#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
# if defined(CONFIG_AUTOBOOT_KEYED)
#ifndef CONFIG_MENU
static inline
#endif
int abortboot(int bootdelay)
{
int abort = 0;
uint64_t etime = endtick(bootdelay);
struct {
char* str;
u_int len;
int retry;
}
delaykey [] = {
{ str: getenv ("bootdelaykey"), retry: 1 },
{ str: getenv ("bootdelaykey2"), retry: 1 },
{ str: getenv ("bootstopkey"), retry: 0 },
{ str: getenv ("bootstopkey2"), retry: 0 },
};
char presskey [MAX_DELAY_STOP_STR];
u_int presskey_len = 0;
u_int presskey_max = 0;
u_int i;
# ifdef CONFIG_AUTOBOOT_PROMPT
printf(CONFIG_AUTOBOOT_PROMPT);
# endif
# ifdef CONFIG_AUTOBOOT_DELAY_STR
if (delaykey[0].str == NULL)
delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR;
# endif
# ifdef CONFIG_AUTOBOOT_DELAY_STR2
if (delaykey[1].str == NULL)
delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2;
# endif
# ifdef CONFIG_AUTOBOOT_STOP_STR
if (delaykey[2].str == NULL)
delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR;
# endif
# ifdef CONFIG_AUTOBOOT_STOP_STR2
if (delaykey[3].str == NULL)
delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2;
# endif
for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
delaykey[i].len = delaykey[i].str == NULL ?
0 : strlen (delaykey[i].str);
delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ?
MAX_DELAY_STOP_STR : delaykey[i].len;
presskey_max = presskey_max > delaykey[i].len ?
presskey_max : delaykey[i].len;
# if DEBUG_BOOTKEYS
printf("%s key:<%s>\n",
delaykey[i].retry ? "delay" : "stop",
delaykey[i].str ? delaykey[i].str : "NULL");
# endif
}
/* In order to keep up with incoming data, check timeout only
* when catch up.
*/
do {
if (tstc()) {
if (presskey_len < presskey_max) {
presskey [presskey_len ++] = getc();
}
else {
for (i = 0; i < presskey_max - 1; i ++)
presskey [i] = presskey [i + 1];
presskey [i] = getc();
}
}
for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
if (delaykey[i].len > 0 &&
presskey_len >= delaykey[i].len &&
memcmp (presskey + presskey_len - delaykey[i].len,
delaykey[i].str,
delaykey[i].len) == 0) {
# if DEBUG_BOOTKEYS
printf("got %skey\n",
delaykey[i].retry ? "delay" : "stop");
# endif
# ifdef CONFIG_BOOT_RETRY_TIME
/* don't retry auto boot */
if (! delaykey[i].retry)
retry_time = -1;
# endif
abort = 1;
}
}
} while (!abort && get_ticks() <= etime);
# if DEBUG_BOOTKEYS
if (!abort)
puts("key timeout\n");
# endif
#ifdef CONFIG_SILENT_CONSOLE
if (abort)
gd->flags &= ~GD_FLG_SILENT;
#endif
return abort;
}
# else /* !defined(CONFIG_AUTOBOOT_KEYED) */
#ifdef CONFIG_MENUKEY
static int menukey = 0;
#endif
#ifndef CONFIG_MENU
static inline
#endif
int abortboot(int bootdelay)
{
int abort = 0;
#ifdef CONFIG_MENUPROMPT
printf(CONFIG_MENUPROMPT);
#else
printf("Hit any key to stop autoboot: %2d ", bootdelay);
#endif
#if defined CONFIG_ZERO_BOOTDELAY_CHECK
/*
* Check if key already pressed
* Don't check if bootdelay < 0
*/
if (bootdelay >= 0) {
if (tstc()) { /* we got a key press */
(void) getc(); /* consume input */
puts ("\b\b\b 0");
abort = 1; /* don't auto boot */
}
}
#endif
while ((bootdelay > 0) && (!abort)) {
int i;
--bootdelay;
/* delay 100 * 10ms */
for (i=0; !abort && i<100; ++i) {
if (tstc()) { /* we got a key press */
abort = 1; /* don't auto boot */
bootdelay = 0; /* no more delay */
# ifdef CONFIG_MENUKEY
menukey = getc();
# else
(void) getc(); /* consume input */
# endif
break;
}
udelay(10000);
}
printf("\b\b\b%2d ", bootdelay);
}
putc('\n');
#ifdef CONFIG_SILENT_CONSOLE
if (abort)
gd->flags &= ~GD_FLG_SILENT;
#endif
return abort;
}
# endif /* CONFIG_AUTOBOOT_KEYED */
#endif /* CONFIG_BOOTDELAY >= 0 */
/*
* Return 0 on success, or != 0 on error.
*/
#ifndef CONFIG_CMD_PXE
static inline
#endif
int run_command2(const char *cmd, int flag)
{
#ifndef CONFIG_SYS_HUSH_PARSER
/*
* run_command can return 0 or 1 for success, so clean up its result.
*/
if (run_command(cmd, flag) == -1)
return 1;
return 0;
#else
return parse_string_outer(cmd,
FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP);
#endif
}
/****************************************************************************/
void main_loop (void)
{
#ifndef CONFIG_SYS_HUSH_PARSER
static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, };
int len;
int rc = 1;
int flag;
#endif
#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
char *s;
int bootdelay;
#endif
#ifdef CONFIG_PREBOOT
char *p;
#endif
#ifdef CONFIG_BOOTCOUNT_LIMIT
unsigned long bootcount = 0;
unsigned long bootlimit = 0;
char *bcs;
char bcs_set[16];
#endif /* CONFIG_BOOTCOUNT_LIMIT */
#ifdef CONFIG_BOOTCOUNT_LIMIT
bootcount = bootcount_load();
bootcount++;
bootcount_store (bootcount);
sprintf (bcs_set, "%lu", bootcount);
setenv ("bootcount", bcs_set);
bcs = getenv ("bootlimit");
bootlimit = bcs ? simple_strtoul (bcs, NULL, 10) : 0;
#endif /* CONFIG_BOOTCOUNT_LIMIT */
#ifdef CONFIG_MODEM_SUPPORT
debug ("DEBUG: main_loop: do_mdm_init=%d\n", do_mdm_init);
if (do_mdm_init) {
char *str = strdup(getenv("mdm_cmd"));
setenv ("preboot", str); /* set or delete definition */
if (str != NULL)
free (str);
mdm_init(); /* wait for modem connection */
}
#endif /* CONFIG_MODEM_SUPPORT */
#ifdef CONFIG_VERSION_VARIABLE
{
setenv ("ver", version_string); /* set version variable */
}
#endif /* CONFIG_VERSION_VARIABLE */
#ifdef CONFIG_SYS_HUSH_PARSER
u_boot_hush_start ();
#endif
#if defined(CONFIG_HUSH_INIT_VAR)
hush_init_var ();
#endif
#ifdef CONFIG_PREBOOT
if ((p = getenv ("preboot")) != NULL) {
# ifdef CONFIG_AUTOBOOT_KEYED
int prev = disable_ctrlc(1); /* disable Control C checking */
# endif
run_command2(p, 0);
# ifdef CONFIG_AUTOBOOT_KEYED
disable_ctrlc(prev); /* restore Control C checking */
# endif
}
#endif /* CONFIG_PREBOOT */
#if defined(CONFIG_UPDATE_TFTP)
update_tftp (0UL);
#endif /* CONFIG_UPDATE_TFTP */
#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
s = getenv ("bootdelay");
bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);
# ifdef CONFIG_BOOT_RETRY_TIME
init_cmd_timeout ();
# endif /* CONFIG_BOOT_RETRY_TIME */
#ifdef CONFIG_POST
if (gd->flags & GD_FLG_POSTFAIL) {
s = getenv("failbootcmd");
}
else
#endif /* CONFIG_POST */
#ifdef CONFIG_BOOTCOUNT_LIMIT
if (bootlimit && (bootcount > bootlimit)) {
printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n",
(unsigned)bootlimit);
s = getenv ("altbootcmd");
}
else
#endif /* CONFIG_BOOTCOUNT_LIMIT */
s = getenv ("bootcmd");
debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");
if (bootdelay >= 0 && s && !abortboot (bootdelay)) {
# ifdef CONFIG_AUTOBOOT_KEYED
int prev = disable_ctrlc(1); /* disable Control C checking */
# endif
run_command2(s, 0);
# ifdef CONFIG_AUTOBOOT_KEYED
disable_ctrlc(prev); /* restore Control C checking */
# endif
}
# ifdef CONFIG_MENUKEY
if (menukey == CONFIG_MENUKEY) {
s = getenv("menucmd");
if (s)
run_command2(s, 0);
}
#endif /* CONFIG_MENUKEY */
#endif /* CONFIG_BOOTDELAY */
/*
* Main Loop for Monitor Command Processing
*/
#ifdef CONFIG_SYS_HUSH_PARSER
parse_file_outer();
/* This point is never reached */
for (;;);
#else
for (;;) {
#ifdef CONFIG_BOOT_RETRY_TIME
if (rc >= 0) {
/* Saw enough of a valid command to
* restart the timeout.
*/
reset_cmd_timeout();
}
#endif
len = readline (CONFIG_SYS_PROMPT);
flag = 0; /* assume no special flags for now */
if (len > 0)
strcpy (lastcommand, console_buffer);
else if (len == 0)
flag |= CMD_FLAG_REPEAT;
#ifdef CONFIG_BOOT_RETRY_TIME
else if (len == -2) {
/* -2 means timed out, retry autoboot
*/
puts ("\nTimed out waiting for command\n");
# ifdef CONFIG_RESET_TO_RETRY
/* Reinit board to run initialization code again */
do_reset (NULL, 0, 0, NULL);
# else
return; /* retry autoboot */
# endif
}
#endif
if (len == -1)
puts ("<INTERRUPT>\n");
else
rc = run_command (lastcommand, flag);
if (rc <= 0) {
/* invalid command or not repeatable, forget it */
lastcommand[0] = 0;
}
}
#endif /*CONFIG_SYS_HUSH_PARSER*/
}
#ifdef CONFIG_BOOT_RETRY_TIME
/***************************************************************************
* initialize command line timeout
*/
void init_cmd_timeout(void)
{
char *s = getenv ("bootretry");
if (s != NULL)
retry_time = (int)simple_strtol(s, NULL, 10);
else
retry_time = CONFIG_BOOT_RETRY_TIME;
if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
retry_time = CONFIG_BOOT_RETRY_MIN;
}
/***************************************************************************
* reset command line timeout to retry_time seconds
*/
void reset_cmd_timeout(void)
{
endtime = endtick(retry_time);
}
#endif
#ifdef CONFIG_CMDLINE_EDITING
/*
* cmdline-editing related codes from vivi.
* Author: Janghoon Lyu <nandy@mizi.com>
*/
#define putnstr(str,n) do { \
printf ("%.*s", (int)n, str); \
} while (0)
#define CTL_CH(c) ((c) - 'a' + 1)
#define CTL_BACKSPACE ('\b')
#define DEL ((char)255)
#define DEL7 ((char)127)
#define CREAD_HIST_CHAR ('!')
#define getcmd_putch(ch) putc(ch)
#define getcmd_getch() getc()
#define getcmd_cbeep() getcmd_putch('\a')
#define HIST_MAX 20
#define HIST_SIZE CONFIG_SYS_CBSIZE
static int hist_max = 0;
static int hist_add_idx = 0;
static int hist_cur = -1;
unsigned hist_num = 0;
char* hist_list[HIST_MAX];
char hist_lines[HIST_MAX][HIST_SIZE + 1]; /* Save room for NULL */
#define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1)
static void hist_init(void)
{
int i;
hist_max = 0;
hist_add_idx = 0;
hist_cur = -1;
hist_num = 0;
for (i = 0; i < HIST_MAX; i++) {
hist_list[i] = hist_lines[i];
hist_list[i][0] = '\0';
}
}
static void cread_add_to_hist(char *line)
{
strcpy(hist_list[hist_add_idx], line);
if (++hist_add_idx >= HIST_MAX)
hist_add_idx = 0;
if (hist_add_idx > hist_max)
hist_max = hist_add_idx;
hist_num++;
}
static char* hist_prev(void)
{
char *ret;
int old_cur;
if (hist_cur < 0)
return NULL;
old_cur = hist_cur;
if (--hist_cur < 0)
hist_cur = hist_max;
if (hist_cur == hist_add_idx) {
hist_cur = old_cur;
ret = NULL;
} else
ret = hist_list[hist_cur];
return (ret);
}
static char* hist_next(void)
{
char *ret;
if (hist_cur < 0)
return NULL;
if (hist_cur == hist_add_idx)
return NULL;
if (++hist_cur > hist_max)
hist_cur = 0;
if (hist_cur == hist_add_idx) {
ret = "";
} else
ret = hist_list[hist_cur];
return (ret);
}
#ifndef CONFIG_CMDLINE_EDITING
static void cread_print_hist_list(void)
{
int i;
unsigned long n;
n = hist_num - hist_max;
i = hist_add_idx + 1;
while (1) {
if (i > hist_max)
i = 0;
if (i == hist_add_idx)
break;
printf("%s\n", hist_list[i]);
n++;
i++;
}
}
#endif /* CONFIG_CMDLINE_EDITING */
#define BEGINNING_OF_LINE() { \
while (num) { \
getcmd_putch(CTL_BACKSPACE); \
num--; \
} \
}
#define ERASE_TO_EOL() { \
if (num < eol_num) { \
printf("%*s", (int)(eol_num - num), ""); \
do { \
getcmd_putch(CTL_BACKSPACE); \
} while (--eol_num > num); \
} \
}
#define REFRESH_TO_EOL() { \
if (num < eol_num) { \
wlen = eol_num - num; \
putnstr(buf + num, wlen); \
num = eol_num; \
} \
}
static void cread_add_char(char ichar, int insert, unsigned long *num,
unsigned long *eol_num, char *buf, unsigned long len)
{
unsigned long wlen;
/* room ??? */
if (insert || *num == *eol_num) {
if (*eol_num > len - 1) {
getcmd_cbeep();
return;
}
(*eol_num)++;
}
if (insert) {
wlen = *eol_num - *num;
if (wlen > 1) {
memmove(&buf[*num+1], &buf[*num], wlen-1);
}
buf[*num] = ichar;
putnstr(buf + *num, wlen);
(*num)++;
while (--wlen) {
getcmd_putch(CTL_BACKSPACE);
}
} else {
/* echo the character */
wlen = 1;
buf[*num] = ichar;
putnstr(buf + *num, wlen);
(*num)++;
}
}
static void cread_add_str(char *str, int strsize, int insert, unsigned long *num,
unsigned long *eol_num, char *buf, unsigned long len)
{
while (strsize--) {
cread_add_char(*str, insert, num, eol_num, buf, len);
str++;
}
}
static int cread_line(const char *const prompt, char *buf, unsigned int *len)
{
unsigned long num = 0;
unsigned long eol_num = 0;
unsigned long wlen;
char ichar;
int insert = 1;
int esc_len = 0;
char esc_save[8];
int init_len = strlen(buf);
if (init_len)
cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len);
while (1) {
#ifdef CONFIG_BOOT_RETRY_TIME
while (!tstc()) { /* while no incoming data */
if (retry_time >= 0 && get_ticks() > endtime)
return (-2); /* timed out */
WATCHDOG_RESET();
}
#endif
ichar = getcmd_getch();
if ((ichar == '\n') || (ichar == '\r')) {
putc('\n');
break;
}
/*
* handle standard linux xterm esc sequences for arrow key, etc.
*/
if (esc_len != 0) {
if (esc_len == 1) {
if (ichar == '[') {
esc_save[esc_len] = ichar;
esc_len = 2;
} else {
cread_add_str(esc_save, esc_len, insert,
&num, &eol_num, buf, *len);
esc_len = 0;
}
continue;
}
switch (ichar) {
case 'D': /* <- key */
ichar = CTL_CH('b');
esc_len = 0;
break;
case 'C': /* -> key */
ichar = CTL_CH('f');
esc_len = 0;
break; /* pass off to ^F handler */
case 'H': /* Home key */
ichar = CTL_CH('a');
esc_len = 0;
break; /* pass off to ^A handler */
case 'A': /* up arrow */
ichar = CTL_CH('p');
esc_len = 0;
break; /* pass off to ^P handler */
case 'B': /* down arrow */
ichar = CTL_CH('n');
esc_len = 0;
break; /* pass off to ^N handler */
default:
esc_save[esc_len++] = ichar;
cread_add_str(esc_save, esc_len, insert,
&num, &eol_num, buf, *len);
esc_len = 0;
continue;
}
}
switch (ichar) {
case 0x1b:
if (esc_len == 0) {
esc_save[esc_len] = ichar;
esc_len = 1;
} else {
puts("impossible condition #876\n");
esc_len = 0;
}
break;
case CTL_CH('a'):
BEGINNING_OF_LINE();
break;
case CTL_CH('c'): /* ^C - break */
*buf = '\0'; /* discard input */
return (-1);
case CTL_CH('f'):
if (num < eol_num) {
getcmd_putch(buf[num]);
num++;
}
break;
case CTL_CH('b'):
if (num) {
getcmd_putch(CTL_BACKSPACE);
num--;
}
break;
case CTL_CH('d'):
if (num < eol_num) {
wlen = eol_num - num - 1;
if (wlen) {
memmove(&buf[num], &buf[num+1], wlen);
putnstr(buf + num, wlen);
}
getcmd_putch(' ');
do {
getcmd_putch(CTL_BACKSPACE);
} while (wlen--);
eol_num--;
}
break;
case CTL_CH('k'):
ERASE_TO_EOL();
break;
case CTL_CH('e'):
REFRESH_TO_EOL();
break;
case CTL_CH('o'):
insert = !insert;
break;
case CTL_CH('x'):
case CTL_CH('u'):
BEGINNING_OF_LINE();
ERASE_TO_EOL();
break;
case DEL:
case DEL7:
case 8:
if (num) {
wlen = eol_num - num;
num--;
memmove(&buf[num], &buf[num+1], wlen);
getcmd_putch(CTL_BACKSPACE);
putnstr(buf + num, wlen);
getcmd_putch(' ');
do {
getcmd_putch(CTL_BACKSPACE);
} while (wlen--);
eol_num--;
}
break;
case CTL_CH('p'):
case CTL_CH('n'):
{
char * hline;
esc_len = 0;
if (ichar == CTL_CH('p'))
hline = hist_prev();
else
hline = hist_next();
if (!hline) {
getcmd_cbeep();
continue;
}
/* nuke the current line */
/* first, go home */
BEGINNING_OF_LINE();
/* erase to end of line */
ERASE_TO_EOL();
/* copy new line into place and display */
strcpy(buf, hline);
eol_num = strlen(buf);
REFRESH_TO_EOL();
continue;
}
#ifdef CONFIG_AUTO_COMPLETE
case '\t': {
int num2, col;
/* do not autocomplete when in the middle */
if (num < eol_num) {
getcmd_cbeep();
break;
}
buf[num] = '\0';
col = strlen(prompt) + eol_num;
num2 = num;
if (cmd_auto_complete(prompt, buf, &num2, &col)) {
col = num2 - num;
num += col;
eol_num += col;
}
break;
}
#endif
default:
cread_add_char(ichar, insert, &num, &eol_num, buf, *len);
break;
}
}
*len = eol_num;
buf[eol_num] = '\0'; /* lose the newline */
if (buf[0] && buf[0] != CREAD_HIST_CHAR)
cread_add_to_hist(buf);
hist_cur = hist_add_idx;
return 0;
}
#endif /* CONFIG_CMDLINE_EDITING */
/****************************************************************************/
/*
* Prompt for input and read a line.
* If CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
* time out when time goes past endtime (timebase time in ticks).
* Return: number of read characters
* -1 if break
* -2 if timed out
*/
int readline (const char *const prompt)
{
/*
* If console_buffer isn't 0-length the user will be prompted to modify
* it instead of entering it from scratch as desired.
*/
console_buffer[0] = '\0';
return readline_into_buffer(prompt, console_buffer);
}
int readline_into_buffer (const char *const prompt, char * buffer)
{
char *p = buffer;
#ifdef CONFIG_CMDLINE_EDITING
unsigned int len = CONFIG_SYS_CBSIZE;
int rc;
static int initted = 0;
/*
* History uses a global array which is not
* writable until after relocation to RAM.
* Revert to non-history version if still
* running from flash.
*/
if (gd->flags & GD_FLG_RELOC) {
if (!initted) {
hist_init();
initted = 1;
}
if (prompt)
puts (prompt);
rc = cread_line(prompt, p, &len);
return rc < 0 ? rc : len;
} else {
#endif /* CONFIG_CMDLINE_EDITING */
char * p_buf = p;
int n = 0; /* buffer index */
int plen = 0; /* prompt length */
int col; /* output column cnt */
char c;
/* print prompt */
if (prompt) {
plen = strlen (prompt);
puts (prompt);
}
col = plen;
for (;;) {
#ifdef CONFIG_BOOT_RETRY_TIME
while (!tstc()) { /* while no incoming data */
if (retry_time >= 0 && get_ticks() > endtime)
return (-2); /* timed out */
WATCHDOG_RESET();
}
#endif
WATCHDOG_RESET(); /* Trigger watchdog, if needed */
#ifdef CONFIG_SHOW_ACTIVITY
while (!tstc()) {
extern void show_activity(int arg);
show_activity(0);
WATCHDOG_RESET();
}
#endif
c = getc();
/*
* Special character handling
*/
switch (c) {
case '\r': /* Enter */
case '\n':
*p = '\0';
puts ("\r\n");
return (p - p_buf);
case '\0': /* nul */
continue;
case 0x03: /* ^C - break */
p_buf[0] = '\0'; /* discard input */
return (-1);
case 0x15: /* ^U - erase line */
while (col > plen) {
puts (erase_seq);
--col;
}
p = p_buf;
n = 0;
continue;
case 0x17: /* ^W - erase word */
p=delete_char(p_buf, p, &col, &n, plen);
while ((n > 0) && (*p != ' ')) {
p=delete_char(p_buf, p, &col, &n, plen);
}
continue;
case 0x08: /* ^H - backspace */
case 0x7F: /* DEL - backspace */
p=delete_char(p_buf, p, &col, &n, plen);
continue;
default:
/*
* Must be a normal character then
*/
if (n < CONFIG_SYS_CBSIZE-2) {
if (c == '\t') { /* expand TABs */
#ifdef CONFIG_AUTO_COMPLETE
/* if auto completion triggered just continue */
*p = '\0';
if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
p = p_buf + n; /* reset */
continue;
}
#endif
puts (tab_seq+(col&07));
col += 8 - (col&07);
} else {
++col; /* echo input */
putc (c);
}
*p++ = c;
++n;
} else { /* Buffer full */
putc ('\a');
}
}
}
#ifdef CONFIG_CMDLINE_EDITING
}
#endif
}
/****************************************************************************/
static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
{
char *s;
if (*np == 0) {
return (p);
}
if (*(--p) == '\t') { /* will retype the whole line */
while (*colp > plen) {
puts (erase_seq);
(*colp)--;
}
for (s=buffer; s<p; ++s) {
if (*s == '\t') {
puts (tab_seq+((*colp) & 07));
*colp += 8 - ((*colp) & 07);
} else {
++(*colp);
putc (*s);
}
}
} else {
puts (erase_seq);
(*colp)--;
}
(*np)--;
return (p);
}
/****************************************************************************/
int parse_line (char *line, char *argv[])
{
int nargs = 0;
#ifdef DEBUG_PARSER
printf ("parse_line: \"%s\"\n", line);
#endif
while (nargs < CONFIG_SYS_MAXARGS) {
/* skip any white space */
while (isblank(*line))
++line;
if (*line == '\0') { /* end of line, no more args */
argv[nargs] = NULL;
#ifdef DEBUG_PARSER
printf ("parse_line: nargs=%d\n", nargs);
#endif
return (nargs);
}
argv[nargs++] = line; /* begin of argument string */
/* find end of string */
while (*line && !isblank(*line))
++line;
if (*line == '\0') { /* end of line, no more args */
argv[nargs] = NULL;
#ifdef DEBUG_PARSER
printf ("parse_line: nargs=%d\n", nargs);
#endif
return (nargs);
}
*line++ = '\0'; /* terminate current arg */
}
printf ("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS);
#ifdef DEBUG_PARSER
printf ("parse_line: nargs=%d\n", nargs);
#endif
return (nargs);
}
/****************************************************************************/
static void process_macros (const char *input, char *output)
{
char c, prev;
const char *varname_start = NULL;
int inputcnt = strlen (input);
int outputcnt = CONFIG_SYS_CBSIZE;
int state = 0; /* 0 = waiting for '$' */
/* 1 = waiting for '(' or '{' */
/* 2 = waiting for ')' or '}' */
/* 3 = waiting for ''' */
#ifdef DEBUG_PARSER
char *output_start = output;
printf ("[PROCESS_MACROS] INPUT len %d: \"%s\"\n", strlen (input),
input);
#endif
prev = '\0'; /* previous character */
while (inputcnt && outputcnt) {
c = *input++;
inputcnt--;
if (state != 3) {
/* remove one level of escape characters */
if ((c == '\\') && (prev != '\\')) {
if (inputcnt-- == 0)
break;
prev = c;
c = *input++;
}
}
switch (state) {
case 0: /* Waiting for (unescaped) $ */
if ((c == '\'') && (prev != '\\')) {
state = 3;
break;
}
if ((c == '$') && (prev != '\\')) {
state++;
} else {
*(output++) = c;
outputcnt--;
}
break;
case 1: /* Waiting for ( */
if (c == '(' || c == '{') {
state++;
varname_start = input;
} else {
state = 0;
*(output++) = '$';
outputcnt--;
if (outputcnt) {
*(output++) = c;
outputcnt--;
}
}
break;
case 2: /* Waiting for ) */
if (c == ')' || c == '}') {
int i;
char envname[CONFIG_SYS_CBSIZE], *envval;
int envcnt = input - varname_start - 1; /* Varname # of chars */
/* Get the varname */
for (i = 0; i < envcnt; i++) {
envname[i] = varname_start[i];
}
envname[i] = 0;
/* Get its value */
envval = getenv (envname);
/* Copy into the line if it exists */
if (envval != NULL)
while ((*envval) && outputcnt) {
*(output++) = *(envval++);
outputcnt--;
}
/* Look for another '$' */
state = 0;
}
break;
case 3: /* Waiting for ' */
if ((c == '\'') && (prev != '\\')) {
state = 0;
} else {
*(output++) = c;
outputcnt--;
}
break;
}
prev = c;
}
if (outputcnt)
*output = 0;
else
*(output - 1) = 0;
#ifdef DEBUG_PARSER
printf ("[PROCESS_MACROS] OUTPUT len %d: \"%s\"\n",
strlen (output_start), output_start);
#endif
}
/****************************************************************************
* returns:
* 1 - command executed, repeatable
* 0 - command executed but not repeatable, interrupted commands are
* always considered not repeatable
* -1 - not executed (unrecognized, bootd recursion or too many args)
* (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
* considered unrecognized)
*
* WARNING:
*
* We must create a temporary copy of the command since the command we get
* may be the result from getenv(), which returns a pointer directly to
* the environment data, which may change magicly when the command we run
* creates or modifies environment variables (like "bootp" does).
*/
int run_command (const char *cmd, int flag)
{
cmd_tbl_t *cmdtp;
char cmdbuf[CONFIG_SYS_CBSIZE]; /* working copy of cmd */
char *token; /* start of token in cmdbuf */
char *sep; /* end of token (separator) in cmdbuf */
char finaltoken[CONFIG_SYS_CBSIZE];
char *str = cmdbuf;
char *argv[CONFIG_SYS_MAXARGS + 1]; /* NULL terminated */
int argc, inquotes;
int repeatable = 1;
int rc = 0;
#ifdef DEBUG_PARSER
printf ("[RUN_COMMAND] cmd[%p]=\"", cmd);
puts (cmd ? cmd : "NULL"); /* use puts - string may be loooong */
puts ("\"\n");
#endif
clear_ctrlc(); /* forget any previous Control C */
if (!cmd || !*cmd) {
return -1; /* empty command */
}
if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
puts ("## Command too long!\n");
return -1;
}
strcpy (cmdbuf, cmd);
/* Process separators and check for invalid
* repeatable commands
*/
#ifdef DEBUG_PARSER
printf ("[PROCESS_SEPARATORS] %s\n", cmd);
#endif
while (*str) {
/*
* Find separator, or string end
* Allow simple escape of ';' by writing "\;"
*/
for (inquotes = 0, sep = str; *sep; sep++) {
if ((*sep=='\'') &&
(*(sep-1) != '\\'))
inquotes=!inquotes;
if (!inquotes &&
(*sep == ';') && /* separator */
( sep != str) && /* past string start */
(*(sep-1) != '\\')) /* and NOT escaped */
break;
}
/*
* Limit the token to data between separators
*/
token = str;
if (*sep) {
str = sep + 1; /* start of command for next pass */
*sep = '\0';
}
else
str = sep; /* no more commands for next pass */
#ifdef DEBUG_PARSER
printf ("token: \"%s\"\n", token);
#endif
/* find macros in this token and replace them */
process_macros (token, finaltoken);
/* Extract arguments */
if ((argc = parse_line (finaltoken, argv)) == 0) {
rc = -1; /* no command at all */
continue;
}
/* Look up command in command table */
if ((cmdtp = find_cmd(argv[0])) == NULL) {
printf ("Unknown command '%s' - try 'help'\n", argv[0]);
rc = -1; /* give up after bad command */
continue;
}
/* found - check max args */
if (argc > cmdtp->maxargs) {
cmd_usage(cmdtp);
rc = -1;
continue;
}
#if defined(CONFIG_CMD_BOOTD)
/* avoid "bootd" recursion */
if (cmdtp->cmd == do_bootd) {
#ifdef DEBUG_PARSER
printf ("[%s]\n", finaltoken);
#endif
if (flag & CMD_FLAG_BOOTD) {
puts ("'bootd' recursion detected\n");
rc = -1;
continue;
} else {
flag |= CMD_FLAG_BOOTD;
}
}
#endif
/* OK - call function to do the command */
if ((cmdtp->cmd) (cmdtp, flag, argc, argv) != 0) {
rc = -1;
}
repeatable &= cmdtp->repeatable;
/* Did the user stop this? */
if (had_ctrlc ())
return -1; /* if stopped then not repeatable */
}
return rc ? rc : repeatable;
}
/****************************************************************************/
#if defined(CONFIG_CMD_RUN)
int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
int i;
if (argc < 2)
return cmd_usage(cmdtp);
for (i=1; i<argc; ++i) {
char *arg;
if ((arg = getenv (argv[i])) == NULL) {
printf ("## Error: \"%s\" not defined\n", argv[i]);
return 1;
}
if (run_command2(arg, flag) != 0)
return 1;
}
return 0;
}
#endif
|
1001-study-uboot
|
common/main.c
|
C
|
gpl3
| 30,465
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* Memory Functions
*
* Copied from FADS ROM, Dan Malek (dmalek@jlc.net)
*/
#include <common.h>
#include <command.h>
#ifdef CONFIG_HAS_DATAFLASH
#include <dataflash.h>
#endif
#include <watchdog.h>
#ifdef CMD_MEM_DEBUG
#define PRINTF(fmt,args...) printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif
static int mod_mem(cmd_tbl_t *, int, int, int, char * const []);
/* Display values from last command.
* Memory modify remembered values are different from display memory.
*/
static uint dp_last_addr, dp_last_size;
static uint dp_last_length = 0x40;
static uint mm_last_addr, mm_last_size;
static ulong base_address = 0;
/* Memory Display
*
* Syntax:
* md{.b, .w, .l} {addr} {len}
*/
#define DISP_LINE_LEN 16
int do_mem_md ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, length;
#if defined(CONFIG_HAS_DATAFLASH)
ulong nbytes, linebytes;
#endif
int size;
int rc = 0;
/* We use the last specified parameters, unless new ones are
* entered.
*/
addr = dp_last_addr;
size = dp_last_size;
length = dp_last_length;
if (argc < 2)
return cmd_usage(cmdtp);
if ((flag & CMD_FLAG_REPEAT) == 0) {
/* New command specified. Check for a size specification.
* Defaults to long if no or incorrect specification.
*/
if ((size = cmd_get_data_size(argv[0], 4)) < 0)
return 1;
/* Address is specified since argc > 1
*/
addr = simple_strtoul(argv[1], NULL, 16);
addr += base_address;
/* If another parameter, it is the length to display.
* Length is the number of objects, not number of bytes.
*/
if (argc > 2)
length = simple_strtoul(argv[2], NULL, 16);
}
#if defined(CONFIG_HAS_DATAFLASH)
/* Print the lines.
*
* We buffer all read data, so we can make sure data is read only
* once, and all accesses are with the specified bus width.
*/
nbytes = length * size;
do {
char linebuf[DISP_LINE_LEN];
void* p;
linebytes = (nbytes>DISP_LINE_LEN)?DISP_LINE_LEN:nbytes;
rc = read_dataflash(addr, (linebytes/size)*size, linebuf);
p = (rc == DATAFLASH_OK) ? linebuf : (void*)addr;
print_buffer(addr, p, size, linebytes/size, DISP_LINE_LEN/size);
nbytes -= linebytes;
addr += linebytes;
if (ctrlc()) {
rc = 1;
break;
}
} while (nbytes > 0);
#else
# if defined(CONFIG_BLACKFIN)
/* See if we're trying to display L1 inst */
if (addr_bfin_on_chip_mem(addr)) {
char linebuf[DISP_LINE_LEN];
ulong linebytes, nbytes = length * size;
do {
linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;
memcpy(linebuf, (void *)addr, linebytes);
print_buffer(addr, linebuf, size, linebytes/size, DISP_LINE_LEN/size);
nbytes -= linebytes;
addr += linebytes;
if (ctrlc()) {
rc = 1;
break;
}
} while (nbytes > 0);
} else
# endif
{
/* Print the lines. */
print_buffer(addr, (void*)addr, size, length, DISP_LINE_LEN/size);
addr += size*length;
}
#endif
dp_last_addr = addr;
dp_last_length = length;
dp_last_size = size;
return (rc);
}
int do_mem_mm ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return mod_mem (cmdtp, 1, flag, argc, argv);
}
int do_mem_nm ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return mod_mem (cmdtp, 0, flag, argc, argv);
}
int do_mem_mw ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, writeval, count;
int size;
if ((argc < 3) || (argc > 4))
return cmd_usage(cmdtp);
/* Check for size specification.
*/
if ((size = cmd_get_data_size(argv[0], 4)) < 1)
return 1;
/* Address is specified since argc > 1
*/
addr = simple_strtoul(argv[1], NULL, 16);
addr += base_address;
/* Get the value to write.
*/
writeval = simple_strtoul(argv[2], NULL, 16);
/* Count ? */
if (argc == 4) {
count = simple_strtoul(argv[3], NULL, 16);
} else {
count = 1;
}
while (count-- > 0) {
if (size == 4)
*((ulong *)addr) = (ulong )writeval;
else if (size == 2)
*((ushort *)addr) = (ushort)writeval;
else
*((u_char *)addr) = (u_char)writeval;
addr += size;
}
return 0;
}
#ifdef CONFIG_MX_CYCLIC
int do_mem_mdc ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
ulong count;
if (argc < 4)
return cmd_usage(cmdtp);
count = simple_strtoul(argv[3], NULL, 10);
for (;;) {
do_mem_md (NULL, 0, 3, argv);
/* delay for <count> ms... */
for (i=0; i<count; i++)
udelay (1000);
/* check for ctrl-c to abort... */
if (ctrlc()) {
puts("Abort\n");
return 0;
}
}
return 0;
}
int do_mem_mwc ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
ulong count;
if (argc < 4)
return cmd_usage(cmdtp);
count = simple_strtoul(argv[3], NULL, 10);
for (;;) {
do_mem_mw (NULL, 0, 3, argv);
/* delay for <count> ms... */
for (i=0; i<count; i++)
udelay (1000);
/* check for ctrl-c to abort... */
if (ctrlc()) {
puts("Abort\n");
return 0;
}
}
return 0;
}
#endif /* CONFIG_MX_CYCLIC */
int do_mem_cmp (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr1, addr2, count, ngood;
int size;
int rcode = 0;
if (argc != 4)
return cmd_usage(cmdtp);
/* Check for size specification.
*/
if ((size = cmd_get_data_size(argv[0], 4)) < 0)
return 1;
addr1 = simple_strtoul(argv[1], NULL, 16);
addr1 += base_address;
addr2 = simple_strtoul(argv[2], NULL, 16);
addr2 += base_address;
count = simple_strtoul(argv[3], NULL, 16);
#ifdef CONFIG_HAS_DATAFLASH
if (addr_dataflash(addr1) | addr_dataflash(addr2)){
puts ("Comparison with DataFlash space not supported.\n\r");
return 0;
}
#endif
#ifdef CONFIG_BLACKFIN
if (addr_bfin_on_chip_mem(addr1) || addr_bfin_on_chip_mem(addr2)) {
puts ("Comparison with L1 instruction memory not supported.\n\r");
return 0;
}
#endif
ngood = 0;
while (count-- > 0) {
if (size == 4) {
ulong word1 = *(ulong *)addr1;
ulong word2 = *(ulong *)addr2;
if (word1 != word2) {
printf("word at 0x%08lx (0x%08lx) "
"!= word at 0x%08lx (0x%08lx)\n",
addr1, word1, addr2, word2);
rcode = 1;
break;
}
}
else if (size == 2) {
ushort hword1 = *(ushort *)addr1;
ushort hword2 = *(ushort *)addr2;
if (hword1 != hword2) {
printf("halfword at 0x%08lx (0x%04x) "
"!= halfword at 0x%08lx (0x%04x)\n",
addr1, hword1, addr2, hword2);
rcode = 1;
break;
}
}
else {
u_char byte1 = *(u_char *)addr1;
u_char byte2 = *(u_char *)addr2;
if (byte1 != byte2) {
printf("byte at 0x%08lx (0x%02x) "
"!= byte at 0x%08lx (0x%02x)\n",
addr1, byte1, addr2, byte2);
rcode = 1;
break;
}
}
ngood++;
addr1 += size;
addr2 += size;
/* reset watchdog from time to time */
if ((count % (64 << 10)) == 0)
WATCHDOG_RESET();
}
printf("Total of %ld %s%s were the same\n",
ngood, size == 4 ? "word" : size == 2 ? "halfword" : "byte",
ngood == 1 ? "" : "s");
return rcode;
}
int do_mem_cp ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, dest, count;
int size;
if (argc != 4)
return cmd_usage(cmdtp);
/* Check for size specification.
*/
if ((size = cmd_get_data_size(argv[0], 4)) < 0)
return 1;
addr = simple_strtoul(argv[1], NULL, 16);
addr += base_address;
dest = simple_strtoul(argv[2], NULL, 16);
dest += base_address;
count = simple_strtoul(argv[3], NULL, 16);
if (count == 0) {
puts ("Zero length ???\n");
return 1;
}
#ifndef CONFIG_SYS_NO_FLASH
/* check if we are copying to Flash */
if ( (addr2info(dest) != NULL)
#ifdef CONFIG_HAS_DATAFLASH
&& (!addr_dataflash(dest))
#endif
) {
int rc;
puts ("Copy to Flash... ");
rc = flash_write ((char *)addr, dest, count*size);
if (rc != 0) {
flash_perror (rc);
return (1);
}
puts ("done\n");
return 0;
}
#endif
#ifdef CONFIG_HAS_DATAFLASH
/* Check if we are copying from RAM or Flash to DataFlash */
if (addr_dataflash(dest) && !addr_dataflash(addr)){
int rc;
puts ("Copy to DataFlash... ");
rc = write_dataflash (dest, addr, count*size);
if (rc != 1) {
dataflash_perror (rc);
return (1);
}
puts ("done\n");
return 0;
}
/* Check if we are copying from DataFlash to RAM */
if (addr_dataflash(addr) && !addr_dataflash(dest)
#ifndef CONFIG_SYS_NO_FLASH
&& (addr2info(dest) == NULL)
#endif
){
int rc;
rc = read_dataflash(addr, count * size, (char *) dest);
if (rc != 1) {
dataflash_perror (rc);
return (1);
}
return 0;
}
if (addr_dataflash(addr) && addr_dataflash(dest)){
puts ("Unsupported combination of source/destination.\n\r");
return 1;
}
#endif
#ifdef CONFIG_BLACKFIN
/* See if we're copying to/from L1 inst */
if (addr_bfin_on_chip_mem(dest) || addr_bfin_on_chip_mem(addr)) {
memcpy((void *)dest, (void *)addr, count * size);
return 0;
}
#endif
while (count-- > 0) {
if (size == 4)
*((ulong *)dest) = *((ulong *)addr);
else if (size == 2)
*((ushort *)dest) = *((ushort *)addr);
else
*((u_char *)dest) = *((u_char *)addr);
addr += size;
dest += size;
/* reset watchdog from time to time */
if ((count % (64 << 10)) == 0)
WATCHDOG_RESET();
}
return 0;
}
int do_mem_base (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc > 1) {
/* Set new base address.
*/
base_address = simple_strtoul(argv[1], NULL, 16);
}
/* Print the current base address.
*/
printf("Base Address: 0x%08lx\n", base_address);
return 0;
}
int do_mem_loop (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, length, i;
int size;
volatile uint *longp;
volatile ushort *shortp;
volatile u_char *cp;
if (argc < 3)
return cmd_usage(cmdtp);
/* Check for a size spefication.
* Defaults to long if no or incorrect specification.
*/
if ((size = cmd_get_data_size(argv[0], 4)) < 0)
return 1;
/* Address is always specified.
*/
addr = simple_strtoul(argv[1], NULL, 16);
/* Length is the number of objects, not number of bytes.
*/
length = simple_strtoul(argv[2], NULL, 16);
/* We want to optimize the loops to run as fast as possible.
* If we have only one object, just run infinite loops.
*/
if (length == 1) {
if (size == 4) {
longp = (uint *)addr;
for (;;)
i = *longp;
}
if (size == 2) {
shortp = (ushort *)addr;
for (;;)
i = *shortp;
}
cp = (u_char *)addr;
for (;;)
i = *cp;
}
if (size == 4) {
for (;;) {
longp = (uint *)addr;
i = length;
while (i-- > 0)
*longp++;
}
}
if (size == 2) {
for (;;) {
shortp = (ushort *)addr;
i = length;
while (i-- > 0)
*shortp++;
}
}
for (;;) {
cp = (u_char *)addr;
i = length;
while (i-- > 0)
*cp++;
}
}
#ifdef CONFIG_LOOPW
int do_mem_loopw (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, length, i, data;
int size;
volatile uint *longp;
volatile ushort *shortp;
volatile u_char *cp;
if (argc < 4)
return cmd_usage(cmdtp);
/* Check for a size spefication.
* Defaults to long if no or incorrect specification.
*/
if ((size = cmd_get_data_size(argv[0], 4)) < 0)
return 1;
/* Address is always specified.
*/
addr = simple_strtoul(argv[1], NULL, 16);
/* Length is the number of objects, not number of bytes.
*/
length = simple_strtoul(argv[2], NULL, 16);
/* data to write */
data = simple_strtoul(argv[3], NULL, 16);
/* We want to optimize the loops to run as fast as possible.
* If we have only one object, just run infinite loops.
*/
if (length == 1) {
if (size == 4) {
longp = (uint *)addr;
for (;;)
*longp = data;
}
if (size == 2) {
shortp = (ushort *)addr;
for (;;)
*shortp = data;
}
cp = (u_char *)addr;
for (;;)
*cp = data;
}
if (size == 4) {
for (;;) {
longp = (uint *)addr;
i = length;
while (i-- > 0)
*longp++ = data;
}
}
if (size == 2) {
for (;;) {
shortp = (ushort *)addr;
i = length;
while (i-- > 0)
*shortp++ = data;
}
}
for (;;) {
cp = (u_char *)addr;
i = length;
while (i-- > 0)
*cp++ = data;
}
}
#endif /* CONFIG_LOOPW */
/*
* Perform a memory test. A more complete alternative test can be
* configured using CONFIG_SYS_ALT_MEMTEST. The complete test loops until
* interrupted by ctrl-c or by a failure of one of the sub-tests.
*/
int do_mem_mtest (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
vu_long *addr, *start, *end;
ulong val;
ulong readback;
ulong errs = 0;
int iterations = 1;
int iteration_limit;
#if defined(CONFIG_SYS_ALT_MEMTEST)
vu_long len;
vu_long offset;
vu_long test_offset;
vu_long pattern;
vu_long temp;
vu_long anti_pattern;
vu_long num_words;
#if defined(CONFIG_SYS_MEMTEST_SCRATCH)
vu_long *dummy = (vu_long*)CONFIG_SYS_MEMTEST_SCRATCH;
#else
vu_long *dummy = 0; /* yes, this is address 0x0, not NULL */
#endif
int j;
static const ulong bitpattern[] = {
0x00000001, /* single bit */
0x00000003, /* two adjacent bits */
0x00000007, /* three adjacent bits */
0x0000000F, /* four adjacent bits */
0x00000005, /* two non-adjacent bits */
0x00000015, /* three non-adjacent bits */
0x00000055, /* four non-adjacent bits */
0xaaaaaaaa, /* alternating 1/0 */
};
#else
ulong incr;
ulong pattern;
#endif
if (argc > 1)
start = (ulong *)simple_strtoul(argv[1], NULL, 16);
else
start = (ulong *)CONFIG_SYS_MEMTEST_START;
if (argc > 2)
end = (ulong *)simple_strtoul(argv[2], NULL, 16);
else
end = (ulong *)(CONFIG_SYS_MEMTEST_END);
if (argc > 3)
pattern = (ulong)simple_strtoul(argv[3], NULL, 16);
else
pattern = 0;
if (argc > 4)
iteration_limit = (ulong)simple_strtoul(argv[4], NULL, 16);
else
iteration_limit = 0;
#if defined(CONFIG_SYS_ALT_MEMTEST)
printf ("Testing %08x ... %08x:\n", (uint)start, (uint)end);
PRINTF("%s:%d: start 0x%p end 0x%p\n",
__FUNCTION__, __LINE__, start, end);
for (;;) {
if (ctrlc()) {
putc ('\n');
return 1;
}
if (iteration_limit && iterations > iteration_limit) {
printf("Tested %d iteration(s) with %lu errors.\n",
iterations-1, errs);
return errs != 0;
}
printf("Iteration: %6d\r", iterations);
PRINTF("\n");
iterations++;
/*
* Data line test: write a pattern to the first
* location, write the 1's complement to a 'parking'
* address (changes the state of the data bus so a
* floating bus doen't give a false OK), and then
* read the value back. Note that we read it back
* into a variable because the next time we read it,
* it might be right (been there, tough to explain to
* the quality guys why it prints a failure when the
* "is" and "should be" are obviously the same in the
* error message).
*
* Rather than exhaustively testing, we test some
* patterns by shifting '1' bits through a field of
* '0's and '0' bits through a field of '1's (i.e.
* pattern and ~pattern).
*/
addr = start;
for (j = 0; j < sizeof(bitpattern)/sizeof(bitpattern[0]); j++) {
val = bitpattern[j];
for(; val != 0; val <<= 1) {
*addr = val;
*dummy = ~val; /* clear the test data off of the bus */
readback = *addr;
if(readback != val) {
printf ("FAILURE (data line): "
"expected %08lx, actual %08lx\n",
val, readback);
errs++;
if (ctrlc()) {
putc ('\n');
return 1;
}
}
*addr = ~val;
*dummy = val;
readback = *addr;
if(readback != ~val) {
printf ("FAILURE (data line): "
"Is %08lx, should be %08lx\n",
readback, ~val);
errs++;
if (ctrlc()) {
putc ('\n');
return 1;
}
}
}
}
/*
* Based on code whose Original Author and Copyright
* information follows: Copyright (c) 1998 by Michael
* Barr. This software is placed into the public
* domain and may be used for any purpose. However,
* this notice must not be changed or removed and no
* warranty is either expressed or implied by its
* publication or distribution.
*/
/*
* Address line test
*
* Description: Test the address bus wiring in a
* memory region by performing a walking
* 1's test on the relevant bits of the
* address and checking for aliasing.
* This test will find single-bit
* address failures such as stuck -high,
* stuck-low, and shorted pins. The base
* address and size of the region are
* selected by the caller.
*
* Notes: For best results, the selected base
* address should have enough LSB 0's to
* guarantee single address bit changes.
* For example, to test a 64-Kbyte
* region, select a base address on a
* 64-Kbyte boundary. Also, select the
* region size as a power-of-two if at
* all possible.
*
* Returns: 0 if the test succeeds, 1 if the test fails.
*/
len = ((ulong)end - (ulong)start)/sizeof(vu_long);
pattern = (vu_long) 0xaaaaaaaa;
anti_pattern = (vu_long) 0x55555555;
PRINTF("%s:%d: length = 0x%.8lx\n",
__FUNCTION__, __LINE__,
len);
/*
* Write the default pattern at each of the
* power-of-two offsets.
*/
for (offset = 1; offset < len; offset <<= 1) {
start[offset] = pattern;
}
/*
* Check for address bits stuck high.
*/
test_offset = 0;
start[test_offset] = anti_pattern;
for (offset = 1; offset < len; offset <<= 1) {
temp = start[offset];
if (temp != pattern) {
printf ("\nFAILURE: Address bit stuck high @ 0x%.8lx:"
" expected 0x%.8lx, actual 0x%.8lx\n",
(ulong)&start[offset], pattern, temp);
errs++;
if (ctrlc()) {
putc ('\n');
return 1;
}
}
}
start[test_offset] = pattern;
WATCHDOG_RESET();
/*
* Check for addr bits stuck low or shorted.
*/
for (test_offset = 1; test_offset < len; test_offset <<= 1) {
start[test_offset] = anti_pattern;
for (offset = 1; offset < len; offset <<= 1) {
temp = start[offset];
if ((temp != pattern) && (offset != test_offset)) {
printf ("\nFAILURE: Address bit stuck low or shorted @"
" 0x%.8lx: expected 0x%.8lx, actual 0x%.8lx\n",
(ulong)&start[offset], pattern, temp);
errs++;
if (ctrlc()) {
putc ('\n');
return 1;
}
}
}
start[test_offset] = pattern;
}
/*
* Description: Test the integrity of a physical
* memory device by performing an
* increment/decrement test over the
* entire region. In the process every
* storage bit in the device is tested
* as a zero and a one. The base address
* and the size of the region are
* selected by the caller.
*
* Returns: 0 if the test succeeds, 1 if the test fails.
*/
num_words = ((ulong)end - (ulong)start)/sizeof(vu_long) + 1;
/*
* Fill memory with a known pattern.
*/
for (pattern = 1, offset = 0; offset < num_words; pattern++, offset++) {
WATCHDOG_RESET();
start[offset] = pattern;
}
/*
* Check each location and invert it for the second pass.
*/
for (pattern = 1, offset = 0; offset < num_words; pattern++, offset++) {
WATCHDOG_RESET();
temp = start[offset];
if (temp != pattern) {
printf ("\nFAILURE (read/write) @ 0x%.8lx:"
" expected 0x%.8lx, actual 0x%.8lx)\n",
(ulong)&start[offset], pattern, temp);
errs++;
if (ctrlc()) {
putc ('\n');
return 1;
}
}
anti_pattern = ~pattern;
start[offset] = anti_pattern;
}
/*
* Check each location for the inverted pattern and zero it.
*/
for (pattern = 1, offset = 0; offset < num_words; pattern++, offset++) {
WATCHDOG_RESET();
anti_pattern = ~pattern;
temp = start[offset];
if (temp != anti_pattern) {
printf ("\nFAILURE (read/write): @ 0x%.8lx:"
" expected 0x%.8lx, actual 0x%.8lx)\n",
(ulong)&start[offset], anti_pattern, temp);
errs++;
if (ctrlc()) {
putc ('\n');
return 1;
}
}
start[offset] = 0;
}
}
#else /* The original, quickie test */
incr = 1;
for (;;) {
if (ctrlc()) {
putc ('\n');
return 1;
}
if (iteration_limit && iterations > iteration_limit) {
printf("Tested %d iteration(s) with %lu errors.\n",
iterations-1, errs);
return errs != 0;
}
++iterations;
printf ("\rPattern %08lX Writing..."
"%12s"
"\b\b\b\b\b\b\b\b\b\b",
pattern, "");
for (addr=start,val=pattern; addr<end; addr++) {
WATCHDOG_RESET();
*addr = val;
val += incr;
}
puts ("Reading...");
for (addr=start,val=pattern; addr<end; addr++) {
WATCHDOG_RESET();
readback = *addr;
if (readback != val) {
printf ("\nMem error @ 0x%08X: "
"found %08lX, expected %08lX\n",
(uint)(uintptr_t)addr, readback, val);
errs++;
if (ctrlc()) {
putc ('\n');
return 1;
}
}
val += incr;
}
/*
* Flip the pattern each time to make lots of zeros and
* then, the next time, lots of ones. We decrement
* the "negative" patterns and increment the "positive"
* patterns to preserve this feature.
*/
if(pattern & 0x80000000) {
pattern = -pattern; /* complement & increment */
}
else {
pattern = ~pattern;
}
incr = -incr;
}
#endif
return 0; /* not reached */
}
/* Modify memory.
*
* Syntax:
* mm{.b, .w, .l} {addr}
* nm{.b, .w, .l} {addr}
*/
static int
mod_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const argv[])
{
ulong addr, i;
int nbytes, size;
if (argc != 2)
return cmd_usage(cmdtp);
#ifdef CONFIG_BOOT_RETRY_TIME
reset_cmd_timeout(); /* got a good command to get here */
#endif
/* We use the last specified parameters, unless new ones are
* entered.
*/
addr = mm_last_addr;
size = mm_last_size;
if ((flag & CMD_FLAG_REPEAT) == 0) {
/* New command specified. Check for a size specification.
* Defaults to long if no or incorrect specification.
*/
if ((size = cmd_get_data_size(argv[0], 4)) < 0)
return 1;
/* Address is specified since argc > 1
*/
addr = simple_strtoul(argv[1], NULL, 16);
addr += base_address;
}
#ifdef CONFIG_HAS_DATAFLASH
if (addr_dataflash(addr)){
puts ("Can't modify DataFlash in place. Use cp instead.\n\r");
return 0;
}
#endif
#ifdef CONFIG_BLACKFIN
if (addr_bfin_on_chip_mem(addr)) {
puts ("Can't modify L1 instruction in place. Use cp instead.\n\r");
return 0;
}
#endif
/* Print the address, followed by value. Then accept input for
* the next value. A non-converted value exits.
*/
do {
printf("%08lx:", addr);
if (size == 4)
printf(" %08x", *((uint *)addr));
else if (size == 2)
printf(" %04x", *((ushort *)addr));
else
printf(" %02x", *((u_char *)addr));
nbytes = readline (" ? ");
if (nbytes == 0 || (nbytes == 1 && console_buffer[0] == '-')) {
/* <CR> pressed as only input, don't modify current
* location and move to next. "-" pressed will go back.
*/
if (incrflag)
addr += nbytes ? -size : size;
nbytes = 1;
#ifdef CONFIG_BOOT_RETRY_TIME
reset_cmd_timeout(); /* good enough to not time out */
#endif
}
#ifdef CONFIG_BOOT_RETRY_TIME
else if (nbytes == -2) {
break; /* timed out, exit the command */
}
#endif
else {
char *endp;
i = simple_strtoul(console_buffer, &endp, 16);
nbytes = endp - console_buffer;
if (nbytes) {
#ifdef CONFIG_BOOT_RETRY_TIME
/* good enough to not time out
*/
reset_cmd_timeout();
#endif
if (size == 4)
*((uint *)addr) = i;
else if (size == 2)
*((ushort *)addr) = i;
else
*((u_char *)addr) = i;
if (incrflag)
addr += size;
}
}
} while (nbytes);
mm_last_addr = addr;
mm_last_size = size;
return 0;
}
#ifdef CONFIG_CMD_CRC32
#ifndef CONFIG_CRC32_VERIFY
int do_mem_crc (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, length;
ulong crc;
ulong *ptr;
if (argc < 3)
return cmd_usage(cmdtp);
addr = simple_strtoul (argv[1], NULL, 16);
addr += base_address;
length = simple_strtoul (argv[2], NULL, 16);
crc = crc32_wd (0, (const uchar *) addr, length, CHUNKSZ_CRC32);
printf ("CRC32 for %08lx ... %08lx ==> %08lx\n",
addr, addr + length - 1, crc);
if (argc > 3) {
ptr = (ulong *) simple_strtoul (argv[3], NULL, 16);
*ptr = crc;
}
return 0;
}
#else /* CONFIG_CRC32_VERIFY */
int do_mem_crc (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, length;
ulong crc;
ulong *ptr;
ulong vcrc;
int verify;
int ac;
char * const *av;
if (argc < 3) {
usage:
return cmd_usage(cmdtp);
}
av = argv + 1;
ac = argc - 1;
if (strcmp(*av, "-v") == 0) {
verify = 1;
av++;
ac--;
if (ac < 3)
goto usage;
} else
verify = 0;
addr = simple_strtoul(*av++, NULL, 16);
addr += base_address;
length = simple_strtoul(*av++, NULL, 16);
crc = crc32_wd (0, (const uchar *) addr, length, CHUNKSZ_CRC32);
if (!verify) {
printf ("CRC32 for %08lx ... %08lx ==> %08lx\n",
addr, addr + length - 1, crc);
if (ac > 2) {
ptr = (ulong *) simple_strtoul (*av++, NULL, 16);
*ptr = crc;
}
} else {
vcrc = simple_strtoul(*av++, NULL, 16);
if (vcrc != crc) {
printf ("CRC32 for %08lx ... %08lx ==> %08lx != %08lx ** ERROR **\n",
addr, addr + length - 1, crc, vcrc);
return 1;
}
}
return 0;
}
#endif /* CONFIG_CRC32_VERIFY */
#endif
/**************************************************/
U_BOOT_CMD(
md, 3, 1, do_mem_md,
"memory display",
"[.b, .w, .l] address [# of objects]"
);
U_BOOT_CMD(
mm, 2, 1, do_mem_mm,
"memory modify (auto-incrementing address)",
"[.b, .w, .l] address"
);
U_BOOT_CMD(
nm, 2, 1, do_mem_nm,
"memory modify (constant address)",
"[.b, .w, .l] address"
);
U_BOOT_CMD(
mw, 4, 1, do_mem_mw,
"memory write (fill)",
"[.b, .w, .l] address value [count]"
);
U_BOOT_CMD(
cp, 4, 1, do_mem_cp,
"memory copy",
"[.b, .w, .l] source target count"
);
U_BOOT_CMD(
cmp, 4, 1, do_mem_cmp,
"memory compare",
"[.b, .w, .l] addr1 addr2 count"
);
#ifdef CONFIG_CMD_CRC32
#ifndef CONFIG_CRC32_VERIFY
U_BOOT_CMD(
crc32, 4, 1, do_mem_crc,
"checksum calculation",
"address count [addr]\n - compute CRC32 checksum [save at addr]"
);
#else /* CONFIG_CRC32_VERIFY */
U_BOOT_CMD(
crc32, 5, 1, do_mem_crc,
"checksum calculation",
"address count [addr]\n - compute CRC32 checksum [save at addr]\n"
"-v address count crc\n - verify crc of memory area"
);
#endif /* CONFIG_CRC32_VERIFY */
#endif
U_BOOT_CMD(
base, 2, 1, do_mem_base,
"print or set address offset",
"\n - print address offset for memory commands\n"
"base off\n - set address offset for memory commands to 'off'"
);
U_BOOT_CMD(
loop, 3, 1, do_mem_loop,
"infinite loop on address range",
"[.b, .w, .l] address number_of_objects"
);
#ifdef CONFIG_LOOPW
U_BOOT_CMD(
loopw, 4, 1, do_mem_loopw,
"infinite write loop on address range",
"[.b, .w, .l] address number_of_objects data_to_write"
);
#endif /* CONFIG_LOOPW */
U_BOOT_CMD(
mtest, 5, 1, do_mem_mtest,
"simple RAM read/write test",
"[start [end [pattern [iterations]]]]"
);
#ifdef CONFIG_MX_CYCLIC
U_BOOT_CMD(
mdc, 4, 1, do_mem_mdc,
"memory display cyclic",
"[.b, .w, .l] address count delay(ms)"
);
U_BOOT_CMD(
mwc, 4, 1, do_mem_mwc,
"memory write cyclic",
"[.b, .w, .l] address value delay(ms)"
);
#endif /* CONFIG_MX_CYCLIC */
|
1001-study-uboot
|
common/cmd_mem.c
|
C
|
gpl3
| 28,163
|
/*
* (C) Copyright 2000
* Subodh Nijsure, SkyStream Networks, snijsure@skystream.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 <command.h>
#if defined(CONFIG_8xx)
#include <mpc8xx.h>
#elif defined (CONFIG_4xx)
extern void ppc4xx_reginfo(void);
#elif defined (CONFIG_5xx)
#include <mpc5xx.h>
#elif defined (CONFIG_MPC5200)
#include <mpc5xxx.h>
#elif defined (CONFIG_MPC86xx)
extern void mpc86xx_reginfo(void);
#elif defined(CONFIG_MPC85xx)
extern void mpc85xx_reginfo(void);
#endif
int do_reginfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
#if defined(CONFIG_8xx)
volatile immap_t *immap = (immap_t *)CONFIG_SYS_IMMR;
volatile memctl8xx_t *memctl = &immap->im_memctl;
volatile sysconf8xx_t *sysconf = &immap->im_siu_conf;
volatile sit8xx_t *timers = &immap->im_sit;
/* Hopefully more PowerPC knowledgable people will add code to display
* other useful registers
*/
printf ("\nSystem Configuration registers\n"
"\tIMMR\t0x%08X\n", get_immr(0));
printf("\tSIUMCR\t0x%08X", sysconf->sc_siumcr);
printf("\tSYPCR\t0x%08X\n",sysconf->sc_sypcr);
printf("\tSWT\t0x%08X", sysconf->sc_swt);
printf("\tSWSR\t0x%04X\n", sysconf->sc_swsr);
printf("\tSIPEND\t0x%08X\tSIMASK\t0x%08X\n",
sysconf->sc_sipend, sysconf->sc_simask);
printf("\tSIEL\t0x%08X\tSIVEC\t0x%08X\n",
sysconf->sc_siel, sysconf->sc_sivec);
printf("\tTESR\t0x%08X\tSDCR\t0x%08X\n",
sysconf->sc_tesr, sysconf->sc_sdcr);
printf ("Memory Controller Registers\n"
"\tBR0\t0x%08X\tOR0\t0x%08X \n", memctl->memc_br0, memctl->memc_or0);
printf("\tBR1\t0x%08X\tOR1\t0x%08X \n", memctl->memc_br1, memctl->memc_or1);
printf("\tBR2\t0x%08X\tOR2\t0x%08X \n", memctl->memc_br2, memctl->memc_or2);
printf("\tBR3\t0x%08X\tOR3\t0x%08X \n", memctl->memc_br3, memctl->memc_or3);
printf("\tBR4\t0x%08X\tOR4\t0x%08X \n", memctl->memc_br4, memctl->memc_or4);
printf("\tBR5\t0x%08X\tOR5\t0x%08X \n", memctl->memc_br5, memctl->memc_or5);
printf("\tBR6\t0x%08X\tOR6\t0x%08X \n", memctl->memc_br6, memctl->memc_or6);
printf("\tBR7\t0x%08X\tOR7\t0x%08X \n", memctl->memc_br7, memctl->memc_or7);
printf ("\n"
"\tmamr\t0x%08X\tmbmr\t0x%08X \n",
memctl->memc_mamr, memctl->memc_mbmr );
printf("\tmstat\t0x%08X\tmptpr\t0x%08X \n",
memctl->memc_mstat, memctl->memc_mptpr );
printf("\tmdr\t0x%08X \n", memctl->memc_mdr);
printf ("\nSystem Integration Timers\n"
"\tTBSCR\t0x%08X\tRTCSC\t0x%08X \n",
timers->sit_tbscr, timers->sit_rtcsc);
printf("\tPISCR\t0x%08X \n", timers->sit_piscr);
/*
* May be some CPM info here?
*/
#elif defined (CONFIG_4xx)
ppc4xx_reginfo();
#elif defined(CONFIG_5xx)
volatile immap_t *immap = (immap_t *)CONFIG_SYS_IMMR;
volatile memctl5xx_t *memctl = &immap->im_memctl;
volatile sysconf5xx_t *sysconf = &immap->im_siu_conf;
volatile sit5xx_t *timers = &immap->im_sit;
volatile car5xx_t *car = &immap->im_clkrst;
volatile uimb5xx_t *uimb = &immap->im_uimb;
puts ("\nSystem Configuration registers\n");
printf("\tIMMR\t0x%08X\tSIUMCR\t0x%08X \n", get_immr(0), sysconf->sc_siumcr);
printf("\tSYPCR\t0x%08X\tSWSR\t0x%04X \n" ,sysconf->sc_sypcr, sysconf->sc_swsr);
printf("\tSIPEND\t0x%08X\tSIMASK\t0x%08X \n", sysconf->sc_sipend, sysconf->sc_simask);
printf("\tSIEL\t0x%08X\tSIVEC\t0x%08X \n", sysconf->sc_siel, sysconf->sc_sivec);
printf("\tTESR\t0x%08X\n", sysconf->sc_tesr);
puts ("\nMemory Controller Registers\n");
printf("\tBR0\t0x%08X\tOR0\t0x%08X \n", memctl->memc_br0, memctl->memc_or0);
printf("\tBR1\t0x%08X\tOR1\t0x%08X \n", memctl->memc_br1, memctl->memc_or1);
printf("\tBR2\t0x%08X\tOR2\t0x%08X \n", memctl->memc_br2, memctl->memc_or2);
printf("\tBR3\t0x%08X\tOR3\t0x%08X \n", memctl->memc_br3, memctl->memc_or3);
printf("\tDMBR\t0x%08X\tDMOR\t0x%08X \n", memctl->memc_dmbr, memctl->memc_dmor );
printf("\tMSTAT\t0x%08X\n", memctl->memc_mstat);
puts ("\nSystem Integration Timers\n");
printf("\tTBSCR\t0x%08X\tRTCSC\t0x%08X \n", timers->sit_tbscr, timers->sit_rtcsc);
printf("\tPISCR\t0x%08X \n", timers->sit_piscr);
puts ("\nClocks and Reset\n");
printf("\tSCCR\t0x%08X\tPLPRCR\t0x%08X \n", car->car_sccr, car->car_plprcr);
puts ("\nU-Bus to IMB3 Bus Interface\n");
printf("\tUMCR\t0x%08X\tUIPEND\t0x%08X \n", uimb->uimb_umcr, uimb->uimb_uipend);
puts ("\n\n");
#elif defined(CONFIG_MPC5200)
puts ("\nMPC5200 registers\n");
printf ("MBAR=%08x\n", CONFIG_SYS_MBAR);
puts ("Memory map registers\n");
printf ("\tCS0: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_CS0_START,
*(volatile ulong*)MPC5XXX_CS0_STOP,
*(volatile ulong*)MPC5XXX_CS0_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x00010000) ? 1 : 0);
printf ("\tCS1: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_CS1_START,
*(volatile ulong*)MPC5XXX_CS1_STOP,
*(volatile ulong*)MPC5XXX_CS1_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x00020000) ? 1 : 0);
printf ("\tCS2: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_CS2_START,
*(volatile ulong*)MPC5XXX_CS2_STOP,
*(volatile ulong*)MPC5XXX_CS2_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x00040000) ? 1 : 0);
printf ("\tCS3: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_CS3_START,
*(volatile ulong*)MPC5XXX_CS3_STOP,
*(volatile ulong*)MPC5XXX_CS3_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x00080000) ? 1 : 0);
printf ("\tCS4: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_CS4_START,
*(volatile ulong*)MPC5XXX_CS4_STOP,
*(volatile ulong*)MPC5XXX_CS4_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x00100000) ? 1 : 0);
printf ("\tCS5: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_CS5_START,
*(volatile ulong*)MPC5XXX_CS5_STOP,
*(volatile ulong*)MPC5XXX_CS5_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x00200000) ? 1 : 0);
printf ("\tCS6: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_CS6_START,
*(volatile ulong*)MPC5XXX_CS6_STOP,
*(volatile ulong*)MPC5XXX_CS6_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x04000000) ? 1 : 0);
printf ("\tCS7: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_CS7_START,
*(volatile ulong*)MPC5XXX_CS7_STOP,
*(volatile ulong*)MPC5XXX_CS7_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x08000000) ? 1 : 0);
printf ("\tBOOTCS: start %08lX\tstop %08lX\tconfig %08lX\ten %d\n",
*(volatile ulong*)MPC5XXX_BOOTCS_START,
*(volatile ulong*)MPC5XXX_BOOTCS_STOP,
*(volatile ulong*)MPC5XXX_BOOTCS_CFG,
(*(volatile ulong*)MPC5XXX_ADDECR & 0x02000000) ? 1 : 0);
printf ("\tSDRAMCS0: %08lX\n",
*(volatile ulong*)MPC5XXX_SDRAM_CS0CFG);
printf ("\tSDRAMCS1: %08lX\n",
*(volatile ulong*)MPC5XXX_SDRAM_CS1CFG);
#elif defined(CONFIG_MPC86xx)
mpc86xx_reginfo();
#elif defined(CONFIG_MPC85xx)
mpc85xx_reginfo();
#elif defined(CONFIG_BLACKFIN)
puts("\nSystem Configuration registers\n");
puts("\nPLL Registers\n");
printf("\tPLL_DIV: 0x%04x PLL_CTL: 0x%04x\n",
bfin_read_PLL_DIV(), bfin_read_PLL_CTL());
printf("\tPLL_STAT: 0x%04x PLL_LOCKCNT: 0x%04x\n",
bfin_read_PLL_STAT(), bfin_read_PLL_LOCKCNT());
printf("\tVR_CTL: 0x%04x\n", bfin_read_VR_CTL());
puts("\nEBIU AMC Registers\n");
printf("\tEBIU_AMGCTL: 0x%04x\n", bfin_read_EBIU_AMGCTL());
printf("\tEBIU_AMBCTL0: 0x%08x EBIU_AMBCTL1: 0x%08x\n",
bfin_read_EBIU_AMBCTL0(), bfin_read_EBIU_AMBCTL1());
# ifdef EBIU_MODE
printf("\tEBIU_MBSCTL: 0x%08x EBIU_ARBSTAT: 0x%08x\n",
bfin_read_EBIU_MBSCTL(), bfin_read_EBIU_ARBSTAT());
printf("\tEBIU_MODE: 0x%08x EBIU_FCTL: 0x%08x\n",
bfin_read_EBIU_MODE(), bfin_read_EBIU_FCTL());
# endif
# ifdef EBIU_RSTCTL
puts("\nEBIU DDR Registers\n");
printf("\tEBIU_DDRCTL0: 0x%08x EBIU_DDRCTL1: 0x%08x\n",
bfin_read_EBIU_DDRCTL0(), bfin_read_EBIU_DDRCTL1());
printf("\tEBIU_DDRCTL2: 0x%08x EBIU_DDRCTL3: 0x%08x\n",
bfin_read_EBIU_DDRCTL2(), bfin_read_EBIU_DDRCTL3());
printf("\tEBIU_DDRQUE: 0x%08x EBIU_RSTCTL 0x%04x\n",
bfin_read_EBIU_DDRQUE(), bfin_read_EBIU_RSTCTL());
printf("\tEBIU_ERRADD: 0x%08x EBIU_ERRMST: 0x%04x\n",
bfin_read_EBIU_ERRADD(), bfin_read_EBIU_ERRMST());
# else
puts("\nEBIU SDC Registers\n");
printf("\tEBIU_SDRRC: 0x%04x EBIU_SDBCTL: 0x%04x\n",
bfin_read_EBIU_SDRRC(), bfin_read_EBIU_SDBCTL());
printf("\tEBIU_SDSTAT: 0x%04x EBIU_SDGCTL: 0x%08x\n",
bfin_read_EBIU_SDSTAT(), bfin_read_EBIU_SDGCTL());
# endif
#endif /* CONFIG_BLACKFIN */
return 0;
}
/**************************************************/
#if defined(CONFIG_CMD_REGINFO)
U_BOOT_CMD(
reginfo, 2, 1, do_reginfo,
"print register information",
""
);
#endif
|
1001-study-uboot
|
common/cmd_reginfo.c
|
C
|
gpl3
| 9,432
|
/*
* (C) Copyright 2002
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2002
* Robert Schwebel, Pengutronix, <r.schwebel@pengutronix.de>
*
* (C) Copyright 2003
* Kai-Uwe Bloem, Auerswald GmbH & Co KG, <linux-development@auerswald.de>
*
* (C) Copyright 2005
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* Added support for reading flash partition table from environment.
* Parsing routines are based on driver/mtd/cmdline.c from the linux 2.4
* kernel tree.
*
* (C) Copyright 2008
* Harald Welte, OpenMoko, Inc., Harald Welte <laforge@openmoko.org>
*
* $Id: cmdlinepart.c,v 1.17 2004/11/26 11:18:47 lavinen Exp $
* Copyright 2002 SYSGO Real-Time Solutions 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
*/
/*
* Three environment variables are used by the parsing routines:
*
* 'partition' - keeps current partition identifier
*
* partition := <part-id>
* <part-id> := <dev-id>,part_num
*
*
* 'mtdids' - linux kernel mtd device id <-> u-boot device id mapping
*
* mtdids=<idmap>[,<idmap>,...]
*
* <idmap> := <dev-id>=<mtd-id>
* <dev-id> := 'nand'|'nor'|'onenand'<dev-num>
* <dev-num> := mtd device number, 0...
* <mtd-id> := unique device tag used by linux kernel to find mtd device (mtd->name)
*
*
* 'mtdparts' - partition list
*
* mtdparts=mtdparts=<mtd-def>[;<mtd-def>...]
*
* <mtd-def> := <mtd-id>:<part-def>[,<part-def>...]
* <mtd-id> := unique device tag used by linux kernel to find mtd device (mtd->name)
* <part-def> := <size>[@<offset>][<name>][<ro-flag>]
* <size> := standard linux memsize OR '-' to denote all remaining space
* <offset> := partition start offset within the device
* <name> := '(' NAME ')'
* <ro-flag> := when set to 'ro' makes partition read-only (not used, passed to kernel)
*
* Notes:
* - each <mtd-id> used in mtdparts must albo exist in 'mtddis' mapping
* - if the above variables are not set defaults for a given target are used
*
* Examples:
*
* 1 NOR Flash, with 1 single writable partition:
* mtdids=nor0=edb7312-nor
* mtdparts=mtdparts=edb7312-nor:-
*
* 1 NOR Flash with 2 partitions, 1 NAND with one
* mtdids=nor0=edb7312-nor,nand0=edb7312-nand
* mtdparts=mtdparts=edb7312-nor:256k(ARMboot)ro,-(root);edb7312-nand:-(home)
*
*/
#include <common.h>
#include <command.h>
#include <malloc.h>
#include <jffs2/load_kernel.h>
#include <linux/list.h>
#include <linux/ctype.h>
#include <linux/err.h>
#include <linux/mtd/mtd.h>
#if defined(CONFIG_CMD_NAND)
#include <linux/mtd/nand.h>
#include <nand.h>
#endif
#if defined(CONFIG_CMD_ONENAND)
#include <linux/mtd/onenand.h>
#include <onenand_uboot.h>
#endif
/* special size referring to all the remaining space in a partition */
#define SIZE_REMAINING 0xFFFFFFFF
/* special offset value, it is used when not provided by user
*
* this value is used temporarily during parsing, later such offests
* are recalculated */
#define OFFSET_NOT_SPECIFIED 0xFFFFFFFF
/* minimum partition size */
#define MIN_PART_SIZE 4096
/* this flag needs to be set in part_info struct mask_flags
* field for read-only partitions */
#define MTD_WRITEABLE_CMD 1
/* default values for mtdids and mtdparts variables */
#if defined(MTDIDS_DEFAULT)
static const char *const mtdids_default = MTDIDS_DEFAULT;
#else
static const char *const mtdids_default = NULL;
#endif
#if defined(MTDPARTS_DEFAULT)
static const char *const mtdparts_default = MTDPARTS_DEFAULT;
#else
static const char *const mtdparts_default = NULL;
#endif
/* copies of last seen 'mtdids', 'mtdparts' and 'partition' env variables */
#define MTDIDS_MAXLEN 128
#define MTDPARTS_MAXLEN 512
#define PARTITION_MAXLEN 16
static char last_ids[MTDIDS_MAXLEN];
static char last_parts[MTDPARTS_MAXLEN];
static char last_partition[PARTITION_MAXLEN];
/* low level jffs2 cache cleaning routine */
extern void jffs2_free_cache(struct part_info *part);
/* mtdids mapping list, filled by parse_ids() */
struct list_head mtdids;
/* device/partition list, parse_cmdline() parses into here */
struct list_head devices;
/* current active device and partition number */
struct mtd_device *current_mtd_dev = NULL;
u8 current_mtd_partnum = 0;
static struct part_info* mtd_part_info(struct mtd_device *dev, unsigned int part_num);
/* command line only routines */
static struct mtdids* id_find_by_mtd_id(const char *mtd_id, unsigned int mtd_id_len);
static int device_del(struct mtd_device *dev);
/**
* Parses a string into a number. The number stored at ptr is
* potentially suffixed with K (for kilobytes, or 1024 bytes),
* M (for megabytes, or 1048576 bytes), or G (for gigabytes, or
* 1073741824). If the number is suffixed with K, M, or G, then
* the return value is the number multiplied by one kilobyte, one
* megabyte, or one gigabyte, respectively.
*
* @param ptr where parse begins
* @param retptr output pointer to next char after parse completes (output)
* @return resulting unsigned int
*/
static unsigned long memsize_parse (const char *const ptr, const char **retptr)
{
unsigned long ret = simple_strtoul(ptr, (char **)retptr, 0);
switch (**retptr) {
case 'G':
case 'g':
ret <<= 10;
case 'M':
case 'm':
ret <<= 10;
case 'K':
case 'k':
ret <<= 10;
(*retptr)++;
default:
break;
}
return ret;
}
/**
* Format string describing supplied size. This routine does the opposite job
* to memsize_parse(). Size in bytes is converted to string and if possible
* shortened by using k (kilobytes), m (megabytes) or g (gigabytes) suffix.
*
* Note, that this routine does not check for buffer overflow, it's the caller
* who must assure enough space.
*
* @param buf output buffer
* @param size size to be converted to string
*/
static void memsize_format(char *buf, u32 size)
{
#define SIZE_GB ((u32)1024*1024*1024)
#define SIZE_MB ((u32)1024*1024)
#define SIZE_KB ((u32)1024)
if ((size % SIZE_GB) == 0)
sprintf(buf, "%ug", size/SIZE_GB);
else if ((size % SIZE_MB) == 0)
sprintf(buf, "%um", size/SIZE_MB);
else if (size % SIZE_KB == 0)
sprintf(buf, "%uk", size/SIZE_KB);
else
sprintf(buf, "%u", size);
}
/**
* This routine does global indexing of all partitions. Resulting index for
* current partition is saved in 'mtddevnum'. Current partition name in
* 'mtddevname'.
*/
static void index_partitions(void)
{
char buf[16];
u16 mtddevnum;
struct part_info *part;
struct list_head *dentry;
struct mtd_device *dev;
debug("--- index partitions ---\n");
if (current_mtd_dev) {
mtddevnum = 0;
list_for_each(dentry, &devices) {
dev = list_entry(dentry, struct mtd_device, link);
if (dev == current_mtd_dev) {
mtddevnum += current_mtd_partnum;
sprintf(buf, "%d", mtddevnum);
setenv("mtddevnum", buf);
break;
}
mtddevnum += dev->num_parts;
}
part = mtd_part_info(current_mtd_dev, current_mtd_partnum);
setenv("mtddevname", part->name);
debug("=> mtddevnum %d,\n=> mtddevname %s\n", mtddevnum, part->name);
} else {
setenv("mtddevnum", NULL);
setenv("mtddevname", NULL);
debug("=> mtddevnum NULL\n=> mtddevname NULL\n");
}
}
/**
* Save current device and partition in environment variable 'partition'.
*/
static void current_save(void)
{
char buf[16];
debug("--- current_save ---\n");
if (current_mtd_dev) {
sprintf(buf, "%s%d,%d", MTD_DEV_TYPE(current_mtd_dev->id->type),
current_mtd_dev->id->num, current_mtd_partnum);
setenv("partition", buf);
strncpy(last_partition, buf, 16);
debug("=> partition %s\n", buf);
} else {
setenv("partition", NULL);
last_partition[0] = '\0';
debug("=> partition NULL\n");
}
index_partitions();
}
/**
* Produce a mtd_info given a type and num.
*
* @param type mtd type
* @param num mtd number
* @param mtd a pointer to an mtd_info instance (output)
* @return 0 if device is valid, 1 otherwise
*/
static int get_mtd_info(u8 type, u8 num, struct mtd_info **mtd)
{
char mtd_dev[16];
sprintf(mtd_dev, "%s%d", MTD_DEV_TYPE(type), num);
*mtd = get_mtd_device_nm(mtd_dev);
if (IS_ERR(*mtd)) {
printf("Device %s not found!\n", mtd_dev);
return 1;
}
return 0;
}
/**
* Performs sanity check for supplied flash partition.
* Table of existing MTD flash devices is searched and partition device
* is located. Alignment with the granularity of nand erasesize is verified.
*
* @param id of the parent device
* @param part partition to validate
* @return 0 if partition is valid, 1 otherwise
*/
static int part_validate_eraseblock(struct mtdids *id, struct part_info *part)
{
struct mtd_info *mtd = NULL;
int i, j;
ulong start;
if (get_mtd_info(id->type, id->num, &mtd))
return 1;
part->sector_size = mtd->erasesize;
if (!mtd->numeraseregions) {
/*
* Only one eraseregion (NAND, OneNAND or uniform NOR),
* checking for alignment is easy here
*/
if ((unsigned long)part->offset % mtd->erasesize) {
printf("%s%d: partition (%s) start offset"
"alignment incorrect\n",
MTD_DEV_TYPE(id->type), id->num, part->name);
return 1;
}
if (part->size % mtd->erasesize) {
printf("%s%d: partition (%s) size alignment incorrect\n",
MTD_DEV_TYPE(id->type), id->num, part->name);
return 1;
}
} else {
/*
* Multiple eraseregions (non-uniform NOR),
* checking for alignment is more complex here
*/
/* Check start alignment */
for (i = 0; i < mtd->numeraseregions; i++) {
start = mtd->eraseregions[i].offset;
for (j = 0; j < mtd->eraseregions[i].numblocks; j++) {
if (part->offset == start)
goto start_ok;
start += mtd->eraseregions[i].erasesize;
}
}
printf("%s%d: partition (%s) start offset alignment incorrect\n",
MTD_DEV_TYPE(id->type), id->num, part->name);
return 1;
start_ok:
/* Check end/size alignment */
for (i = 0; i < mtd->numeraseregions; i++) {
start = mtd->eraseregions[i].offset;
for (j = 0; j < mtd->eraseregions[i].numblocks; j++) {
if ((part->offset + part->size) == start)
goto end_ok;
start += mtd->eraseregions[i].erasesize;
}
}
/* Check last sector alignment */
if ((part->offset + part->size) == start)
goto end_ok;
printf("%s%d: partition (%s) size alignment incorrect\n",
MTD_DEV_TYPE(id->type), id->num, part->name);
return 1;
end_ok:
return 0;
}
return 0;
}
/**
* Performs sanity check for supplied partition. Offset and size are verified
* to be within valid range. Partition type is checked and either
* parts_validate_nor() or parts_validate_nand() is called with the argument
* of part.
*
* @param id of the parent device
* @param part partition to validate
* @return 0 if partition is valid, 1 otherwise
*/
static int part_validate(struct mtdids *id, struct part_info *part)
{
if (part->size == SIZE_REMAINING)
part->size = id->size - part->offset;
if (part->offset > id->size) {
printf("%s: offset %08x beyond flash size %08x\n",
id->mtd_id, part->offset, id->size);
return 1;
}
if ((part->offset + part->size) <= part->offset) {
printf("%s%d: partition (%s) size too big\n",
MTD_DEV_TYPE(id->type), id->num, part->name);
return 1;
}
if (part->offset + part->size > id->size) {
printf("%s: partitioning exceeds flash size\n", id->mtd_id);
return 1;
}
/*
* Now we need to check if the partition starts and ends on
* sector (eraseblock) regions
*/
return part_validate_eraseblock(id, part);
}
/**
* Delete selected partition from the partion list of the specified device.
*
* @param dev device to delete partition from
* @param part partition to delete
* @return 0 on success, 1 otherwise
*/
static int part_del(struct mtd_device *dev, struct part_info *part)
{
u8 current_save_needed = 0;
/* if there is only one partition, remove whole device */
if (dev->num_parts == 1)
return device_del(dev);
/* otherwise just delete this partition */
if (dev == current_mtd_dev) {
/* we are modyfing partitions for the current device,
* update current */
struct part_info *curr_pi;
curr_pi = mtd_part_info(current_mtd_dev, current_mtd_partnum);
if (curr_pi) {
if (curr_pi == part) {
printf("current partition deleted, resetting current to 0\n");
current_mtd_partnum = 0;
} else if (part->offset <= curr_pi->offset) {
current_mtd_partnum--;
}
current_save_needed = 1;
}
}
list_del(&part->link);
free(part);
dev->num_parts--;
if (current_save_needed > 0)
current_save();
else
index_partitions();
return 0;
}
/**
* Delete all partitions from parts head list, free memory.
*
* @param head list of partitions to delete
*/
static void part_delall(struct list_head *head)
{
struct list_head *entry, *n;
struct part_info *part_tmp;
/* clean tmp_list and free allocated memory */
list_for_each_safe(entry, n, head) {
part_tmp = list_entry(entry, struct part_info, link);
list_del(entry);
free(part_tmp);
}
}
/**
* Add new partition to the supplied partition list. Make sure partitions are
* sorted by offset in ascending order.
*
* @param head list this partition is to be added to
* @param new partition to be added
*/
static int part_sort_add(struct mtd_device *dev, struct part_info *part)
{
struct list_head *entry;
struct part_info *new_pi, *curr_pi;
/* link partition to parrent dev */
part->dev = dev;
if (list_empty(&dev->parts)) {
debug("part_sort_add: list empty\n");
list_add(&part->link, &dev->parts);
dev->num_parts++;
index_partitions();
return 0;
}
new_pi = list_entry(&part->link, struct part_info, link);
/* get current partition info if we are updating current device */
curr_pi = NULL;
if (dev == current_mtd_dev)
curr_pi = mtd_part_info(current_mtd_dev, current_mtd_partnum);
list_for_each(entry, &dev->parts) {
struct part_info *pi;
pi = list_entry(entry, struct part_info, link);
/* be compliant with kernel cmdline, allow only one partition at offset zero */
if ((new_pi->offset == pi->offset) && (pi->offset == 0)) {
printf("cannot add second partition at offset 0\n");
return 1;
}
if (new_pi->offset <= pi->offset) {
list_add_tail(&part->link, entry);
dev->num_parts++;
if (curr_pi && (pi->offset <= curr_pi->offset)) {
/* we are modyfing partitions for the current
* device, update current */
current_mtd_partnum++;
current_save();
} else {
index_partitions();
}
return 0;
}
}
list_add_tail(&part->link, &dev->parts);
dev->num_parts++;
index_partitions();
return 0;
}
/**
* Add provided partition to the partition list of a given device.
*
* @param dev device to which partition is added
* @param part partition to be added
* @return 0 on success, 1 otherwise
*/
static int part_add(struct mtd_device *dev, struct part_info *part)
{
/* verify alignment and size */
if (part_validate(dev->id, part) != 0)
return 1;
/* partition is ok, add it to the list */
if (part_sort_add(dev, part) != 0)
return 1;
return 0;
}
/**
* Parse one partition definition, allocate memory and return pointer to this
* location in retpart.
*
* @param partdef pointer to the partition definition string i.e. <part-def>
* @param ret output pointer to next char after parse completes (output)
* @param retpart pointer to the allocated partition (output)
* @return 0 on success, 1 otherwise
*/
static int part_parse(const char *const partdef, const char **ret, struct part_info **retpart)
{
struct part_info *part;
unsigned long size;
unsigned long offset;
const char *name;
int name_len;
unsigned int mask_flags;
const char *p;
p = partdef;
*retpart = NULL;
*ret = NULL;
/* fetch the partition size */
if (*p == '-') {
/* assign all remaining space to this partition */
debug("'-': remaining size assigned\n");
size = SIZE_REMAINING;
p++;
} else {
size = memsize_parse(p, &p);
if (size < MIN_PART_SIZE) {
printf("partition size too small (%lx)\n", size);
return 1;
}
}
/* check for offset */
offset = OFFSET_NOT_SPECIFIED;
if (*p == '@') {
p++;
offset = memsize_parse(p, &p);
}
/* now look for the name */
if (*p == '(') {
name = ++p;
if ((p = strchr(name, ')')) == NULL) {
printf("no closing ) found in partition name\n");
return 1;
}
name_len = p - name + 1;
if ((name_len - 1) == 0) {
printf("empty partition name\n");
return 1;
}
p++;
} else {
/* 0x00000000@0x00000000 */
name_len = 22;
name = NULL;
}
/* test for options */
mask_flags = 0;
if (strncmp(p, "ro", 2) == 0) {
mask_flags |= MTD_WRITEABLE_CMD;
p += 2;
}
/* check for next partition definition */
if (*p == ',') {
if (size == SIZE_REMAINING) {
*ret = NULL;
printf("no partitions allowed after a fill-up partition\n");
return 1;
}
*ret = ++p;
} else if ((*p == ';') || (*p == '\0')) {
*ret = p;
} else {
printf("unexpected character '%c' at the end of partition\n", *p);
*ret = NULL;
return 1;
}
/* allocate memory */
part = (struct part_info *)malloc(sizeof(struct part_info) + name_len);
if (!part) {
printf("out of memory\n");
return 1;
}
memset(part, 0, sizeof(struct part_info) + name_len);
part->size = size;
part->offset = offset;
part->mask_flags = mask_flags;
part->name = (char *)(part + 1);
if (name) {
/* copy user provided name */
strncpy(part->name, name, name_len - 1);
part->auto_name = 0;
} else {
/* auto generated name in form of size@offset */
sprintf(part->name, "0x%08lx@0x%08lx", size, offset);
part->auto_name = 1;
}
part->name[name_len - 1] = '\0';
INIT_LIST_HEAD(&part->link);
debug("+ partition: name %-22s size 0x%08x offset 0x%08x mask flags %d\n",
part->name, part->size,
part->offset, part->mask_flags);
*retpart = part;
return 0;
}
/**
* Check device number to be within valid range for given device type.
*
* @param type mtd type
* @param num mtd number
* @param size a pointer to the size of the mtd device (output)
* @return 0 if device is valid, 1 otherwise
*/
int mtd_device_validate(u8 type, u8 num, u32 *size)
{
struct mtd_info *mtd = NULL;
if (get_mtd_info(type, num, &mtd))
return 1;
*size = mtd->size;
return 0;
}
/**
* Delete all mtd devices from a supplied devices list, free memory allocated for
* each device and delete all device partitions.
*
* @return 0 on success, 1 otherwise
*/
static int device_delall(struct list_head *head)
{
struct list_head *entry, *n;
struct mtd_device *dev_tmp;
/* clean devices list */
list_for_each_safe(entry, n, head) {
dev_tmp = list_entry(entry, struct mtd_device, link);
list_del(entry);
part_delall(&dev_tmp->parts);
free(dev_tmp);
}
INIT_LIST_HEAD(&devices);
return 0;
}
/**
* If provided device exists it's partitions are deleted, device is removed
* from device list and device memory is freed.
*
* @param dev device to be deleted
* @return 0 on success, 1 otherwise
*/
static int device_del(struct mtd_device *dev)
{
part_delall(&dev->parts);
list_del(&dev->link);
free(dev);
if (dev == current_mtd_dev) {
/* we just deleted current device */
if (list_empty(&devices)) {
current_mtd_dev = NULL;
} else {
/* reset first partition from first dev from the
* devices list as current */
current_mtd_dev = list_entry(devices.next, struct mtd_device, link);
current_mtd_partnum = 0;
}
current_save();
return 0;
}
index_partitions();
return 0;
}
/**
* Search global device list and return pointer to the device of type and num
* specified.
*
* @param type device type
* @param num device number
* @return NULL if requested device does not exist
*/
struct mtd_device *device_find(u8 type, u8 num)
{
struct list_head *entry;
struct mtd_device *dev_tmp;
list_for_each(entry, &devices) {
dev_tmp = list_entry(entry, struct mtd_device, link);
if ((dev_tmp->id->type == type) && (dev_tmp->id->num == num))
return dev_tmp;
}
return NULL;
}
/**
* Add specified device to the global device list.
*
* @param dev device to be added
*/
static void device_add(struct mtd_device *dev)
{
u8 current_save_needed = 0;
if (list_empty(&devices)) {
current_mtd_dev = dev;
current_mtd_partnum = 0;
current_save_needed = 1;
}
list_add_tail(&dev->link, &devices);
if (current_save_needed > 0)
current_save();
else
index_partitions();
}
/**
* Parse device type, name and mtd-id. If syntax is ok allocate memory and
* return pointer to the device structure.
*
* @param mtd_dev pointer to the device definition string i.e. <mtd-dev>
* @param ret output pointer to next char after parse completes (output)
* @param retdev pointer to the allocated device (output)
* @return 0 on success, 1 otherwise
*/
static int device_parse(const char *const mtd_dev, const char **ret, struct mtd_device **retdev)
{
struct mtd_device *dev;
struct part_info *part;
struct mtdids *id;
const char *mtd_id;
unsigned int mtd_id_len;
const char *p;
const char *pend;
LIST_HEAD(tmp_list);
struct list_head *entry, *n;
u16 num_parts;
u32 offset;
int err = 1;
debug("===device_parse===\n");
assert(retdev);
*retdev = NULL;
if (ret)
*ret = NULL;
/* fetch <mtd-id> */
mtd_id = p = mtd_dev;
if (!(p = strchr(mtd_id, ':'))) {
printf("no <mtd-id> identifier\n");
return 1;
}
mtd_id_len = p - mtd_id + 1;
p++;
/* verify if we have a valid device specified */
if ((id = id_find_by_mtd_id(mtd_id, mtd_id_len - 1)) == NULL) {
printf("invalid mtd device '%.*s'\n", mtd_id_len - 1, mtd_id);
return 1;
}
#ifdef DEBUG
pend = strchr(p, ';');
#endif
debug("dev type = %d (%s), dev num = %d, mtd-id = %s\n",
id->type, MTD_DEV_TYPE(id->type),
id->num, id->mtd_id);
debug("parsing partitions %.*s\n", (pend ? pend - p : strlen(p)), p);
/* parse partitions */
num_parts = 0;
offset = 0;
if ((dev = device_find(id->type, id->num)) != NULL) {
/* if device already exists start at the end of the last partition */
part = list_entry(dev->parts.prev, struct part_info, link);
offset = part->offset + part->size;
}
while (p && (*p != '\0') && (*p != ';')) {
err = 1;
if ((part_parse(p, &p, &part) != 0) || (!part))
break;
/* calculate offset when not specified */
if (part->offset == OFFSET_NOT_SPECIFIED)
part->offset = offset;
else
offset = part->offset;
/* verify alignment and size */
if (part_validate(id, part) != 0)
break;
offset += part->size;
/* partition is ok, add it to the list */
list_add_tail(&part->link, &tmp_list);
num_parts++;
err = 0;
}
if (err == 1) {
part_delall(&tmp_list);
return 1;
}
if (num_parts == 0) {
printf("no partitions for device %s%d (%s)\n",
MTD_DEV_TYPE(id->type), id->num, id->mtd_id);
return 1;
}
debug("\ntotal partitions: %d\n", num_parts);
/* check for next device presence */
if (p) {
if (*p == ';') {
if (ret)
*ret = ++p;
} else if (*p == '\0') {
if (ret)
*ret = p;
} else {
printf("unexpected character '%c' at the end of device\n", *p);
if (ret)
*ret = NULL;
return 1;
}
}
/* allocate memory for mtd_device structure */
if ((dev = (struct mtd_device *)malloc(sizeof(struct mtd_device))) == NULL) {
printf("out of memory\n");
return 1;
}
memset(dev, 0, sizeof(struct mtd_device));
dev->id = id;
dev->num_parts = 0; /* part_sort_add increments num_parts */
INIT_LIST_HEAD(&dev->parts);
INIT_LIST_HEAD(&dev->link);
/* move partitions from tmp_list to dev->parts */
list_for_each_safe(entry, n, &tmp_list) {
part = list_entry(entry, struct part_info, link);
list_del(entry);
if (part_sort_add(dev, part) != 0) {
device_del(dev);
return 1;
}
}
*retdev = dev;
debug("===\n\n");
return 0;
}
/**
* Initialize global device list.
*
* @return 0 on success, 1 otherwise
*/
static int mtd_devices_init(void)
{
last_parts[0] = '\0';
current_mtd_dev = NULL;
current_save();
return device_delall(&devices);
}
/*
* Search global mtdids list and find id of requested type and number.
*
* @return pointer to the id if it exists, NULL otherwise
*/
static struct mtdids* id_find(u8 type, u8 num)
{
struct list_head *entry;
struct mtdids *id;
list_for_each(entry, &mtdids) {
id = list_entry(entry, struct mtdids, link);
if ((id->type == type) && (id->num == num))
return id;
}
return NULL;
}
/**
* Search global mtdids list and find id of a requested mtd_id.
*
* Note: first argument is not null terminated.
*
* @param mtd_id string containing requested mtd_id
* @param mtd_id_len length of supplied mtd_id
* @return pointer to the id if it exists, NULL otherwise
*/
static struct mtdids* id_find_by_mtd_id(const char *mtd_id, unsigned int mtd_id_len)
{
struct list_head *entry;
struct mtdids *id;
debug("--- id_find_by_mtd_id: '%.*s' (len = %d)\n",
mtd_id_len, mtd_id, mtd_id_len);
list_for_each(entry, &mtdids) {
id = list_entry(entry, struct mtdids, link);
debug("entry: '%s' (len = %d)\n",
id->mtd_id, strlen(id->mtd_id));
if (mtd_id_len != strlen(id->mtd_id))
continue;
if (strncmp(id->mtd_id, mtd_id, mtd_id_len) == 0)
return id;
}
return NULL;
}
/**
* Parse device id string <dev-id> := 'nand'|'nor'|'onenand'<dev-num>,
* return device type and number.
*
* @param id string describing device id
* @param ret_id output pointer to next char after parse completes (output)
* @param dev_type parsed device type (output)
* @param dev_num parsed device number (output)
* @return 0 on success, 1 otherwise
*/
int mtd_id_parse(const char *id, const char **ret_id, u8 *dev_type, u8 *dev_num)
{
const char *p = id;
*dev_type = 0;
if (strncmp(p, "nand", 4) == 0) {
*dev_type = MTD_DEV_TYPE_NAND;
p += 4;
} else if (strncmp(p, "nor", 3) == 0) {
*dev_type = MTD_DEV_TYPE_NOR;
p += 3;
} else if (strncmp(p, "onenand", 7) == 0) {
*dev_type = MTD_DEV_TYPE_ONENAND;
p += 7;
} else {
printf("incorrect device type in %s\n", id);
return 1;
}
if (!isdigit(*p)) {
printf("incorrect device number in %s\n", id);
return 1;
}
*dev_num = simple_strtoul(p, (char **)&p, 0);
if (ret_id)
*ret_id = p;
return 0;
}
/**
* Process all devices and generate corresponding mtdparts string describing
* all partitions on all devices.
*
* @param buf output buffer holding generated mtdparts string (output)
* @param buflen buffer size
* @return 0 on success, 1 otherwise
*/
static int generate_mtdparts(char *buf, u32 buflen)
{
struct list_head *pentry, *dentry;
struct mtd_device *dev;
struct part_info *part, *prev_part;
char *p = buf;
char tmpbuf[32];
u32 size, offset, len, part_cnt;
u32 maxlen = buflen - 1;
debug("--- generate_mtdparts ---\n");
if (list_empty(&devices)) {
buf[0] = '\0';
return 0;
}
sprintf(p, "mtdparts=");
p += 9;
list_for_each(dentry, &devices) {
dev = list_entry(dentry, struct mtd_device, link);
/* copy mtd_id */
len = strlen(dev->id->mtd_id) + 1;
if (len > maxlen)
goto cleanup;
memcpy(p, dev->id->mtd_id, len - 1);
p += len - 1;
*(p++) = ':';
maxlen -= len;
/* format partitions */
prev_part = NULL;
part_cnt = 0;
list_for_each(pentry, &dev->parts) {
part = list_entry(pentry, struct part_info, link);
size = part->size;
offset = part->offset;
part_cnt++;
/* partition size */
memsize_format(tmpbuf, size);
len = strlen(tmpbuf);
if (len > maxlen)
goto cleanup;
memcpy(p, tmpbuf, len);
p += len;
maxlen -= len;
/* add offset only when there is a gap between
* partitions */
if ((!prev_part && (offset != 0)) ||
(prev_part && ((prev_part->offset + prev_part->size) != part->offset))) {
memsize_format(tmpbuf, offset);
len = strlen(tmpbuf) + 1;
if (len > maxlen)
goto cleanup;
*(p++) = '@';
memcpy(p, tmpbuf, len - 1);
p += len - 1;
maxlen -= len;
}
/* copy name only if user supplied */
if(!part->auto_name) {
len = strlen(part->name) + 2;
if (len > maxlen)
goto cleanup;
*(p++) = '(';
memcpy(p, part->name, len - 2);
p += len - 2;
*(p++) = ')';
maxlen -= len;
}
/* ro mask flag */
if (part->mask_flags && MTD_WRITEABLE_CMD) {
len = 2;
if (len > maxlen)
goto cleanup;
*(p++) = 'r';
*(p++) = 'o';
maxlen -= 2;
}
/* print ',' separator if there are other partitions
* following */
if (dev->num_parts > part_cnt) {
if (1 > maxlen)
goto cleanup;
*(p++) = ',';
maxlen--;
}
prev_part = part;
}
/* print ';' separator if there are other devices following */
if (dentry->next != &devices) {
if (1 > maxlen)
goto cleanup;
*(p++) = ';';
maxlen--;
}
}
/* we still have at least one char left, as we decremented maxlen at
* the begining */
*p = '\0';
return 0;
cleanup:
last_parts[0] = '\0';
return 1;
}
/**
* Call generate_mtdparts to process all devices and generate corresponding
* mtdparts string, save it in mtdparts environment variable.
*
* @param buf output buffer holding generated mtdparts string (output)
* @param buflen buffer size
* @return 0 on success, 1 otherwise
*/
static int generate_mtdparts_save(char *buf, u32 buflen)
{
int ret;
ret = generate_mtdparts(buf, buflen);
if ((buf[0] != '\0') && (ret == 0))
setenv("mtdparts", buf);
else
setenv("mtdparts", NULL);
return ret;
}
#if defined(CONFIG_CMD_MTDPARTS_SHOW_NET_SIZES)
/**
* Get the net size (w/o bad blocks) of the given partition.
*
* @param mtd the mtd info
* @param part the partition
* @return the calculated net size of this partition
*/
static uint64_t net_part_size(struct mtd_info *mtd, struct part_info *part)
{
uint64_t i, net_size = 0;
if (!mtd->block_isbad)
return part->size;
for (i = 0; i < part->size; i += mtd->erasesize) {
if (!mtd->block_isbad(mtd, part->offset + i))
net_size += mtd->erasesize;
}
return net_size;
}
#endif
static void print_partition_table(void)
{
struct list_head *dentry, *pentry;
struct part_info *part;
struct mtd_device *dev;
int part_num;
list_for_each(dentry, &devices) {
dev = list_entry(dentry, struct mtd_device, link);
/* list partitions for given device */
part_num = 0;
#if defined(CONFIG_CMD_MTDPARTS_SHOW_NET_SIZES)
struct mtd_info *mtd;
if (get_mtd_info(dev->id->type, dev->id->num, &mtd))
return;
printf("\ndevice %s%d <%s>, # parts = %d\n",
MTD_DEV_TYPE(dev->id->type), dev->id->num,
dev->id->mtd_id, dev->num_parts);
printf(" #: name\t\tsize\t\tnet size\toffset\t\tmask_flags\n");
list_for_each(pentry, &dev->parts) {
u32 net_size;
char *size_note;
part = list_entry(pentry, struct part_info, link);
net_size = net_part_size(mtd, part);
size_note = part->size == net_size ? " " : " (!)";
printf("%2d: %-20s0x%08x\t0x%08x%s\t0x%08x\t%d\n",
part_num, part->name, part->size,
net_size, size_note, part->offset,
part->mask_flags);
#else /* !defined(CONFIG_CMD_MTDPARTS_SHOW_NET_SIZES) */
printf("\ndevice %s%d <%s>, # parts = %d\n",
MTD_DEV_TYPE(dev->id->type), dev->id->num,
dev->id->mtd_id, dev->num_parts);
printf(" #: name\t\tsize\t\toffset\t\tmask_flags\n");
list_for_each(pentry, &dev->parts) {
part = list_entry(pentry, struct part_info, link);
printf("%2d: %-20s0x%08x\t0x%08x\t%d\n",
part_num, part->name, part->size,
part->offset, part->mask_flags);
#endif /* defined(CONFIG_CMD_MTDPARTS_SHOW_NET_SIZES) */
part_num++;
}
}
if (list_empty(&devices))
printf("no partitions defined\n");
}
/**
* Format and print out a partition list for each device from global device
* list.
*/
static void list_partitions(void)
{
struct part_info *part;
debug("\n---list_partitions---\n");
print_partition_table();
/* current_mtd_dev is not NULL only when we have non empty device list */
if (current_mtd_dev) {
part = mtd_part_info(current_mtd_dev, current_mtd_partnum);
if (part) {
printf("\nactive partition: %s%d,%d - (%s) 0x%08x @ 0x%08x\n",
MTD_DEV_TYPE(current_mtd_dev->id->type),
current_mtd_dev->id->num, current_mtd_partnum,
part->name, part->size, part->offset);
} else {
printf("could not get current partition info\n\n");
}
}
printf("\ndefaults:\n");
printf("mtdids : %s\n",
mtdids_default ? mtdids_default : "none");
/*
* Using printf() here results in printbuffer overflow
* if default mtdparts string is greater than console
* printbuffer. Use puts() to prevent system crashes.
*/
puts("mtdparts: ");
puts(mtdparts_default ? mtdparts_default : "none");
puts("\n");
}
/**
* Given partition identifier in form of <dev_type><dev_num>,<part_num> find
* corresponding device and verify partition number.
*
* @param id string describing device and partition or partition name
* @param dev pointer to the requested device (output)
* @param part_num verified partition number (output)
* @param part pointer to requested partition (output)
* @return 0 on success, 1 otherwise
*/
int find_dev_and_part(const char *id, struct mtd_device **dev,
u8 *part_num, struct part_info **part)
{
struct list_head *dentry, *pentry;
u8 type, dnum, pnum;
const char *p;
debug("--- find_dev_and_part ---\nid = %s\n", id);
list_for_each(dentry, &devices) {
*part_num = 0;
*dev = list_entry(dentry, struct mtd_device, link);
list_for_each(pentry, &(*dev)->parts) {
*part = list_entry(pentry, struct part_info, link);
if (strcmp((*part)->name, id) == 0)
return 0;
(*part_num)++;
}
}
p = id;
*dev = NULL;
*part = NULL;
*part_num = 0;
if (mtd_id_parse(p, &p, &type, &dnum) != 0)
return 1;
if ((*p++ != ',') || (*p == '\0')) {
printf("no partition number specified\n");
return 1;
}
pnum = simple_strtoul(p, (char **)&p, 0);
if (*p != '\0') {
printf("unexpected trailing character '%c'\n", *p);
return 1;
}
if ((*dev = device_find(type, dnum)) == NULL) {
printf("no such device %s%d\n", MTD_DEV_TYPE(type), dnum);
return 1;
}
if ((*part = mtd_part_info(*dev, pnum)) == NULL) {
printf("no such partition\n");
*dev = NULL;
return 1;
}
*part_num = pnum;
return 0;
}
/**
* Find and delete partition. For partition id format see find_dev_and_part().
*
* @param id string describing device and partition
* @return 0 on success, 1 otherwise
*/
static int delete_partition(const char *id)
{
u8 pnum;
struct mtd_device *dev;
struct part_info *part;
if (find_dev_and_part(id, &dev, &pnum, &part) == 0) {
debug("delete_partition: device = %s%d, partition %d = (%s) 0x%08x@0x%08x\n",
MTD_DEV_TYPE(dev->id->type), dev->id->num, pnum,
part->name, part->size, part->offset);
if (part_del(dev, part) != 0)
return 1;
if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
printf("generated mtdparts too long, reseting to null\n");
return 1;
}
return 0;
}
printf("partition %s not found\n", id);
return 1;
}
#if defined(CONFIG_CMD_MTDPARTS_SPREAD)
/**
* Increase the size of the given partition so that it's net size is at least
* as large as the size member and such that the next partition would start on a
* good block if it were adjacent to this partition.
*
* @param mtd the mtd device
* @param part the partition
* @param next_offset pointer to the offset of the next partition after this
* partition's size has been modified (output)
*/
static void spread_partition(struct mtd_info *mtd, struct part_info *part,
uint64_t *next_offset)
{
uint64_t net_size, padding_size = 0;
int truncated;
mtd_get_len_incl_bad(mtd, part->offset, part->size, &net_size,
&truncated);
/*
* Absorb bad blocks immediately following this
* partition also into the partition, such that
* the next partition starts with a good block.
*/
if (!truncated) {
mtd_get_len_incl_bad(mtd, part->offset + net_size,
mtd->erasesize, &padding_size, &truncated);
if (truncated)
padding_size = 0;
else
padding_size -= mtd->erasesize;
}
if (truncated) {
printf("truncated partition %s to %lld bytes\n", part->name,
(uint64_t) net_size + padding_size);
}
part->size = net_size + padding_size;
*next_offset = part->offset + part->size;
}
/**
* Adjust all of the partition sizes, such that all partitions are at least
* as big as their mtdparts environment variable sizes and they each start
* on a good block.
*
* @return 0 on success, 1 otherwise
*/
static int spread_partitions(void)
{
struct list_head *dentry, *pentry;
struct mtd_device *dev;
struct part_info *part;
struct mtd_info *mtd;
int part_num;
uint64_t cur_offs;
list_for_each(dentry, &devices) {
dev = list_entry(dentry, struct mtd_device, link);
if (get_mtd_info(dev->id->type, dev->id->num, &mtd))
return 1;
part_num = 0;
cur_offs = 0;
list_for_each(pentry, &dev->parts) {
part = list_entry(pentry, struct part_info, link);
debug("spread_partitions: device = %s%d, partition %d ="
" (%s) 0x%08x@0x%08x\n",
MTD_DEV_TYPE(dev->id->type), dev->id->num,
part_num, part->name, part->size,
part->offset);
if (cur_offs > part->offset)
part->offset = cur_offs;
spread_partition(mtd, part, &cur_offs);
part_num++;
}
}
index_partitions();
if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
printf("generated mtdparts too long, reseting to null\n");
return 1;
}
return 0;
}
#endif /* CONFIG_CMD_MTDPARTS_SPREAD */
/**
* Accept character string describing mtd partitions and call device_parse()
* for each entry. Add created devices to the global devices list.
*
* @param mtdparts string specifing mtd partitions
* @return 0 on success, 1 otherwise
*/
static int parse_mtdparts(const char *const mtdparts)
{
const char *p = mtdparts;
struct mtd_device *dev;
int err = 1;
debug("\n---parse_mtdparts---\nmtdparts = %s\n\n", p);
/* delete all devices and partitions */
if (mtd_devices_init() != 0) {
printf("could not initialise device list\n");
return err;
}
/* re-read 'mtdparts' variable, mtd_devices_init may be updating env */
p = getenv("mtdparts");
if (strncmp(p, "mtdparts=", 9) != 0) {
printf("mtdparts variable doesn't start with 'mtdparts='\n");
return err;
}
p += 9;
while (p && (*p != '\0')) {
err = 1;
if ((device_parse(p, &p, &dev) != 0) || (!dev))
break;
debug("+ device: %s\t%d\t%s\n", MTD_DEV_TYPE(dev->id->type),
dev->id->num, dev->id->mtd_id);
/* check if parsed device is already on the list */
if (device_find(dev->id->type, dev->id->num) != NULL) {
printf("device %s%d redefined, please correct mtdparts variable\n",
MTD_DEV_TYPE(dev->id->type), dev->id->num);
break;
}
list_add_tail(&dev->link, &devices);
err = 0;
}
if (err == 1) {
device_delall(&devices);
return 1;
}
return 0;
}
/**
* Parse provided string describing mtdids mapping (see file header for mtdids
* variable format). Allocate memory for each entry and add all found entries
* to the global mtdids list.
*
* @param ids mapping string
* @return 0 on success, 1 otherwise
*/
static int parse_mtdids(const char *const ids)
{
const char *p = ids;
const char *mtd_id;
int mtd_id_len;
struct mtdids *id;
struct list_head *entry, *n;
struct mtdids *id_tmp;
u8 type, num;
u32 size;
int ret = 1;
debug("\n---parse_mtdids---\nmtdids = %s\n\n", ids);
/* clean global mtdids list */
list_for_each_safe(entry, n, &mtdids) {
id_tmp = list_entry(entry, struct mtdids, link);
debug("mtdids del: %d %d\n", id_tmp->type, id_tmp->num);
list_del(entry);
free(id_tmp);
}
last_ids[0] = '\0';
INIT_LIST_HEAD(&mtdids);
while(p && (*p != '\0')) {
ret = 1;
/* parse 'nor'|'nand'|'onenand'<dev-num> */
if (mtd_id_parse(p, &p, &type, &num) != 0)
break;
if (*p != '=') {
printf("mtdids: incorrect <dev-num>\n");
break;
}
p++;
/* check if requested device exists */
if (mtd_device_validate(type, num, &size) != 0)
return 1;
/* locate <mtd-id> */
mtd_id = p;
if ((p = strchr(mtd_id, ',')) != NULL) {
mtd_id_len = p - mtd_id + 1;
p++;
} else {
mtd_id_len = strlen(mtd_id) + 1;
}
if (mtd_id_len == 0) {
printf("mtdids: no <mtd-id> identifier\n");
break;
}
/* check if this id is already on the list */
int double_entry = 0;
list_for_each(entry, &mtdids) {
id_tmp = list_entry(entry, struct mtdids, link);
if ((id_tmp->type == type) && (id_tmp->num == num)) {
double_entry = 1;
break;
}
}
if (double_entry) {
printf("device id %s%d redefined, please correct mtdids variable\n",
MTD_DEV_TYPE(type), num);
break;
}
/* allocate mtdids structure */
if (!(id = (struct mtdids *)malloc(sizeof(struct mtdids) + mtd_id_len))) {
printf("out of memory\n");
break;
}
memset(id, 0, sizeof(struct mtdids) + mtd_id_len);
id->num = num;
id->type = type;
id->size = size;
id->mtd_id = (char *)(id + 1);
strncpy(id->mtd_id, mtd_id, mtd_id_len - 1);
id->mtd_id[mtd_id_len - 1] = '\0';
INIT_LIST_HEAD(&id->link);
debug("+ id %s%d\t%16d bytes\t%s\n",
MTD_DEV_TYPE(id->type), id->num,
id->size, id->mtd_id);
list_add_tail(&id->link, &mtdids);
ret = 0;
}
if (ret == 1) {
/* clean mtdids list and free allocated memory */
list_for_each_safe(entry, n, &mtdids) {
id_tmp = list_entry(entry, struct mtdids, link);
list_del(entry);
free(id_tmp);
}
return 1;
}
return 0;
}
/**
* Parse and initialize global mtdids mapping and create global
* device/partition list.
*
* @return 0 on success, 1 otherwise
*/
int mtdparts_init(void)
{
static int initialized = 0;
const char *ids, *parts;
const char *current_partition;
int ids_changed;
char tmp_ep[PARTITION_MAXLEN];
debug("\n---mtdparts_init---\n");
if (!initialized) {
INIT_LIST_HEAD(&mtdids);
INIT_LIST_HEAD(&devices);
memset(last_ids, 0, MTDIDS_MAXLEN);
memset(last_parts, 0, MTDPARTS_MAXLEN);
memset(last_partition, 0, PARTITION_MAXLEN);
initialized = 1;
}
/* get variables */
ids = getenv("mtdids");
parts = getenv("mtdparts");
current_partition = getenv("partition");
/* save it for later parsing, cannot rely on current partition pointer
* as 'partition' variable may be updated during init */
tmp_ep[0] = '\0';
if (current_partition)
strncpy(tmp_ep, current_partition, PARTITION_MAXLEN);
debug("last_ids : %s\n", last_ids);
debug("env_ids : %s\n", ids);
debug("last_parts: %s\n", last_parts);
debug("env_parts : %s\n\n", parts);
debug("last_partition : %s\n", last_partition);
debug("env_partition : %s\n", current_partition);
/* if mtdids varible is empty try to use defaults */
if (!ids) {
if (mtdids_default) {
debug("mtdids variable not defined, using default\n");
ids = mtdids_default;
setenv("mtdids", (char *)ids);
} else {
printf("mtdids not defined, no default present\n");
return 1;
}
}
if (strlen(ids) > MTDIDS_MAXLEN - 1) {
printf("mtdids too long (> %d)\n", MTDIDS_MAXLEN);
return 1;
}
/* do no try to use defaults when mtdparts variable is not defined,
* just check the length */
if (!parts)
printf("mtdparts variable not set, see 'help mtdparts'\n");
if (parts && (strlen(parts) > MTDPARTS_MAXLEN - 1)) {
printf("mtdparts too long (> %d)\n", MTDPARTS_MAXLEN);
return 1;
}
/* check if we have already parsed those mtdids */
if ((last_ids[0] != '\0') && (strcmp(last_ids, ids) == 0)) {
ids_changed = 0;
} else {
ids_changed = 1;
if (parse_mtdids(ids) != 0) {
mtd_devices_init();
return 1;
}
/* ok it's good, save new ids */
strncpy(last_ids, ids, MTDIDS_MAXLEN);
}
/* parse partitions if either mtdparts or mtdids were updated */
if (parts && ((last_parts[0] == '\0') || ((strcmp(last_parts, parts) != 0)) || ids_changed)) {
if (parse_mtdparts(parts) != 0)
return 1;
if (list_empty(&devices)) {
printf("mtdparts_init: no valid partitions\n");
return 1;
}
/* ok it's good, save new parts */
strncpy(last_parts, parts, MTDPARTS_MAXLEN);
/* reset first partition from first dev from the list as current */
current_mtd_dev = list_entry(devices.next, struct mtd_device, link);
current_mtd_partnum = 0;
current_save();
debug("mtdparts_init: current_mtd_dev = %s%d, current_mtd_partnum = %d\n",
MTD_DEV_TYPE(current_mtd_dev->id->type),
current_mtd_dev->id->num, current_mtd_partnum);
}
/* mtdparts variable was reset to NULL, delete all devices/partitions */
if (!parts && (last_parts[0] != '\0'))
return mtd_devices_init();
/* do not process current partition if mtdparts variable is null */
if (!parts)
return 0;
/* is current partition set in environment? if so, use it */
if ((tmp_ep[0] != '\0') && (strcmp(tmp_ep, last_partition) != 0)) {
struct part_info *p;
struct mtd_device *cdev;
u8 pnum;
debug("--- getting current partition: %s\n", tmp_ep);
if (find_dev_and_part(tmp_ep, &cdev, &pnum, &p) == 0) {
current_mtd_dev = cdev;
current_mtd_partnum = pnum;
current_save();
}
} else if (getenv("partition") == NULL) {
debug("no partition variable set, setting...\n");
current_save();
}
return 0;
}
/**
* Return pointer to the partition of a requested number from a requested
* device.
*
* @param dev device that is to be searched for a partition
* @param part_num requested partition number
* @return pointer to the part_info, NULL otherwise
*/
static struct part_info* mtd_part_info(struct mtd_device *dev, unsigned int part_num)
{
struct list_head *entry;
struct part_info *part;
int num;
if (!dev)
return NULL;
debug("\n--- mtd_part_info: partition number %d for device %s%d (%s)\n",
part_num, MTD_DEV_TYPE(dev->id->type),
dev->id->num, dev->id->mtd_id);
if (part_num >= dev->num_parts) {
printf("invalid partition number %d for device %s%d (%s)\n",
part_num, MTD_DEV_TYPE(dev->id->type),
dev->id->num, dev->id->mtd_id);
return NULL;
}
/* locate partition number, return it */
num = 0;
list_for_each(entry, &dev->parts) {
part = list_entry(entry, struct part_info, link);
if (part_num == num++) {
return part;
}
}
return NULL;
}
/***************************************************/
/* U-boot commands */
/***************************************************/
/* command line only */
/**
* Routine implementing u-boot chpart command. Sets new current partition based
* on the user supplied partition id. For partition id format see find_dev_and_part().
*
* @param cmdtp command internal data
* @param flag command flag
* @param argc number of arguments supplied to the command
* @param argv arguments list
* @return 0 on success, 1 otherwise
*/
int do_chpart(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
/* command line only */
struct mtd_device *dev;
struct part_info *part;
u8 pnum;
if (mtdparts_init() !=0)
return 1;
if (argc < 2) {
printf("no partition id specified\n");
return 1;
}
if (find_dev_and_part(argv[1], &dev, &pnum, &part) != 0)
return 1;
current_mtd_dev = dev;
current_mtd_partnum = pnum;
current_save();
printf("partition changed to %s%d,%d\n",
MTD_DEV_TYPE(dev->id->type), dev->id->num, pnum);
return 0;
}
/**
* Routine implementing u-boot mtdparts command. Initialize/update default global
* partition list and process user partition request (list, add, del).
*
* @param cmdtp command internal data
* @param flag command flag
* @param argc number of arguments supplied to the command
* @param argv arguments list
* @return 0 on success, 1 otherwise
*/
int do_mtdparts(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc == 2) {
if (strcmp(argv[1], "default") == 0) {
setenv("mtdids", (char *)mtdids_default);
setenv("mtdparts", (char *)mtdparts_default);
setenv("partition", NULL);
mtdparts_init();
return 0;
} else if (strcmp(argv[1], "delall") == 0) {
/* this may be the first run, initialize lists if needed */
mtdparts_init();
setenv("mtdparts", NULL);
/* mtd_devices_init() calls current_save() */
return mtd_devices_init();
}
}
/* make sure we are in sync with env variables */
if (mtdparts_init() != 0)
return 1;
if (argc == 1) {
list_partitions();
return 0;
}
/* mtdparts add <mtd-dev> <size>[@<offset>] <name> [ro] */
if (((argc == 5) || (argc == 6)) && (strncmp(argv[1], "add", 3) == 0)) {
#define PART_ADD_DESC_MAXLEN 64
char tmpbuf[PART_ADD_DESC_MAXLEN];
#if defined(CONFIG_CMD_MTDPARTS_SPREAD)
struct mtd_info *mtd;
uint64_t next_offset;
#endif
u8 type, num, len;
struct mtd_device *dev;
struct mtd_device *dev_tmp;
struct mtdids *id;
struct part_info *p;
if (mtd_id_parse(argv[2], NULL, &type, &num) != 0)
return 1;
if ((id = id_find(type, num)) == NULL) {
printf("no such device %s defined in mtdids variable\n", argv[2]);
return 1;
}
len = strlen(id->mtd_id) + 1; /* 'mtd_id:' */
len += strlen(argv[3]); /* size@offset */
len += strlen(argv[4]) + 2; /* '(' name ')' */
if (argv[5] && (strlen(argv[5]) == 2))
len += 2; /* 'ro' */
if (len >= PART_ADD_DESC_MAXLEN) {
printf("too long partition description\n");
return 1;
}
sprintf(tmpbuf, "%s:%s(%s)%s",
id->mtd_id, argv[3], argv[4], argv[5] ? argv[5] : "");
debug("add tmpbuf: %s\n", tmpbuf);
if ((device_parse(tmpbuf, NULL, &dev) != 0) || (!dev))
return 1;
debug("+ %s\t%d\t%s\n", MTD_DEV_TYPE(dev->id->type),
dev->id->num, dev->id->mtd_id);
p = list_entry(dev->parts.next, struct part_info, link);
#if defined(CONFIG_CMD_MTDPARTS_SPREAD)
if (get_mtd_info(dev->id->type, dev->id->num, &mtd))
return 1;
if (!strcmp(&argv[1][3], ".spread")) {
spread_partition(mtd, p, &next_offset);
debug("increased %s to %d bytes\n", p->name, p->size);
}
#endif
dev_tmp = device_find(dev->id->type, dev->id->num);
if (dev_tmp == NULL) {
device_add(dev);
} else if (part_add(dev_tmp, p) != 0) {
/* merge new partition with existing ones*/
device_del(dev);
return 1;
}
if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
printf("generated mtdparts too long, reseting to null\n");
return 1;
}
return 0;
}
/* mtdparts del part-id */
if ((argc == 3) && (strcmp(argv[1], "del") == 0)) {
debug("del: part-id = %s\n", argv[2]);
return delete_partition(argv[2]);
}
#if defined(CONFIG_CMD_MTDPARTS_SPREAD)
if ((argc == 2) && (strcmp(argv[1], "spread") == 0))
return spread_partitions();
#endif /* CONFIG_CMD_MTDPARTS_SPREAD */
return cmd_usage(cmdtp);
}
/***************************************************/
U_BOOT_CMD(
chpart, 2, 0, do_chpart,
"change active partition",
"part-id\n"
" - change active partition (e.g. part-id = nand0,1)"
);
U_BOOT_CMD(
mtdparts, 6, 0, do_mtdparts,
"define flash/nand partitions",
"\n"
" - list partition table\n"
"mtdparts delall\n"
" - delete all partitions\n"
"mtdparts del part-id\n"
" - delete partition (e.g. part-id = nand0,1)\n"
"mtdparts add <mtd-dev> <size>[@<offset>] [<name>] [ro]\n"
" - add partition\n"
#if defined(CONFIG_CMD_MTDPARTS_SPREAD)
"mtdparts add.spread <mtd-dev> <size>[@<offset>] [<name>] [ro]\n"
" - add partition, padding size by skipping bad blocks\n"
#endif
"mtdparts default\n"
" - reset partition table to defaults\n"
#if defined(CONFIG_CMD_MTDPARTS_SPREAD)
"mtdparts spread\n"
" - adjust the sizes of the partitions so they are\n"
" at least as big as the mtdparts variable specifies\n"
" and they each start on a good block\n\n"
#else
"\n"
#endif /* CONFIG_CMD_MTDPARTS_SPREAD */
"-----\n\n"
"this command uses three environment variables:\n\n"
"'partition' - keeps current partition identifier\n\n"
"partition := <part-id>\n"
"<part-id> := <dev-id>,part_num\n\n"
"'mtdids' - linux kernel mtd device id <-> u-boot device id mapping\n\n"
"mtdids=<idmap>[,<idmap>,...]\n\n"
"<idmap> := <dev-id>=<mtd-id>\n"
"<dev-id> := 'nand'|'nor'|'onenand'<dev-num>\n"
"<dev-num> := mtd device number, 0...\n"
"<mtd-id> := unique device tag used by linux kernel to find mtd device (mtd->name)\n\n"
"'mtdparts' - partition list\n\n"
"mtdparts=mtdparts=<mtd-def>[;<mtd-def>...]\n\n"
"<mtd-def> := <mtd-id>:<part-def>[,<part-def>...]\n"
"<mtd-id> := unique device tag used by linux kernel to find mtd device (mtd->name)\n"
"<part-def> := <size>[@<offset>][<name>][<ro-flag>]\n"
"<size> := standard linux memsize OR '-' to denote all remaining space\n"
"<offset> := partition start offset within the device\n"
"<name> := '(' NAME ')'\n"
"<ro-flag> := when set to 'ro' makes partition read-only (not used, passed to kernel)"
);
/***************************************************/
|
1001-study-uboot
|
common/cmd_mtdparts.c
|
C
|
gpl3
| 53,247
|
/*
* (C) Copyright 2001
* Erik Theisen, Wave 7 Optics, etheisen@mindspring.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
*/
/*
* AMCC 4XX DCR Functions
*/
#include <common.h>
#include <config.h>
#include <command.h>
unsigned long get_dcr (unsigned short);
unsigned long set_dcr (unsigned short, unsigned long);
/* =======================================================================
* Interpreter command to retrieve an AMCC PPC 4xx Device Control Register
* =======================================================================
*/
int do_getdcr ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[] )
{
unsigned short dcrn; /* Device Control Register Num */
unsigned long value; /* DCR's value */
unsigned long get_dcr (unsigned short);
/* Validate arguments */
if (argc < 2)
return cmd_usage(cmdtp);
/* Get a DCR */
dcrn = (unsigned short) simple_strtoul (argv[1], NULL, 16);
value = get_dcr (dcrn);
printf ("%04x: %08lx\n", dcrn, value);
return 0;
}
/* ======================================================================
* Interpreter command to set an AMCC PPC 4xx Device Control Register
* ======================================================================
*/
int do_setdcr (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned short dcrn; /* Device Control Register Num */
unsigned long value;
/* DCR's value */
int nbytes;
/* Validate arguments */
if (argc < 2)
return cmd_usage(cmdtp);
/* Set a DCR */
dcrn = (unsigned short) simple_strtoul (argv[1], NULL, 16);
do {
value = get_dcr (dcrn);
printf ("%04x: %08lx", dcrn, value);
nbytes = readline (" ? ");
if (nbytes == 0) {
/*
* <CR> pressed as only input, don't modify current
* location and exit command.
*/
nbytes = 1;
return 0;
} else {
unsigned long i;
char *endp;
i = simple_strtoul (console_buffer, &endp, 16);
nbytes = endp - console_buffer;
if (nbytes)
set_dcr (dcrn, i);
}
} while (nbytes);
return 0;
}
/* =======================================================================
* Interpreter command to retrieve an register value through AMCC PPC 4xx
* Device Control Register inderect addressing.
* =======================================================================
*/
int do_getidcr (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unsigned short adr_dcrn; /* Device Control Register Num for Address */
unsigned short dat_dcrn; /* Device Control Register Num for Data */
unsigned short offset; /* Register's offset */
unsigned long value; /* Register's value */
char *ptr = NULL;
char buf[80];
/* Validate arguments */
if (argc < 3)
return cmd_usage(cmdtp);
/* Find out whether ther is '.' (dot) symbol in the first parameter. */
strncpy (buf, argv[1], sizeof(buf)-1);
buf[sizeof(buf)-1] = 0; /* will guarantee zero-end string */
ptr = strchr (buf, '.');
if (ptr != NULL) {
/* First parameter has format adr_dcrn.dat_dcrn */
*ptr++ = 0; /* erase '.', create zero-end string */
adr_dcrn = (unsigned short) simple_strtoul (buf, NULL, 16);
dat_dcrn = (unsigned short) simple_strtoul (ptr, NULL, 16);
} else {
/*
* First parameter has format adr_dcrn; dat_dcrn will be
* calculated as adr_dcrn+1.
*/
adr_dcrn = (unsigned short) simple_strtoul (buf, NULL, 16);
dat_dcrn = adr_dcrn+1;
}
/* Register's offset */
offset = (unsigned short) simple_strtoul (argv[2], NULL, 16);
/* Disable interrupts */
disable_interrupts ();
/* Set offset */
set_dcr (adr_dcrn, offset);
/* get data */
value = get_dcr (dat_dcrn);
/* Enable interrupts */
enable_interrupts ();
printf ("%04x.%04x-%04x Read %08lx\n", adr_dcrn, dat_dcrn, offset, value);
return 0;
}
/* =======================================================================
* Interpreter command to update an register value through AMCC PPC 4xx
* Device Control Register inderect addressing.
* =======================================================================
*/
int do_setidcr (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned short adr_dcrn; /* Device Control Register Num for Address */
unsigned short dat_dcrn; /* Device Control Register Num for Data */
unsigned short offset; /* Register's offset */
unsigned long value; /* Register's value */
char *ptr = NULL;
char buf[80];
/* Validate arguments */
if (argc < 4)
return cmd_usage(cmdtp);
/* Find out whether ther is '.' (dot) symbol in the first parameter. */
strncpy (buf, argv[1], sizeof(buf)-1);
buf[sizeof(buf)-1] = 0; /* will guarantee zero-end string */
ptr = strchr (buf, '.');
if (ptr != NULL) {
/* First parameter has format adr_dcrn.dat_dcrn */
*ptr++ = 0; /* erase '.', create zero-end string */
adr_dcrn = (unsigned short) simple_strtoul (buf, NULL, 16);
dat_dcrn = (unsigned short) simple_strtoul (ptr, NULL, 16);
} else {
/*
* First parameter has format adr_dcrn; dat_dcrn will be
* calculated as adr_dcrn+1.
*/
adr_dcrn = (unsigned short) simple_strtoul (buf, NULL, 16);
dat_dcrn = adr_dcrn+1;
}
/* Register's offset */
offset = (unsigned short) simple_strtoul (argv[2], NULL, 16);
/* New value */
value = (unsigned long) simple_strtoul (argv[3], NULL, 16);
/* Disable interrupts */
disable_interrupts ();
/* Set offset */
set_dcr (adr_dcrn, offset);
/* set data */
set_dcr (dat_dcrn, value);
/* Enable interrupts */
enable_interrupts ();
printf ("%04x.%04x-%04x Write %08lx\n", adr_dcrn, dat_dcrn, offset, value);
return 0;
}
/***************************************************/
U_BOOT_CMD(
getdcr, 2, 1, do_getdcr,
"Get an AMCC PPC 4xx DCR's value",
"dcrn - return a DCR's value."
);
U_BOOT_CMD(
setdcr, 2, 1, do_setdcr,
"Set an AMCC PPC 4xx DCR's value",
"dcrn - set a DCR's value."
);
U_BOOT_CMD(
getidcr, 3, 1, do_getidcr,
"Get a register value via indirect DCR addressing",
"adr_dcrn[.dat_dcrn] offset - write offset to adr_dcrn, read value from dat_dcrn."
);
U_BOOT_CMD(
setidcr, 4, 1, do_setidcr,
"Set a register value via indirect DCR addressing",
"adr_dcrn[.dat_dcrn] offset value - write offset to adr_dcrn, write value to dat_dcrn."
);
|
1001-study-uboot
|
common/cmd_dcr.c
|
C
|
gpl3
| 6,921
|
/*
* Copyright 2008-2009 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 <command.h>
int
cpu_cmd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unsigned long cpuid;
if (argc < 3)
return cmd_usage(cmdtp);
cpuid = simple_strtoul(argv[1], NULL, 10);
if (!is_core_valid(cpuid)) {
printf ("Core num: %lu is not valid\n", cpuid);
return 1;
}
if (argc == 3) {
if (strncmp(argv[2], "reset", 5) == 0)
cpu_reset(cpuid);
else if (strncmp(argv[2], "status", 6) == 0)
cpu_status(cpuid);
else if (strncmp(argv[2], "disable", 7) == 0)
return cpu_disable(cpuid);
else
return cmd_usage(cmdtp);
return 0;
}
/* 4 or greater, make sure its release */
if (strncmp(argv[2], "release", 7) != 0)
return cmd_usage(cmdtp);
if (cpu_release(cpuid, argc - 3, argv + 3))
return cmd_usage(cmdtp);
return 0;
}
#ifdef CONFIG_PPC
#define CPU_ARCH_HELP \
" [args] : <pir> <r3> <r6>\n" \
" pir - processor id (if writeable)\n" \
" r3 - value for gpr 3\n" \
" r6 - value for gpr 6\n" \
"\n" \
" Use '-' for any arg if you want the default value.\n" \
" Default for r3 is <num> and r6 is 0\n" \
"\n" \
" When cpu <num> is released r4 and r5 = 0.\n" \
" r7 will contain the size of the initial mapped area"
#endif
U_BOOT_CMD(
cpu, CONFIG_SYS_MAXARGS, 1, cpu_cmd,
"Multiprocessor CPU boot manipulation and release",
"<num> reset - Reset cpu <num>\n"
"cpu <num> status - Status of cpu <num>\n"
"cpu <num> disable - Disable cpu <num>\n"
"cpu <num> release <addr> [args] - Release cpu <num> at <addr> with [args]"
#ifdef CPU_ARCH_HELP
"\n"
CPU_ARCH_HELP
#endif
);
|
1001-study-uboot
|
common/cmd_mp.c
|
C
|
gpl3
| 2,612
|
/*
* (C) Copyright 2001
* Gerald Van Baren, Custom IDEAS, vanbaren@cideas.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
*/
/*
* I2C Functions similar to the standard memory functions.
*
* There are several parameters in many of the commands that bear further
* explanations:
*
* {i2c_chip} is the I2C chip address (the first byte sent on the bus).
* Each I2C chip on the bus has a unique address. On the I2C data bus,
* the address is the upper seven bits and the LSB is the "read/write"
* bit. Note that the {i2c_chip} address specified on the command
* line is not shifted up: e.g. a typical EEPROM memory chip may have
* an I2C address of 0x50, but the data put on the bus will be 0xA0
* for write and 0xA1 for read. This "non shifted" address notation
* matches at least half of the data sheets :-/.
*
* {addr} is the address (or offset) within the chip. Small memory
* chips have 8 bit addresses. Large memory chips have 16 bit
* addresses. Other memory chips have 9, 10, or 11 bit addresses.
* Many non-memory chips have multiple registers and {addr} is used
* as the register index. Some non-memory chips have only one register
* and therefore don't need any {addr} parameter.
*
* The default {addr} parameter is one byte (.1) which works well for
* memories and registers with 8 bits of address space.
*
* You can specify the length of the {addr} field with the optional .0,
* .1, or .2 modifier (similar to the .b, .w, .l modifier). If you are
* manipulating a single register device which doesn't use an address
* field, use "0.0" for the address and the ".0" length field will
* suppress the address in the I2C data stream. This also works for
* successive reads using the I2C auto-incrementing memory pointer.
*
* If you are manipulating a large memory with 2-byte addresses, use
* the .2 address modifier, e.g. 210.2 addresses location 528 (decimal).
*
* Then there are the unfortunate memory chips that spill the most
* significant 1, 2, or 3 bits of address into the chip address byte.
* This effectively makes one chip (logically) look like 2, 4, or
* 8 chips. This is handled (awkwardly) by #defining
* CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW and using the .1 modifier on the
* {addr} field (since .1 is the default, it doesn't actually have to
* be specified). Examples: given a memory chip at I2C chip address
* 0x50, the following would happen...
* i2c md 50 0 10 display 16 bytes starting at 0x000
* On the bus: <S> A0 00 <E> <S> A1 <rd> ... <rd>
* i2c md 50 100 10 display 16 bytes starting at 0x100
* On the bus: <S> A2 00 <E> <S> A3 <rd> ... <rd>
* i2c md 50 210 10 display 16 bytes starting at 0x210
* On the bus: <S> A4 10 <E> <S> A5 <rd> ... <rd>
* This is awfully ugly. It would be nice if someone would think up
* a better way of handling this.
*
* Adapted from cmd_mem.c which is copyright Wolfgang Denk (wd@denx.de).
*/
#include <common.h>
#include <command.h>
#include <environment.h>
#include <i2c.h>
#include <malloc.h>
#include <asm/byteorder.h>
/* Display values from last command.
* Memory modify remembered values are different from display memory.
*/
static uchar i2c_dp_last_chip;
static uint i2c_dp_last_addr;
static uint i2c_dp_last_alen;
static uint i2c_dp_last_length = 0x10;
static uchar i2c_mm_last_chip;
static uint i2c_mm_last_addr;
static uint i2c_mm_last_alen;
/* If only one I2C bus is present, the list of devices to ignore when
* the probe command is issued is represented by a 1D array of addresses.
* When multiple buses are present, the list is an array of bus-address
* pairs. The following macros take care of this */
#if defined(CONFIG_SYS_I2C_NOPROBES)
#if defined(CONFIG_I2C_MULTI_BUS)
static struct
{
uchar bus;
uchar addr;
} i2c_no_probes[] = CONFIG_SYS_I2C_NOPROBES;
#define GET_BUS_NUM i2c_get_bus_num()
#define COMPARE_BUS(b,i) (i2c_no_probes[(i)].bus == (b))
#define COMPARE_ADDR(a,i) (i2c_no_probes[(i)].addr == (a))
#define NO_PROBE_ADDR(i) i2c_no_probes[(i)].addr
#else /* single bus */
static uchar i2c_no_probes[] = CONFIG_SYS_I2C_NOPROBES;
#define GET_BUS_NUM 0
#define COMPARE_BUS(b,i) ((b) == 0) /* Make compiler happy */
#define COMPARE_ADDR(a,i) (i2c_no_probes[(i)] == (a))
#define NO_PROBE_ADDR(i) i2c_no_probes[(i)]
#endif /* CONFIG_MULTI_BUS */
#define NUM_ELEMENTS_NOPROBE (sizeof(i2c_no_probes)/sizeof(i2c_no_probes[0]))
#endif
#if defined(CONFIG_I2C_MUX)
static I2C_MUX_DEVICE *i2c_mux_devices = NULL;
static int i2c_mux_busid = CONFIG_SYS_MAX_I2C_BUS;
DECLARE_GLOBAL_DATA_PTR;
#endif
#define DISP_LINE_LEN 16
/* implement possible board specific board init */
void __def_i2c_init_board(void)
{
return;
}
void i2c_init_board(void)
__attribute__((weak, alias("__def_i2c_init_board")));
/* TODO: Implement architecture-specific get/set functions */
unsigned int __def_i2c_get_bus_speed(void)
{
return CONFIG_SYS_I2C_SPEED;
}
unsigned int i2c_get_bus_speed(void)
__attribute__((weak, alias("__def_i2c_get_bus_speed")));
int __def_i2c_set_bus_speed(unsigned int speed)
{
if (speed != CONFIG_SYS_I2C_SPEED)
return -1;
return 0;
}
int i2c_set_bus_speed(unsigned int)
__attribute__((weak, alias("__def_i2c_set_bus_speed")));
/*
* get_alen: small parser helper function to get address length
* returns the address length
*/
static uint get_alen(char *arg)
{
int j;
int alen;
alen = 1;
for (j = 0; j < 8; j++) {
if (arg[j] == '.') {
alen = arg[j+1] - '0';
break;
} else if (arg[j] == '\0')
break;
}
return alen;
}
/*
* Syntax:
* i2c read {i2c_chip} {devaddr}{.0, .1, .2} {len} {memaddr}
*/
static int do_i2c_read ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
u_char chip;
uint devaddr, alen, length;
u_char *memaddr;
if (argc != 5)
return cmd_usage(cmdtp);
/*
* I2C chip address
*/
chip = simple_strtoul(argv[1], NULL, 16);
/*
* I2C data address within the chip. This can be 1 or
* 2 bytes long. Some day it might be 3 bytes long :-).
*/
devaddr = simple_strtoul(argv[2], NULL, 16);
alen = get_alen(argv[2]);
if (alen > 3)
return cmd_usage(cmdtp);
/*
* Length is the number of objects, not number of bytes.
*/
length = simple_strtoul(argv[3], NULL, 16);
/*
* memaddr is the address where to store things in memory
*/
memaddr = (u_char *)simple_strtoul(argv[4], NULL, 16);
if (i2c_read(chip, devaddr, alen, memaddr, length) != 0) {
puts ("Error reading the chip.\n");
return 1;
}
return 0;
}
/*
* Syntax:
* i2c md {i2c_chip} {addr}{.0, .1, .2} {len}
*/
static int do_i2c_md ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
u_char chip;
uint addr, alen, length;
int j, nbytes, linebytes;
/* We use the last specified parameters, unless new ones are
* entered.
*/
chip = i2c_dp_last_chip;
addr = i2c_dp_last_addr;
alen = i2c_dp_last_alen;
length = i2c_dp_last_length;
if (argc < 3)
return cmd_usage(cmdtp);
if ((flag & CMD_FLAG_REPEAT) == 0) {
/*
* New command specified.
*/
/*
* I2C chip address
*/
chip = simple_strtoul(argv[1], NULL, 16);
/*
* I2C data address within the chip. This can be 1 or
* 2 bytes long. Some day it might be 3 bytes long :-).
*/
addr = simple_strtoul(argv[2], NULL, 16);
alen = get_alen(argv[2]);
if (alen > 3)
return cmd_usage(cmdtp);
/*
* If another parameter, it is the length to display.
* Length is the number of objects, not number of bytes.
*/
if (argc > 3)
length = simple_strtoul(argv[3], NULL, 16);
}
/*
* Print the lines.
*
* We buffer all read data, so we can make sure data is read only
* once.
*/
nbytes = length;
do {
unsigned char linebuf[DISP_LINE_LEN];
unsigned char *cp;
linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;
if (i2c_read(chip, addr, alen, linebuf, linebytes) != 0)
puts ("Error reading the chip.\n");
else {
printf("%04x:", addr);
cp = linebuf;
for (j=0; j<linebytes; j++) {
printf(" %02x", *cp++);
addr++;
}
puts (" ");
cp = linebuf;
for (j=0; j<linebytes; j++) {
if ((*cp < 0x20) || (*cp > 0x7e))
puts (".");
else
printf("%c", *cp);
cp++;
}
putc ('\n');
}
nbytes -= linebytes;
} while (nbytes > 0);
i2c_dp_last_chip = chip;
i2c_dp_last_addr = addr;
i2c_dp_last_alen = alen;
i2c_dp_last_length = length;
return 0;
}
/* Write (fill) memory
*
* Syntax:
* i2c mw {i2c_chip} {addr}{.0, .1, .2} {data} [{count}]
*/
static int do_i2c_mw ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
uchar chip;
ulong addr;
uint alen;
uchar byte;
int count;
if ((argc < 4) || (argc > 5))
return cmd_usage(cmdtp);
/*
* Chip is always specified.
*/
chip = simple_strtoul(argv[1], NULL, 16);
/*
* Address is always specified.
*/
addr = simple_strtoul(argv[2], NULL, 16);
alen = get_alen(argv[2]);
if (alen > 3)
return cmd_usage(cmdtp);
/*
* Value to write is always specified.
*/
byte = simple_strtoul(argv[3], NULL, 16);
/*
* Optional count
*/
if (argc == 5)
count = simple_strtoul(argv[4], NULL, 16);
else
count = 1;
while (count-- > 0) {
if (i2c_write(chip, addr++, alen, &byte, 1) != 0)
puts ("Error writing the chip.\n");
/*
* Wait for the write to complete. The write can take
* up to 10mSec (we allow a little more time).
*/
/*
* No write delay with FRAM devices.
*/
#if !defined(CONFIG_SYS_I2C_FRAM)
udelay(11000);
#endif
}
return (0);
}
/* Calculate a CRC on memory
*
* Syntax:
* i2c crc32 {i2c_chip} {addr}{.0, .1, .2} {count}
*/
static int do_i2c_crc (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
uchar chip;
ulong addr;
uint alen;
int count;
uchar byte;
ulong crc;
ulong err;
if (argc < 4)
return cmd_usage(cmdtp);
/*
* Chip is always specified.
*/
chip = simple_strtoul(argv[1], NULL, 16);
/*
* Address is always specified.
*/
addr = simple_strtoul(argv[2], NULL, 16);
alen = get_alen(argv[2]);
if (alen > 3)
return cmd_usage(cmdtp);
/*
* Count is always specified
*/
count = simple_strtoul(argv[3], NULL, 16);
printf ("CRC32 for %08lx ... %08lx ==> ", addr, addr + count - 1);
/*
* CRC a byte at a time. This is going to be slooow, but hey, the
* memories are small and slow too so hopefully nobody notices.
*/
crc = 0;
err = 0;
while (count-- > 0) {
if (i2c_read(chip, addr, alen, &byte, 1) != 0)
err++;
crc = crc32 (crc, &byte, 1);
addr++;
}
if (err > 0)
puts ("Error reading the chip,\n");
else
printf ("%08lx\n", crc);
return 0;
}
/* Modify memory.
*
* Syntax:
* i2c mm{.b, .w, .l} {i2c_chip} {addr}{.0, .1, .2}
* i2c nm{.b, .w, .l} {i2c_chip} {addr}{.0, .1, .2}
*/
static int
mod_i2c_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const argv[])
{
uchar chip;
ulong addr;
uint alen;
ulong data;
int size = 1;
int nbytes;
if (argc != 3)
return cmd_usage(cmdtp);
#ifdef CONFIG_BOOT_RETRY_TIME
reset_cmd_timeout(); /* got a good command to get here */
#endif
/*
* We use the last specified parameters, unless new ones are
* entered.
*/
chip = i2c_mm_last_chip;
addr = i2c_mm_last_addr;
alen = i2c_mm_last_alen;
if ((flag & CMD_FLAG_REPEAT) == 0) {
/*
* New command specified. Check for a size specification.
* Defaults to byte if no or incorrect specification.
*/
size = cmd_get_data_size(argv[0], 1);
/*
* Chip is always specified.
*/
chip = simple_strtoul(argv[1], NULL, 16);
/*
* Address is always specified.
*/
addr = simple_strtoul(argv[2], NULL, 16);
alen = get_alen(argv[2]);
if (alen > 3)
return cmd_usage(cmdtp);
}
/*
* Print the address, followed by value. Then accept input for
* the next value. A non-converted value exits.
*/
do {
printf("%08lx:", addr);
if (i2c_read(chip, addr, alen, (uchar *)&data, size) != 0)
puts ("\nError reading the chip,\n");
else {
data = cpu_to_be32(data);
if (size == 1)
printf(" %02lx", (data >> 24) & 0x000000FF);
else if (size == 2)
printf(" %04lx", (data >> 16) & 0x0000FFFF);
else
printf(" %08lx", data);
}
nbytes = readline (" ? ");
if (nbytes == 0) {
/*
* <CR> pressed as only input, don't modify current
* location and move to next.
*/
if (incrflag)
addr += size;
nbytes = size;
#ifdef CONFIG_BOOT_RETRY_TIME
reset_cmd_timeout(); /* good enough to not time out */
#endif
}
#ifdef CONFIG_BOOT_RETRY_TIME
else if (nbytes == -2)
break; /* timed out, exit the command */
#endif
else {
char *endp;
data = simple_strtoul(console_buffer, &endp, 16);
if (size == 1)
data = data << 24;
else if (size == 2)
data = data << 16;
data = be32_to_cpu(data);
nbytes = endp - console_buffer;
if (nbytes) {
#ifdef CONFIG_BOOT_RETRY_TIME
/*
* good enough to not time out
*/
reset_cmd_timeout();
#endif
if (i2c_write(chip, addr, alen, (uchar *)&data, size) != 0)
puts ("Error writing the chip.\n");
#ifdef CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS
udelay(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS * 1000);
#endif
if (incrflag)
addr += size;
}
}
} while (nbytes);
i2c_mm_last_chip = chip;
i2c_mm_last_addr = addr;
i2c_mm_last_alen = alen;
return 0;
}
/*
* Syntax:
* i2c probe {addr}{.0, .1, .2}
*/
static int do_i2c_probe (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int j;
#if defined(CONFIG_SYS_I2C_NOPROBES)
int k, skip;
uchar bus = GET_BUS_NUM;
#endif /* NOPROBES */
puts ("Valid chip addresses:");
for (j = 0; j < 128; j++) {
#if defined(CONFIG_SYS_I2C_NOPROBES)
skip = 0;
for (k=0; k < NUM_ELEMENTS_NOPROBE; k++) {
if (COMPARE_BUS(bus, k) && COMPARE_ADDR(j, k)) {
skip = 1;
break;
}
}
if (skip)
continue;
#endif
if (i2c_probe(j) == 0)
printf(" %02X", j);
}
putc ('\n');
#if defined(CONFIG_SYS_I2C_NOPROBES)
puts ("Excluded chip addresses:");
for (k=0; k < NUM_ELEMENTS_NOPROBE; k++) {
if (COMPARE_BUS(bus,k))
printf(" %02X", NO_PROBE_ADDR(k));
}
putc ('\n');
#endif
return 0;
}
/*
* Syntax:
* i2c loop {i2c_chip} {addr}{.0, .1, .2} [{length}] [{delay}]
* {length} - Number of bytes to read
* {delay} - A DECIMAL number and defaults to 1000 uSec
*/
static int do_i2c_loop(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
u_char chip;
ulong alen;
uint addr;
uint length;
u_char bytes[16];
int delay;
if (argc < 3)
return cmd_usage(cmdtp);
/*
* Chip is always specified.
*/
chip = simple_strtoul(argv[1], NULL, 16);
/*
* Address is always specified.
*/
addr = simple_strtoul(argv[2], NULL, 16);
alen = get_alen(argv[2]);
if (alen > 3)
return cmd_usage(cmdtp);
/*
* Length is the number of objects, not number of bytes.
*/
length = 1;
length = simple_strtoul(argv[3], NULL, 16);
if (length > sizeof(bytes))
length = sizeof(bytes);
/*
* The delay time (uSec) is optional.
*/
delay = 1000;
if (argc > 3)
delay = simple_strtoul(argv[4], NULL, 10);
/*
* Run the loop...
*/
while (1) {
if (i2c_read(chip, addr, alen, bytes, length) != 0)
puts ("Error reading the chip.\n");
udelay(delay);
}
/* NOTREACHED */
return 0;
}
/*
* The SDRAM command is separately configured because many
* (most?) embedded boards don't use SDRAM DIMMs.
*/
#if defined(CONFIG_CMD_SDRAM)
static void print_ddr2_tcyc (u_char const b)
{
printf ("%d.", (b >> 4) & 0x0F);
switch (b & 0x0F) {
case 0x0:
case 0x1:
case 0x2:
case 0x3:
case 0x4:
case 0x5:
case 0x6:
case 0x7:
case 0x8:
case 0x9:
printf ("%d ns\n", b & 0x0F);
break;
case 0xA:
puts ("25 ns\n");
break;
case 0xB:
puts ("33 ns\n");
break;
case 0xC:
puts ("66 ns\n");
break;
case 0xD:
puts ("75 ns\n");
break;
default:
puts ("?? ns\n");
break;
}
}
static void decode_bits (u_char const b, char const *str[], int const do_once)
{
u_char mask;
for (mask = 0x80; mask != 0x00; mask >>= 1, ++str) {
if (b & mask) {
puts (*str);
if (do_once)
return;
}
}
}
/*
* Syntax:
* i2c sdram {i2c_chip}
*/
static int do_sdram (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
enum { unknown, EDO, SDRAM, DDR2 } type;
u_char chip;
u_char data[128];
u_char cksum;
int j;
static const char *decode_CAS_DDR2[] = {
" TBD", " 6", " 5", " 4", " 3", " 2", " TBD", " TBD"
};
static const char *decode_CAS_default[] = {
" TBD", " 7", " 6", " 5", " 4", " 3", " 2", " 1"
};
static const char *decode_CS_WE_default[] = {
" TBD", " 6", " 5", " 4", " 3", " 2", " 1", " 0"
};
static const char *decode_byte21_default[] = {
" TBD (bit 7)\n",
" Redundant row address\n",
" Differential clock input\n",
" Registerd DQMB inputs\n",
" Buffered DQMB inputs\n",
" On-card PLL\n",
" Registered address/control lines\n",
" Buffered address/control lines\n"
};
static const char *decode_byte22_DDR2[] = {
" TBD (bit 7)\n",
" TBD (bit 6)\n",
" TBD (bit 5)\n",
" TBD (bit 4)\n",
" TBD (bit 3)\n",
" Supports partial array self refresh\n",
" Supports 50 ohm ODT\n",
" Supports weak driver\n"
};
static const char *decode_row_density_DDR2[] = {
"512 MiB", "256 MiB", "128 MiB", "16 GiB",
"8 GiB", "4 GiB", "2 GiB", "1 GiB"
};
static const char *decode_row_density_default[] = {
"512 MiB", "256 MiB", "128 MiB", "64 MiB",
"32 MiB", "16 MiB", "8 MiB", "4 MiB"
};
if (argc < 2)
return cmd_usage(cmdtp);
/*
* Chip is always specified.
*/
chip = simple_strtoul (argv[1], NULL, 16);
if (i2c_read (chip, 0, 1, data, sizeof (data)) != 0) {
puts ("No SDRAM Serial Presence Detect found.\n");
return 1;
}
cksum = 0;
for (j = 0; j < 63; j++) {
cksum += data[j];
}
if (cksum != data[63]) {
printf ("WARNING: Configuration data checksum failure:\n"
" is 0x%02x, calculated 0x%02x\n", data[63], cksum);
}
printf ("SPD data revision %d.%d\n",
(data[62] >> 4) & 0x0F, data[62] & 0x0F);
printf ("Bytes used 0x%02X\n", data[0]);
printf ("Serial memory size 0x%02X\n", 1 << data[1]);
puts ("Memory type ");
switch (data[2]) {
case 2:
type = EDO;
puts ("EDO\n");
break;
case 4:
type = SDRAM;
puts ("SDRAM\n");
break;
case 8:
type = DDR2;
puts ("DDR2\n");
break;
default:
type = unknown;
puts ("unknown\n");
break;
}
puts ("Row address bits ");
if ((data[3] & 0x00F0) == 0)
printf ("%d\n", data[3] & 0x0F);
else
printf ("%d/%d\n", data[3] & 0x0F, (data[3] >> 4) & 0x0F);
puts ("Column address bits ");
if ((data[4] & 0x00F0) == 0)
printf ("%d\n", data[4] & 0x0F);
else
printf ("%d/%d\n", data[4] & 0x0F, (data[4] >> 4) & 0x0F);
switch (type) {
case DDR2:
printf ("Number of ranks %d\n",
(data[5] & 0x07) + 1);
break;
default:
printf ("Module rows %d\n", data[5]);
break;
}
switch (type) {
case DDR2:
printf ("Module data width %d bits\n", data[6]);
break;
default:
printf ("Module data width %d bits\n",
(data[7] << 8) | data[6]);
break;
}
puts ("Interface signal levels ");
switch(data[8]) {
case 0: puts ("TTL 5.0 V\n"); break;
case 1: puts ("LVTTL\n"); break;
case 2: puts ("HSTL 1.5 V\n"); break;
case 3: puts ("SSTL 3.3 V\n"); break;
case 4: puts ("SSTL 2.5 V\n"); break;
case 5: puts ("SSTL 1.8 V\n"); break;
default: puts ("unknown\n"); break;
}
switch (type) {
case DDR2:
printf ("SDRAM cycle time ");
print_ddr2_tcyc (data[9]);
break;
default:
printf ("SDRAM cycle time %d.%d ns\n",
(data[9] >> 4) & 0x0F, data[9] & 0x0F);
break;
}
switch (type) {
case DDR2:
printf ("SDRAM access time 0.%d%d ns\n",
(data[10] >> 4) & 0x0F, data[10] & 0x0F);
break;
default:
printf ("SDRAM access time %d.%d ns\n",
(data[10] >> 4) & 0x0F, data[10] & 0x0F);
break;
}
puts ("EDC configuration ");
switch (data[11]) {
case 0: puts ("None\n"); break;
case 1: puts ("Parity\n"); break;
case 2: puts ("ECC\n"); break;
default: puts ("unknown\n"); break;
}
if ((data[12] & 0x80) == 0)
puts ("No self refresh, rate ");
else
puts ("Self refresh, rate ");
switch(data[12] & 0x7F) {
case 0: puts ("15.625 us\n"); break;
case 1: puts ("3.9 us\n"); break;
case 2: puts ("7.8 us\n"); break;
case 3: puts ("31.3 us\n"); break;
case 4: puts ("62.5 us\n"); break;
case 5: puts ("125 us\n"); break;
default: puts ("unknown\n"); break;
}
switch (type) {
case DDR2:
printf ("SDRAM width (primary) %d\n", data[13]);
break;
default:
printf ("SDRAM width (primary) %d\n", data[13] & 0x7F);
if ((data[13] & 0x80) != 0) {
printf (" (second bank) %d\n",
2 * (data[13] & 0x7F));
}
break;
}
switch (type) {
case DDR2:
if (data[14] != 0)
printf ("EDC width %d\n", data[14]);
break;
default:
if (data[14] != 0) {
printf ("EDC width %d\n",
data[14] & 0x7F);
if ((data[14] & 0x80) != 0) {
printf (" (second bank) %d\n",
2 * (data[14] & 0x7F));
}
}
break;
}
if (DDR2 != type) {
printf ("Min clock delay, back-to-back random column addresses "
"%d\n", data[15]);
}
puts ("Burst length(s) ");
if (data[16] & 0x80) puts (" Page");
if (data[16] & 0x08) puts (" 8");
if (data[16] & 0x04) puts (" 4");
if (data[16] & 0x02) puts (" 2");
if (data[16] & 0x01) puts (" 1");
putc ('\n');
printf ("Number of banks %d\n", data[17]);
switch (type) {
case DDR2:
puts ("CAS latency(s) ");
decode_bits (data[18], decode_CAS_DDR2, 0);
putc ('\n');
break;
default:
puts ("CAS latency(s) ");
decode_bits (data[18], decode_CAS_default, 0);
putc ('\n');
break;
}
if (DDR2 != type) {
puts ("CS latency(s) ");
decode_bits (data[19], decode_CS_WE_default, 0);
putc ('\n');
}
if (DDR2 != type) {
puts ("WE latency(s) ");
decode_bits (data[20], decode_CS_WE_default, 0);
putc ('\n');
}
switch (type) {
case DDR2:
puts ("Module attributes:\n");
if (data[21] & 0x80)
puts (" TBD (bit 7)\n");
if (data[21] & 0x40)
puts (" Analysis probe installed\n");
if (data[21] & 0x20)
puts (" TBD (bit 5)\n");
if (data[21] & 0x10)
puts (" FET switch external enable\n");
printf (" %d PLLs on DIMM\n", (data[21] >> 2) & 0x03);
if (data[20] & 0x11) {
printf (" %d active registers on DIMM\n",
(data[21] & 0x03) + 1);
}
break;
default:
puts ("Module attributes:\n");
if (!data[21])
puts (" (none)\n");
else
decode_bits (data[21], decode_byte21_default, 0);
break;
}
switch (type) {
case DDR2:
decode_bits (data[22], decode_byte22_DDR2, 0);
break;
default:
puts ("Device attributes:\n");
if (data[22] & 0x80) puts (" TBD (bit 7)\n");
if (data[22] & 0x40) puts (" TBD (bit 6)\n");
if (data[22] & 0x20) puts (" Upper Vcc tolerance 5%\n");
else puts (" Upper Vcc tolerance 10%\n");
if (data[22] & 0x10) puts (" Lower Vcc tolerance 5%\n");
else puts (" Lower Vcc tolerance 10%\n");
if (data[22] & 0x08) puts (" Supports write1/read burst\n");
if (data[22] & 0x04) puts (" Supports precharge all\n");
if (data[22] & 0x02) puts (" Supports auto precharge\n");
if (data[22] & 0x01) puts (" Supports early RAS# precharge\n");
break;
}
switch (type) {
case DDR2:
printf ("SDRAM cycle time (2nd highest CAS latency) ");
print_ddr2_tcyc (data[23]);
break;
default:
printf ("SDRAM cycle time (2nd highest CAS latency) %d."
"%d ns\n", (data[23] >> 4) & 0x0F, data[23] & 0x0F);
break;
}
switch (type) {
case DDR2:
printf ("SDRAM access from clock (2nd highest CAS latency) 0."
"%d%d ns\n", (data[24] >> 4) & 0x0F, data[24] & 0x0F);
break;
default:
printf ("SDRAM access from clock (2nd highest CAS latency) %d."
"%d ns\n", (data[24] >> 4) & 0x0F, data[24] & 0x0F);
break;
}
switch (type) {
case DDR2:
printf ("SDRAM cycle time (3rd highest CAS latency) ");
print_ddr2_tcyc (data[25]);
break;
default:
printf ("SDRAM cycle time (3rd highest CAS latency) %d."
"%d ns\n", (data[25] >> 4) & 0x0F, data[25] & 0x0F);
break;
}
switch (type) {
case DDR2:
printf ("SDRAM access from clock (3rd highest CAS latency) 0."
"%d%d ns\n", (data[26] >> 4) & 0x0F, data[26] & 0x0F);
break;
default:
printf ("SDRAM access from clock (3rd highest CAS latency) %d."
"%d ns\n", (data[26] >> 4) & 0x0F, data[26] & 0x0F);
break;
}
switch (type) {
case DDR2:
printf ("Minimum row precharge %d.%02d ns\n",
(data[27] >> 2) & 0x3F, 25 * (data[27] & 0x03));
break;
default:
printf ("Minimum row precharge %d ns\n", data[27]);
break;
}
switch (type) {
case DDR2:
printf ("Row active to row active min %d.%02d ns\n",
(data[28] >> 2) & 0x3F, 25 * (data[28] & 0x03));
break;
default:
printf ("Row active to row active min %d ns\n", data[28]);
break;
}
switch (type) {
case DDR2:
printf ("RAS to CAS delay min %d.%02d ns\n",
(data[29] >> 2) & 0x3F, 25 * (data[29] & 0x03));
break;
default:
printf ("RAS to CAS delay min %d ns\n", data[29]);
break;
}
printf ("Minimum RAS pulse width %d ns\n", data[30]);
switch (type) {
case DDR2:
puts ("Density of each row ");
decode_bits (data[31], decode_row_density_DDR2, 1);
putc ('\n');
break;
default:
puts ("Density of each row ");
decode_bits (data[31], decode_row_density_default, 1);
putc ('\n');
break;
}
switch (type) {
case DDR2:
puts ("Command and Address setup ");
if (data[32] >= 0xA0) {
printf ("1.%d%d ns\n",
((data[32] >> 4) & 0x0F) - 10, data[32] & 0x0F);
} else {
printf ("0.%d%d ns\n",
((data[32] >> 4) & 0x0F), data[32] & 0x0F);
}
break;
default:
printf ("Command and Address setup %c%d.%d ns\n",
(data[32] & 0x80) ? '-' : '+',
(data[32] >> 4) & 0x07, data[32] & 0x0F);
break;
}
switch (type) {
case DDR2:
puts ("Command and Address hold ");
if (data[33] >= 0xA0) {
printf ("1.%d%d ns\n",
((data[33] >> 4) & 0x0F) - 10, data[33] & 0x0F);
} else {
printf ("0.%d%d ns\n",
((data[33] >> 4) & 0x0F), data[33] & 0x0F);
}
break;
default:
printf ("Command and Address hold %c%d.%d ns\n",
(data[33] & 0x80) ? '-' : '+',
(data[33] >> 4) & 0x07, data[33] & 0x0F);
break;
}
switch (type) {
case DDR2:
printf ("Data signal input setup 0.%d%d ns\n",
(data[34] >> 4) & 0x0F, data[34] & 0x0F);
break;
default:
printf ("Data signal input setup %c%d.%d ns\n",
(data[34] & 0x80) ? '-' : '+',
(data[34] >> 4) & 0x07, data[34] & 0x0F);
break;
}
switch (type) {
case DDR2:
printf ("Data signal input hold 0.%d%d ns\n",
(data[35] >> 4) & 0x0F, data[35] & 0x0F);
break;
default:
printf ("Data signal input hold %c%d.%d ns\n",
(data[35] & 0x80) ? '-' : '+',
(data[35] >> 4) & 0x07, data[35] & 0x0F);
break;
}
puts ("Manufacturer's JEDEC ID ");
for (j = 64; j <= 71; j++)
printf ("%02X ", data[j]);
putc ('\n');
printf ("Manufacturing Location %02X\n", data[72]);
puts ("Manufacturer's Part Number ");
for (j = 73; j <= 90; j++)
printf ("%02X ", data[j]);
putc ('\n');
printf ("Revision Code %02X %02X\n", data[91], data[92]);
printf ("Manufacturing Date %02X %02X\n", data[93], data[94]);
puts ("Assembly Serial Number ");
for (j = 95; j <= 98; j++)
printf ("%02X ", data[j]);
putc ('\n');
if (DDR2 != type) {
printf ("Speed rating PC%d\n",
data[126] == 0x66 ? 66 : data[126]);
}
return 0;
}
#endif
#if defined(CONFIG_I2C_MUX)
static int do_i2c_add_bus(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
int ret=0;
if (argc == 1) {
/* show all busses */
I2C_MUX *mux;
I2C_MUX_DEVICE *device = i2c_mux_devices;
printf ("Busses reached over muxes:\n");
while (device != NULL) {
printf ("Bus ID: %x\n", device->busid);
printf (" reached over Mux(es):\n");
mux = device->mux;
while (mux != NULL) {
printf (" %s@%x ch: %x\n", mux->name, mux->chip, mux->channel);
mux = mux->next;
}
device = device->next;
}
} else {
(void)i2c_mux_ident_muxstring ((uchar *)argv[1]);
ret = 0;
}
return ret;
}
#endif /* CONFIG_I2C_MUX */
#if defined(CONFIG_I2C_MULTI_BUS)
static int do_i2c_bus_num(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
int bus_idx, ret=0;
if (argc == 1)
/* querying current setting */
printf("Current bus is %d\n", i2c_get_bus_num());
else {
bus_idx = simple_strtoul(argv[1], NULL, 10);
printf("Setting bus to %d\n", bus_idx);
ret = i2c_set_bus_num(bus_idx);
if (ret)
printf("Failure changing bus number (%d)\n", ret);
}
return ret;
}
#endif /* CONFIG_I2C_MULTI_BUS */
static int do_i2c_bus_speed(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
int speed, ret=0;
if (argc == 1)
/* querying current speed */
printf("Current bus speed=%d\n", i2c_get_bus_speed());
else {
speed = simple_strtoul(argv[1], NULL, 10);
printf("Setting bus speed to %d Hz\n", speed);
ret = i2c_set_bus_speed(speed);
if (ret)
printf("Failure changing bus speed (%d)\n", ret);
}
return ret;
}
static int do_i2c_mm(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
return mod_i2c_mem (cmdtp, 1, flag, argc, argv);
}
static int do_i2c_nm(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
return mod_i2c_mem (cmdtp, 0, flag, argc, argv);
}
static int do_i2c_reset(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
i2c_init(CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE);
return 0;
}
static cmd_tbl_t cmd_i2c_sub[] = {
#if defined(CONFIG_I2C_MUX)
U_BOOT_CMD_MKENT(bus, 1, 1, do_i2c_add_bus, "", ""),
#endif /* CONFIG_I2C_MUX */
U_BOOT_CMD_MKENT(crc32, 3, 1, do_i2c_crc, "", ""),
#if defined(CONFIG_I2C_MULTI_BUS)
U_BOOT_CMD_MKENT(dev, 1, 1, do_i2c_bus_num, "", ""),
#endif /* CONFIG_I2C_MULTI_BUS */
U_BOOT_CMD_MKENT(loop, 3, 1, do_i2c_loop, "", ""),
U_BOOT_CMD_MKENT(md, 3, 1, do_i2c_md, "", ""),
U_BOOT_CMD_MKENT(mm, 2, 1, do_i2c_mm, "", ""),
U_BOOT_CMD_MKENT(mw, 3, 1, do_i2c_mw, "", ""),
U_BOOT_CMD_MKENT(nm, 2, 1, do_i2c_nm, "", ""),
U_BOOT_CMD_MKENT(probe, 0, 1, do_i2c_probe, "", ""),
U_BOOT_CMD_MKENT(read, 5, 1, do_i2c_read, "", ""),
U_BOOT_CMD_MKENT(reset, 0, 1, do_i2c_reset, "", ""),
#if defined(CONFIG_CMD_SDRAM)
U_BOOT_CMD_MKENT(sdram, 1, 1, do_sdram, "", ""),
#endif
U_BOOT_CMD_MKENT(speed, 1, 1, do_i2c_bus_speed, "", ""),
};
#ifdef CONFIG_NEEDS_MANUAL_RELOC
void i2c_reloc(void) {
fixup_cmdtable(cmd_i2c_sub, ARRAY_SIZE(cmd_i2c_sub));
}
#endif
static int do_i2c(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
cmd_tbl_t *c;
if (argc < 2)
return cmd_usage(cmdtp);
/* Strip off leading 'i2c' command argument */
argc--;
argv++;
c = find_cmd_tbl(argv[0], &cmd_i2c_sub[0], ARRAY_SIZE(cmd_i2c_sub));
if (c)
return c->cmd(cmdtp, flag, argc, argv);
else
return cmd_usage(cmdtp);
}
/***************************************************/
U_BOOT_CMD(
i2c, 6, 1, do_i2c,
"I2C sub-system",
#if defined(CONFIG_I2C_MUX)
"bus [muxtype:muxaddr:muxchannel] - add a new bus reached over muxes\ni2c "
#endif /* CONFIG_I2C_MUX */
"crc32 chip address[.0, .1, .2] count - compute CRC32 checksum\n"
#if defined(CONFIG_I2C_MULTI_BUS)
"i2c dev [dev] - show or set current I2C bus\n"
#endif /* CONFIG_I2C_MULTI_BUS */
"i2c loop chip address[.0, .1, .2] [# of objects] - looping read of device\n"
"i2c md chip address[.0, .1, .2] [# of objects] - read from I2C device\n"
"i2c mm chip address[.0, .1, .2] - write to I2C device (auto-incrementing)\n"
"i2c mw chip address[.0, .1, .2] value [count] - write to I2C device (fill)\n"
"i2c nm chip address[.0, .1, .2] - write to I2C device (constant address)\n"
"i2c probe - show devices on the I2C bus\n"
"i2c read chip address[.0, .1, .2] length memaddress - read to memory \n"
"i2c reset - re-init the I2C Controller\n"
#if defined(CONFIG_CMD_SDRAM)
"i2c sdram chip - print SDRAM configuration information\n"
#endif
"i2c speed [speed] - show or set I2C bus speed"
);
#if defined(CONFIG_I2C_MUX)
static int i2c_mux_add_device(I2C_MUX_DEVICE *dev)
{
I2C_MUX_DEVICE *devtmp = i2c_mux_devices;
if (i2c_mux_devices == NULL) {
i2c_mux_devices = dev;
return 0;
}
while (devtmp->next != NULL)
devtmp = devtmp->next;
devtmp->next = dev;
return 0;
}
I2C_MUX_DEVICE *i2c_mux_search_device(int id)
{
I2C_MUX_DEVICE *device = i2c_mux_devices;
while (device != NULL) {
if (device->busid == id)
return device;
device = device->next;
}
return NULL;
}
/* searches in the buf from *pos the next ':'.
* returns:
* 0 if found (with *pos = where)
* < 0 if an error occured
* > 0 if the end of buf is reached
*/
static int i2c_mux_search_next (int *pos, uchar *buf, int len)
{
while ((buf[*pos] != ':') && (*pos < len)) {
*pos += 1;
}
if (*pos >= len)
return 1;
if (buf[*pos] != ':')
return -1;
return 0;
}
static int i2c_mux_get_busid (void)
{
int tmp = i2c_mux_busid;
i2c_mux_busid ++;
return tmp;
}
/* Analyses a Muxstring and immediately sends the
commands to the muxes. Runs from flash.
*/
int i2c_mux_ident_muxstring_f (uchar *buf)
{
int pos = 0;
int oldpos;
int ret = 0;
int len = strlen((char *)buf);
int chip;
uchar channel;
int was = 0;
while (ret == 0) {
oldpos = pos;
/* search name */
ret = i2c_mux_search_next(&pos, buf, len);
if (ret != 0)
printf ("ERROR\n");
/* search address */
pos ++;
oldpos = pos;
ret = i2c_mux_search_next(&pos, buf, len);
if (ret != 0)
printf ("ERROR\n");
buf[pos] = 0;
chip = simple_strtoul((char *)&buf[oldpos], NULL, 16);
buf[pos] = ':';
/* search channel */
pos ++;
oldpos = pos;
ret = i2c_mux_search_next(&pos, buf, len);
if (ret < 0)
printf ("ERROR\n");
was = 0;
if (buf[pos] != 0) {
buf[pos] = 0;
was = 1;
}
channel = simple_strtoul((char *)&buf[oldpos], NULL, 16);
if (was)
buf[pos] = ':';
if (i2c_write(chip, 0, 0, &channel, 1) != 0) {
printf ("Error setting Mux: chip:%x channel: \
%x\n", chip, channel);
return -1;
}
pos ++;
oldpos = pos;
}
return 0;
}
/* Analyses a Muxstring and if this String is correct
* adds a new I2C Bus.
*/
I2C_MUX_DEVICE *i2c_mux_ident_muxstring (uchar *buf)
{
I2C_MUX_DEVICE *device;
I2C_MUX *mux;
int pos = 0;
int oldpos;
int ret = 0;
int len = strlen((char *)buf);
int was = 0;
device = (I2C_MUX_DEVICE *)malloc (sizeof(I2C_MUX_DEVICE));
device->mux = NULL;
device->busid = i2c_mux_get_busid ();
device->next = NULL;
while (ret == 0) {
mux = (I2C_MUX *)malloc (sizeof(I2C_MUX));
mux->next = NULL;
/* search name of mux */
oldpos = pos;
ret = i2c_mux_search_next(&pos, buf, len);
if (ret != 0)
printf ("%s no name.\n", __FUNCTION__);
mux->name = (char *)malloc (pos - oldpos + 1);
memcpy (mux->name, &buf[oldpos], pos - oldpos);
mux->name[pos - oldpos] = 0;
/* search address */
pos ++;
oldpos = pos;
ret = i2c_mux_search_next(&pos, buf, len);
if (ret != 0)
printf ("%s no mux address.\n", __FUNCTION__);
buf[pos] = 0;
mux->chip = simple_strtoul((char *)&buf[oldpos], NULL, 16);
buf[pos] = ':';
/* search channel */
pos ++;
oldpos = pos;
ret = i2c_mux_search_next(&pos, buf, len);
if (ret < 0)
printf ("%s no mux channel.\n", __FUNCTION__);
was = 0;
if (buf[pos] != 0) {
buf[pos] = 0;
was = 1;
}
mux->channel = simple_strtoul((char *)&buf[oldpos], NULL, 16);
if (was)
buf[pos] = ':';
if (device->mux == NULL)
device->mux = mux;
else {
I2C_MUX *muxtmp = device->mux;
while (muxtmp->next != NULL) {
muxtmp = muxtmp->next;
}
muxtmp->next = mux;
}
pos ++;
oldpos = pos;
}
if (ret > 0) {
/* Add Device */
i2c_mux_add_device (device);
return device;
}
return NULL;
}
int i2x_mux_select_mux(int bus)
{
I2C_MUX_DEVICE *dev;
I2C_MUX *mux;
if ((gd->flags & GD_FLG_RELOC) != GD_FLG_RELOC) {
/* select Default Mux Bus */
#if defined(CONFIG_SYS_I2C_IVM_BUS)
i2c_mux_ident_muxstring_f ((uchar *)CONFIG_SYS_I2C_IVM_BUS);
#else
{
unsigned char *buf;
buf = (unsigned char *) getenv("EEprom_ivm");
if (buf != NULL)
i2c_mux_ident_muxstring_f (buf);
}
#endif
return 0;
}
dev = i2c_mux_search_device(bus);
if (dev == NULL)
return -1;
mux = dev->mux;
while (mux != NULL) {
/* do deblocking on each level of mux, before mux config */
i2c_init_board();
if (i2c_write(mux->chip, 0, 0, &mux->channel, 1) != 0) {
printf ("Error setting Mux: chip:%x channel: \
%x\n", mux->chip, mux->channel);
return -1;
}
mux = mux->next;
}
/* do deblocking on each level of mux and after mux config */
i2c_init_board();
return 0;
}
#endif /* CONFIG_I2C_MUX */
|
1001-study-uboot
|
common/cmd_i2c.c
|
C
|
gpl3
| 37,880
|
/*
* Copyright 2008 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.
*/
#include <common.h>
#include <ddr_spd.h>
/* used for ddr1 and ddr2 spd */
static int
spd_check(const u8 *buf, u8 spd_rev, u8 spd_cksum)
{
unsigned int cksum = 0;
unsigned int i;
/*
* Check SPD revision supported
* Rev 1.X or less supported by this code
*/
if (spd_rev >= 0x20) {
printf("SPD revision %02X not supported by this code\n",
spd_rev);
return 1;
}
if (spd_rev > 0x13) {
printf("SPD revision %02X not verified by this code\n",
spd_rev);
}
/*
* Calculate checksum
*/
for (i = 0; i < 63; i++) {
cksum += *buf++;
}
cksum &= 0xFF;
if (cksum != spd_cksum) {
printf("SPD checksum unexpected. "
"Checksum in SPD = %02X, computed SPD = %02X\n",
spd_cksum, cksum);
return 1;
}
return 0;
}
unsigned int
ddr1_spd_check(const ddr1_spd_eeprom_t *spd)
{
const u8 *p = (const u8 *)spd;
return spd_check(p, spd->spd_rev, spd->cksum);
}
unsigned int
ddr2_spd_check(const ddr2_spd_eeprom_t *spd)
{
const u8 *p = (const u8 *)spd;
return spd_check(p, spd->spd_rev, spd->cksum);
}
/*
* CRC16 compute for DDR3 SPD
* Copied from DDR3 SPD spec.
*/
static int
crc16(char *ptr, int count)
{
int crc, i;
crc = 0;
while (--count >= 0) {
crc = crc ^ (int)*ptr++ << 8;
for (i = 0; i < 8; ++i)
if (crc & 0x8000)
crc = crc << 1 ^ 0x1021;
else
crc = crc << 1;
}
return crc & 0xffff;
}
unsigned int
ddr3_spd_check(const ddr3_spd_eeprom_t *spd)
{
char *p = (char *)spd;
int csum16;
int len;
char crc_lsb; /* byte 126 */
char crc_msb; /* byte 127 */
/*
* SPD byte0[7] - CRC coverage
* 0 = CRC covers bytes 0~125
* 1 = CRC covers bytes 0~116
*/
len = !(spd->info_size_crc & 0x80) ? 126 : 117;
csum16 = crc16(p, len);
crc_lsb = (char) (csum16 & 0xff);
crc_msb = (char) (csum16 >> 8);
if (spd->crc[0] == crc_lsb && spd->crc[1] == crc_msb) {
return 0;
} else {
printf("SPD checksum unexpected.\n"
"Checksum lsb in SPD = %02X, computed SPD = %02X\n"
"Checksum msb in SPD = %02X, computed SPD = %02X\n",
spd->crc[0], crc_lsb, spd->crc[1], crc_msb);
return 1;
}
}
|
1001-study-uboot
|
common/ddr_spd.c
|
C
|
gpl3
| 2,318
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* Boot support
*/
#include <common.h>
#include <command.h>
#include <stdio_dev.h>
extern void _do_coninfo (void);
int do_coninfo (cmd_tbl_t * cmd, int flag, int argc, char * const argv[])
{
int l;
struct list_head *list = stdio_get_list();
struct list_head *pos;
struct stdio_dev *dev;
/* Scan for valid output and input devices */
puts ("List of available devices:\n");
list_for_each(pos, list) {
dev = list_entry(pos, struct stdio_dev, list);
printf ("%-8s %08x %c%c%c ",
dev->name,
dev->flags,
(dev->flags & DEV_FLAGS_SYSTEM) ? 'S' : '.',
(dev->flags & DEV_FLAGS_INPUT) ? 'I' : '.',
(dev->flags & DEV_FLAGS_OUTPUT) ? 'O' : '.');
for (l = 0; l < MAX_FILES; l++) {
if (stdio_devices[l] == dev) {
printf ("%s ", stdio_names[l]);
}
}
putc ('\n');
}
return 0;
}
/***************************************************/
U_BOOT_CMD(
coninfo, 3, 1, do_coninfo,
"print console devices and information",
""
);
|
1001-study-uboot
|
common/cmd_console.c
|
C
|
gpl3
| 1,843
|
/*
* Copyright (c) 2001 William L. Pitts
* All rights reserved.
*
* Redistribution and use in source and binary forms are freely
* permitted provided that the above copyright notice and this
* paragraph and the following disclaimer are duplicated in all
* such forms.
*
* This software is provided "AS IS" and without any express or
* implied warranties, including, without limitation, the implied
* warranties of merchantability and fitness for a particular
* purpose.
*/
#include <common.h>
#include <command.h>
#include <linux/ctype.h>
#include <net.h>
#include <elf.h>
#include <vxworks.h>
#if defined(CONFIG_WALNUT) || defined(CONFIG_SYS_VXWORKS_MAC_PTR)
DECLARE_GLOBAL_DATA_PTR;
#endif
int valid_elf_image (unsigned long addr);
static unsigned long load_elf_image_phdr(unsigned long addr);
static unsigned long load_elf_image_shdr(unsigned long addr);
/* Allow ports to override the default behavior */
__attribute__((weak))
unsigned long do_bootelf_exec (ulong (*entry)(int, char * const[]),
int argc, char * const argv[])
{
unsigned long ret;
/*
* QNX images require the data cache is disabled.
* Data cache is already flushed, so just turn it off.
*/
int dcache = dcache_status ();
if (dcache)
dcache_disable ();
/*
* pass address parameter as argv[0] (aka command name),
* and all remaining args
*/
ret = entry (argc, argv);
if (dcache)
dcache_enable ();
return ret;
}
/* ======================================================================
* Interpreter command to boot an arbitrary ELF image from memory.
* ====================================================================== */
int do_bootelf (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unsigned long addr; /* Address of the ELF image */
unsigned long rc; /* Return value from user code */
char *sload, *saddr;
/* -------------------------------------------------- */
int rcode = 0;
sload = saddr = NULL;
if (argc == 3) {
sload = argv[1];
saddr = argv[2];
} else if (argc == 2) {
if (argv[1][0] == '-')
sload = argv[1];
else
saddr = argv[1];
}
if (saddr)
addr = simple_strtoul(saddr, NULL, 16);
else
addr = load_addr;
if (!valid_elf_image (addr))
return 1;
if (sload && sload[1] == 'p')
addr = load_elf_image_phdr(addr);
else
addr = load_elf_image_shdr(addr);
printf ("## Starting application at 0x%08lx ...\n", addr);
/*
* pass address parameter as argv[0] (aka command name),
* and all remaining args
*/
rc = do_bootelf_exec ((void *)addr, argc - 1, argv + 1);
if (rc != 0)
rcode = 1;
printf ("## Application terminated, rc = 0x%lx\n", rc);
return rcode;
}
/* ======================================================================
* Interpreter command to boot VxWorks from a memory image. The image can
* be either an ELF image or a raw binary. Will attempt to setup the
* bootline and other parameters correctly.
* ====================================================================== */
int do_bootvx (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unsigned long addr; /* Address of image */
unsigned long bootaddr; /* Address to put the bootline */
char *bootline; /* Text of the bootline */
char *tmp; /* Temporary char pointer */
char build_buf[128]; /* Buffer for building the bootline */
/* ---------------------------------------------------
*
* Check the loadaddr variable.
* If we don't know where the image is then we're done.
*/
if (argc < 2)
addr = load_addr;
else
addr = simple_strtoul (argv[1], NULL, 16);
#if defined(CONFIG_CMD_NET)
/* Check to see if we need to tftp the image ourselves before starting */
if ((argc == 2) && (strcmp (argv[1], "tftp") == 0)) {
if (NetLoop(TFTPGET) <= 0)
return 1;
printf("Automatic boot of VxWorks image at address 0x%08lx "
"...\n", addr);
}
#endif
/* This should equate
* to NV_RAM_ADRS + NV_BOOT_OFFSET + NV_ENET_OFFSET
* from the VxWorks BSP header files.
* This will vary from board to board
*/
#if defined(CONFIG_WALNUT)
tmp = (char *) CONFIG_SYS_NVRAM_BASE_ADDR + 0x500;
eth_getenv_enetaddr("ethaddr", (uchar *)build_buf);
memcpy(tmp, &build_buf[3], 3);
#elif defined(CONFIG_SYS_VXWORKS_MAC_PTR)
tmp = (char *) CONFIG_SYS_VXWORKS_MAC_PTR;
eth_getenv_enetaddr("ethaddr", (uchar *)build_buf);
memcpy(tmp, build_buf, 6);
#else
puts ("## Ethernet MAC address not copied to NV RAM\n");
#endif
/*
* Use bootaddr to find the location in memory that VxWorks
* will look for the bootline string. The default value for
* PowerPC is LOCAL_MEM_LOCAL_ADRS + BOOT_LINE_OFFSET which
* defaults to 0x4200
*/
if ((tmp = getenv ("bootaddr")) == NULL)
bootaddr = CONFIG_SYS_VXWORKS_BOOT_ADDR;
else
bootaddr = simple_strtoul (tmp, NULL, 16);
/*
* Check to see if the bootline is defined in the 'bootargs'
* parameter. If it is not defined, we may be able to
* construct the info
*/
if ((bootline = getenv ("bootargs")) != NULL) {
memcpy ((void *) bootaddr, bootline,
max (strlen (bootline), 255));
flush_cache (bootaddr, max (strlen (bootline), 255));
} else {
sprintf (build_buf, CONFIG_SYS_VXWORKS_BOOT_DEVICE);
if ((tmp = getenv ("bootfile")) != NULL) {
sprintf (&build_buf[strlen (build_buf)],
"%s:%s ", CONFIG_SYS_VXWORKS_SERVERNAME, tmp);
} else {
sprintf (&build_buf[strlen (build_buf)],
"%s:file ", CONFIG_SYS_VXWORKS_SERVERNAME);
}
if ((tmp = getenv ("ipaddr")) != NULL) {
sprintf (&build_buf[strlen (build_buf)], "e=%s ", tmp);
}
if ((tmp = getenv ("serverip")) != NULL) {
sprintf (&build_buf[strlen (build_buf)], "h=%s ", tmp);
}
if ((tmp = getenv ("hostname")) != NULL) {
sprintf (&build_buf[strlen (build_buf)], "tn=%s ", tmp);
}
#ifdef CONFIG_SYS_VXWORKS_ADD_PARAMS
sprintf (&build_buf[strlen (build_buf)],
CONFIG_SYS_VXWORKS_ADD_PARAMS);
#endif
memcpy ((void *) bootaddr, build_buf,
max (strlen (build_buf), 255));
flush_cache (bootaddr, max (strlen (build_buf), 255));
}
/*
* If the data at the load address is an elf image, then
* treat it like an elf image. Otherwise, assume that it is a
* binary image
*/
if (valid_elf_image (addr)) {
addr = load_elf_image_shdr (addr);
} else {
puts ("## Not an ELF image, assuming binary\n");
/* leave addr as load_addr */
}
printf ("## Using bootline (@ 0x%lx): %s\n", bootaddr,
(char *) bootaddr);
printf ("## Starting vxWorks at 0x%08lx ...\n", addr);
((void (*)(void)) addr) ();
puts ("## vxWorks terminated\n");
return 1;
}
/* ======================================================================
* Determine if a valid ELF image exists at the given memory location.
* First looks at the ELF header magic field, the makes sure that it is
* executable and makes sure that it is for a PowerPC.
* ====================================================================== */
int valid_elf_image (unsigned long addr)
{
Elf32_Ehdr *ehdr; /* Elf header structure pointer */
/* -------------------------------------------------- */
ehdr = (Elf32_Ehdr *) addr;
if (!IS_ELF (*ehdr)) {
printf ("## No elf image at address 0x%08lx\n", addr);
return 0;
}
if (ehdr->e_type != ET_EXEC) {
printf ("## Not a 32-bit elf image at address 0x%08lx\n", addr);
return 0;
}
#if 0
if (ehdr->e_machine != EM_PPC) {
printf ("## Not a PowerPC elf image at address 0x%08lx\n",
addr);
return 0;
}
#endif
return 1;
}
/* ======================================================================
* A very simple elf loader, assumes the image is valid, returns the
* entry point address.
* ====================================================================== */
static unsigned long load_elf_image_phdr(unsigned long addr)
{
Elf32_Ehdr *ehdr; /* Elf header structure pointer */
Elf32_Phdr *phdr; /* Program header structure pointer */
int i;
ehdr = (Elf32_Ehdr *) addr;
phdr = (Elf32_Phdr *) (addr + ehdr->e_phoff);
/* Load each program header */
for (i = 0; i < ehdr->e_phnum; ++i) {
void *dst = (void *) phdr->p_paddr;
void *src = (void *) addr + phdr->p_offset;
debug("Loading phdr %i to 0x%p (%i bytes)\n",
i, dst, phdr->p_filesz);
if (phdr->p_filesz)
memcpy(dst, src, phdr->p_filesz);
if (phdr->p_filesz != phdr->p_memsz)
memset(dst + phdr->p_filesz, 0x00, phdr->p_memsz - phdr->p_filesz);
flush_cache((unsigned long)dst, phdr->p_filesz);
++phdr;
}
return ehdr->e_entry;
}
static unsigned long load_elf_image_shdr(unsigned long addr)
{
Elf32_Ehdr *ehdr; /* Elf header structure pointer */
Elf32_Shdr *shdr; /* Section header structure pointer */
unsigned char *strtab = 0; /* String table pointer */
unsigned char *image; /* Binary image pointer */
int i; /* Loop counter */
/* -------------------------------------------------- */
ehdr = (Elf32_Ehdr *) addr;
/* Find the section header string table for output info */
shdr = (Elf32_Shdr *) (addr + ehdr->e_shoff +
(ehdr->e_shstrndx * sizeof (Elf32_Shdr)));
if (shdr->sh_type == SHT_STRTAB)
strtab = (unsigned char *) (addr + shdr->sh_offset);
/* Load each appropriate section */
for (i = 0; i < ehdr->e_shnum; ++i) {
shdr = (Elf32_Shdr *) (addr + ehdr->e_shoff +
(i * sizeof (Elf32_Shdr)));
if (!(shdr->sh_flags & SHF_ALLOC)
|| shdr->sh_addr == 0 || shdr->sh_size == 0) {
continue;
}
if (strtab) {
debug("%sing %s @ 0x%08lx (%ld bytes)\n",
(shdr->sh_type == SHT_NOBITS) ?
"Clear" : "Load",
&strtab[shdr->sh_name],
(unsigned long) shdr->sh_addr,
(long) shdr->sh_size);
}
if (shdr->sh_type == SHT_NOBITS) {
memset ((void *)shdr->sh_addr, 0, shdr->sh_size);
} else {
image = (unsigned char *) addr + shdr->sh_offset;
memcpy ((void *) shdr->sh_addr,
(const void *) image,
shdr->sh_size);
}
flush_cache (shdr->sh_addr, shdr->sh_size);
}
return ehdr->e_entry;
}
/* ====================================================================== */
U_BOOT_CMD(
bootelf, 3, 0, do_bootelf,
"Boot from an ELF image in memory",
"[-p|-s] [address]\n"
"\t- load ELF image at [address] via program headers (-p)\n"
"\t or via section headers (-s)"
);
U_BOOT_CMD(
bootvx, 2, 0, do_bootvx,
"Boot vxWorks from an ELF image",
" [address] - load address of vxWorks ELF image."
);
|
1001-study-uboot
|
common/cmd_elf.c
|
C
|
gpl3
| 10,413
|
/*
* (C) Copyright 2002-2007
* Detlev Zundel, DENX Software Engineering, dzu@denx.de.
*
* Code used from linux/kernel/printk.c
* Copyright (C) 1991, 1992 Linus Torvalds
*
* 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
*
* Comments:
*
* After relocating the code, the environment variable "loglevel" is
* copied to console_loglevel. The functionality is similar to the
* handling in the Linux kernel, i.e. messages logged with a priority
* less than console_loglevel are also output to stdout.
*
* If you want messages with the default level (e.g. POST messages) to
* appear on stdout also, make sure the environment variable
* "loglevel" is set at boot time to a number higher than
* default_message_loglevel below.
*/
/*
* Logbuffer handling routines
*/
#include <common.h>
#include <command.h>
#include <stdio_dev.h>
#include <post.h>
#include <logbuff.h>
DECLARE_GLOBAL_DATA_PTR;
/* Local prototypes */
static void logbuff_putc (const char c);
static void logbuff_puts (const char *s);
static int logbuff_printk(const char *line);
static char buf[1024];
/* This combination will not print messages with the default loglevel */
static unsigned console_loglevel = 3;
static unsigned default_message_loglevel = 4;
static unsigned log_version = 1;
#ifdef CONFIG_ALT_LB_ADDR
static volatile logbuff_t *log;
#else
static logbuff_t *log;
#endif
static char *lbuf;
unsigned long __logbuffer_base(void)
{
return CONFIG_SYS_SDRAM_BASE + gd->ram_size - LOGBUFF_LEN;
}
unsigned long logbuffer_base (void) __attribute__((weak, alias("__logbuffer_base")));
void logbuff_init_ptrs (void)
{
unsigned long tag, post_word;
char *s;
#ifdef CONFIG_ALT_LB_ADDR
log = (logbuff_t *)CONFIG_ALT_LH_ADDR;
lbuf = (char *)CONFIG_ALT_LB_ADDR;
#else
log = (logbuff_t *)(logbuffer_base ()) - 1;
lbuf = (char *)log->buf;
#endif
/* Set up log version */
if ((s = getenv ("logversion")) != NULL)
log_version = (int)simple_strtoul (s, NULL, 10);
if (log_version == 2)
tag = log->v2.tag;
else
tag = log->v1.tag;
post_word = post_word_load();
#ifdef CONFIG_POST
/* The post routines have setup the word so we can simply test it */
if (tag != LOGBUFF_MAGIC || (post_word & POST_COLDBOOT)) {
logbuff_reset ();
}
#else
/* No post routines, so we do our own checking */
if (tag != LOGBUFF_MAGIC || post_word != LOGBUFF_MAGIC) {
logbuff_reset ();
post_word_store (LOGBUFF_MAGIC);
}
#endif
if (log_version == 2 && (long)log->v2.start > (long)log->v2.con)
log->v2.start = log->v2.con;
/* Initialize default loglevel if present */
if ((s = getenv ("loglevel")) != NULL)
console_loglevel = (int)simple_strtoul (s, NULL, 10);
gd->flags |= GD_FLG_LOGINIT;
}
void logbuff_reset (void)
{
#ifndef CONFIG_ALT_LB_ADDR
memset (log, 0, sizeof (logbuff_t));
#endif
if (log_version == 2) {
log->v2.tag = LOGBUFF_MAGIC;
#ifdef CONFIG_ALT_LB_ADDR
log->v2.start = 0;
log->v2.con = 0;
log->v2.end = 0;
log->v2.chars = 0;
#endif
} else {
log->v1.tag = LOGBUFF_MAGIC;
#ifdef CONFIG_ALT_LB_ADDR
log->v1.dummy = 0;
log->v1.start = 0;
log->v1.size = 0;
log->v1.chars = 0;
#endif
}
}
int drv_logbuff_init (void)
{
struct stdio_dev logdev;
int rc;
/* Device initialization */
memset (&logdev, 0, sizeof (logdev));
strcpy (logdev.name, "logbuff");
logdev.ext = 0; /* No extensions */
logdev.flags = DEV_FLAGS_OUTPUT; /* Output only */
logdev.putc = logbuff_putc; /* 'putc' function */
logdev.puts = logbuff_puts; /* 'puts' function */
rc = stdio_register (&logdev);
return (rc == 0) ? 1 : rc;
}
static void logbuff_putc (const char c)
{
char buf[2];
buf[0] = c;
buf[1] = '\0';
logbuff_printk (buf);
}
static void logbuff_puts (const char *s)
{
logbuff_printk (s);
}
void logbuff_log(char *msg)
{
if ((gd->flags & GD_FLG_LOGINIT)) {
logbuff_printk (msg);
} else {
/* Can happen only for pre-relocated errors as logging */
/* at that stage should be disabled */
puts (msg);
}
}
/*
* Subroutine: do_log
*
* Description: Handler for 'log' command..
*
* Inputs: argv[1] contains the subcommand
*
* Return: None
*
*/
int do_log (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *s;
unsigned long i, start, size;
if (strcmp(argv[1],"append") == 0) {
/* Log concatenation of all arguments separated by spaces */
for (i=2; i<argc; i++) {
logbuff_printk (argv[i]);
logbuff_putc ((i<argc-1) ? ' ' : '\n');
}
return 0;
}
switch (argc) {
case 2:
if (strcmp(argv[1],"show") == 0) {
if (log_version == 2) {
start = log->v2.start;
size = log->v2.end - log->v2.start;
}
else {
start = log->v1.start;
size = log->v1.size;
}
for (i=0; i < (size&LOGBUFF_MASK); i++) {
s = lbuf+((start+i)&LOGBUFF_MASK);
putc (*s);
}
return 0;
} else if (strcmp(argv[1],"reset") == 0) {
logbuff_reset ();
return 0;
} else if (strcmp(argv[1],"info") == 0) {
printf ("Logbuffer at %08lx\n", (unsigned long)lbuf);
if (log_version == 2) {
printf ("log_start = %08lx\n", log->v2.start);
printf ("log_end = %08lx\n", log->v2.end);
printf ("logged_chars = %08lx\n", log->v2.chars);
}
else {
printf ("log_start = %08lx\n", log->v1.start);
printf ("log_size = %08lx\n", log->v1.size);
printf ("logged_chars = %08lx\n", log->v1.chars);
}
return 0;
}
return cmd_usage(cmdtp);
default:
return cmd_usage(cmdtp);
}
}
U_BOOT_CMD(
log, 255, 1, do_log,
"manipulate logbuffer",
"info - show pointer details\n"
"log reset - clear contents\n"
"log show - show contents\n"
"log append <msg> - append <msg> to the logbuffer"
);
static int logbuff_printk(const char *line)
{
int i;
char *msg, *p, *buf_end;
int line_feed;
static signed char msg_level = -1;
strcpy (buf + 3, line);
i = strlen (line);
buf_end = buf + 3 + i;
for (p = buf + 3; p < buf_end; p++) {
msg = p;
if (msg_level < 0) {
if (
p[0] != '<' ||
p[1] < '0' ||
p[1] > '7' ||
p[2] != '>'
) {
p -= 3;
p[0] = '<';
p[1] = default_message_loglevel + '0';
p[2] = '>';
} else
msg += 3;
msg_level = p[1] - '0';
}
line_feed = 0;
for (; p < buf_end; p++) {
if (log_version == 2) {
lbuf[log->v2.end & LOGBUFF_MASK] = *p;
log->v2.end++;
if (log->v2.end - log->v2.start > LOGBUFF_LEN)
log->v2.start++;
log->v2.chars++;
}
else {
lbuf[(log->v1.start + log->v1.size) &
LOGBUFF_MASK] = *p;
if (log->v1.size < LOGBUFF_LEN)
log->v1.size++;
else
log->v1.start++;
log->v1.chars++;
}
if (*p == '\n') {
line_feed = 1;
break;
}
}
if (msg_level < console_loglevel) {
printf("%s", msg);
}
if (line_feed)
msg_level = -1;
}
return i;
}
|
1001-study-uboot
|
common/cmd_log.c
|
C
|
gpl3
| 7,537
|
/*
* 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 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>
/*
* TODO(clchiou): This function actually minics the bottom-half of the
* run_command() function. Since this function has ARM-dependent timer
* codes, we cannot merge it with the run_command() for now.
*/
static int run_command_and_time_it(int flag, int argc, char * const argv[],
ulong *cycles)
{
cmd_tbl_t *cmdtp = find_cmd(argv[0]);
int retval = 0;
if (!cmdtp) {
printf("%s: command not found\n", argv[0]);
return 1;
}
if (argc > cmdtp->maxargs)
return cmd_usage(cmdtp);
/*
* TODO(clchiou): get_timer_masked() is only defined in certain ARM
* boards. We could use the new timer API that Graeme is proposing
* so that this piece of code would be arch-independent.
*/
*cycles = get_timer_masked();
retval = cmdtp->cmd(cmdtp, flag, argc, argv);
*cycles = get_timer_masked() - *cycles;
return retval;
}
static void report_time(ulong cycles)
{
ulong minutes, seconds, milliseconds;
ulong total_seconds, remainder;
total_seconds = cycles / CONFIG_SYS_HZ;
remainder = cycles % CONFIG_SYS_HZ;
minutes = total_seconds / 60;
seconds = total_seconds % 60;
/* approximate millisecond value */
milliseconds = (remainder * 1000 + CONFIG_SYS_HZ / 2) / CONFIG_SYS_HZ;
printf("\ntime:");
if (minutes)
printf(" %lu minutes,", minutes);
printf(" %lu.%03lu seconds, %lu ticks\n",
seconds, milliseconds, cycles);
}
static int do_time(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong cycles = 0;
int retval = 0;
if (argc == 1)
return cmd_usage(cmdtp);
retval = run_command_and_time_it(0, argc - 1, argv + 1, &cycles);
report_time(cycles);
return retval;
}
U_BOOT_CMD(time, CONFIG_SYS_MAXARGS, 0, do_time,
"run commands and summarize execution time",
"command [args...]\n");
|
1001-study-uboot
|
common/cmd_time.c
|
C
|
gpl3
| 2,634
|
/*
* (C) Copyright 2001
* Erik Theisen, Wave 7 Optics, etheisen@mindspring.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 <command.h>
#include <dtt.h>
#include <i2c.h>
static unsigned long sensor_initialized;
static void _initialize_dtt(void)
{
int i;
unsigned char sensors[] = CONFIG_DTT_SENSORS;
for (i = 0; i < sizeof(sensors); i++) {
if ((sensor_initialized & (1 << i)) == 0) {
if (dtt_init_one(sensors[i]) != 0) {
printf("DTT%d: Failed init!\n", i);
continue;
}
sensor_initialized |= (1 << i);
}
}
}
void dtt_init(void)
{
int old_bus;
/* switch to correct I2C bus */
old_bus = I2C_GET_BUS();
I2C_SET_BUS(CONFIG_SYS_DTT_BUS_NUM);
_initialize_dtt();
/* switch back to original I2C bus */
I2C_SET_BUS(old_bus);
}
int do_dtt (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
int i;
unsigned char sensors[] = CONFIG_DTT_SENSORS;
int old_bus;
/* Force a compilation error, if there are more then 32 sensors */
BUILD_BUG_ON(sizeof(sensors) > 32);
/* switch to correct I2C bus */
old_bus = I2C_GET_BUS();
I2C_SET_BUS(CONFIG_SYS_DTT_BUS_NUM);
_initialize_dtt();
/*
* Loop through sensors, read
* temperature, and output it.
*/
for (i = 0; i < sizeof(sensors); i++)
printf("DTT%d: %i C\n", i + 1, dtt_get_temp(sensors[i]));
/* switch back to original I2C bus */
I2C_SET_BUS(old_bus);
return 0;
} /* do_dtt() */
/***************************************************/
U_BOOT_CMD(
dtt, 1, 1, do_dtt,
"Read temperature from Digital Thermometer and Thermostat",
""
);
|
1001-study-uboot
|
common/cmd_dtt.c
|
C
|
gpl3
| 2,357
|
/*
* (C) Copyright 2001
* Denis Peter, MPL AG Switzerland
*
* 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
*
*
*
*/
/*
* SCSI support.
*/
#include <common.h>
#include <command.h>
#include <asm/processor.h>
#include <scsi.h>
#include <image.h>
#include <pci.h>
#ifdef CONFIG_SCSI_SYM53C8XX
#define SCSI_VEND_ID 0x1000
#ifndef CONFIG_SCSI_DEV_ID
#define SCSI_DEV_ID 0x0001
#else
#define SCSI_DEV_ID CONFIG_SCSI_DEV_ID
#endif
#elif defined CONFIG_SATA_ULI5288
#define SCSI_VEND_ID 0x10b9
#define SCSI_DEV_ID 0x5288
#elif !defined(CONFIG_SCSI_AHCI_PLAT)
#error no scsi device defined
#endif
static ccb tempccb; /* temporary scsi command buffer */
static unsigned char tempbuff[512]; /* temporary data buffer */
static int scsi_max_devs; /* number of highest available scsi device */
static int scsi_curr_dev; /* current device */
static block_dev_desc_t scsi_dev_desc[CONFIG_SYS_SCSI_MAX_DEVICE];
/********************************************************************************
* forward declerations of some Setup Routines
*/
void scsi_setup_test_unit_ready(ccb * pccb);
void scsi_setup_read_capacity(ccb * pccb);
void scsi_setup_read6(ccb * pccb, unsigned long start, unsigned short blocks);
void scsi_setup_read_ext(ccb * pccb, unsigned long start, unsigned short blocks);
void scsi_setup_inquiry(ccb * pccb);
void scsi_ident_cpy (unsigned char *dest, unsigned char *src, unsigned int len);
ulong scsi_read(int device, ulong blknr, ulong blkcnt, void *buffer);
/*********************************************************************************
* (re)-scan the scsi bus and reports scsi device info
* to the user if mode = 1
*/
void scsi_scan(int mode)
{
unsigned char i,perq,modi,lun;
unsigned long capacity,blksz;
ccb* pccb=(ccb *)&tempccb;
if(mode==1) {
printf("scanning bus for devices...\n");
}
for(i=0;i<CONFIG_SYS_SCSI_MAX_DEVICE;i++) {
scsi_dev_desc[i].target=0xff;
scsi_dev_desc[i].lun=0xff;
scsi_dev_desc[i].lba=0;
scsi_dev_desc[i].blksz=0;
scsi_dev_desc[i].type=DEV_TYPE_UNKNOWN;
scsi_dev_desc[i].vendor[0]=0;
scsi_dev_desc[i].product[0]=0;
scsi_dev_desc[i].revision[0]=0;
scsi_dev_desc[i].removable=FALSE;
scsi_dev_desc[i].if_type=IF_TYPE_SCSI;
scsi_dev_desc[i].dev=i;
scsi_dev_desc[i].part_type=PART_TYPE_UNKNOWN;
scsi_dev_desc[i].block_read=scsi_read;
}
scsi_max_devs=0;
for(i=0;i<CONFIG_SYS_SCSI_MAX_SCSI_ID;i++) {
pccb->target=i;
for(lun=0;lun<CONFIG_SYS_SCSI_MAX_LUN;lun++) {
pccb->lun=lun;
pccb->pdata=(unsigned char *)&tempbuff;
pccb->datalen=512;
scsi_setup_inquiry(pccb);
if(scsi_exec(pccb)!=TRUE) {
if(pccb->contr_stat==SCSI_SEL_TIME_OUT) {
debug ("Selection timeout ID %d\n",pccb->target);
continue; /* selection timeout => assuming no device present */
}
scsi_print_error(pccb);
continue;
}
perq=tempbuff[0];
modi=tempbuff[1];
if((perq & 0x1f)==0x1f) {
continue; /* skip unknown devices */
}
if((modi&0x80)==0x80) /* drive is removable */
scsi_dev_desc[scsi_max_devs].removable=TRUE;
/* get info for this device */
scsi_ident_cpy((unsigned char *)&scsi_dev_desc[scsi_max_devs].vendor[0],
&tempbuff[8], 8);
scsi_ident_cpy((unsigned char *)&scsi_dev_desc[scsi_max_devs].product[0],
&tempbuff[16], 16);
scsi_ident_cpy((unsigned char *)&scsi_dev_desc[scsi_max_devs].revision[0],
&tempbuff[32], 4);
scsi_dev_desc[scsi_max_devs].target=pccb->target;
scsi_dev_desc[scsi_max_devs].lun=pccb->lun;
pccb->datalen=0;
scsi_setup_test_unit_ready(pccb);
if(scsi_exec(pccb)!=TRUE) {
if(scsi_dev_desc[scsi_max_devs].removable==TRUE) {
scsi_dev_desc[scsi_max_devs].type=perq;
goto removable;
}
scsi_print_error(pccb);
continue;
}
pccb->datalen=8;
scsi_setup_read_capacity(pccb);
if(scsi_exec(pccb)!=TRUE) {
scsi_print_error(pccb);
continue;
}
capacity=((unsigned long)tempbuff[0]<<24)|((unsigned long)tempbuff[1]<<16)|
((unsigned long)tempbuff[2]<<8)|((unsigned long)tempbuff[3]);
blksz=((unsigned long)tempbuff[4]<<24)|((unsigned long)tempbuff[5]<<16)|
((unsigned long)tempbuff[6]<<8)|((unsigned long)tempbuff[7]);
scsi_dev_desc[scsi_max_devs].lba=capacity;
scsi_dev_desc[scsi_max_devs].blksz=blksz;
scsi_dev_desc[scsi_max_devs].type=perq;
init_part(&scsi_dev_desc[scsi_max_devs]);
removable:
if(mode==1) {
printf (" Device %d: ", scsi_max_devs);
dev_print(&scsi_dev_desc[scsi_max_devs]);
} /* if mode */
scsi_max_devs++;
} /* next LUN */
}
if(scsi_max_devs>0)
scsi_curr_dev=0;
else
scsi_curr_dev = -1;
}
#ifdef CONFIG_PCI
void scsi_init(void)
{
int busdevfunc;
busdevfunc=pci_find_device(SCSI_VEND_ID,SCSI_DEV_ID,0); /* get PCI Device ID */
if(busdevfunc==-1) {
printf("Error SCSI Controller (%04X,%04X) not found\n",SCSI_VEND_ID,SCSI_DEV_ID);
return;
}
#ifdef DEBUG
else {
printf("SCSI Controller (%04X,%04X) found (%d:%d:%d)\n",SCSI_VEND_ID,SCSI_DEV_ID,(busdevfunc>>16)&0xFF,(busdevfunc>>11)&0x1F,(busdevfunc>>8)&0x7);
}
#endif
scsi_low_level_init(busdevfunc);
scsi_scan(1);
}
#endif
#ifdef CONFIG_PARTITIONS
block_dev_desc_t * scsi_get_dev(int dev)
{
return (dev < CONFIG_SYS_SCSI_MAX_DEVICE) ? &scsi_dev_desc[dev] : NULL;
}
#endif
/******************************************************************************
* scsi boot command intepreter. Derived from diskboot
*/
int do_scsiboot (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *boot_device = NULL;
char *ep;
int dev, part = 0;
ulong addr, cnt;
disk_partition_t info;
image_header_t *hdr;
#if defined(CONFIG_FIT)
const void *fit_hdr = NULL;
#endif
switch (argc) {
case 1:
addr = CONFIG_SYS_LOAD_ADDR;
boot_device = getenv ("bootdevice");
break;
case 2:
addr = simple_strtoul(argv[1], NULL, 16);
boot_device = getenv ("bootdevice");
break;
case 3:
addr = simple_strtoul(argv[1], NULL, 16);
boot_device = argv[2];
break;
default:
return cmd_usage(cmdtp);
}
if (!boot_device) {
puts ("\n** No boot device **\n");
return 1;
}
dev = simple_strtoul(boot_device, &ep, 16);
printf("booting from dev %d\n",dev);
if (scsi_dev_desc[dev].type == DEV_TYPE_UNKNOWN) {
printf ("\n** Device %d not available\n", dev);
return 1;
}
if (*ep) {
if (*ep != ':') {
puts ("\n** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = simple_strtoul(++ep, NULL, 16);
}
if (get_partition_info (&scsi_dev_desc[dev], part, &info)) {
printf("error reading partinfo\n");
return 1;
}
if ((strncmp((char *)(info.type), BOOT_PART_TYPE, sizeof(info.type)) != 0) &&
(strncmp((char *)(info.type), BOOT_PART_COMP, sizeof(info.type)) != 0)) {
printf ("\n** Invalid partition type \"%.32s\""
" (expect \"" BOOT_PART_TYPE "\")\n",
info.type);
return 1;
}
printf ("\nLoading from SCSI device %d, partition %d: "
"Name: %.32s Type: %.32s\n",
dev, part, info.name, info.type);
debug ("First Block: %ld, # of blocks: %ld, Block Size: %ld\n",
info.start, info.size, info.blksz);
if (scsi_read (dev, info.start, 1, (ulong *)addr) != 1) {
printf ("** Read error on %d:%d\n", dev, part);
return 1;
}
switch (genimg_get_format ((void *)addr)) {
case IMAGE_FORMAT_LEGACY:
hdr = (image_header_t *)addr;
if (!image_check_hcrc (hdr)) {
puts ("\n** Bad Header Checksum **\n");
return 1;
}
image_print_contents (hdr);
cnt = image_get_image_size (hdr);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
fit_hdr = (const void *)addr;
puts ("Fit image detected...\n");
cnt = fit_get_size (fit_hdr);
break;
#endif
default:
puts ("** Unknown image type\n");
return 1;
}
cnt += info.blksz - 1;
cnt /= info.blksz;
cnt -= 1;
if (scsi_read (dev, info.start+1, cnt,
(ulong *)(addr+info.blksz)) != cnt) {
printf ("** Read error on %d:%d\n", dev, part);
return 1;
}
#if defined(CONFIG_FIT)
/* This cannot be done earlier, we need complete FIT image in RAM first */
if (genimg_get_format ((void *)addr) == IMAGE_FORMAT_FIT) {
if (!fit_check_format (fit_hdr)) {
puts ("** Bad FIT image format\n");
return 1;
}
fit_print_contents (fit_hdr);
}
#endif
/* Loading ok, update default load address */
load_addr = addr;
flush_cache (addr, (cnt+1)*info.blksz);
return bootm_maybe_autostart(cmdtp, argv[0]);
}
/*********************************************************************************
* scsi command intepreter
*/
int do_scsi (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
switch (argc) {
case 0:
case 1: return cmd_usage(cmdtp);
case 2:
if (strncmp(argv[1],"res",3) == 0) {
printf("\nReset SCSI\n");
scsi_bus_reset();
scsi_scan(1);
return 0;
}
if (strncmp(argv[1],"inf",3) == 0) {
int i;
for (i=0; i<CONFIG_SYS_SCSI_MAX_DEVICE; ++i) {
if(scsi_dev_desc[i].type==DEV_TYPE_UNKNOWN)
continue; /* list only known devices */
printf ("SCSI dev. %d: ", i);
dev_print(&scsi_dev_desc[i]);
}
return 0;
}
if (strncmp(argv[1],"dev",3) == 0) {
if ((scsi_curr_dev < 0) || (scsi_curr_dev >= CONFIG_SYS_SCSI_MAX_DEVICE)) {
printf("\nno SCSI devices available\n");
return 1;
}
printf ("\n Device %d: ", scsi_curr_dev);
dev_print(&scsi_dev_desc[scsi_curr_dev]);
return 0;
}
if (strncmp(argv[1],"scan",4) == 0) {
scsi_scan(1);
return 0;
}
if (strncmp(argv[1],"part",4) == 0) {
int dev, ok;
for (ok=0, dev=0; dev<CONFIG_SYS_SCSI_MAX_DEVICE; ++dev) {
if (scsi_dev_desc[dev].type!=DEV_TYPE_UNKNOWN) {
ok++;
if (dev)
printf("\n");
debug ("print_part of %x\n",dev);
print_part(&scsi_dev_desc[dev]);
}
}
if (!ok)
printf("\nno SCSI devices available\n");
return 1;
}
return cmd_usage(cmdtp);
case 3:
if (strncmp(argv[1],"dev",3) == 0) {
int dev = (int)simple_strtoul(argv[2], NULL, 10);
printf ("\nSCSI device %d: ", dev);
if (dev >= CONFIG_SYS_SCSI_MAX_DEVICE) {
printf("unknown device\n");
return 1;
}
printf ("\n Device %d: ", dev);
dev_print(&scsi_dev_desc[dev]);
if(scsi_dev_desc[dev].type == DEV_TYPE_UNKNOWN) {
return 1;
}
scsi_curr_dev = dev;
printf("... is now current device\n");
return 0;
}
if (strncmp(argv[1],"part",4) == 0) {
int dev = (int)simple_strtoul(argv[2], NULL, 10);
if(scsi_dev_desc[dev].type != DEV_TYPE_UNKNOWN) {
print_part(&scsi_dev_desc[dev]);
}
else {
printf ("\nSCSI device %d not available\n", dev);
}
return 1;
}
return cmd_usage(cmdtp);
default:
/* at least 4 args */
if (strcmp(argv[1],"read") == 0) {
ulong addr = simple_strtoul(argv[2], NULL, 16);
ulong blk = simple_strtoul(argv[3], NULL, 16);
ulong cnt = simple_strtoul(argv[4], NULL, 16);
ulong n;
printf ("\nSCSI read: device %d block # %ld, count %ld ... ",
scsi_curr_dev, blk, cnt);
n = scsi_read(scsi_curr_dev, blk, cnt, (ulong *)addr);
printf ("%ld blocks read: %s\n",n,(n==cnt) ? "OK" : "ERROR");
return 0;
}
} /* switch */
return cmd_usage(cmdtp);
}
/****************************************************************************************
* scsi_read
*/
#define SCSI_MAX_READ_BLK 0xFFFF /* almost the maximum amount of the scsi_ext command.. */
ulong scsi_read(int device, ulong blknr, ulong blkcnt, void *buffer)
{
ulong start,blks, buf_addr;
unsigned short smallblks;
ccb* pccb=(ccb *)&tempccb;
device&=0xff;
/* Setup device
*/
pccb->target=scsi_dev_desc[device].target;
pccb->lun=scsi_dev_desc[device].lun;
buf_addr=(unsigned long)buffer;
start=blknr;
blks=blkcnt;
debug ("\nscsi_read: dev %d startblk %lx, blccnt %lx buffer %lx\n",device,start,blks,(unsigned long)buffer);
do {
pccb->pdata=(unsigned char *)buf_addr;
if(blks>SCSI_MAX_READ_BLK) {
pccb->datalen=scsi_dev_desc[device].blksz * SCSI_MAX_READ_BLK;
smallblks=SCSI_MAX_READ_BLK;
scsi_setup_read_ext(pccb,start,smallblks);
start+=SCSI_MAX_READ_BLK;
blks-=SCSI_MAX_READ_BLK;
}
else {
pccb->datalen=scsi_dev_desc[device].blksz * blks;
smallblks=(unsigned short) blks;
scsi_setup_read_ext(pccb,start,smallblks);
start+=blks;
blks=0;
}
debug ("scsi_read_ext: startblk %lx, blccnt %x buffer %lx\n",start,smallblks,buf_addr);
if(scsi_exec(pccb)!=TRUE) {
scsi_print_error(pccb);
blkcnt-=blks;
break;
}
buf_addr+=pccb->datalen;
} while(blks!=0);
debug ("scsi_read_ext: end startblk %lx, blccnt %x buffer %lx\n",start,smallblks,buf_addr);
return(blkcnt);
}
/* copy src to dest, skipping leading and trailing blanks
* and null terminate the string
*/
void scsi_ident_cpy (unsigned char *dest, unsigned char *src, unsigned int len)
{
int start,end;
start=0;
while(start<len) {
if(src[start]!=' ')
break;
start++;
}
end=len-1;
while(end>start) {
if(src[end]!=' ')
break;
end--;
}
for( ; start<=end; start++) {
*dest++=src[start];
}
*dest='\0';
}
/* Trim trailing blanks, and NUL-terminate string
*/
void scsi_trim_trail (unsigned char *str, unsigned int len)
{
unsigned char *p = str + len - 1;
while (len-- > 0) {
*p-- = '\0';
if (*p != ' ') {
return;
}
}
}
/************************************************************************************
* Some setup (fill-in) routines
*/
void scsi_setup_test_unit_ready(ccb * pccb)
{
pccb->cmd[0]=SCSI_TST_U_RDY;
pccb->cmd[1]=pccb->lun<<5;
pccb->cmd[2]=0;
pccb->cmd[3]=0;
pccb->cmd[4]=0;
pccb->cmd[5]=0;
pccb->cmdlen=6;
pccb->msgout[0]=SCSI_IDENTIFY; /* NOT USED */
}
void scsi_setup_read_capacity(ccb * pccb)
{
pccb->cmd[0]=SCSI_RD_CAPAC;
pccb->cmd[1]=pccb->lun<<5;
pccb->cmd[2]=0;
pccb->cmd[3]=0;
pccb->cmd[4]=0;
pccb->cmd[5]=0;
pccb->cmd[6]=0;
pccb->cmd[7]=0;
pccb->cmd[8]=0;
pccb->cmd[9]=0;
pccb->cmdlen=10;
pccb->msgout[0]=SCSI_IDENTIFY; /* NOT USED */
}
void scsi_setup_read_ext(ccb * pccb, unsigned long start, unsigned short blocks)
{
pccb->cmd[0]=SCSI_READ10;
pccb->cmd[1]=pccb->lun<<5;
pccb->cmd[2]=((unsigned char) (start>>24))&0xff;
pccb->cmd[3]=((unsigned char) (start>>16))&0xff;
pccb->cmd[4]=((unsigned char) (start>>8))&0xff;
pccb->cmd[5]=((unsigned char) (start))&0xff;
pccb->cmd[6]=0;
pccb->cmd[7]=((unsigned char) (blocks>>8))&0xff;
pccb->cmd[8]=(unsigned char) blocks & 0xff;
pccb->cmd[6]=0;
pccb->cmdlen=10;
pccb->msgout[0]=SCSI_IDENTIFY; /* NOT USED */
debug ("scsi_setup_read_ext: cmd: %02X %02X startblk %02X%02X%02X%02X blccnt %02X%02X\n",
pccb->cmd[0],pccb->cmd[1],
pccb->cmd[2],pccb->cmd[3],pccb->cmd[4],pccb->cmd[5],
pccb->cmd[7],pccb->cmd[8]);
}
void scsi_setup_read6(ccb * pccb, unsigned long start, unsigned short blocks)
{
pccb->cmd[0]=SCSI_READ6;
pccb->cmd[1]=pccb->lun<<5 | (((unsigned char)(start>>16))&0x1f);
pccb->cmd[2]=((unsigned char) (start>>8))&0xff;
pccb->cmd[3]=((unsigned char) (start))&0xff;
pccb->cmd[4]=(unsigned char) blocks & 0xff;
pccb->cmd[5]=0;
pccb->cmdlen=6;
pccb->msgout[0]=SCSI_IDENTIFY; /* NOT USED */
debug ("scsi_setup_read6: cmd: %02X %02X startblk %02X%02X blccnt %02X\n",
pccb->cmd[0],pccb->cmd[1],
pccb->cmd[2],pccb->cmd[3],pccb->cmd[4]);
}
void scsi_setup_inquiry(ccb * pccb)
{
pccb->cmd[0]=SCSI_INQUIRY;
pccb->cmd[1]=pccb->lun<<5;
pccb->cmd[2]=0;
pccb->cmd[3]=0;
if(pccb->datalen>255)
pccb->cmd[4]=255;
else
pccb->cmd[4]=(unsigned char)pccb->datalen;
pccb->cmd[5]=0;
pccb->cmdlen=6;
pccb->msgout[0]=SCSI_IDENTIFY; /* NOT USED */
}
U_BOOT_CMD(
scsi, 5, 1, do_scsi,
"SCSI sub-system",
"reset - reset SCSI controller\n"
"scsi info - show available SCSI devices\n"
"scsi scan - (re-)scan SCSI bus\n"
"scsi device [dev] - show or set current device\n"
"scsi part [dev] - print partition table of one or all SCSI devices\n"
"scsi read addr blk# cnt - read `cnt' blocks starting at block `blk#'\n"
" to memory address `addr'"
);
U_BOOT_CMD(
scsiboot, 3, 1, do_scsiboot,
"boot from SCSI device",
"loadAddr dev:part"
);
|
1001-study-uboot
|
common/cmd_scsi.c
|
C
|
gpl3
| 16,745
|
/*
* (C) Copyright 2001
* Denis Peter, MPL AG, d.peter@mpl.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
*
*/
/*
* Floppy Disk support
*/
#include <common.h>
#include <config.h>
#include <command.h>
#include <image.h>
#undef FDC_DEBUG
#ifdef FDC_DEBUG
#define PRINTF(fmt,args...) printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
/*#if defined(CONFIG_CMD_DATE) */
/*#include <rtc.h> */
/*#endif */
typedef struct {
int flags; /* connected drives ect */
unsigned long blnr; /* Logical block nr */
uchar drive; /* drive no */
uchar cmdlen; /* cmd length */
uchar cmd[16]; /* cmd desc */
uchar dma; /* if > 0 dma enabled */
uchar result[11]; /* status information */
uchar resultlen; /* lenght of result */
} FDC_COMMAND_STRUCT;
/* flags: only the lower 8bit used:
* bit 0 if set drive 0 is present
* bit 1 if set drive 1 is present
* bit 2 if set drive 2 is present
* bit 3 if set drive 3 is present
* bit 4 if set disk in drive 0 is inserted
* bit 5 if set disk in drive 1 is inserted
* bit 6 if set disk in drive 2 is inserted
* bit 7 if set disk in drive 4 is inserted
*/
/* cmd indexes */
#define COMMAND 0
#define DRIVE 1
#define CONFIG0 1
#define SPEC_HUTSRT 1
#define TRACK 2
#define CONFIG1 2
#define SPEC_HLT 2
#define HEAD 3
#define CONFIG2 3
#define SECTOR 4
#define SECTOR_SIZE 5
#define LAST_TRACK 6
#define GAP 7
#define DTL 8
/* result indexes */
#define STATUS_0 0
#define STATUS_PCN 1
#define STATUS_1 1
#define STATUS_2 2
#define STATUS_TRACK 3
#define STATUS_HEAD 4
#define STATUS_SECT 5
#define STATUS_SECT_SIZE 6
/* Register addresses */
#define FDC_BASE 0x3F0
#define FDC_SRA FDC_BASE + 0 /* Status Register A */
#define FDC_SRB FDC_BASE + 1 /* Status Register B */
#define FDC_DOR FDC_BASE + 2 /* Digital Output Register */
#define FDC_TDR FDC_BASE + 3 /* Tape Drive Register */
#define FDC_DSR FDC_BASE + 4 /* Data rate Register */
#define FDC_MSR FDC_BASE + 4 /* Main Status Register */
#define FDC_FIFO FDC_BASE + 5 /* FIFO */
#define FDC_DIR FDC_BASE + 6 /* Digital Input Register */
#define FDC_CCR FDC_BASE + 7 /* Configuration Control */
/* Commands */
#define FDC_CMD_SENSE_INT 0x08
#define FDC_CMD_CONFIGURE 0x13
#define FDC_CMD_SPECIFY 0x03
#define FDC_CMD_RECALIBRATE 0x07
#define FDC_CMD_READ 0x06
#define FDC_CMD_READ_TRACK 0x02
#define FDC_CMD_READ_ID 0x0A
#define FDC_CMD_DUMP_REG 0x0E
#define FDC_CMD_SEEK 0x0F
#define FDC_CMD_SENSE_INT_LEN 0x01
#define FDC_CMD_CONFIGURE_LEN 0x04
#define FDC_CMD_SPECIFY_LEN 0x03
#define FDC_CMD_RECALIBRATE_LEN 0x02
#define FDC_CMD_READ_LEN 0x09
#define FDC_CMD_READ_TRACK_LEN 0x09
#define FDC_CMD_READ_ID_LEN 0x02
#define FDC_CMD_DUMP_REG_LEN 0x01
#define FDC_CMD_SEEK_LEN 0x03
#define FDC_FIFO_THR 0x0C
#define FDC_FIFO_DIS 0x00
#define FDC_IMPLIED_SEEK 0x01
#define FDC_POLL_DIS 0x00
#define FDC_PRE_TRK 0x00
#define FDC_CONFIGURE FDC_FIFO_THR | (FDC_POLL_DIS<<4) | (FDC_FIFO_DIS<<5) | (FDC_IMPLIED_SEEK << 6)
#define FDC_MFM_MODE 0x01 /* MFM enable */
#define FDC_SKIP_MODE 0x00 /* skip enable */
#define FDC_TIME_OUT 100000 /* time out */
#define FDC_RW_RETRIES 3 /* read write retries */
#define FDC_CAL_RETRIES 3 /* calibration and seek retries */
/* Disk structure */
typedef struct {
unsigned int size; /* nr of sectors total */
unsigned int sect; /* sectors per track */
unsigned int head; /* nr of heads */
unsigned int track; /* nr of tracks */
unsigned int stretch; /* !=0 means double track steps */
unsigned char gap; /* gap1 size */
unsigned char rate; /* data rate. |= 0x40 for perpendicular */
unsigned char spec1; /* stepping rate, head unload time */
unsigned char fmt_gap;/* gap2 size */
unsigned char hlt; /* head load time */
unsigned char sect_code;/* Sector Size code */
const char * name; /* used only for predefined formats */
} FD_GEO_STRUCT;
/* supported Floppy types (currently only one) */
const static FD_GEO_STRUCT floppy_type[2] = {
{ 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,16,2,"H1440" }, /* 7 1.44MB 3.5" */
{ 0, 0,0, 0,0,0x00,0x00,0x00,0x00, 0,0,NULL }, /* end of table */
};
static FDC_COMMAND_STRUCT cmd; /* global command struct */
/* If the boot drive number is undefined, we assume it's drive 0 */
#ifndef CONFIG_SYS_FDC_DRIVE_NUMBER
#define CONFIG_SYS_FDC_DRIVE_NUMBER 0
#endif
/* Hardware access */
#ifndef CONFIG_SYS_ISA_IO_STRIDE
#define CONFIG_SYS_ISA_IO_STRIDE 1
#endif
#ifndef CONFIG_SYS_ISA_IO_OFFSET
#define CONFIG_SYS_ISA_IO_OFFSET 0
#endif
/* Supporting Functions */
/* reads a Register of the FDC */
unsigned char read_fdc_reg(unsigned int addr)
{
volatile unsigned char *val =
(volatile unsigned char *)(CONFIG_SYS_ISA_IO_BASE_ADDRESS +
(addr * CONFIG_SYS_ISA_IO_STRIDE) +
CONFIG_SYS_ISA_IO_OFFSET);
return val [0];
}
/* writes a Register of the FDC */
void write_fdc_reg(unsigned int addr, unsigned char val)
{
volatile unsigned char *tmp =
(volatile unsigned char *)(CONFIG_SYS_ISA_IO_BASE_ADDRESS +
(addr * CONFIG_SYS_ISA_IO_STRIDE) +
CONFIG_SYS_ISA_IO_OFFSET);
tmp[0]=val;
}
/* waits for an interrupt (polling) */
int wait_for_fdc_int(void)
{
unsigned long timeout;
timeout = FDC_TIME_OUT;
while((read_fdc_reg(FDC_SRA)&0x80)==0) {
timeout--;
udelay(10);
if(timeout==0) /* timeout occured */
return FALSE;
}
return TRUE;
}
/* reads a byte from the FIFO of the FDC and checks direction and RQM bit
of the MSR. returns -1 if timeout, or byte if ok */
int read_fdc_byte(void)
{
unsigned long timeout;
timeout = FDC_TIME_OUT;
while((read_fdc_reg(FDC_MSR)&0xC0)!=0xC0) {
/* direction out and ready */
udelay(10);
timeout--;
if(timeout==0) /* timeout occured */
return -1;
}
return read_fdc_reg(FDC_FIFO);
}
/* if the direction of the FIFO is wrong, this routine is used to
empty the FIFO. Should _not_ be used */
int fdc_need_more_output(void)
{
unsigned char c;
while((read_fdc_reg(FDC_MSR)&0xC0)==0xC0) {
c=(unsigned char)read_fdc_byte();
printf("Error: more output: %x\n",c);
}
return TRUE;
}
/* writes a byte to the FIFO of the FDC and checks direction and RQM bit
of the MSR */
int write_fdc_byte(unsigned char val)
{
unsigned long timeout;
timeout = FDC_TIME_OUT;
while((read_fdc_reg(FDC_MSR)&0xC0)!=0x80) {
/* direction in and ready for byte */
timeout--;
udelay(10);
fdc_need_more_output();
if(timeout==0) /* timeout occured */
return FALSE;
}
write_fdc_reg(FDC_FIFO,val);
return TRUE;
}
/* sets up all FDC commands and issues it to the FDC. If
the command causes direct results (no Execution Phase)
the result is be read as well. */
int fdc_issue_cmd(FDC_COMMAND_STRUCT *pCMD,FD_GEO_STRUCT *pFG)
{
int i;
unsigned long head,track,sect,timeout;
track = pCMD->blnr / (pFG->sect * pFG->head); /* track nr */
sect = pCMD->blnr % (pFG->sect * pFG->head); /* remaining blocks */
head = sect / pFG->sect; /* head nr */
sect = sect % pFG->sect; /* remaining blocks */
sect++; /* sectors are 1 based */
PRINTF("Cmd 0x%02x Track %ld, Head %ld, Sector %ld, Drive %d (blnr %ld)\n",
pCMD->cmd[0],track,head,sect,pCMD->drive,pCMD->blnr);
if(head|=0) { /* max heads = 2 */
pCMD->cmd[DRIVE]=pCMD->drive | 0x04; /* head 1 */
pCMD->cmd[HEAD]=(unsigned char) head; /* head register */
}
else {
pCMD->cmd[DRIVE]=pCMD->drive; /* head 0 */
pCMD->cmd[HEAD]=(unsigned char) head; /* head register */
}
pCMD->cmd[TRACK]=(unsigned char) track; /* track */
switch (pCMD->cmd[COMMAND]) {
case FDC_CMD_READ:
pCMD->cmd[SECTOR]=(unsigned char) sect; /* sector */
pCMD->cmd[SECTOR_SIZE]=pFG->sect_code; /* sector size code */
pCMD->cmd[LAST_TRACK]=pFG->sect; /* End of track */
pCMD->cmd[GAP]=pFG->gap; /* gap */
pCMD->cmd[DTL]=0xFF; /* DTL */
pCMD->cmdlen=FDC_CMD_READ_LEN;
pCMD->cmd[COMMAND]|=(FDC_MFM_MODE<<6); /* set MFM bit */
pCMD->cmd[COMMAND]|=(FDC_SKIP_MODE<<5); /* set Skip bit */
pCMD->resultlen=0; /* result only after execution */
break;
case FDC_CMD_SEEK:
pCMD->cmdlen=FDC_CMD_SEEK_LEN;
pCMD->resultlen=0; /* no result */
break;
case FDC_CMD_CONFIGURE:
pCMD->cmd[CONFIG0]=0;
pCMD->cmd[CONFIG1]=FDC_CONFIGURE; /* FIFO Threshold, Poll, Enable FIFO */
pCMD->cmd[CONFIG2]=FDC_PRE_TRK; /* Precompensation Track */
pCMD->cmdlen=FDC_CMD_CONFIGURE_LEN;
pCMD->resultlen=0; /* no result */
break;
case FDC_CMD_SPECIFY:
pCMD->cmd[SPEC_HUTSRT]=pFG->spec1;
pCMD->cmd[SPEC_HLT]=(pFG->hlt)<<1; /* head load time */
if(pCMD->dma==0)
pCMD->cmd[SPEC_HLT]|=0x1; /* no dma */
pCMD->cmdlen=FDC_CMD_SPECIFY_LEN;
pCMD->resultlen=0; /* no result */
break;
case FDC_CMD_DUMP_REG:
pCMD->cmdlen=FDC_CMD_DUMP_REG_LEN;
pCMD->resultlen=10; /* 10 byte result */
break;
case FDC_CMD_READ_ID:
pCMD->cmd[COMMAND]|=(FDC_MFM_MODE<<6); /* set MFM bit */
pCMD->cmdlen=FDC_CMD_READ_ID_LEN;
pCMD->resultlen=7; /* 7 byte result */
break;
case FDC_CMD_RECALIBRATE:
pCMD->cmd[DRIVE]&=0x03; /* don't set the head bit */
pCMD->cmdlen=FDC_CMD_RECALIBRATE_LEN;
pCMD->resultlen=0; /* no result */
break;
break;
case FDC_CMD_SENSE_INT:
pCMD->cmdlen=FDC_CMD_SENSE_INT_LEN;
pCMD->resultlen=2;
break;
}
for(i=0;i<pCMD->cmdlen;i++) {
/* PRINTF("write cmd%d = 0x%02X\n",i,pCMD->cmd[i]); */
if(write_fdc_byte(pCMD->cmd[i])==FALSE) {
PRINTF("Error: timeout while issue cmd%d\n",i);
return FALSE;
}
}
timeout=FDC_TIME_OUT;
for(i=0;i<pCMD->resultlen;i++) {
while((read_fdc_reg(FDC_MSR)&0xC0)!=0xC0) {
timeout--;
if(timeout==0) {
PRINTF(" timeout while reading result%d MSR=0x%02X\n",i,read_fdc_reg(FDC_MSR));
return FALSE;
}
}
pCMD->result[i]=(unsigned char)read_fdc_byte();
}
return TRUE;
}
/* selects the drive assigned in the cmd structur and
switches on the Motor */
void select_fdc_drive(FDC_COMMAND_STRUCT *pCMD)
{
unsigned char val;
val=(1<<(4+pCMD->drive))|pCMD->drive|0xC; /* set reset, dma gate and motor bits */
if((read_fdc_reg(FDC_DOR)&val)!=val) {
write_fdc_reg(FDC_DOR,val);
for(val=0;val<255;val++)
udelay(500); /* wait some time to start motor */
}
}
/* switches off the Motor of the specified drive */
void stop_fdc_drive(FDC_COMMAND_STRUCT *pCMD)
{
unsigned char val;
val=(1<<(4+pCMD->drive))|pCMD->drive; /* sets motor bits */
write_fdc_reg(FDC_DOR,(read_fdc_reg(FDC_DOR)&~val));
}
/* issues a recalibrate command, waits for interrupt and
* issues a sense_interrupt */
int fdc_recalibrate(FDC_COMMAND_STRUCT *pCMD,FD_GEO_STRUCT *pFG)
{
pCMD->cmd[COMMAND]=FDC_CMD_RECALIBRATE;
if(fdc_issue_cmd(pCMD,pFG)==FALSE)
return FALSE;
while(wait_for_fdc_int()!=TRUE);
pCMD->cmd[COMMAND]=FDC_CMD_SENSE_INT;
return(fdc_issue_cmd(pCMD,pFG));
}
/* issues a recalibrate command, waits for interrupt and
* issues a sense_interrupt */
int fdc_seek(FDC_COMMAND_STRUCT *pCMD,FD_GEO_STRUCT *pFG)
{
pCMD->cmd[COMMAND]=FDC_CMD_SEEK;
if(fdc_issue_cmd(pCMD,pFG)==FALSE)
return FALSE;
while(wait_for_fdc_int()!=TRUE);
pCMD->cmd[COMMAND]=FDC_CMD_SENSE_INT;
return(fdc_issue_cmd(pCMD,pFG));
}
/* terminates current command, by not servicing the FIFO
* waits for interrupt and fills in the result bytes */
int fdc_terminate(FDC_COMMAND_STRUCT *pCMD)
{
int i;
for(i=0;i<100;i++)
udelay(500); /* wait 500usec for fifo overrun */
while((read_fdc_reg(FDC_SRA)&0x80)==0x00); /* wait as long as no int has occured */
for(i=0;i<7;i++) {
pCMD->result[i]=(unsigned char)read_fdc_byte();
}
return TRUE;
}
/* reads data from FDC, seek commands are issued automatic */
int fdc_read_data(unsigned char *buffer, unsigned long blocks,FDC_COMMAND_STRUCT *pCMD, FD_GEO_STRUCT *pFG)
{
/* first seek to start address */
unsigned long len,readblk,i,timeout,ii,offset;
unsigned char c,retriesrw,retriescal;
unsigned char *bufferw; /* working buffer */
int sect_size;
int flags;
flags=disable_interrupts(); /* switch off all Interrupts */
select_fdc_drive(pCMD); /* switch on drive */
sect_size=0x080<<pFG->sect_code;
retriesrw=0;
retriescal=0;
offset=0;
if(fdc_seek(pCMD,pFG)==FALSE) {
stop_fdc_drive(pCMD);
if (flags)
enable_interrupts();
return FALSE;
}
if((pCMD->result[STATUS_0]&0x20)!=0x20) {
printf("Seek error Status: %02X\n",pCMD->result[STATUS_0]);
stop_fdc_drive(pCMD);
if (flags)
enable_interrupts();
return FALSE;
}
/* now determine the next seek point */
/* lastblk=pCMD->blnr + blocks; */
/* readblk=(pFG->head*pFG->sect)-(pCMD->blnr%(pFG->head*pFG->sect)); */
readblk=pFG->sect-(pCMD->blnr%pFG->sect);
PRINTF("1st nr of block possible read %ld start %ld\n",readblk,pCMD->blnr);
if(readblk>blocks) /* is end within 1st track */
readblk=blocks; /* yes, correct it */
PRINTF("we read %ld blocks start %ld\n",readblk,pCMD->blnr);
bufferw = &buffer[0]; /* setup working buffer */
do {
retryrw:
len=sect_size * readblk;
pCMD->cmd[COMMAND]=FDC_CMD_READ;
if(fdc_issue_cmd(pCMD,pFG)==FALSE) {
stop_fdc_drive(pCMD);
if (flags)
enable_interrupts();
return FALSE;
}
for (i=0;i<len;i++) {
timeout=FDC_TIME_OUT;
do {
c=read_fdc_reg(FDC_MSR);
if((c&0xC0)==0xC0) {
bufferw[i]=read_fdc_reg(FDC_FIFO);
break;
}
if((c&0xC0)==0x80) { /* output */
PRINTF("Transfer error transfered: at %ld, MSR=%02X\n",i,c);
if(i>6) {
for(ii=0;ii<7;ii++) {
pCMD->result[ii]=bufferw[(i-7+ii)];
} /* for */
}
if(retriesrw++>FDC_RW_RETRIES) {
if (retriescal++>FDC_CAL_RETRIES) {
stop_fdc_drive(pCMD);
if (flags)
enable_interrupts();
return FALSE;
}
else {
PRINTF(" trying to recalibrate Try %d\n",retriescal);
if(fdc_recalibrate(pCMD,pFG)==FALSE) {
stop_fdc_drive(pCMD);
if (flags)
enable_interrupts();
return FALSE;
}
retriesrw=0;
goto retrycal;
} /* else >FDC_CAL_RETRIES */
}
else {
PRINTF("Read retry %d\n",retriesrw);
goto retryrw;
} /* else >FDC_RW_RETRIES */
}/* if output */
timeout--;
}while(TRUE);
} /* for len */
/* the last sector of a track or all data has been read,
* we need to get the results */
fdc_terminate(pCMD);
offset+=(sect_size*readblk); /* set up buffer pointer */
bufferw = &buffer[offset];
pCMD->blnr+=readblk; /* update current block nr */
blocks-=readblk; /* update blocks */
if(blocks==0)
break; /* we are finish */
/* setup new read blocks */
/* readblk=pFG->head*pFG->sect; */
readblk=pFG->sect;
if(readblk>blocks)
readblk=blocks;
retrycal:
/* a seek is necessary */
if(fdc_seek(pCMD,pFG)==FALSE) {
stop_fdc_drive(pCMD);
if (flags)
enable_interrupts();
return FALSE;
}
if((pCMD->result[STATUS_0]&0x20)!=0x20) {
PRINTF("Seek error Status: %02X\n",pCMD->result[STATUS_0]);
stop_fdc_drive(pCMD);
return FALSE;
}
}while(TRUE); /* start over */
stop_fdc_drive(pCMD); /* switch off drive */
if (flags)
enable_interrupts();
return TRUE;
}
/* Scan all drives and check if drive is present and disk is inserted */
int fdc_check_drive(FDC_COMMAND_STRUCT *pCMD, FD_GEO_STRUCT *pFG)
{
int i,drives,state;
/* OK procedure of data book is satisfied.
* trying to get some information over the drives */
state=0; /* no drives, no disks */
for(drives=0;drives<4;drives++) {
pCMD->drive=drives;
select_fdc_drive(pCMD);
pCMD->blnr=0; /* set to the 1st block */
if(fdc_recalibrate(pCMD,pFG)==FALSE)
continue;
if((pCMD->result[STATUS_0]&0x10)==0x10)
continue;
/* ok drive connected check for disk */
state|=(1<<drives);
pCMD->blnr=pFG->size; /* set to the last block */
if(fdc_seek(pCMD,pFG)==FALSE)
continue;
pCMD->blnr=0; /* set to the 1st block */
if(fdc_recalibrate(pCMD,pFG)==FALSE)
continue;
pCMD->cmd[COMMAND]=FDC_CMD_READ_ID;
if(fdc_issue_cmd(pCMD,pFG)==FALSE)
continue;
state|=(0x10<<drives);
}
stop_fdc_drive(pCMD);
for(i=0;i<4;i++) {
PRINTF("Floppy Drive %d %sconnected %sDisk inserted %s\n",i,
((state&(1<<i))==(1<<i)) ? "":"not ",
((state&(0x10<<i))==(0x10<<i)) ? "":"no ",
((state&(0x10<<i))==(0x10<<i)) ? pFG->name : "");
}
pCMD->flags=state;
return TRUE;
}
/**************************************************************************
* int fdc_setup
* setup the fdc according the datasheet
* assuming in PS2 Mode
*/
int fdc_setup(int drive, FDC_COMMAND_STRUCT *pCMD, FD_GEO_STRUCT *pFG)
{
int i;
#ifdef CONFIG_SYS_FDC_HW_INIT
fdc_hw_init ();
#endif
/* first, we reset the FDC via the DOR */
write_fdc_reg(FDC_DOR,0x00);
for(i=0; i<255; i++) /* then we wait some time */
udelay(500);
/* then, we clear the reset in the DOR */
pCMD->drive=drive;
select_fdc_drive(pCMD);
/* initialize the CCR */
write_fdc_reg(FDC_CCR,pFG->rate);
/* then initialize the DSR */
write_fdc_reg(FDC_DSR,pFG->rate);
if(wait_for_fdc_int()==FALSE) {
PRINTF("Time Out after writing CCR\n");
return FALSE;
}
/* now issue sense Interrupt and status command
* assuming only one drive present (drive 0) */
pCMD->dma=0; /* we don't use any dma at all */
for(i=0;i<4;i++) {
/* issue sense interrupt for all 4 possible drives */
pCMD->cmd[COMMAND]=FDC_CMD_SENSE_INT;
if(fdc_issue_cmd(pCMD,pFG)==FALSE) {
PRINTF("Sense Interrupt for drive %d failed\n",i);
}
}
/* issue the configure command */
pCMD->drive=drive;
select_fdc_drive(pCMD);
pCMD->cmd[COMMAND]=FDC_CMD_CONFIGURE;
if(fdc_issue_cmd(pCMD,pFG)==FALSE) {
PRINTF(" configure timeout\n");
stop_fdc_drive(pCMD);
return FALSE;
}
/* issue specify command */
pCMD->cmd[COMMAND]=FDC_CMD_SPECIFY;
if(fdc_issue_cmd(pCMD,pFG)==FALSE) {
PRINTF(" specify timeout\n");
stop_fdc_drive(pCMD);
return FALSE;
}
/* then, we clear the reset in the DOR */
/* fdc_check_drive(pCMD,pFG); */
/* write_fdc_reg(FDC_DOR,0x04); */
return TRUE;
}
#if defined(CONFIG_CMD_FDOS)
/* Low level functions for the Floppy-DOS layer */
/**************************************************************************
* int fdc_fdos_init
* initialize the FDC layer
*
*/
int fdc_fdos_init (int drive)
{
FD_GEO_STRUCT *pFG = (FD_GEO_STRUCT *)floppy_type;
FDC_COMMAND_STRUCT *pCMD = &cmd;
/* setup FDC and scan for drives */
if(fdc_setup(drive,pCMD,pFG)==FALSE) {
printf("\n** Error in setup FDC **\n");
return FALSE;
}
if(fdc_check_drive(pCMD,pFG)==FALSE) {
printf("\n** Error in check_drives **\n");
return FALSE;
}
if((pCMD->flags&(1<<drive))==0) {
/* drive not available */
printf("\n** Drive %d not available **\n",drive);
return FALSE;
}
if((pCMD->flags&(0x10<<drive))==0) {
/* no disk inserted */
printf("\n** No disk inserted in drive %d **\n",drive);
return FALSE;
}
/* ok, we have a valid source */
pCMD->drive=drive;
/* read first block */
pCMD->blnr=0;
return TRUE;
}
/**************************************************************************
* int fdc_fdos_seek
* parameter is a block number
*/
int fdc_fdos_seek (int where)
{
FD_GEO_STRUCT *pFG = (FD_GEO_STRUCT *)floppy_type;
FDC_COMMAND_STRUCT *pCMD = &cmd;
pCMD -> blnr = where ;
return (fdc_seek (pCMD, pFG));
}
/**************************************************************************
* int fdc_fdos_read
* the length is in block number
*/
int fdc_fdos_read (void *buffer, int len)
{
FD_GEO_STRUCT *pFG = (FD_GEO_STRUCT *)floppy_type;
FDC_COMMAND_STRUCT *pCMD = &cmd;
return (fdc_read_data (buffer, len, pCMD, pFG));
}
#endif
#if defined(CONFIG_CMD_FDC)
/****************************************************************************
* main routine do_fdcboot
*/
int do_fdcboot (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
FD_GEO_STRUCT *pFG = (FD_GEO_STRUCT *)floppy_type;
FDC_COMMAND_STRUCT *pCMD = &cmd;
unsigned long addr,imsize;
image_header_t *hdr; /* used for fdc boot */
unsigned char boot_drive;
int i,nrofblk;
#if defined(CONFIG_FIT)
const void *fit_hdr = NULL;
#endif
switch (argc) {
case 1:
addr = CONFIG_SYS_LOAD_ADDR;
boot_drive=CONFIG_SYS_FDC_DRIVE_NUMBER;
break;
case 2:
addr = simple_strtoul(argv[1], NULL, 16);
boot_drive=CONFIG_SYS_FDC_DRIVE_NUMBER;
break;
case 3:
addr = simple_strtoul(argv[1], NULL, 16);
boot_drive=simple_strtoul(argv[2], NULL, 10);
break;
default:
return cmd_usage(cmdtp);
}
/* setup FDC and scan for drives */
if(fdc_setup(boot_drive,pCMD,pFG)==FALSE) {
printf("\n** Error in setup FDC **\n");
return 1;
}
if(fdc_check_drive(pCMD,pFG)==FALSE) {
printf("\n** Error in check_drives **\n");
return 1;
}
if((pCMD->flags&(1<<boot_drive))==0) {
/* drive not available */
printf("\n** Drive %d not availabe **\n",boot_drive);
return 1;
}
if((pCMD->flags&(0x10<<boot_drive))==0) {
/* no disk inserted */
printf("\n** No disk inserted in drive %d **\n",boot_drive);
return 1;
}
/* ok, we have a valid source */
pCMD->drive=boot_drive;
/* read first block */
pCMD->blnr=0;
if(fdc_read_data((unsigned char *)addr,1,pCMD,pFG)==FALSE) {
printf("\nRead error:");
for(i=0;i<7;i++)
printf("result%d: 0x%02X\n",i,pCMD->result[i]);
return 1;
}
switch (genimg_get_format ((void *)addr)) {
case IMAGE_FORMAT_LEGACY:
hdr = (image_header_t *)addr;
image_print_contents (hdr);
imsize = image_get_image_size (hdr);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
fit_hdr = (const void *)addr;
puts ("Fit image detected...\n");
imsize = fit_get_size (fit_hdr);
break;
#endif
default:
puts ("** Unknown image type\n");
return 1;
}
nrofblk=imsize/512;
if((imsize%512)>0)
nrofblk++;
printf("Loading %ld Bytes (%d blocks) at 0x%08lx..\n",imsize,nrofblk,addr);
pCMD->blnr=0;
if(fdc_read_data((unsigned char *)addr,nrofblk,pCMD,pFG)==FALSE) {
/* read image block */
printf("\nRead error:");
for(i=0;i<7;i++)
printf("result%d: 0x%02X\n",i,pCMD->result[i]);
return 1;
}
printf("OK %ld Bytes loaded.\n",imsize);
flush_cache (addr, imsize);
#if defined(CONFIG_FIT)
/* This cannot be done earlier, we need complete FIT image in RAM first */
if (genimg_get_format ((void *)addr) == IMAGE_FORMAT_FIT) {
if (!fit_check_format (fit_hdr)) {
puts ("** Bad FIT image format\n");
return 1;
}
fit_print_contents (fit_hdr);
}
#endif
/* Loading ok, update default load address */
load_addr = addr;
return bootm_maybe_autostart(cmdtp, argv[0]);
}
U_BOOT_CMD(
fdcboot, 3, 1, do_fdcboot,
"boot from floppy device",
"loadAddr drive"
);
#endif
|
1001-study-uboot
|
common/cmd_fdc.c
|
C
|
gpl3
| 23,278
|
/*
* Copyright 2010-2011 Calxeda, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope 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 <http://www.gnu.org/licenses/>.
*/
#include <common.h>
#include <command.h>
#include <malloc.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <errno.h>
#include <linux/list.h>
#include "menu.h"
#define MAX_TFTP_PATH_LEN 127
/*
* Like getenv, but prints an error if envvar isn't defined in the
* environment. It always returns what getenv does, so it can be used in
* place of getenv without changing error handling otherwise.
*/
static char *from_env(char *envvar)
{
char *ret;
ret = getenv(envvar);
if (!ret)
printf("missing environment variable: %s\n", envvar);
return ret;
}
/*
* Convert an ethaddr from the environment to the format used by pxelinux
* filenames based on mac addresses. Convert's ':' to '-', and adds "01-" to
* the beginning of the ethernet address to indicate a hardware type of
* Ethernet. Also converts uppercase hex characters into lowercase, to match
* pxelinux's behavior.
*
* Returns 1 for success, -ENOENT if 'ethaddr' is undefined in the
* environment, or some other value < 0 on error.
*/
static int format_mac_pxe(char *outbuf, size_t outbuf_len)
{
size_t ethaddr_len;
char *p, *ethaddr;
ethaddr = from_env("ethaddr");
if (!ethaddr)
return -ENOENT;
ethaddr_len = strlen(ethaddr);
/*
* ethaddr_len + 4 gives room for "01-", ethaddr, and a NUL byte at
* the end.
*/
if (outbuf_len < ethaddr_len + 4) {
printf("outbuf is too small (%d < %d)\n",
outbuf_len, ethaddr_len + 4);
return -EINVAL;
}
strcpy(outbuf, "01-");
for (p = outbuf + 3; *ethaddr; ethaddr++, p++) {
if (*ethaddr == ':')
*p = '-';
else
*p = tolower(*ethaddr);
}
*p = '\0';
return 1;
}
/*
* Returns the directory the file specified in the bootfile env variable is
* in. If bootfile isn't defined in the environment, return NULL, which should
* be interpreted as "don't prepend anything to paths".
*/
static int get_bootfile_path(char *bootfile_path, size_t bootfile_path_size)
{
char *bootfile, *last_slash;
size_t path_len;
bootfile = from_env("bootfile");
if (!bootfile) {
bootfile_path[0] = '\0';
return 1;
}
last_slash = strrchr(bootfile, '/');
if (last_slash == NULL) {
bootfile_path[0] = '\0';
return 1;
}
path_len = (last_slash - bootfile) + 1;
if (bootfile_path_size < path_len) {
printf("bootfile_path too small. (%d < %d)\n",
bootfile_path_size, path_len);
return -1;
}
strncpy(bootfile_path, bootfile, path_len);
bootfile_path[path_len] = '\0';
return 1;
}
/*
* As in pxelinux, paths to files referenced from files we retrieve are
* relative to the location of bootfile. get_relfile takes such a path and
* joins it with the bootfile path to get the full path to the target file. If
* the bootfile path is NULL, we use file_path as is.
*
* Returns 1 for success, or < 0 on error.
*/
static int get_relfile(char *file_path, void *file_addr)
{
size_t path_len;
char relfile[MAX_TFTP_PATH_LEN+1];
char addr_buf[10];
char *tftp_argv[] = {"tftp", NULL, NULL, NULL};
int err;
err = get_bootfile_path(relfile, sizeof(relfile));
if (err < 0)
return err;
path_len = strlen(file_path);
path_len += strlen(relfile);
if (path_len > MAX_TFTP_PATH_LEN) {
printf("Base path too long (%s%s)\n",
relfile,
file_path);
return -ENAMETOOLONG;
}
strcat(relfile, file_path);
printf("Retrieving file: %s\n", relfile);
sprintf(addr_buf, "%p", file_addr);
tftp_argv[1] = addr_buf;
tftp_argv[2] = relfile;
if (do_tftpb(NULL, 0, 3, tftp_argv))
return -ENOENT;
return 1;
}
/*
* Retrieve the file at 'file_path' to the locate given by 'file_addr'. If
* 'bootfile' was specified in the environment, the path to bootfile will be
* prepended to 'file_path' and the resulting path will be used.
*
* Returns 1 on success, or < 0 for error.
*/
static int get_pxe_file(char *file_path, void *file_addr)
{
unsigned long config_file_size;
char *tftp_filesize;
int err;
err = get_relfile(file_path, file_addr);
if (err < 0)
return err;
/*
* the file comes without a NUL byte at the end, so find out its size
* and add the NUL byte.
*/
tftp_filesize = from_env("filesize");
if (!tftp_filesize)
return -ENOENT;
if (strict_strtoul(tftp_filesize, 16, &config_file_size) < 0)
return -EINVAL;
*(char *)(file_addr + config_file_size) = '\0';
return 1;
}
#define PXELINUX_DIR "pxelinux.cfg/"
/*
* Retrieves a file in the 'pxelinux.cfg' folder. Since this uses get_pxe_file
* to do the hard work, the location of the 'pxelinux.cfg' folder is generated
* from the bootfile path, as described above.
*
* Returns 1 on success or < 0 on error.
*/
static int get_pxelinux_path(char *file, void *pxefile_addr_r)
{
size_t base_len = strlen(PXELINUX_DIR);
char path[MAX_TFTP_PATH_LEN+1];
if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
printf("path (%s%s) too long, skipping\n",
PXELINUX_DIR, file);
return -ENAMETOOLONG;
}
sprintf(path, PXELINUX_DIR "%s", file);
return get_pxe_file(path, pxefile_addr_r);
}
/*
* Looks for a pxe file with a name based on the pxeuuid environment variable.
*
* Returns 1 on success or < 0 on error.
*/
static int pxe_uuid_path(void *pxefile_addr_r)
{
char *uuid_str;
uuid_str = from_env("pxeuuid");
if (!uuid_str)
return -ENOENT;
return get_pxelinux_path(uuid_str, pxefile_addr_r);
}
/*
* Looks for a pxe file with a name based on the 'ethaddr' environment
* variable.
*
* Returns 1 on success or < 0 on error.
*/
static int pxe_mac_path(void *pxefile_addr_r)
{
char mac_str[21];
int err;
err = format_mac_pxe(mac_str, sizeof(mac_str));
if (err < 0)
return err;
return get_pxelinux_path(mac_str, pxefile_addr_r);
}
/*
* Looks for pxe files with names based on our IP address. See pxelinux
* documentation for details on what these file names look like. We match
* that exactly.
*
* Returns 1 on success or < 0 on error.
*/
static int pxe_ipaddr_paths(void *pxefile_addr_r)
{
char ip_addr[9];
int mask_pos, err;
sprintf(ip_addr, "%08X", ntohl(NetOurIP));
for (mask_pos = 7; mask_pos >= 0; mask_pos--) {
err = get_pxelinux_path(ip_addr, pxefile_addr_r);
if (err > 0)
return err;
ip_addr[mask_pos] = '\0';
}
return -ENOENT;
}
/*
* Entry point for the 'pxe get' command.
* This Follows pxelinux's rules to download a config file from a tftp server.
* The file is stored at the location given by the pxefile_addr_r environment
* variable, which must be set.
*
* UUID comes from pxeuuid env variable, if defined
* MAC addr comes from ethaddr env variable, if defined
* IP
*
* see http://syslinux.zytor.com/wiki/index.php/PXELINUX
*
* Returns 0 on success or 1 on error.
*/
static int
do_pxe_get(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *pxefile_addr_str;
void *pxefile_addr_r;
int err;
if (argc != 1)
return cmd_usage(cmdtp);
pxefile_addr_str = from_env("pxefile_addr_r");
if (!pxefile_addr_str)
return 1;
err = strict_strtoul(pxefile_addr_str, 16,
(unsigned long *)&pxefile_addr_r);
if (err < 0)
return 1;
/*
* Keep trying paths until we successfully get a file we're looking
* for.
*/
if (pxe_uuid_path(pxefile_addr_r) > 0
|| pxe_mac_path(pxefile_addr_r) > 0
|| pxe_ipaddr_paths(pxefile_addr_r) > 0
|| get_pxelinux_path("default", pxefile_addr_r) > 0) {
printf("Config file found\n");
return 0;
}
printf("Config file not found\n");
return 1;
}
/*
* Wrapper to make it easier to store the file at file_path in the location
* specified by envaddr_name. file_path will be joined to the bootfile path,
* if any is specified.
*
* Returns 1 on success or < 0 on error.
*/
static int get_relfile_envaddr(char *file_path, char *envaddr_name)
{
void *file_addr;
char *envaddr;
envaddr = from_env(envaddr_name);
if (!envaddr)
return -ENOENT;
if (strict_strtoul(envaddr, 16, (unsigned long *)&file_addr) < 0)
return -EINVAL;
return get_relfile(file_path, file_addr);
}
/*
* A note on the pxe file parser.
*
* We're parsing files that use syslinux grammar, which has a few quirks.
* String literals must be recognized based on context - there is no
* quoting or escaping support. There's also nothing to explicitly indicate
* when a label section completes. We deal with that by ending a label
* section whenever we see a line that doesn't include.
*
* As with the syslinux family, this same file format could be reused in the
* future for non pxe purposes. The only action it takes during parsing that
* would throw this off is handling of include files. It assumes we're using
* pxe, and does a tftp download of a file listed as an include file in the
* middle of the parsing operation. That could be handled by refactoring it to
* take a 'include file getter' function.
*/
/*
* Describes a single label given in a pxe file.
*
* Create these with the 'label_create' function given below.
*
* name - the name of the menu as given on the 'menu label' line.
* kernel - the path to the kernel file to use for this label.
* append - kernel command line to use when booting this label
* initrd - path to the initrd to use for this label.
* attempted - 0 if we haven't tried to boot this label, 1 if we have.
* localboot - 1 if this label specified 'localboot', 0 otherwise.
* list - lets these form a list, which a pxe_menu struct will hold.
*/
struct pxe_label {
char *name;
char *kernel;
char *append;
char *initrd;
int attempted;
int localboot;
struct list_head list;
};
/*
* Describes a pxe menu as given via pxe files.
*
* title - the name of the menu as given by a 'menu title' line.
* default_label - the name of the default label, if any.
* timeout - time in tenths of a second to wait for a user key-press before
* booting the default label.
* prompt - if 0, don't prompt for a choice unless the timeout period is
* interrupted. If 1, always prompt for a choice regardless of
* timeout.
* labels - a list of labels defined for the menu.
*/
struct pxe_menu {
char *title;
char *default_label;
int timeout;
int prompt;
struct list_head labels;
};
/*
* Allocates memory for and initializes a pxe_label. This uses malloc, so the
* result must be free()'d to reclaim the memory.
*
* Returns NULL if malloc fails.
*/
static struct pxe_label *label_create(void)
{
struct pxe_label *label;
label = malloc(sizeof(struct pxe_label));
if (!label)
return NULL;
memset(label, 0, sizeof(struct pxe_label));
return label;
}
/*
* Free the memory used by a pxe_label, including that used by its name,
* kernel, append and initrd members, if they're non NULL.
*
* So - be sure to only use dynamically allocated memory for the members of
* the pxe_label struct, unless you want to clean it up first. These are
* currently only created by the pxe file parsing code.
*/
static void label_destroy(struct pxe_label *label)
{
if (label->name)
free(label->name);
if (label->kernel)
free(label->kernel);
if (label->append)
free(label->append);
if (label->initrd)
free(label->initrd);
free(label);
}
/*
* Print a label and its string members if they're defined.
*
* This is passed as a callback to the menu code for displaying each
* menu entry.
*/
static void label_print(void *data)
{
struct pxe_label *label = data;
printf("Label: %s\n", label->name);
if (label->kernel)
printf("\tkernel: %s\n", label->kernel);
if (label->append)
printf("\tappend: %s\n", label->append);
if (label->initrd)
printf("\tinitrd: %s\n", label->initrd);
}
/*
* Boot a label that specified 'localboot'. This requires that the 'localcmd'
* environment variable is defined. Its contents will be executed as U-boot
* command. If the label specified an 'append' line, its contents will be
* used to overwrite the contents of the 'bootargs' environment variable prior
* to running 'localcmd'.
*
* Returns 1 on success or < 0 on error.
*/
static int label_localboot(struct pxe_label *label)
{
char *localcmd, *dupcmd;
int ret;
localcmd = from_env("localcmd");
if (!localcmd)
return -ENOENT;
/*
* dup the command to avoid any issues with the version of it existing
* in the environment changing during the execution of the command.
*/
dupcmd = strdup(localcmd);
if (!dupcmd)
return -ENOMEM;
if (label->append)
setenv("bootargs", label->append);
printf("running: %s\n", dupcmd);
ret = run_command2(dupcmd, 0);
free(dupcmd);
return ret;
}
/*
* Boot according to the contents of a pxe_label.
*
* If we can't boot for any reason, we return. A successful boot never
* returns.
*
* The kernel will be stored in the location given by the 'kernel_addr_r'
* environment variable.
*
* If the label specifies an initrd file, it will be stored in the location
* given by the 'ramdisk_addr_r' environment variable.
*
* If the label specifies an 'append' line, its contents will overwrite that
* of the 'bootargs' environment variable.
*/
static void label_boot(struct pxe_label *label)
{
char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
int bootm_argc = 3;
label_print(label);
label->attempted = 1;
if (label->localboot) {
label_localboot(label);
return;
}
if (label->kernel == NULL) {
printf("No kernel given, skipping %s\n",
label->name);
return;
}
if (label->initrd) {
if (get_relfile_envaddr(label->initrd, "ramdisk_addr_r") < 0) {
printf("Skipping %s for failure retrieving initrd\n",
label->name);
return;
}
bootm_argv[2] = getenv("ramdisk_addr_r");
} else {
bootm_argv[2] = "-";
}
if (get_relfile_envaddr(label->kernel, "kernel_addr_r") < 0) {
printf("Skipping %s for failure retrieving kernel\n",
label->name);
return;
}
if (label->append)
setenv("bootargs", label->append);
bootm_argv[1] = getenv("kernel_addr_r");
/*
* fdt usage is optional. If there is an fdt_addr specified, we will
* pass it along to bootm, and adjust argc appropriately.
*/
bootm_argv[3] = getenv("fdt_addr");
if (bootm_argv[3])
bootm_argc = 4;
do_bootm(NULL, 0, bootm_argc, bootm_argv);
}
/*
* Tokens for the pxe file parser.
*/
enum token_type {
T_EOL,
T_STRING,
T_EOF,
T_MENU,
T_TITLE,
T_TIMEOUT,
T_LABEL,
T_KERNEL,
T_APPEND,
T_INITRD,
T_LOCALBOOT,
T_DEFAULT,
T_PROMPT,
T_INCLUDE,
T_INVALID
};
/*
* A token - given by a value and a type.
*/
struct token {
char *val;
enum token_type type;
};
/*
* Keywords recognized.
*/
static const struct token keywords[] = {
{"menu", T_MENU},
{"title", T_TITLE},
{"timeout", T_TIMEOUT},
{"default", T_DEFAULT},
{"prompt", T_PROMPT},
{"label", T_LABEL},
{"kernel", T_KERNEL},
{"localboot", T_LOCALBOOT},
{"append", T_APPEND},
{"initrd", T_INITRD},
{"include", T_INCLUDE},
{NULL, T_INVALID}
};
/*
* Since pxe(linux) files don't have a token to identify the start of a
* literal, we have to keep track of when we're in a state where a literal is
* expected vs when we're in a state a keyword is expected.
*/
enum lex_state {
L_NORMAL = 0,
L_KEYWORD,
L_SLITERAL
};
/*
* get_string retrieves a string from *p and stores it as a token in
* *t.
*
* get_string used for scanning both string literals and keywords.
*
* Characters from *p are copied into t-val until a character equal to
* delim is found, or a NUL byte is reached. If delim has the special value of
* ' ', any whitespace character will be used as a delimiter.
*
* If lower is unequal to 0, uppercase characters will be converted to
* lowercase in the result. This is useful to make keywords case
* insensitive.
*
* The location of *p is updated to point to the first character after the end
* of the token - the ending delimiter.
*
* On success, the new value of t->val is returned. Memory for t->val is
* allocated using malloc and must be free()'d to reclaim it. If insufficient
* memory is available, NULL is returned.
*/
static char *get_string(char **p, struct token *t, char delim, int lower)
{
char *b, *e;
size_t len, i;
/*
* b and e both start at the beginning of the input stream.
*
* e is incremented until we find the ending delimiter, or a NUL byte
* is reached. Then, we take e - b to find the length of the token.
*/
b = e = *p;
while (*e) {
if ((delim == ' ' && isspace(*e)) || delim == *e)
break;
e++;
}
len = e - b;
/*
* Allocate memory to hold the string, and copy it in, converting
* characters to lowercase if lower is != 0.
*/
t->val = malloc(len + 1);
if (!t->val)
return NULL;
for (i = 0; i < len; i++, b++) {
if (lower)
t->val[i] = tolower(*b);
else
t->val[i] = *b;
}
t->val[len] = '\0';
/*
* Update *p so the caller knows where to continue scanning.
*/
*p = e;
t->type = T_STRING;
return t->val;
}
/*
* Populate a keyword token with a type and value.
*/
static void get_keyword(struct token *t)
{
int i;
for (i = 0; keywords[i].val; i++) {
if (!strcmp(t->val, keywords[i].val)) {
t->type = keywords[i].type;
break;
}
}
}
/*
* Get the next token. We have to keep track of which state we're in to know
* if we're looking to get a string literal or a keyword.
*
* *p is updated to point at the first character after the current token.
*/
static void get_token(char **p, struct token *t, enum lex_state state)
{
char *c = *p;
t->type = T_INVALID;
/* eat non EOL whitespace */
while (isblank(*c))
c++;
/*
* eat comments. note that string literals can't begin with #, but
* can contain a # after their first character.
*/
if (*c == '#') {
while (*c && *c != '\n')
c++;
}
if (*c == '\n') {
t->type = T_EOL;
c++;
} else if (*c == '\0') {
t->type = T_EOF;
c++;
} else if (state == L_SLITERAL) {
get_string(&c, t, '\n', 0);
} else if (state == L_KEYWORD) {
/*
* when we expect a keyword, we first get the next string
* token delimited by whitespace, and then check if it
* matches a keyword in our keyword list. if it does, it's
* converted to a keyword token of the appropriate type, and
* if not, it remains a string token.
*/
get_string(&c, t, ' ', 1);
get_keyword(t);
}
*p = c;
}
/*
* Increment *c until we get to the end of the current line, or EOF.
*/
static void eol_or_eof(char **c)
{
while (**c && **c != '\n')
(*c)++;
}
/*
* All of these parse_* functions share some common behavior.
*
* They finish with *c pointing after the token they parse, and return 1 on
* success, or < 0 on error.
*/
/*
* Parse a string literal and store a pointer it at *dst. String literals
* terminate at the end of the line.
*/
static int parse_sliteral(char **c, char **dst)
{
struct token t;
char *s = *c;
get_token(c, &t, L_SLITERAL);
if (t.type != T_STRING) {
printf("Expected string literal: %.*s\n", (int)(*c - s), s);
return -EINVAL;
}
*dst = t.val;
return 1;
}
/*
* Parse a base 10 (unsigned) integer and store it at *dst.
*/
static int parse_integer(char **c, int *dst)
{
struct token t;
char *s = *c;
unsigned long temp;
get_token(c, &t, L_SLITERAL);
if (t.type != T_STRING) {
printf("Expected string: %.*s\n", (int)(*c - s), s);
return -EINVAL;
}
if (strict_strtoul(t.val, 10, &temp) < 0) {
printf("Expected unsigned integer: %s\n", t.val);
return -EINVAL;
}
*dst = (int)temp;
free(t.val);
return 1;
}
static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level);
/*
* Parse an include statement, and retrieve and parse the file it mentions.
*
* base should point to a location where it's safe to store the file, and
* nest_level should indicate how many nested includes have occurred. For this
* include, nest_level has already been incremented and doesn't need to be
* incremented here.
*/
static int handle_include(char **c, char *base,
struct pxe_menu *cfg, int nest_level)
{
char *include_path;
char *s = *c;
int err;
err = parse_sliteral(c, &include_path);
if (err < 0) {
printf("Expected include path: %.*s\n",
(int)(*c - s), s);
return err;
}
err = get_pxe_file(include_path, base);
if (err < 0) {
printf("Couldn't retrieve %s\n", include_path);
return err;
}
return parse_pxefile_top(base, cfg, nest_level);
}
/*
* Parse lines that begin with 'menu'.
*
* b and nest are provided to handle the 'menu include' case.
*
* b should be the address where the file currently being parsed is stored.
*
* nest_level should be 1 when parsing the top level pxe file, 2 when parsing
* a file it includes, 3 when parsing a file included by that file, and so on.
*/
static int parse_menu(char **c, struct pxe_menu *cfg, char *b, int nest_level)
{
struct token t;
char *s = *c;
int err = 0;
get_token(c, &t, L_KEYWORD);
switch (t.type) {
case T_TITLE:
err = parse_sliteral(c, &cfg->title);
break;
case T_INCLUDE:
err = handle_include(c, b + strlen(b) + 1, cfg,
nest_level + 1);
break;
default:
printf("Ignoring malformed menu command: %.*s\n",
(int)(*c - s), s);
}
if (err < 0)
return err;
eol_or_eof(c);
return 1;
}
/*
* Handles parsing a 'menu line' when we're parsing a label.
*/
static int parse_label_menu(char **c, struct pxe_menu *cfg,
struct pxe_label *label)
{
struct token t;
char *s;
s = *c;
get_token(c, &t, L_KEYWORD);
switch (t.type) {
case T_DEFAULT:
if (cfg->default_label)
free(cfg->default_label);
cfg->default_label = strdup(label->name);
if (!cfg->default_label)
return -ENOMEM;
break;
default:
printf("Ignoring malformed menu command: %.*s\n",
(int)(*c - s), s);
}
eol_or_eof(c);
return 0;
}
/*
* Parses a label and adds it to the list of labels for a menu.
*
* A label ends when we either get to the end of a file, or
* get some input we otherwise don't have a handler defined
* for.
*
*/
static int parse_label(char **c, struct pxe_menu *cfg)
{
struct token t;
char *s = *c;
struct pxe_label *label;
int err;
label = label_create();
if (!label)
return -ENOMEM;
err = parse_sliteral(c, &label->name);
if (err < 0) {
printf("Expected label name: %.*s\n", (int)(*c - s), s);
label_destroy(label);
return -EINVAL;
}
list_add_tail(&label->list, &cfg->labels);
while (1) {
s = *c;
get_token(c, &t, L_KEYWORD);
err = 0;
switch (t.type) {
case T_MENU:
err = parse_label_menu(c, cfg, label);
break;
case T_KERNEL:
err = parse_sliteral(c, &label->kernel);
break;
case T_APPEND:
err = parse_sliteral(c, &label->append);
break;
case T_INITRD:
err = parse_sliteral(c, &label->initrd);
break;
case T_LOCALBOOT:
err = parse_integer(c, &label->localboot);
break;
case T_EOL:
break;
default:
/*
* put the token back! we don't want it - it's the end
* of a label and whatever token this is, it's
* something for the menu level context to handle.
*/
*c = s;
return 1;
}
if (err < 0)
return err;
}
}
/*
* This 16 comes from the limit pxelinux imposes on nested includes.
*
* There is no reason at all we couldn't do more, but some limit helps prevent
* infinite (until crash occurs) recursion if a file tries to include itself.
*/
#define MAX_NEST_LEVEL 16
/*
* Entry point for parsing a menu file. nest_level indicates how many times
* we've nested in includes. It will be 1 for the top level menu file.
*
* Returns 1 on success, < 0 on error.
*/
static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level)
{
struct token t;
char *s, *b, *label_name;
int err;
b = p;
if (nest_level > MAX_NEST_LEVEL) {
printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
return -EMLINK;
}
while (1) {
s = p;
get_token(&p, &t, L_KEYWORD);
err = 0;
switch (t.type) {
case T_MENU:
err = parse_menu(&p, cfg, b, nest_level);
break;
case T_TIMEOUT:
err = parse_integer(&p, &cfg->timeout);
break;
case T_LABEL:
err = parse_label(&p, cfg);
break;
case T_DEFAULT:
err = parse_sliteral(&p, &label_name);
if (label_name) {
if (cfg->default_label)
free(cfg->default_label);
cfg->default_label = label_name;
}
break;
case T_PROMPT:
err = parse_integer(&p, &cfg->prompt);
break;
case T_EOL:
break;
case T_EOF:
return 1;
default:
printf("Ignoring unknown command: %.*s\n",
(int)(p - s), s);
eol_or_eof(&p);
}
if (err < 0)
return err;
}
}
/*
* Free the memory used by a pxe_menu and its labels.
*/
static void destroy_pxe_menu(struct pxe_menu *cfg)
{
struct list_head *pos, *n;
struct pxe_label *label;
if (cfg->title)
free(cfg->title);
if (cfg->default_label)
free(cfg->default_label);
list_for_each_safe(pos, n, &cfg->labels) {
label = list_entry(pos, struct pxe_label, list);
label_destroy(label);
}
free(cfg);
}
/*
* Entry point for parsing a pxe file. This is only used for the top level
* file.
*
* Returns NULL if there is an error, otherwise, returns a pointer to a
* pxe_menu struct populated with the results of parsing the pxe file (and any
* files it includes). The resulting pxe_menu struct can be free()'d by using
* the destroy_pxe_menu() function.
*/
static struct pxe_menu *parse_pxefile(char *menucfg)
{
struct pxe_menu *cfg;
cfg = malloc(sizeof(struct pxe_menu));
if (!cfg)
return NULL;
memset(cfg, 0, sizeof(struct pxe_menu));
INIT_LIST_HEAD(&cfg->labels);
if (parse_pxefile_top(menucfg, cfg, 1) < 0) {
destroy_pxe_menu(cfg);
return NULL;
}
return cfg;
}
/*
* Converts a pxe_menu struct into a menu struct for use with U-boot's generic
* menu code.
*/
static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
{
struct pxe_label *label;
struct list_head *pos;
struct menu *m;
int err;
/*
* Create a menu and add items for all the labels.
*/
m = menu_create(cfg->title, cfg->timeout, cfg->prompt, label_print);
if (!m)
return NULL;
list_for_each(pos, &cfg->labels) {
label = list_entry(pos, struct pxe_label, list);
if (menu_item_add(m, label->name, label) != 1) {
menu_destroy(m);
return NULL;
}
}
/*
* After we've created items for each label in the menu, set the
* menu's default label if one was specified.
*/
if (cfg->default_label) {
err = menu_default_set(m, cfg->default_label);
if (err != 1) {
if (err != -ENOENT) {
menu_destroy(m);
return NULL;
}
printf("Missing default: %s\n", cfg->default_label);
}
}
return m;
}
/*
* Try to boot any labels we have yet to attempt to boot.
*/
static void boot_unattempted_labels(struct pxe_menu *cfg)
{
struct list_head *pos;
struct pxe_label *label;
list_for_each(pos, &cfg->labels) {
label = list_entry(pos, struct pxe_label, list);
if (!label->attempted)
label_boot(label);
}
}
/*
* Boot the system as prescribed by a pxe_menu.
*
* Use the menu system to either get the user's choice or the default, based
* on config or user input. If there is no default or user's choice,
* attempted to boot labels in the order they were given in pxe files.
* If the default or user's choice fails to boot, attempt to boot other
* labels in the order they were given in pxe files.
*
* If this function returns, there weren't any labels that successfully
* booted, or the user interrupted the menu selection via ctrl+c.
*/
static void handle_pxe_menu(struct pxe_menu *cfg)
{
void *choice;
struct menu *m;
int err;
m = pxe_menu_to_menu(cfg);
if (!m)
return;
err = menu_get_choice(m, &choice);
menu_destroy(m);
/*
* err == 1 means we got a choice back from menu_get_choice.
*
* err == -ENOENT if the menu was setup to select the default but no
* default was set. in that case, we should continue trying to boot
* labels that haven't been attempted yet.
*
* otherwise, the user interrupted or there was some other error and
* we give up.
*/
if (err == 1)
label_boot(choice);
else if (err != -ENOENT)
return;
boot_unattempted_labels(cfg);
}
/*
* Boots a system using a pxe file
*
* Returns 0 on success, 1 on error.
*/
static int
do_pxe_boot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unsigned long pxefile_addr_r;
struct pxe_menu *cfg;
char *pxefile_addr_str;
if (argc == 1) {
pxefile_addr_str = from_env("pxefile_addr_r");
if (!pxefile_addr_str)
return 1;
} else if (argc == 2) {
pxefile_addr_str = argv[1];
} else {
return cmd_usage(cmdtp);
}
if (strict_strtoul(pxefile_addr_str, 16, &pxefile_addr_r) < 0) {
printf("Invalid pxefile address: %s\n", pxefile_addr_str);
return 1;
}
cfg = parse_pxefile((char *)(pxefile_addr_r));
if (cfg == NULL) {
printf("Error parsing config file\n");
return 1;
}
handle_pxe_menu(cfg);
destroy_pxe_menu(cfg);
return 0;
}
static cmd_tbl_t cmd_pxe_sub[] = {
U_BOOT_CMD_MKENT(get, 1, 1, do_pxe_get, "", ""),
U_BOOT_CMD_MKENT(boot, 2, 1, do_pxe_boot, "", "")
};
int do_pxe(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
cmd_tbl_t *cp;
if (argc < 2)
return cmd_usage(cmdtp);
/* drop initial "pxe" arg */
argc--;
argv++;
cp = find_cmd_tbl(argv[0], cmd_pxe_sub, ARRAY_SIZE(cmd_pxe_sub));
if (cp)
return cp->cmd(cmdtp, flag, argc, argv);
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
pxe, 3, 1, do_pxe,
"commands to get and boot from pxe files",
"get - try to retrieve a pxe file using tftp\npxe "
"boot [pxefile_addr_r] - boot from the pxe file at pxefile_addr_r\n"
);
|
1001-study-uboot
|
common/cmd_pxe.c
|
C
|
gpl3
| 29,992
|
/*
* (C) Copyright 2000-2010
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Andreas Heppel <aheppel@sysgo.de>
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/* #define DEBUG */
#include <common.h>
#include <command.h>
#include <environment.h>
#include <linux/stddef.h>
#include <malloc.h>
#include <search.h>
#include <errno.h>
DECLARE_GLOBAL_DATA_PTR;
#if defined(CONFIG_CMD_SAVEENV) && defined(CONFIG_CMD_FLASH)
#define CMD_SAVEENV
#elif defined(CONFIG_ENV_ADDR_REDUND)
#error CONFIG_ENV_ADDR_REDUND must have CONFIG_CMD_SAVEENV & CONFIG_CMD_FLASH
#endif
#if defined(CONFIG_ENV_SIZE_REDUND) && \
(CONFIG_ENV_SIZE_REDUND < CONFIG_ENV_SIZE)
#error CONFIG_ENV_SIZE_REDUND should not be less then CONFIG_ENV_SIZE
#endif
char *env_name_spec = "Flash";
#ifdef ENV_IS_EMBEDDED
env_t *env_ptr = &environment;
static env_t *flash_addr = (env_t *)CONFIG_ENV_ADDR;
#else /* ! ENV_IS_EMBEDDED */
env_t *env_ptr = (env_t *)CONFIG_ENV_ADDR;
static env_t *flash_addr = (env_t *)CONFIG_ENV_ADDR;
#endif /* ENV_IS_EMBEDDED */
#if defined(CMD_SAVEENV) || defined(CONFIG_ENV_ADDR_REDUND)
/* CONFIG_ENV_ADDR is supposed to be on sector boundary */
static ulong end_addr = CONFIG_ENV_ADDR + CONFIG_ENV_SECT_SIZE - 1;
#endif
#ifdef CONFIG_ENV_ADDR_REDUND
static env_t *flash_addr_new = (env_t *)CONFIG_ENV_ADDR_REDUND;
/* CONFIG_ENV_ADDR_REDUND is supposed to be on sector boundary */
static ulong end_addr_new = CONFIG_ENV_ADDR_REDUND + CONFIG_ENV_SECT_SIZE - 1;
#endif /* CONFIG_ENV_ADDR_REDUND */
uchar env_get_char_spec(int index)
{
return *((uchar *)(gd->env_addr + index));
}
#ifdef CONFIG_ENV_ADDR_REDUND
int env_init(void)
{
int crc1_ok = 0, crc2_ok = 0;
uchar flag1 = flash_addr->flags;
uchar flag2 = flash_addr_new->flags;
ulong addr_default = (ulong)&default_environment[0];
ulong addr1 = (ulong)&(flash_addr->data);
ulong addr2 = (ulong)&(flash_addr_new->data);
crc1_ok = crc32(0, flash_addr->data, ENV_SIZE) == flash_addr->crc;
crc2_ok =
crc32(0, flash_addr_new->data, ENV_SIZE) == flash_addr_new->crc;
if (crc1_ok && !crc2_ok) {
gd->env_addr = addr1;
gd->env_valid = 1;
} else if (!crc1_ok && crc2_ok) {
gd->env_addr = addr2;
gd->env_valid = 1;
} else if (!crc1_ok && !crc2_ok) {
gd->env_addr = addr_default;
gd->env_valid = 0;
} else if (flag1 == ACTIVE_FLAG && flag2 == OBSOLETE_FLAG) {
gd->env_addr = addr1;
gd->env_valid = 1;
} else if (flag1 == OBSOLETE_FLAG && flag2 == ACTIVE_FLAG) {
gd->env_addr = addr2;
gd->env_valid = 1;
} else if (flag1 == flag2) {
gd->env_addr = addr1;
gd->env_valid = 2;
} else if (flag1 == 0xFF) {
gd->env_addr = addr1;
gd->env_valid = 2;
} else if (flag2 == 0xFF) {
gd->env_addr = addr2;
gd->env_valid = 2;
}
return 0;
}
#ifdef CMD_SAVEENV
int saveenv(void)
{
env_t env_new;
ssize_t len;
char *res, *saved_data = NULL;
char flag = OBSOLETE_FLAG, new_flag = ACTIVE_FLAG;
int rc = 1;
#if CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE
ulong up_data = 0;
#endif
debug("Protect off %08lX ... %08lX\n", (ulong)flash_addr, end_addr);
if (flash_sect_protect(0, (ulong)flash_addr, end_addr))
goto done;
debug("Protect off %08lX ... %08lX\n",
(ulong)flash_addr_new, end_addr_new);
if (flash_sect_protect(0, (ulong)flash_addr_new, end_addr_new))
goto done;
res = (char *)&env_new.data;
len = hexport_r(&env_htab, '\0', &res, ENV_SIZE, 0, NULL);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
goto done;
}
env_new.crc = crc32(0, env_new.data, ENV_SIZE);
env_new.flags = new_flag;
#if CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE
up_data = end_addr_new + 1 - ((long)flash_addr_new + CONFIG_ENV_SIZE);
debug("Data to save 0x%lX\n", up_data);
if (up_data) {
saved_data = malloc(up_data);
if (saved_data == NULL) {
printf("Unable to save the rest of sector (%ld)\n",
up_data);
goto done;
}
memcpy(saved_data,
(void *)((long)flash_addr_new + CONFIG_ENV_SIZE),
up_data);
debug("Data (start 0x%lX, len 0x%lX) saved at 0x%p\n",
(long)flash_addr_new + CONFIG_ENV_SIZE,
up_data, saved_data);
}
#endif
puts("Erasing Flash...");
debug(" %08lX ... %08lX ...", (ulong)flash_addr_new, end_addr_new);
if (flash_sect_erase((ulong)flash_addr_new, end_addr_new))
goto done;
puts("Writing to Flash... ");
debug(" %08lX ... %08lX ...",
(ulong)&(flash_addr_new->data),
sizeof(env_ptr->data) + (ulong)&(flash_addr_new->data));
rc = flash_write((char *)&env_new, (ulong)flash_addr_new,
sizeof(env_new));
if (rc)
goto perror;
rc = flash_write(&flag, (ulong)&(flash_addr->flags),
sizeof(flash_addr->flags));
if (rc)
goto perror;
#if CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE
if (up_data) { /* restore the rest of sector */
debug("Restoring the rest of data to 0x%lX len 0x%lX\n",
(long)flash_addr_new + CONFIG_ENV_SIZE, up_data);
if (flash_write(saved_data,
(long)flash_addr_new + CONFIG_ENV_SIZE,
up_data))
goto perror;
}
#endif
puts("done\n");
{
env_t *etmp = flash_addr;
ulong ltmp = end_addr;
flash_addr = flash_addr_new;
flash_addr_new = etmp;
end_addr = end_addr_new;
end_addr_new = ltmp;
}
rc = 0;
goto done;
perror:
flash_perror(rc);
done:
if (saved_data)
free(saved_data);
/* try to re-protect */
flash_sect_protect(1, (ulong)flash_addr, end_addr);
flash_sect_protect(1, (ulong)flash_addr_new, end_addr_new);
return rc;
}
#endif /* CMD_SAVEENV */
#else /* ! CONFIG_ENV_ADDR_REDUND */
int env_init(void)
{
if (crc32(0, env_ptr->data, ENV_SIZE) == env_ptr->crc) {
gd->env_addr = (ulong)&(env_ptr->data);
gd->env_valid = 1;
return 0;
}
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 0;
return 0;
}
#ifdef CMD_SAVEENV
int saveenv(void)
{
env_t env_new;
ssize_t len;
int rc = 1;
char *res, *saved_data = NULL;
#if CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE
ulong up_data = 0;
up_data = end_addr + 1 - ((long)flash_addr + CONFIG_ENV_SIZE);
debug("Data to save 0x%lx\n", up_data);
if (up_data) {
saved_data = malloc(up_data);
if (saved_data == NULL) {
printf("Unable to save the rest of sector (%ld)\n",
up_data);
goto done;
}
memcpy(saved_data,
(void *)((long)flash_addr + CONFIG_ENV_SIZE), up_data);
debug("Data (start 0x%lx, len 0x%lx) saved at 0x%lx\n",
(ulong)flash_addr + CONFIG_ENV_SIZE,
up_data,
(ulong)saved_data);
}
#endif /* CONFIG_ENV_SECT_SIZE */
debug("Protect off %08lX ... %08lX\n", (ulong)flash_addr, end_addr);
if (flash_sect_protect(0, (long)flash_addr, end_addr))
goto done;
res = (char *)&env_new.data;
len = hexport_r(&env_htab, '\0', &res, ENV_SIZE, 0, NULL);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
goto done;
}
env_new.crc = crc32(0, env_new.data, ENV_SIZE);
puts("Erasing Flash...");
if (flash_sect_erase((long)flash_addr, end_addr))
goto done;
puts("Writing to Flash... ");
rc = flash_write((char *)&env_new, (long)flash_addr, CONFIG_ENV_SIZE);
if (rc != 0)
goto perror;
#if CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE
if (up_data) { /* restore the rest of sector */
debug("Restoring the rest of data to 0x%lx len 0x%lx\n",
(ulong)flash_addr + CONFIG_ENV_SIZE, up_data);
if (flash_write(saved_data,
(long)flash_addr + CONFIG_ENV_SIZE,
up_data))
goto perror;
}
#endif
puts("done\n");
rc = 0;
goto done;
perror:
flash_perror(rc);
done:
if (saved_data)
free(saved_data);
/* try to re-protect */
flash_sect_protect(1, (long)flash_addr, end_addr);
return rc;
}
#endif /* CMD_SAVEENV */
#endif /* CONFIG_ENV_ADDR_REDUND */
void env_relocate_spec(void)
{
#ifdef CONFIG_ENV_ADDR_REDUND
if (gd->env_addr != (ulong)&(flash_addr->data)) {
env_t *etmp = flash_addr;
ulong ltmp = end_addr;
flash_addr = flash_addr_new;
flash_addr_new = etmp;
end_addr = end_addr_new;
end_addr_new = ltmp;
}
if (flash_addr_new->flags != OBSOLETE_FLAG &&
crc32(0, flash_addr_new->data, ENV_SIZE) == flash_addr_new->crc) {
char flag = OBSOLETE_FLAG;
gd->env_valid = 2;
flash_sect_protect(0, (ulong)flash_addr_new, end_addr_new);
flash_write(&flag,
(ulong)&(flash_addr_new->flags),
sizeof(flash_addr_new->flags));
flash_sect_protect(1, (ulong)flash_addr_new, end_addr_new);
}
if (flash_addr->flags != ACTIVE_FLAG &&
(flash_addr->flags & ACTIVE_FLAG) == ACTIVE_FLAG) {
char flag = ACTIVE_FLAG;
gd->env_valid = 2;
flash_sect_protect(0, (ulong)flash_addr, end_addr);
flash_write(&flag,
(ulong)&(flash_addr->flags),
sizeof(flash_addr->flags));
flash_sect_protect(1, (ulong)flash_addr, end_addr);
}
if (gd->env_valid == 2)
puts("*** Warning - some problems detected "
"reading environment; recovered successfully\n\n");
#endif /* CONFIG_ENV_ADDR_REDUND */
env_import((char *)flash_addr, 1);
}
|
1001-study-uboot
|
common/env_flash.c
|
C
|
gpl3
| 9,595
|
/*
* (C) Copyright 2001
* Gerald Van Baren, Custom IDEAS, vanbaren@cideas.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
*/
/*
* MII Utilities
*/
#include <common.h>
#include <command.h>
#include <miiphy.h>
typedef struct _MII_reg_desc_t {
ushort regno;
char * name;
} MII_reg_desc_t;
static const MII_reg_desc_t reg_0_5_desc_tbl[] = {
{ MII_BMCR, "PHY control register" },
{ MII_BMSR, "PHY status register" },
{ MII_PHYSID1, "PHY ID 1 register" },
{ MII_PHYSID2, "PHY ID 2 register" },
{ MII_ADVERTISE, "Autonegotiation advertisement register" },
{ MII_LPA, "Autonegotiation partner abilities register" },
};
typedef struct _MII_field_desc_t {
ushort hi;
ushort lo;
ushort mask;
char * name;
} MII_field_desc_t;
static const MII_field_desc_t reg_0_desc_tbl[] = {
{ 15, 15, 0x01, "reset" },
{ 14, 14, 0x01, "loopback" },
{ 13, 6, 0x81, "speed selection" }, /* special */
{ 12, 12, 0x01, "A/N enable" },
{ 11, 11, 0x01, "power-down" },
{ 10, 10, 0x01, "isolate" },
{ 9, 9, 0x01, "restart A/N" },
{ 8, 8, 0x01, "duplex" }, /* special */
{ 7, 7, 0x01, "collision test enable" },
{ 5, 0, 0x3f, "(reserved)" }
};
static const MII_field_desc_t reg_1_desc_tbl[] = {
{ 15, 15, 0x01, "100BASE-T4 able" },
{ 14, 14, 0x01, "100BASE-X full duplex able" },
{ 13, 13, 0x01, "100BASE-X half duplex able" },
{ 12, 12, 0x01, "10 Mbps full duplex able" },
{ 11, 11, 0x01, "10 Mbps half duplex able" },
{ 10, 10, 0x01, "100BASE-T2 full duplex able" },
{ 9, 9, 0x01, "100BASE-T2 half duplex able" },
{ 8, 8, 0x01, "extended status" },
{ 7, 7, 0x01, "(reserved)" },
{ 6, 6, 0x01, "MF preamble suppression" },
{ 5, 5, 0x01, "A/N complete" },
{ 4, 4, 0x01, "remote fault" },
{ 3, 3, 0x01, "A/N able" },
{ 2, 2, 0x01, "link status" },
{ 1, 1, 0x01, "jabber detect" },
{ 0, 0, 0x01, "extended capabilities" },
};
static const MII_field_desc_t reg_2_desc_tbl[] = {
{ 15, 0, 0xffff, "OUI portion" },
};
static const MII_field_desc_t reg_3_desc_tbl[] = {
{ 15, 10, 0x3f, "OUI portion" },
{ 9, 4, 0x3f, "manufacturer part number" },
{ 3, 0, 0x0f, "manufacturer rev. number" },
};
static const MII_field_desc_t reg_4_desc_tbl[] = {
{ 15, 15, 0x01, "next page able" },
{ 14, 14, 0x01, "reserved" },
{ 13, 13, 0x01, "remote fault" },
{ 12, 12, 0x01, "reserved" },
{ 11, 11, 0x01, "asymmetric pause" },
{ 10, 10, 0x01, "pause enable" },
{ 9, 9, 0x01, "100BASE-T4 able" },
{ 8, 8, 0x01, "100BASE-TX full duplex able" },
{ 7, 7, 0x01, "100BASE-TX able" },
{ 6, 6, 0x01, "10BASE-T full duplex able" },
{ 5, 5, 0x01, "10BASE-T able" },
{ 4, 0, 0x1f, "xxx to do" },
};
static const MII_field_desc_t reg_5_desc_tbl[] = {
{ 15, 15, 0x01, "next page able" },
{ 14, 14, 0x01, "acknowledge" },
{ 13, 13, 0x01, "remote fault" },
{ 12, 12, 0x01, "(reserved)" },
{ 11, 11, 0x01, "asymmetric pause able" },
{ 10, 10, 0x01, "pause able" },
{ 9, 9, 0x01, "100BASE-T4 able" },
{ 8, 8, 0x01, "100BASE-X full duplex able" },
{ 7, 7, 0x01, "100BASE-TX able" },
{ 6, 6, 0x01, "10BASE-T full duplex able" },
{ 5, 5, 0x01, "10BASE-T able" },
{ 4, 0, 0x1f, "xxx to do" },
};
typedef struct _MII_field_desc_and_len_t {
const MII_field_desc_t *pdesc;
ushort len;
} MII_field_desc_and_len_t;
static const MII_field_desc_and_len_t desc_and_len_tbl[] = {
{ reg_0_desc_tbl, ARRAY_SIZE(reg_0_desc_tbl) },
{ reg_1_desc_tbl, ARRAY_SIZE(reg_1_desc_tbl) },
{ reg_2_desc_tbl, ARRAY_SIZE(reg_2_desc_tbl) },
{ reg_3_desc_tbl, ARRAY_SIZE(reg_3_desc_tbl) },
{ reg_4_desc_tbl, ARRAY_SIZE(reg_4_desc_tbl) },
{ reg_5_desc_tbl, ARRAY_SIZE(reg_5_desc_tbl) },
};
static void dump_reg(
ushort regval,
const MII_reg_desc_t *prd,
const MII_field_desc_and_len_t *pdl);
static int special_field(
ushort regno,
const MII_field_desc_t *pdesc,
ushort regval);
static void MII_dump_0_to_5(
ushort regvals[6],
uchar reglo,
uchar reghi)
{
ulong i;
for (i = 0; i < 6; i++) {
if ((reglo <= i) && (i <= reghi))
dump_reg(regvals[i], ®_0_5_desc_tbl[i],
&desc_and_len_tbl[i]);
}
}
static void dump_reg(
ushort regval,
const MII_reg_desc_t *prd,
const MII_field_desc_and_len_t *pdl)
{
ulong i;
ushort mask_in_place;
const MII_field_desc_t *pdesc;
printf("%u. (%04hx) -- %s --\n",
prd->regno, regval, prd->name);
for (i = 0; i < pdl->len; i++) {
pdesc = &pdl->pdesc[i];
mask_in_place = pdesc->mask << pdesc->lo;
printf(" (%04hx:%04hx) %u.",
mask_in_place,
regval & mask_in_place,
prd->regno);
if (special_field(prd->regno, pdesc, regval)) {
}
else {
if (pdesc->hi == pdesc->lo)
printf("%2u ", pdesc->lo);
else
printf("%2u-%2u", pdesc->hi, pdesc->lo);
printf(" = %5u %s",
(regval & mask_in_place) >> pdesc->lo,
pdesc->name);
}
printf("\n");
}
printf("\n");
}
/* Special fields:
** 0.6,13
** 0.8
** 2.15-0
** 3.15-0
** 4.4-0
** 5.4-0
*/
static int special_field(
ushort regno,
const MII_field_desc_t *pdesc,
ushort regval)
{
if ((regno == MII_BMCR) && (pdesc->lo == 6)) {
ushort speed_bits = regval & (BMCR_SPEED1000 | BMCR_SPEED100);
printf("%2u,%2u = b%u%u speed selection = %s Mbps",
6, 13,
(regval >> 6) & 1,
(regval >> 13) & 1,
speed_bits == BMCR_SPEED1000 ? "1000" :
speed_bits == BMCR_SPEED100 ? "100" :
"10");
return 1;
}
else if ((regno == MII_BMCR) && (pdesc->lo == 8)) {
printf("%2u = %5u duplex = %s",
pdesc->lo,
(regval >> pdesc->lo) & 1,
((regval >> pdesc->lo) & 1) ? "full" : "half");
return 1;
}
else if ((regno == MII_ADVERTISE) && (pdesc->lo == 0)) {
ushort sel_bits = (regval >> pdesc->lo) & pdesc->mask;
printf("%2u-%2u = %5u selector = %s",
pdesc->hi, pdesc->lo, sel_bits,
sel_bits == PHY_ANLPAR_PSB_802_3 ?
"IEEE 802.3" :
sel_bits == PHY_ANLPAR_PSB_802_9 ?
"IEEE 802.9 ISLAN-16T" :
"???");
return 1;
}
else if ((regno == MII_LPA) && (pdesc->lo == 0)) {
ushort sel_bits = (regval >> pdesc->lo) & pdesc->mask;
printf("%2u-%2u = %u selector = %s",
pdesc->hi, pdesc->lo, sel_bits,
sel_bits == PHY_ANLPAR_PSB_802_3 ?
"IEEE 802.3" :
sel_bits == PHY_ANLPAR_PSB_802_9 ?
"IEEE 802.9 ISLAN-16T" :
"???");
return 1;
}
return 0;
}
static char last_op[2];
static uint last_data;
static uint last_addr_lo;
static uint last_addr_hi;
static uint last_reg_lo;
static uint last_reg_hi;
static void extract_range(
char * input,
unsigned char * plo,
unsigned char * phi)
{
char * end;
*plo = simple_strtoul(input, &end, 16);
if (*end == '-') {
end++;
*phi = simple_strtoul(end, NULL, 16);
}
else {
*phi = *plo;
}
}
/* ---------------------------------------------------------------- */
static int do_mii(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char op[2];
unsigned char addrlo, addrhi, reglo, reghi;
unsigned char addr, reg;
unsigned short data;
int rcode = 0;
const char *devname;
if (argc < 2)
return cmd_usage(cmdtp);
#if defined(CONFIG_MII_INIT)
mii_init ();
#endif
/*
* We use the last specified parameters, unless new ones are
* entered.
*/
op[0] = last_op[0];
op[1] = last_op[1];
addrlo = last_addr_lo;
addrhi = last_addr_hi;
reglo = last_reg_lo;
reghi = last_reg_hi;
data = last_data;
if ((flag & CMD_FLAG_REPEAT) == 0) {
op[0] = argv[1][0];
if (strlen(argv[1]) > 1)
op[1] = argv[1][1];
else
op[1] = '\0';
if (argc >= 3)
extract_range(argv[2], &addrlo, &addrhi);
if (argc >= 4)
extract_range(argv[3], ®lo, ®hi);
if (argc >= 5)
data = simple_strtoul (argv[4], NULL, 16);
}
/* use current device */
devname = miiphy_get_current_dev();
/*
* check info/read/write.
*/
if (op[0] == 'i') {
unsigned char j, start, end;
unsigned int oui;
unsigned char model;
unsigned char rev;
/*
* Look for any and all PHYs. Valid addresses are 0..31.
*/
if (argc >= 3) {
start = addrlo; end = addrhi;
} else {
start = 0; end = 31;
}
for (j = start; j <= end; j++) {
if (miiphy_info (devname, j, &oui, &model, &rev) == 0) {
printf("PHY 0x%02X: "
"OUI = 0x%04X, "
"Model = 0x%02X, "
"Rev = 0x%02X, "
"%3dbase%s, %s\n",
j, oui, model, rev,
miiphy_speed (devname, j),
miiphy_is_1000base_x (devname, j)
? "X" : "T",
(miiphy_duplex (devname, j) == FULL)
? "FDX" : "HDX");
}
}
} else if (op[0] == 'r') {
for (addr = addrlo; addr <= addrhi; addr++) {
for (reg = reglo; reg <= reghi; reg++) {
data = 0xffff;
if (miiphy_read (devname, addr, reg, &data) != 0) {
printf(
"Error reading from the PHY addr=%02x reg=%02x\n",
addr, reg);
rcode = 1;
} else {
if ((addrlo != addrhi) || (reglo != reghi))
printf("addr=%02x reg=%02x data=",
(uint)addr, (uint)reg);
printf("%04X\n", data & 0x0000FFFF);
}
}
if ((addrlo != addrhi) && (reglo != reghi))
printf("\n");
}
} else if (op[0] == 'w') {
for (addr = addrlo; addr <= addrhi; addr++) {
for (reg = reglo; reg <= reghi; reg++) {
if (miiphy_write (devname, addr, reg, data) != 0) {
printf("Error writing to the PHY addr=%02x reg=%02x\n",
addr, reg);
rcode = 1;
}
}
}
} else if (strncmp(op, "du", 2) == 0) {
ushort regs[6];
int ok = 1;
if ((reglo > 5) || (reghi > 5)) {
printf(
"The MII dump command only formats the "
"standard MII registers, 0-5.\n");
return 1;
}
for (addr = addrlo; addr <= addrhi; addr++) {
for (reg = reglo; reg < reghi + 1; reg++) {
if (miiphy_read(devname, addr, reg, ®s[reg]) != 0) {
ok = 0;
printf(
"Error reading from the PHY addr=%02x reg=%02x\n",
addr, reg);
rcode = 1;
}
}
if (ok)
MII_dump_0_to_5(regs, reglo, reghi);
printf("\n");
}
} else if (strncmp(op, "de", 2) == 0) {
if (argc == 2)
miiphy_listdev ();
else
miiphy_set_current_dev (argv[2]);
} else {
return cmd_usage(cmdtp);
}
/*
* Save the parameters for repeats.
*/
last_op[0] = op[0];
last_op[1] = op[1];
last_addr_lo = addrlo;
last_addr_hi = addrhi;
last_reg_lo = reglo;
last_reg_hi = reghi;
last_data = data;
return rcode;
}
/***************************************************/
U_BOOT_CMD(
mii, 5, 1, do_mii,
"MII utility commands",
"device - list available devices\n"
"mii device <devname> - set current device\n"
"mii info <addr> - display MII PHY info\n"
"mii read <addr> <reg> - read MII PHY <addr> register <reg>\n"
"mii write <addr> <reg> <data> - write MII PHY <addr> register <reg>\n"
"mii dump <addr> <reg> - pretty-print <addr> <reg> (0-5 only)\n"
"Addr and/or reg may be ranges, e.g. 2-7."
);
|
1001-study-uboot
|
common/cmd_mii.c
|
C
|
gpl3
| 12,227
|
/*
* (C) Copyright 2010 DENX Software Engineering
* Wolfgang Denk <wd@denx.de>
*
* (C) Copyright 2005-2009 Samsung Electronics
* Kyungmin Park <kyungmin.park@samsung.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 <command.h>
#include <environment.h>
#include <linux/stddef.h>
#include <malloc.h>
#include <search.h>
#include <errno.h>
#include <onenand_uboot.h>
#include <linux/mtd/compat.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/onenand.h>
char *env_name_spec = "OneNAND";
#define ONENAND_MAX_ENV_SIZE 4096
#define ONENAND_ENV_SIZE(mtd) (ONENAND_MAX_ENV_SIZE - ENV_HEADER_SIZE)
DECLARE_GLOBAL_DATA_PTR;
uchar env_get_char_spec(int index)
{
return *((uchar *)(gd->env_addr + index));
}
void env_relocate_spec(void)
{
struct mtd_info *mtd = &onenand_mtd;
#ifdef CONFIG_ENV_ADDR_FLEX
struct onenand_chip *this = &onenand_chip;
#endif
int rc;
size_t retlen;
#ifdef ENV_IS_EMBEDDED
char *buf = (char *)&environment;
#else
loff_t env_addr = CONFIG_ENV_ADDR;
char onenand_env[ONENAND_MAX_ENV_SIZE];
char *buf = (char *)&onenand_env[0];
#endif /* ENV_IS_EMBEDDED */
#ifndef ENV_IS_EMBEDDED
# ifdef CONFIG_ENV_ADDR_FLEX
if (FLEXONENAND(this))
env_addr = CONFIG_ENV_ADDR_FLEX;
# endif
/* Check OneNAND exist */
if (mtd->writesize)
/* Ignore read fail */
mtd->read(mtd, env_addr, ONENAND_MAX_ENV_SIZE,
&retlen, (u_char *)buf);
else
mtd->writesize = MAX_ONENAND_PAGESIZE;
#endif /* !ENV_IS_EMBEDDED */
rc = env_import(buf, 1);
if (rc)
gd->env_valid = 1;
}
int saveenv(void)
{
env_t env_new;
ssize_t len;
char *res;
struct mtd_info *mtd = &onenand_mtd;
#ifdef CONFIG_ENV_ADDR_FLEX
struct onenand_chip *this = &onenand_chip;
#endif
loff_t env_addr = CONFIG_ENV_ADDR;
size_t retlen;
struct erase_info instr = {
.callback = NULL,
};
res = (char *)&env_new.data;
len = hexport_r(&env_htab, '\0', &res, ENV_SIZE, 0, NULL);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
return 1;
}
env_new.crc = crc32(0, env_new.data, ENV_SIZE);
instr.len = CONFIG_ENV_SIZE;
#ifdef CONFIG_ENV_ADDR_FLEX
if (FLEXONENAND(this)) {
env_addr = CONFIG_ENV_ADDR_FLEX;
instr.len = CONFIG_ENV_SIZE_FLEX;
instr.len <<= onenand_mtd.eraseregions[0].numblocks == 1 ?
1 : 0;
}
#endif
instr.addr = env_addr;
instr.mtd = mtd;
if (mtd->erase(mtd, &instr)) {
printf("OneNAND: erase failed at 0x%08llx\n", env_addr);
return 1;
}
if (mtd->write(mtd, env_addr, ONENAND_MAX_ENV_SIZE, &retlen,
(u_char *)&env_new)) {
printf("OneNAND: write failed at 0x%llx\n", instr.addr);
return 2;
}
return 0;
}
int env_init(void)
{
/* use default */
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 1;
return 0;
}
|
1001-study-uboot
|
common/env_onenand.c
|
C
|
gpl3
| 3,484
|
/*
* (C) Copyright 2008
* Stefan Roese, DENX Software Engineering, sr@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
*
*/
/*
* UBIFS command support
*/
#undef DEBUG
#include <common.h>
#include <config.h>
#include <command.h>
#include "../fs/ubifs/ubifs.h"
static int ubifs_initialized;
static int ubifs_mounted;
extern struct super_block *ubifs_sb;
/* Prototypes */
int ubifs_init(void);
int ubifs_mount(char *vol_name);
void ubifs_umount(struct ubifs_info *c);
int ubifs_ls(char *dir_name);
int ubifs_load(char *filename, u32 addr, u32 size);
int do_ubifs_mount(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *vol_name;
int ret;
if (argc != 2)
return cmd_usage(cmdtp);
vol_name = argv[1];
debug("Using volume %s\n", vol_name);
if (ubifs_initialized == 0) {
ubifs_init();
ubifs_initialized = 1;
}
ret = ubifs_mount(vol_name);
if (ret)
return -1;
ubifs_mounted = 1;
return 0;
}
int ubifs_is_mounted(void)
{
return ubifs_mounted;
}
void cmd_ubifs_umount(void)
{
if (ubifs_sb) {
printf("Unmounting UBIFS volume %s!\n",
((struct ubifs_info *)(ubifs_sb->s_fs_info))->vi.name);
ubifs_umount(ubifs_sb->s_fs_info);
}
ubifs_sb = NULL;
ubifs_mounted = 0;
ubifs_initialized = 0;
}
int do_ubifs_umount(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc != 1)
return cmd_usage(cmdtp);
if (ubifs_initialized == 0) {
printf("No UBIFS volume mounted!\n");
return -1;
}
cmd_ubifs_umount();
return 0;
}
int do_ubifs_ls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = "/";
int ret;
if (!ubifs_mounted) {
printf("UBIFS not mounted, use ubifsmount to mount volume first!\n");
return -1;
}
if (argc == 2)
filename = argv[1];
debug("Using filename %s\n", filename);
ret = ubifs_ls(filename);
if (ret)
printf("%s not found!\n", filename);
return ret;
}
int do_ubifs_load(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename;
char *endp;
int ret;
u32 addr;
u32 size = 0;
if (!ubifs_mounted) {
printf("UBIFS not mounted, use ubifs mount to mount volume first!\n");
return -1;
}
if (argc < 3)
return cmd_usage(cmdtp);
addr = simple_strtoul(argv[1], &endp, 16);
if (endp == argv[1])
return cmd_usage(cmdtp);
filename = argv[2];
if (argc == 4) {
size = simple_strtoul(argv[3], &endp, 16);
if (endp == argv[3])
return cmd_usage(cmdtp);
}
debug("Loading file '%s' to address 0x%08x (size %d)\n", filename, addr, size);
ret = ubifs_load(filename, addr, size);
if (ret)
printf("%s not found!\n", filename);
return ret;
}
U_BOOT_CMD(
ubifsmount, 2, 0, do_ubifs_mount,
"mount UBIFS volume",
"<volume-name>\n"
" - mount 'volume-name' volume"
);
U_BOOT_CMD(
ubifsumount, 1, 0, do_ubifs_umount,
"unmount UBIFS volume",
" - unmount current volume"
);
U_BOOT_CMD(
ubifsls, 2, 0, do_ubifs_ls,
"list files in a directory",
"[directory]\n"
" - list files in a 'directory' (default '/')"
);
U_BOOT_CMD(
ubifsload, 4, 0, do_ubifs_load,
"load file from an UBIFS filesystem",
"<addr> <filename> [bytes]\n"
" - load file 'filename' to address 'addr'"
);
|
1001-study-uboot
|
common/cmd_ubifs.c
|
C
|
gpl3
| 3,928
|
/*
* Copyright 2000-2009
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <version.h>
#include <linux/compiler.h>
const char __weak version_string[] = U_BOOT_VERSION_STRING;
int do_version(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
printf("\n%s\n", version_string);
#ifdef CC_VERSION_STRING
puts(CC_VERSION_STRING "\n");
#endif
#ifdef LD_VERSION_STRING
puts(LD_VERSION_STRING "\n");
#endif
return 0;
}
U_BOOT_CMD(
version, 1, 1, do_version,
"print monitor, compiler and linker version",
""
);
|
1001-study-uboot
|
common/cmd_version.c
|
C
|
gpl3
| 1,382
|
#
# (C) Copyright 2004-2006
# Wolfgang Denk, DENX Software Engineering, wd@denx.de.
#
# See file CREDITS for list of people who contributed to this
# project.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
#
include $(TOPDIR)/config.mk
LIB = $(obj)libcommon.o
# core
ifndef CONFIG_SPL_BUILD
COBJS-y += main.o
COBJS-y += command.o
COBJS-y += exports.o
COBJS-$(CONFIG_SYS_HUSH_PARSER) += hush.o
COBJS-y += image.o
COBJS-y += s_record.o
COBJS-$(CONFIG_SERIAL_MULTI) += serial.o
COBJS-y += xyzModem.o
# core command
COBJS-y += cmd_boot.o
COBJS-$(CONFIG_CMD_BOOTM) += cmd_bootm.o
COBJS-y += cmd_help.o
COBJS-y += cmd_nvedit.o
COBJS-y += cmd_version.o
# environment
COBJS-y += env_common.o
COBJS-$(CONFIG_ENV_IS_IN_DATAFLASH) += env_dataflash.o
COBJS-$(CONFIG_ENV_IS_IN_EEPROM) += env_eeprom.o
XCOBJS-$(CONFIG_ENV_IS_EMBEDDED) += env_embedded.o
COBJS-$(CONFIG_ENV_IS_IN_EEPROM) += env_embedded.o
XCOBJS-$(CONFIG_ENV_IS_IN_FLASH) += env_embedded.o
COBJS-$(CONFIG_ENV_IS_IN_NVRAM) += env_embedded.o
COBJS-$(CONFIG_ENV_IS_IN_FLASH) += env_flash.o
COBJS-$(CONFIG_ENV_IS_IN_MG_DISK) += env_mgdisk.o
COBJS-$(CONFIG_ENV_IS_IN_MMC) += env_mmc.o
COBJS-$(CONFIG_ENV_IS_IN_NAND) += env_nand.o
COBJS-$(CONFIG_ENV_IS_IN_NVRAM) += env_nvram.o
COBJS-$(CONFIG_ENV_IS_IN_ONENAND) += env_onenand.o
COBJS-$(CONFIG_ENV_IS_IN_SPI_FLASH) += env_sf.o
COBJS-$(CONFIG_ENV_IS_NOWHERE) += env_nowhere.o
# command
COBJS-$(CONFIG_CMD_AMBAPP) += cmd_ambapp.o
COBJS-$(CONFIG_SOURCE) += cmd_source.o
COBJS-$(CONFIG_CMD_SOURCE) += cmd_source.o
COBJS-$(CONFIG_CMD_BDI) += cmd_bdinfo.o
COBJS-$(CONFIG_CMD_BEDBUG) += bedbug.o cmd_bedbug.o
COBJS-$(CONFIG_CMD_BMP) += cmd_bmp.o
COBJS-$(CONFIG_CMD_BOOTLDR) += cmd_bootldr.o
COBJS-$(CONFIG_CMD_CACHE) += cmd_cache.o
COBJS-$(CONFIG_CMD_CONSOLE) += cmd_console.o
COBJS-$(CONFIG_CMD_CPLBINFO) += cmd_cplbinfo.o
COBJS-$(CONFIG_DATAFLASH_MMC_SELECT) += cmd_dataflash_mmc_mux.o
COBJS-$(CONFIG_CMD_DATE) += cmd_date.o
ifdef CONFIG_4xx
COBJS-$(CONFIG_CMD_SETGETDCR) += cmd_dcr.o
endif
ifdef CONFIG_POST
COBJS-$(CONFIG_CMD_DIAG) += cmd_diag.o
endif
COBJS-$(CONFIG_CMD_DISPLAY) += cmd_display.o
COBJS-$(CONFIG_CMD_DTT) += cmd_dtt.o
COBJS-$(CONFIG_CMD_ECHO) += cmd_echo.o
COBJS-$(CONFIG_ENV_IS_IN_EEPROM) += cmd_eeprom.o
COBJS-$(CONFIG_CMD_EEPROM) += cmd_eeprom.o
COBJS-$(CONFIG_CMD_ELF) += cmd_elf.o
COBJS-$(CONFIG_SYS_HUSH_PARSER) += cmd_exit.o
COBJS-$(CONFIG_CMD_EXT2) += cmd_ext2.o
COBJS-$(CONFIG_CMD_FAT) += cmd_fat.o
COBJS-$(CONFIG_CMD_FDC)$(CONFIG_CMD_FDOS) += cmd_fdc.o
COBJS-$(CONFIG_OF_LIBFDT) += cmd_fdt.o fdt_support.o
COBJS-$(CONFIG_CMD_FDOS) += cmd_fdos.o
COBJS-$(CONFIG_CMD_FITUPD) += cmd_fitupd.o
COBJS-$(CONFIG_CMD_FLASH) += cmd_flash.o
ifdef CONFIG_FPGA
COBJS-$(CONFIG_CMD_FPGA) += cmd_fpga.o
endif
COBJS-$(CONFIG_CMD_GPIO) += cmd_gpio.o
COBJS-$(CONFIG_CMD_I2C) += cmd_i2c.o
COBJS-$(CONFIG_CMD_IDE) += cmd_ide.o
COBJS-$(CONFIG_CMD_IMMAP) += cmd_immap.o
COBJS-$(CONFIG_CMD_IRQ) += cmd_irq.o
COBJS-$(CONFIG_CMD_ITEST) += cmd_itest.o
COBJS-$(CONFIG_CMD_JFFS2) += cmd_jffs2.o
COBJS-$(CONFIG_CMD_CRAMFS) += cmd_cramfs.o
COBJS-$(CONFIG_CMD_LDRINFO) += cmd_ldrinfo.o
COBJS-$(CONFIG_CMD_LED) += cmd_led.o
COBJS-$(CONFIG_CMD_LICENSE) += cmd_license.o
COBJS-y += cmd_load.o
COBJS-$(CONFIG_LOGBUFFER) += cmd_log.o
COBJS-$(CONFIG_ID_EEPROM) += cmd_mac.o
COBJS-$(CONFIG_CMD_MD5SUM) += cmd_md5sum.o
COBJS-$(CONFIG_CMD_MEMORY) += cmd_mem.o
COBJS-$(CONFIG_CMD_MFSL) += cmd_mfsl.o
COBJS-$(CONFIG_CMD_MG_DISK) += cmd_mgdisk.o
COBJS-$(CONFIG_MII) += miiphyutil.o
COBJS-$(CONFIG_CMD_MII) += miiphyutil.o
COBJS-$(CONFIG_PHYLIB) += miiphyutil.o
COBJS-$(CONFIG_CMD_MII) += cmd_mii.o
ifdef CONFIG_PHYLIB
COBJS-$(CONFIG_CMD_MII) += cmd_mdio.o
endif
COBJS-$(CONFIG_CMD_MISC) += cmd_misc.o
COBJS-$(CONFIG_CMD_MMC) += cmd_mmc.o
COBJS-$(CONFIG_CMD_MMC_SPI) += cmd_mmc_spi.o
COBJS-$(CONFIG_MP) += cmd_mp.o
COBJS-$(CONFIG_CMD_MTDPARTS) += cmd_mtdparts.o
COBJS-$(CONFIG_CMD_NAND) += cmd_nand.o
COBJS-$(CONFIG_CMD_NET) += cmd_net.o
COBJS-$(CONFIG_CMD_ONENAND) += cmd_onenand.o
COBJS-$(CONFIG_CMD_OTP) += cmd_otp.o
ifdef CONFIG_PCI
COBJS-$(CONFIG_CMD_PCI) += cmd_pci.o
endif
COBJS-y += cmd_pcmcia.o
COBJS-$(CONFIG_CMD_PORTIO) += cmd_portio.o
COBJS-$(CONFIG_CMD_PXE) += cmd_pxe.o
COBJS-$(CONFIG_CMD_REGINFO) += cmd_reginfo.o
COBJS-$(CONFIG_CMD_REISER) += cmd_reiser.o
COBJS-$(CONFIG_CMD_SATA) += cmd_sata.o
COBJS-$(CONFIG_CMD_SF) += cmd_sf.o
COBJS-$(CONFIG_CMD_SCSI) += cmd_scsi.o
COBJS-$(CONFIG_CMD_SHA1SUM) += cmd_sha1sum.o
COBJS-$(CONFIG_CMD_SETEXPR) += cmd_setexpr.o
COBJS-$(CONFIG_CMD_SPI) += cmd_spi.o
COBJS-$(CONFIG_CMD_SPIBOOTLDR) += cmd_spibootldr.o
COBJS-$(CONFIG_CMD_STRINGS) += cmd_strings.o
COBJS-$(CONFIG_CMD_TERMINAL) += cmd_terminal.o
COBJS-$(CONFIG_CMD_TIME) += cmd_time.o
COBJS-$(CONFIG_SYS_HUSH_PARSER) += cmd_test.o
COBJS-$(CONFIG_CMD_TPM) += cmd_tpm.o
COBJS-$(CONFIG_CMD_TSI148) += cmd_tsi148.o
COBJS-$(CONFIG_CMD_UBI) += cmd_ubi.o
COBJS-$(CONFIG_CMD_UBIFS) += cmd_ubifs.o
COBJS-$(CONFIG_CMD_UNIVERSE) += cmd_universe.o
COBJS-$(CONFIG_CMD_UNZIP) += cmd_unzip.o
ifdef CONFIG_CMD_USB
COBJS-y += cmd_usb.o
COBJS-y += usb.o
COBJS-$(CONFIG_USB_STORAGE) += usb_storage.o
endif
COBJS-$(CONFIG_CMD_XIMG) += cmd_ximg.o
COBJS-$(CONFIG_YAFFS2) += cmd_yaffs2.o
# others
ifdef CONFIG_DDR_SPD
SPD := y
endif
ifdef CONFIG_SPD_EEPROM
SPD := y
endif
COBJS-$(SPD) += ddr_spd.o
COBJS-$(CONFIG_HWCONFIG) += hwconfig.o
COBJS-$(CONFIG_CONSOLE_MUX) += iomux.o
COBJS-y += flash.o
COBJS-$(CONFIG_CMD_KGDB) += kgdb.o kgdb_stubs.o
COBJS-$(CONFIG_KALLSYMS) += kallsyms.o
COBJS-$(CONFIG_LCD) += lcd.o
COBJS-$(CONFIG_LYNXKDI) += lynxkdi.o
COBJS-$(CONFIG_MENU) += menu.o
COBJS-$(CONFIG_MODEM_SUPPORT) += modem.o
COBJS-$(CONFIG_UPDATE_TFTP) += update.o
COBJS-$(CONFIG_USB_KEYBOARD) += usb_kbd.o
endif
COBJS-y += console.o
COBJS-y += dlmalloc.o
COBJS-y += memsize.o
COBJS-y += stdio.o
COBJS := $(sort $(COBJS-y))
XCOBJS := $(sort $(XCOBJS-y))
SRCS := $(COBJS:.o=.c) $(XCOBJS:.o=.c)
OBJS := $(addprefix $(obj),$(COBJS))
XOBJS := $(addprefix $(obj),$(XCOBJS))
CPPFLAGS += -I..
all: $(LIB) $(XOBJS)
$(LIB): $(obj).depend $(OBJS)
$(call cmd_link_o_target, $(OBJS))
$(obj)env_embedded.o: $(src)env_embedded.c $(obj)../tools/envcrc
$(CC) $(AFLAGS) -Wa,--no-warn \
-DENV_CRC=$(shell $(obj)../tools/envcrc) \
-c -o $@ $(src)env_embedded.c
$(obj)../tools/envcrc:
$(MAKE) -C ../tools
#########################################################################
# defines $(obj).depend target
include $(SRCTREE)/rules.mk
sinclude $(obj).depend
#########################################################################
|
1001-study-uboot
|
common/Makefile
|
Makefile
|
gpl3
| 7,148
|
#include <common.h>
#include <exports.h>
#include <spi.h>
DECLARE_GLOBAL_DATA_PTR;
__attribute__((unused)) static void dummy(void)
{
}
unsigned long get_version(void)
{
return XF_VERSION;
}
/* Reuse _exports.h with a little trickery to avoid bitrot */
#define EXPORT_FUNC(sym) gd->jt[XF_##sym] = (void *)sym;
#if !defined(CONFIG_X86) && !defined(CONFIG_PPC)
# define install_hdlr dummy
# define free_hdlr dummy
#else /* kludge for non-standard function naming */
# define install_hdlr irq_install_handler
# define free_hdlr irq_free_handler
#endif
#ifndef CONFIG_CMD_I2C
# define i2c_write dummy
# define i2c_read dummy
#endif
#ifndef CONFIG_CMD_SPI
# define spi_init dummy
# define spi_setup_slave dummy
# define spi_free_slave dummy
# define spi_claim_bus dummy
# define spi_release_bus dummy
# define spi_xfer dummy
#endif
void jumptable_init(void)
{
gd->jt = malloc(XF_MAX * sizeof(void *));
#include <_exports.h>
}
|
1001-study-uboot
|
common/exports.c
|
C
|
gpl3
| 1,000
|
/*
* Copyright (c) Orbacom Systems, Inc <www.orbacom.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms are freely
* permitted provided that the above copyright notice and this
* paragraph and the following disclaimer are duplicated in all
* such forms.
*
* This software is provided "AS IS" and without any express or
* implied warranties, including, without limitation, the implied
* warranties of merchantability and fitness for a particular
* purpose.
*/
#include <common.h>
#include <asm/processor.h>
#include <image.h>
#include <net.h>
#include <lynxkdi.h>
DECLARE_GLOBAL_DATA_PTR;
#if defined(CONFIG_MPC8260) || defined(CONFIG_440EP) || defined(CONFIG_440GR)
void lynxkdi_boot(image_header_t *hdr)
{
void (*lynxkdi)(void) = (void(*)(void))image_get_ep(hdr);
lynxos_bootparms_t *parms = (lynxos_bootparms_t *)0x0020;
bd_t *kbd;
u32 *psz = (u32 *)(image_get_load(hdr) + 0x0204);
memset(parms, 0, sizeof(*parms));
kbd = gd->bd;
parms->clock_ref = kbd->bi_busfreq;
parms->dramsz = kbd->bi_memsize;
eth_getenv_enetaddr("ethaddr", parms->ethaddr);
mtspr(SPRN_SPRG2, 0x0020);
/* Do a simple check for Bluecat so we can pass the
* kernel command line parameters.
*/
/* FIXME: NOT SURE HERE ! */
if (le32_to_cpu(*psz) == image_get_data_size(hdr)) {
char *args;
char *cmdline = (char *)(image_get_load(hdr) + 0x020c);
int len;
printf("Booting Bluecat KDI ...\n");
udelay(200*1000); /* Allow serial port to flush */
if ((args = getenv("bootargs")) == NULL)
args = "";
/* Prepend the cmdline */
len = strlen(args);
if (len && (len + strlen(cmdline) + 2 < (0x0400 - 0x020c))) {
memmove(cmdline + strlen(args) + 1, cmdline,
strlen(cmdline));
strcpy(cmdline, args);
cmdline[len] = ' ';
}
}
else {
printf("Booting LynxOS KDI ...\n");
}
lynxkdi();
}
#else
#error "Lynx KDI support not implemented for configured CPU"
#endif
|
1001-study-uboot
|
common/lynxkdi.c
|
C
|
gpl3
| 1,925
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/* #define DEBUG */
#include <common.h>
#include <flash.h>
#if !defined(CONFIG_SYS_NO_FLASH)
#include <mtd/cfi_flash.h>
extern flash_info_t flash_info[]; /* info for FLASH chips */
/*-----------------------------------------------------------------------
* Functions
*/
/*-----------------------------------------------------------------------
* Set protection status for monitor sectors
*
* The monitor is always located in the _first_ Flash bank.
* If necessary you have to map the second bank at lower addresses.
*/
void
flash_protect (int flag, ulong from, ulong to, flash_info_t *info)
{
ulong b_end;
short s_end;
int i;
/* Do nothing if input data is bad. */
if (!info || info->sector_count == 0 || info->size == 0 || to < from) {
return;
}
s_end = info->sector_count - 1; /* index of last sector */
b_end = info->start[0] + info->size - 1; /* bank end address */
debug ("flash_protect %s: from 0x%08lX to 0x%08lX\n",
(flag & FLAG_PROTECT_SET) ? "ON" :
(flag & FLAG_PROTECT_CLEAR) ? "OFF" : "???",
from, to);
/* There is nothing to do if we have no data about the flash
* or the protect range and flash range don't overlap.
*/
if (info->flash_id == FLASH_UNKNOWN ||
to < info->start[0] || from > b_end) {
return;
}
for (i=0; i<info->sector_count; ++i) {
ulong end; /* last address in current sect */
end = (i == s_end) ? b_end : info->start[i + 1] - 1;
/* Update protection if any part of the sector
* is in the specified range.
*/
if (from <= end && to >= info->start[i]) {
if (flag & FLAG_PROTECT_CLEAR) {
#if defined(CONFIG_SYS_FLASH_PROTECTION)
flash_real_protect(info, i, 0);
#else
info->protect[i] = 0;
#endif /* CONFIG_SYS_FLASH_PROTECTION */
debug ("protect off %d\n", i);
}
else if (flag & FLAG_PROTECT_SET) {
#if defined(CONFIG_SYS_FLASH_PROTECTION)
flash_real_protect(info, i, 1);
#else
info->protect[i] = 1;
#endif /* CONFIG_SYS_FLASH_PROTECTION */
debug ("protect on %d\n", i);
}
}
}
}
/*-----------------------------------------------------------------------
*/
flash_info_t *
addr2info (ulong addr)
{
#ifndef CONFIG_SPD823TS
flash_info_t *info;
int i;
for (i=0, info = &flash_info[0]; i<CONFIG_SYS_MAX_FLASH_BANKS; ++i, ++info) {
if (info->flash_id != FLASH_UNKNOWN &&
addr >= info->start[0] &&
/* WARNING - The '- 1' is needed if the flash
* is at the end of the address space, since
* info->start[0] + info->size wraps back to 0.
* Please don't change this unless you understand this.
*/
addr <= info->start[0] + info->size - 1) {
return (info);
}
}
#endif /* CONFIG_SPD823TS */
return (NULL);
}
/*-----------------------------------------------------------------------
* Copy memory to flash.
* Make sure all target addresses are within Flash bounds,
* and no protected sectors are hit.
* Returns:
* ERR_OK 0 - OK
* ERR_TIMOUT 1 - write timeout
* ERR_NOT_ERASED 2 - Flash not erased
* ERR_PROTECTED 4 - target range includes protected sectors
* ERR_INVAL 8 - target address not in Flash memory
* ERR_ALIGN 16 - target address not aligned on boundary
* (only some targets require alignment)
*/
int
flash_write (char *src, ulong addr, ulong cnt)
{
#ifdef CONFIG_SPD823TS
return (ERR_TIMOUT); /* any other error codes are possible as well */
#else
int i;
ulong end = addr + cnt - 1;
flash_info_t *info_first = addr2info (addr);
flash_info_t *info_last = addr2info (end );
flash_info_t *info;
if (cnt == 0) {
return (ERR_OK);
}
if (!info_first || !info_last) {
return (ERR_INVAL);
}
for (info = info_first; info <= info_last; ++info) {
ulong b_end = info->start[0] + info->size; /* bank end addr */
short s_end = info->sector_count - 1;
for (i=0; i<info->sector_count; ++i) {
ulong e_addr = (i == s_end) ? b_end : info->start[i + 1];
if ((end >= info->start[i]) && (addr < e_addr) &&
(info->protect[i] != 0) ) {
return (ERR_PROTECTED);
}
}
}
/* finally write data to flash */
for (info = info_first; info <= info_last && cnt>0; ++info) {
ulong len;
len = info->start[0] + info->size - addr;
if (len > cnt)
len = cnt;
if ((i = write_buff(info, (uchar *)src, addr, len)) != 0) {
return (i);
}
cnt -= len;
addr += len;
src += len;
}
return (ERR_OK);
#endif /* CONFIG_SPD823TS */
}
/*-----------------------------------------------------------------------
*/
void flash_perror (int err)
{
switch (err) {
case ERR_OK:
break;
case ERR_TIMOUT:
puts ("Timeout writing to Flash\n");
break;
case ERR_NOT_ERASED:
puts ("Flash not Erased\n");
break;
case ERR_PROTECTED:
puts ("Can't write to protected Flash sectors\n");
break;
case ERR_INVAL:
puts ("Outside available Flash\n");
break;
case ERR_ALIGN:
puts ("Start and/or end address not on sector boundary\n");
break;
case ERR_UNKNOWN_FLASH_VENDOR:
puts ("Unknown Vendor of Flash\n");
break;
case ERR_UNKNOWN_FLASH_TYPE:
puts ("Unknown Type of Flash\n");
break;
case ERR_PROG_ERROR:
puts ("General Flash Programming Error\n");
break;
default:
printf ("%s[%d] FIXME: rc=%d\n", __FILE__, __LINE__, err);
break;
}
}
/*-----------------------------------------------------------------------
*/
#endif /* !CONFIG_SYS_NO_FLASH */
|
1001-study-uboot
|
common/flash.c
|
C
|
gpl3
| 6,229
|
/*
* Common LCD routines for supported CPUs
*
* (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
*/
/************************************************************************/
/* ** HEADER FILES */
/************************************************************************/
/* #define DEBUG */
#include <config.h>
#include <common.h>
#include <command.h>
#include <stdarg.h>
#include <linux/types.h>
#include <stdio_dev.h>
#if defined(CONFIG_POST)
#include <post.h>
#endif
#include <lcd.h>
#include <watchdog.h>
#if defined(CONFIG_CPU_PXA25X) || defined(CONFIG_CPU_PXA27X) || \
defined(CONFIG_CPU_MONAHANS)
#define CONFIG_CPU_PXA
#include <asm/byteorder.h>
#endif
#if defined(CONFIG_MPC823)
#include <lcdvideo.h>
#endif
#if defined(CONFIG_ATMEL_LCD)
#include <atmel_lcdc.h>
#endif
/************************************************************************/
/* ** FONT DATA */
/************************************************************************/
#include <video_font.h> /* Get font data, width and height */
#include <video_font_data.h>
/************************************************************************/
/* ** LOGO DATA */
/************************************************************************/
#ifdef CONFIG_LCD_LOGO
# include <bmp_logo.h> /* Get logo data, width and height */
# include <bmp_logo_data.h>
# if (CONSOLE_COLOR_WHITE >= BMP_LOGO_OFFSET) && (LCD_BPP != LCD_COLOR16)
# error Default Color Map overlaps with Logo Color Map
# endif
#endif
DECLARE_GLOBAL_DATA_PTR;
ulong lcd_setmem (ulong addr);
static void lcd_drawchars (ushort x, ushort y, uchar *str, int count);
static inline void lcd_puts_xy (ushort x, ushort y, uchar *s);
static inline void lcd_putc_xy (ushort x, ushort y, uchar c);
static int lcd_init (void *lcdbase);
static void *lcd_logo (void);
static int lcd_getbgcolor (void);
static void lcd_setfgcolor (int color);
static void lcd_setbgcolor (int color);
char lcd_is_enabled = 0;
#ifdef NOT_USED_SO_FAR
static void lcd_getcolreg (ushort regno,
ushort *red, ushort *green, ushort *blue);
static int lcd_getfgcolor (void);
#endif /* NOT_USED_SO_FAR */
/************************************************************************/
/*----------------------------------------------------------------------*/
static void console_scrollup (void)
{
/* Copy up rows ignoring the first one */
memcpy (CONSOLE_ROW_FIRST, CONSOLE_ROW_SECOND, CONSOLE_SCROLL_SIZE);
/* Clear the last one */
memset (CONSOLE_ROW_LAST, COLOR_MASK(lcd_color_bg), CONSOLE_ROW_SIZE);
}
/*----------------------------------------------------------------------*/
static inline void console_back (void)
{
if (--console_col < 0) {
console_col = CONSOLE_COLS-1 ;
if (--console_row < 0) {
console_row = 0;
}
}
lcd_putc_xy (console_col * VIDEO_FONT_WIDTH,
console_row * VIDEO_FONT_HEIGHT,
' ');
}
/*----------------------------------------------------------------------*/
static inline void console_newline (void)
{
++console_row;
console_col = 0;
/* Check if we need to scroll the terminal */
if (console_row >= CONSOLE_ROWS) {
/* Scroll everything up */
console_scrollup () ;
--console_row;
}
}
/*----------------------------------------------------------------------*/
void lcd_putc (const char c)
{
if (!lcd_is_enabled) {
serial_putc(c);
return;
}
switch (c) {
case '\r': console_col = 0;
return;
case '\n': console_newline();
return;
case '\t': /* Tab (8 chars alignment) */
console_col += 8;
console_col &= ~7;
if (console_col >= CONSOLE_COLS) {
console_newline();
}
return;
case '\b': console_back();
return;
default: lcd_putc_xy (console_col * VIDEO_FONT_WIDTH,
console_row * VIDEO_FONT_HEIGHT,
c);
if (++console_col >= CONSOLE_COLS) {
console_newline();
}
return;
}
/* NOTREACHED */
}
/*----------------------------------------------------------------------*/
void lcd_puts (const char *s)
{
if (!lcd_is_enabled) {
serial_puts (s);
return;
}
while (*s) {
lcd_putc (*s++);
}
}
/*----------------------------------------------------------------------*/
void lcd_printf(const char *fmt, ...)
{
va_list args;
char buf[CONFIG_SYS_PBSIZE];
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
lcd_puts(buf);
}
/************************************************************************/
/* ** Low-Level Graphics Routines */
/************************************************************************/
static void lcd_drawchars (ushort x, ushort y, uchar *str, int count)
{
uchar *dest;
ushort row;
#if LCD_BPP == LCD_MONOCHROME
ushort off = x * (1 << LCD_BPP) % 8;
#endif
dest = (uchar *)(lcd_base + y * lcd_line_length + x * (1 << LCD_BPP) / 8);
for (row=0; row < VIDEO_FONT_HEIGHT; ++row, dest += lcd_line_length) {
uchar *s = str;
int i;
#if LCD_BPP == LCD_COLOR16
ushort *d = (ushort *)dest;
#else
uchar *d = dest;
#endif
#if LCD_BPP == LCD_MONOCHROME
uchar rest = *d & -(1 << (8-off));
uchar sym;
#endif
for (i=0; i<count; ++i) {
uchar c, bits;
c = *s++;
bits = video_fontdata[c * VIDEO_FONT_HEIGHT + row];
#if LCD_BPP == LCD_MONOCHROME
sym = (COLOR_MASK(lcd_color_fg) & bits) |
(COLOR_MASK(lcd_color_bg) & ~bits);
*d++ = rest | (sym >> off);
rest = sym << (8-off);
#elif LCD_BPP == LCD_COLOR8
for (c=0; c<8; ++c) {
*d++ = (bits & 0x80) ?
lcd_color_fg : lcd_color_bg;
bits <<= 1;
}
#elif LCD_BPP == LCD_COLOR16
for (c=0; c<8; ++c) {
*d++ = (bits & 0x80) ?
lcd_color_fg : lcd_color_bg;
bits <<= 1;
}
#endif
}
#if LCD_BPP == LCD_MONOCHROME
*d = rest | (*d & ((1 << (8-off)) - 1));
#endif
}
}
/*----------------------------------------------------------------------*/
static inline void lcd_puts_xy (ushort x, ushort y, uchar *s)
{
#if defined(CONFIG_LCD_LOGO) && !defined(CONFIG_LCD_INFO_BELOW_LOGO)
lcd_drawchars (x, y+BMP_LOGO_HEIGHT, s, strlen ((char *)s));
#else
lcd_drawchars (x, y, s, strlen ((char *)s));
#endif
}
/*----------------------------------------------------------------------*/
static inline void lcd_putc_xy (ushort x, ushort y, uchar c)
{
#if defined(CONFIG_LCD_LOGO) && !defined(CONFIG_LCD_INFO_BELOW_LOGO)
lcd_drawchars (x, y+BMP_LOGO_HEIGHT, &c, 1);
#else
lcd_drawchars (x, y, &c, 1);
#endif
}
/************************************************************************/
/** Small utility to check that you got the colours right */
/************************************************************************/
#ifdef LCD_TEST_PATTERN
#define N_BLK_VERT 2
#define N_BLK_HOR 3
static int test_colors[N_BLK_HOR*N_BLK_VERT] = {
CONSOLE_COLOR_RED, CONSOLE_COLOR_GREEN, CONSOLE_COLOR_YELLOW,
CONSOLE_COLOR_BLUE, CONSOLE_COLOR_MAGENTA, CONSOLE_COLOR_CYAN,
};
static void test_pattern (void)
{
ushort v_max = panel_info.vl_row;
ushort h_max = panel_info.vl_col;
ushort v_step = (v_max + N_BLK_VERT - 1) / N_BLK_VERT;
ushort h_step = (h_max + N_BLK_HOR - 1) / N_BLK_HOR;
ushort v, h;
uchar *pix = (uchar *)lcd_base;
printf ("[LCD] Test Pattern: %d x %d [%d x %d]\n",
h_max, v_max, h_step, v_step);
/* WARNING: Code silently assumes 8bit/pixel */
for (v=0; v<v_max; ++v) {
uchar iy = v / v_step;
for (h=0; h<h_max; ++h) {
uchar ix = N_BLK_HOR * iy + (h/h_step);
*pix++ = test_colors[ix];
}
}
}
#endif /* LCD_TEST_PATTERN */
/************************************************************************/
/* ** GENERIC Initialization Routines */
/************************************************************************/
int drv_lcd_init (void)
{
struct stdio_dev lcddev;
int rc;
lcd_base = (void *)(gd->fb_base);
lcd_line_length = (panel_info.vl_col * NBITS (panel_info.vl_bpix)) / 8;
lcd_init (lcd_base); /* LCD initialization */
/* Device initialization */
memset (&lcddev, 0, sizeof (lcddev));
strcpy (lcddev.name, "lcd");
lcddev.ext = 0; /* No extensions */
lcddev.flags = DEV_FLAGS_OUTPUT; /* Output only */
lcddev.putc = lcd_putc; /* 'putc' function */
lcddev.puts = lcd_puts; /* 'puts' function */
rc = stdio_register (&lcddev);
return (rc == 0) ? 1 : rc;
}
/*----------------------------------------------------------------------*/
static
int do_lcd_clear(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
{
lcd_clear();
return 0;
}
void lcd_clear(void)
{
#if LCD_BPP == LCD_MONOCHROME
/* Setting the palette */
lcd_initcolregs();
#elif LCD_BPP == LCD_COLOR8
/* Setting the palette */
lcd_setcolreg (CONSOLE_COLOR_BLACK, 0, 0, 0);
lcd_setcolreg (CONSOLE_COLOR_RED, 0xFF, 0, 0);
lcd_setcolreg (CONSOLE_COLOR_GREEN, 0, 0xFF, 0);
lcd_setcolreg (CONSOLE_COLOR_YELLOW, 0xFF, 0xFF, 0);
lcd_setcolreg (CONSOLE_COLOR_BLUE, 0, 0, 0xFF);
lcd_setcolreg (CONSOLE_COLOR_MAGENTA, 0xFF, 0, 0xFF);
lcd_setcolreg (CONSOLE_COLOR_CYAN, 0, 0xFF, 0xFF);
lcd_setcolreg (CONSOLE_COLOR_GREY, 0xAA, 0xAA, 0xAA);
lcd_setcolreg (CONSOLE_COLOR_WHITE, 0xFF, 0xFF, 0xFF);
#endif
#ifndef CONFIG_SYS_WHITE_ON_BLACK
lcd_setfgcolor (CONSOLE_COLOR_BLACK);
lcd_setbgcolor (CONSOLE_COLOR_WHITE);
#else
lcd_setfgcolor (CONSOLE_COLOR_WHITE);
lcd_setbgcolor (CONSOLE_COLOR_BLACK);
#endif /* CONFIG_SYS_WHITE_ON_BLACK */
#ifdef LCD_TEST_PATTERN
test_pattern();
#else
/* set framebuffer to background color */
memset ((char *)lcd_base,
COLOR_MASK(lcd_getbgcolor()),
lcd_line_length*panel_info.vl_row);
#endif
/* Paint the logo and retrieve LCD base address */
debug ("[LCD] Drawing the logo...\n");
lcd_console_address = lcd_logo ();
console_col = 0;
console_row = 0;
}
U_BOOT_CMD(
cls, 1, 1, do_lcd_clear,
"clear screen",
""
);
/*----------------------------------------------------------------------*/
static int lcd_init (void *lcdbase)
{
/* Initialize the lcd controller */
debug ("[LCD] Initializing LCD frambuffer at %p\n", lcdbase);
lcd_ctrl_init (lcdbase);
lcd_is_enabled = 1;
lcd_clear();
lcd_enable ();
/* Initialize the console */
console_col = 0;
#ifdef CONFIG_LCD_INFO_BELOW_LOGO
console_row = 7 + BMP_LOGO_HEIGHT / VIDEO_FONT_HEIGHT;
#else
console_row = 1; /* leave 1 blank line below logo */
#endif
return 0;
}
/************************************************************************/
/* ** ROM capable initialization part - needed to reserve FB memory */
/************************************************************************/
/*
* This is called early in the system initialization to grab memory
* for the LCD controller.
* Returns new address for monitor, after reserving LCD buffer memory
*
* Note that this is running from ROM, so no write access to global data.
*/
ulong lcd_setmem (ulong addr)
{
ulong size;
int line_length = (panel_info.vl_col * NBITS (panel_info.vl_bpix)) / 8;
debug ("LCD panel info: %d x %d, %d bit/pix\n",
panel_info.vl_col, panel_info.vl_row, NBITS (panel_info.vl_bpix) );
size = line_length * panel_info.vl_row;
/* Round up to nearest full page */
size = (size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
/* Allocate pages for the frame buffer. */
addr -= size;
debug ("Reserving %ldk for LCD Framebuffer at: %08lx\n", size>>10, addr);
return (addr);
}
/*----------------------------------------------------------------------*/
static void lcd_setfgcolor (int color)
{
lcd_color_fg = color;
}
/*----------------------------------------------------------------------*/
static void lcd_setbgcolor (int color)
{
lcd_color_bg = color;
}
/*----------------------------------------------------------------------*/
#ifdef NOT_USED_SO_FAR
static int lcd_getfgcolor (void)
{
return lcd_color_fg;
}
#endif /* NOT_USED_SO_FAR */
/*----------------------------------------------------------------------*/
static int lcd_getbgcolor (void)
{
return lcd_color_bg;
}
/*----------------------------------------------------------------------*/
/************************************************************************/
/* ** Chipset depending Bitmap / Logo stuff... */
/************************************************************************/
#ifdef CONFIG_LCD_LOGO
void bitmap_plot (int x, int y)
{
#ifdef CONFIG_ATMEL_LCD
uint *cmap;
#else
ushort *cmap;
#endif
ushort i, j;
uchar *bmap;
uchar *fb;
ushort *fb16;
#if defined(CONFIG_CPU_PXA)
struct pxafb_info *fbi = &panel_info.pxa;
#elif defined(CONFIG_MPC823)
volatile immap_t *immr = (immap_t *) CONFIG_SYS_IMMR;
volatile cpm8xx_t *cp = &(immr->im_cpm);
#endif
debug ("Logo: width %d height %d colors %d cmap %d\n",
BMP_LOGO_WIDTH, BMP_LOGO_HEIGHT, BMP_LOGO_COLORS,
(int)(sizeof(bmp_logo_palette)/(sizeof(ushort))));
bmap = &bmp_logo_bitmap[0];
fb = (uchar *)(lcd_base + y * lcd_line_length + x);
if (NBITS(panel_info.vl_bpix) < 12) {
/* Leave room for default color map */
#if defined(CONFIG_CPU_PXA)
cmap = (ushort *)fbi->palette;
#elif defined(CONFIG_MPC823)
cmap = (ushort *)&(cp->lcd_cmap[BMP_LOGO_OFFSET*sizeof(ushort)]);
#elif defined(CONFIG_ATMEL_LCD)
cmap = (uint *) (panel_info.mmio + ATMEL_LCDC_LUT(0));
#else
/*
* default case: generic system with no cmap (most likely 16bpp)
* We set cmap to the source palette, so no change is done.
* This avoids even more ifdef in the next stanza
*/
cmap = bmp_logo_palette;
#endif
WATCHDOG_RESET();
/* Set color map */
for (i=0; i<(sizeof(bmp_logo_palette)/(sizeof(ushort))); ++i) {
ushort colreg = bmp_logo_palette[i];
#ifdef CONFIG_ATMEL_LCD
uint lut_entry;
#ifdef CONFIG_ATMEL_LCD_BGR555
lut_entry = ((colreg & 0x000F) << 11) |
((colreg & 0x00F0) << 2) |
((colreg & 0x0F00) >> 7);
#else /* CONFIG_ATMEL_LCD_RGB565 */
lut_entry = ((colreg & 0x000F) << 1) |
((colreg & 0x00F0) << 3) |
((colreg & 0x0F00) << 4);
#endif
*(cmap + BMP_LOGO_OFFSET) = lut_entry;
cmap++;
#else /* !CONFIG_ATMEL_LCD */
#ifdef CONFIG_SYS_INVERT_COLORS
*cmap++ = 0xffff - colreg;
#else
*cmap++ = colreg;
#endif
#endif /* CONFIG_ATMEL_LCD */
}
WATCHDOG_RESET();
for (i=0; i<BMP_LOGO_HEIGHT; ++i) {
memcpy (fb, bmap, BMP_LOGO_WIDTH);
bmap += BMP_LOGO_WIDTH;
fb += panel_info.vl_col;
}
}
else { /* true color mode */
u16 col16;
fb16 = (ushort *)(lcd_base + y * lcd_line_length + x);
for (i=0; i<BMP_LOGO_HEIGHT; ++i) {
for (j=0; j<BMP_LOGO_WIDTH; j++) {
col16 = bmp_logo_palette[(bmap[j]-16)];
fb16[j] =
((col16 & 0x000F) << 1) |
((col16 & 0x00F0) << 3) |
((col16 & 0x0F00) << 4);
}
bmap += BMP_LOGO_WIDTH;
fb16 += panel_info.vl_col;
}
}
WATCHDOG_RESET();
}
#endif /* CONFIG_LCD_LOGO */
/*----------------------------------------------------------------------*/
#if defined(CONFIG_CMD_BMP) || defined(CONFIG_SPLASH_SCREEN)
/*
* Display the BMP file located at address bmp_image.
* Only uncompressed.
*/
#ifdef CONFIG_SPLASH_SCREEN_ALIGN
#define BMP_ALIGN_CENTER 0x7FFF
#endif
int lcd_display_bitmap(ulong bmp_image, int x, int y)
{
#if !defined(CONFIG_MCC200)
ushort *cmap = NULL;
#endif
ushort *cmap_base = NULL;
ushort i, j;
uchar *fb;
bmp_image_t *bmp=(bmp_image_t *)bmp_image;
uchar *bmap;
ushort padded_line;
unsigned long width, height, byte_width;
unsigned long pwidth = panel_info.vl_col;
unsigned colors, bpix, bmp_bpix;
#if defined(CONFIG_CPU_PXA)
struct pxafb_info *fbi = &panel_info.pxa;
#elif defined(CONFIG_MPC823)
volatile immap_t *immr = (immap_t *) CONFIG_SYS_IMMR;
volatile cpm8xx_t *cp = &(immr->im_cpm);
#endif
if (!((bmp->header.signature[0]=='B') &&
(bmp->header.signature[1]=='M'))) {
printf ("Error: no valid bmp image at %lx\n", bmp_image);
return 1;
}
width = le32_to_cpu (bmp->header.width);
height = le32_to_cpu (bmp->header.height);
bmp_bpix = le16_to_cpu(bmp->header.bit_count);
colors = 1 << bmp_bpix;
bpix = NBITS(panel_info.vl_bpix);
if ((bpix != 1) && (bpix != 8) && (bpix != 16)) {
printf ("Error: %d bit/pixel mode, but BMP has %d bit/pixel\n",
bpix, bmp_bpix);
return 1;
}
/* We support displaying 8bpp BMPs on 16bpp LCDs */
if (bpix != bmp_bpix && (bmp_bpix != 8 || bpix != 16)) {
printf ("Error: %d bit/pixel mode, but BMP has %d bit/pixel\n",
bpix,
le16_to_cpu(bmp->header.bit_count));
return 1;
}
debug ("Display-bmp: %d x %d with %d colors\n",
(int)width, (int)height, (int)colors);
#if !defined(CONFIG_MCC200)
/* MCC200 LCD doesn't need CMAP, supports 1bpp b&w only */
if (bmp_bpix == 8) {
#if defined(CONFIG_CPU_PXA)
cmap = (ushort *)fbi->palette;
#elif defined(CONFIG_MPC823)
cmap = (ushort *)&(cp->lcd_cmap[255*sizeof(ushort)]);
#elif !defined(CONFIG_ATMEL_LCD)
cmap = panel_info.cmap;
#endif
cmap_base = cmap;
/* Set color map */
for (i=0; i<colors; ++i) {
bmp_color_table_entry_t cte = bmp->color_table[i];
#if !defined(CONFIG_ATMEL_LCD)
ushort colreg =
( ((cte.red) << 8) & 0xf800) |
( ((cte.green) << 3) & 0x07e0) |
( ((cte.blue) >> 3) & 0x001f) ;
#ifdef CONFIG_SYS_INVERT_COLORS
*cmap = 0xffff - colreg;
#else
*cmap = colreg;
#endif
#if defined(CONFIG_MPC823)
cmap--;
#else
cmap++;
#endif
#else /* CONFIG_ATMEL_LCD */
lcd_setcolreg(i, cte.red, cte.green, cte.blue);
#endif
}
}
#endif
/*
* BMP format for Monochrome assumes that the state of a
* pixel is described on a per Bit basis, not per Byte.
* So, in case of Monochrome BMP we should align widths
* on a byte boundary and convert them from Bit to Byte
* units.
* Probably, PXA250 and MPC823 process 1bpp BMP images in
* their own ways, so make the converting to be MCC200
* specific.
*/
#if defined(CONFIG_MCC200)
if (bpix==1)
{
width = ((width + 7) & ~7) >> 3;
x = ((x + 7) & ~7) >> 3;
pwidth= ((pwidth + 7) & ~7) >> 3;
}
#endif
padded_line = (width&0x3) ? ((width&~0x3)+4) : (width);
#ifdef CONFIG_SPLASH_SCREEN_ALIGN
if (x == BMP_ALIGN_CENTER)
x = max(0, (pwidth - width) / 2);
else if (x < 0)
x = max(0, pwidth - width + x + 1);
if (y == BMP_ALIGN_CENTER)
y = max(0, (panel_info.vl_row - height) / 2);
else if (y < 0)
y = max(0, panel_info.vl_row - height + y + 1);
#endif /* CONFIG_SPLASH_SCREEN_ALIGN */
if ((x + width)>pwidth)
width = pwidth - x;
if ((y + height)>panel_info.vl_row)
height = panel_info.vl_row - y;
bmap = (uchar *)bmp + le32_to_cpu (bmp->header.data_offset);
fb = (uchar *) (lcd_base +
(y + height - 1) * lcd_line_length + x * bpix / 8);
switch (bmp_bpix) {
case 1: /* pass through */
case 8:
if (bpix != 16)
byte_width = width;
else
byte_width = width * 2;
for (i = 0; i < height; ++i) {
WATCHDOG_RESET();
for (j = 0; j < width; j++) {
if (bpix != 16) {
#if defined(CONFIG_CPU_PXA) || defined(CONFIG_ATMEL_LCD)
*(fb++) = *(bmap++);
#elif defined(CONFIG_MPC823) || defined(CONFIG_MCC200)
*(fb++) = 255 - *(bmap++);
#endif
} else {
*(uint16_t *)fb = cmap_base[*(bmap++)];
fb += sizeof(uint16_t) / sizeof(*fb);
}
}
bmap += (width - padded_line);
fb -= (byte_width + lcd_line_length);
}
break;
#if defined(CONFIG_BMP_16BPP)
case 16:
for (i = 0; i < height; ++i) {
WATCHDOG_RESET();
for (j = 0; j < width; j++) {
#if defined(CONFIG_ATMEL_LCD_BGR555)
*(fb++) = ((bmap[0] & 0x1f) << 2) |
(bmap[1] & 0x03);
*(fb++) = (bmap[0] & 0xe0) |
((bmap[1] & 0x7c) >> 2);
bmap += 2;
#else
*(fb++) = *(bmap++);
*(fb++) = *(bmap++);
#endif
}
bmap += (padded_line - width) * 2;
fb -= (width * 2 + lcd_line_length);
}
break;
#endif /* CONFIG_BMP_16BPP */
default:
break;
};
return (0);
}
#endif
static void *lcd_logo (void)
{
#ifdef CONFIG_SPLASH_SCREEN
char *s;
ulong addr;
static int do_splash = 1;
if (do_splash && (s = getenv("splashimage")) != NULL) {
int x = 0, y = 0;
do_splash = 0;
addr = simple_strtoul (s, NULL, 16);
#ifdef CONFIG_SPLASH_SCREEN_ALIGN
if ((s = getenv ("splashpos")) != NULL) {
if (s[0] == 'm')
x = BMP_ALIGN_CENTER;
else
x = simple_strtol (s, NULL, 0);
if ((s = strchr (s + 1, ',')) != NULL) {
if (s[1] == 'm')
y = BMP_ALIGN_CENTER;
else
y = simple_strtol (s + 1, NULL, 0);
}
}
#endif /* CONFIG_SPLASH_SCREEN_ALIGN */
#ifdef CONFIG_VIDEO_BMP_GZIP
bmp_image_t *bmp = (bmp_image_t *)addr;
unsigned long len;
if (!((bmp->header.signature[0]=='B') &&
(bmp->header.signature[1]=='M'))) {
addr = (ulong)gunzip_bmp(addr, &len);
}
#endif
if (lcd_display_bitmap (addr, x, y) == 0) {
return ((void *)lcd_base);
}
}
#endif /* CONFIG_SPLASH_SCREEN */
#ifdef CONFIG_LCD_LOGO
bitmap_plot (0, 0);
#endif /* CONFIG_LCD_LOGO */
#ifdef CONFIG_LCD_INFO
console_col = LCD_INFO_X / VIDEO_FONT_WIDTH;
console_row = LCD_INFO_Y / VIDEO_FONT_HEIGHT;
lcd_show_board_info();
#endif /* CONFIG_LCD_INFO */
#if defined(CONFIG_LCD_LOGO) && !defined(CONFIG_LCD_INFO_BELOW_LOGO)
return ((void *)((ulong)lcd_base + BMP_LOGO_HEIGHT * lcd_line_length));
#else
return ((void *)lcd_base);
#endif /* CONFIG_LCD_LOGO && !CONFIG_LCD_INFO_BELOW_LOGO */
}
/************************************************************************/
/************************************************************************/
|
1001-study-uboot
|
common/lcd.c
|
C
|
gpl3
| 21,987
|
/*
* BedBug Functions
*/
#include <common.h>
#include <command.h>
#include <linux/ctype.h>
#include <net.h>
#include <bedbug/type.h>
#include <bedbug/bedbug.h>
#include <bedbug/regs.h>
#include <bedbug/ppc.h>
DECLARE_GLOBAL_DATA_PTR;
extern void show_regs __P ((struct pt_regs *));
extern int run_command __P ((const char *, int));
ulong dis_last_addr = 0; /* Last address disassembled */
ulong dis_last_len = 20; /* Default disassembler length */
CPU_DEBUG_CTX bug_ctx; /* Bedbug context structure */
/* ======================================================================
* U-Boot's puts function does not append a newline, so the bedbug stuff
* will use this for the output of the dis/assembler.
* ====================================================================== */
int bedbug_puts (const char *str)
{
/* -------------------------------------------------- */
printf ("%s\r\n", str);
return 0;
} /* bedbug_puts */
/* ======================================================================
* Initialize the bug_ctx structure used by the bedbug debugger. This is
* specific to the CPU since each has different debug registers and
* settings.
* ====================================================================== */
void bedbug_init (void)
{
/* -------------------------------------------------- */
#if defined(CONFIG_4xx)
void bedbug405_init (void);
bedbug405_init ();
#elif defined(CONFIG_8xx)
void bedbug860_init (void);
bedbug860_init ();
#endif
#if defined(CONFIG_MPC824X) || defined(CONFIG_MPC8260)
/* Processors that are 603e core based */
void bedbug603e_init (void);
bedbug603e_init ();
#endif
return;
} /* bedbug_init */
/* ======================================================================
* Entry point from the interpreter to the disassembler. Repeated calls
* will resume from the last disassembled address.
* ====================================================================== */
int do_bedbug_dis (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong addr; /* Address to start disassembly from */
ulong len; /* # of instructions to disassemble */
/* -------------------------------------------------- */
/* Setup to go from the last address if none is given */
addr = dis_last_addr;
len = dis_last_len;
if (argc < 2)
return cmd_usage(cmdtp);
if ((flag & CMD_FLAG_REPEAT) == 0) {
/* New command */
addr = simple_strtoul (argv[1], NULL, 16);
/* If an extra param is given then it is the length */
if (argc > 2)
len = simple_strtoul (argv[2], NULL, 16);
}
/* Run the disassembler */
disppc ((unsigned char *) addr, 0, len, bedbug_puts, F_RADHEX);
dis_last_addr = addr + (len * 4);
dis_last_len = len;
return 0;
} /* do_bedbug_dis */
U_BOOT_CMD (ds, 3, 1, do_bedbug_dis,
"disassemble memory",
"ds <address> [# instructions]");
/* ======================================================================
* Entry point from the interpreter to the assembler. Assembles
* instructions in consecutive memory locations until a '.' (period) is
* entered on a line by itself.
* ====================================================================== */
int do_bedbug_asm (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
long mem_addr; /* Address to assemble into */
unsigned long instr; /* Machine code for text */
char prompt[15]; /* Prompt string for user input */
int asm_err; /* Error code from the assembler */
/* -------------------------------------------------- */
int rcode = 0;
if (argc < 2)
return cmd_usage(cmdtp);
printf ("\nEnter '.' when done\n");
mem_addr = simple_strtoul (argv[1], NULL, 16);
while (1) {
putc ('\n');
disppc ((unsigned char *) mem_addr, 0, 1, bedbug_puts,
F_RADHEX);
sprintf (prompt, "%08lx: ", mem_addr);
readline (prompt);
if (console_buffer[0] && strcmp (console_buffer, ".")) {
if ((instr =
asmppc (mem_addr, console_buffer,
&asm_err)) != 0) {
*(unsigned long *) mem_addr = instr;
mem_addr += 4;
} else {
printf ("*** Error: %s ***\n",
asm_error_str (asm_err));
rcode = 1;
}
} else {
break;
}
}
return rcode;
} /* do_bedbug_asm */
U_BOOT_CMD (as, 2, 0, do_bedbug_asm,
"assemble memory", "as <address>");
/* ======================================================================
* Used to set a break point from the interpreter. Simply calls into the
* CPU-specific break point set routine.
* ====================================================================== */
int do_bedbug_break (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
/* -------------------------------------------------- */
if (bug_ctx.do_break)
(*bug_ctx.do_break) (cmdtp, flag, argc, argv);
return 0;
} /* do_bedbug_break */
U_BOOT_CMD (break, 3, 0, do_bedbug_break,
"set or clear a breakpoint",
" - Set or clear a breakpoint\n"
"break <address> - Break at an address\n"
"break off <bp#> - Disable breakpoint.\n"
"break show - List breakpoints.");
/* ======================================================================
* Called from the debug interrupt routine. Simply calls the CPU-specific
* breakpoint handling routine.
* ====================================================================== */
void do_bedbug_breakpoint (struct pt_regs *regs)
{
/* -------------------------------------------------- */
if (bug_ctx.break_isr)
(*bug_ctx.break_isr) (regs);
return;
} /* do_bedbug_breakpoint */
/* ======================================================================
* Called from the CPU-specific breakpoint handling routine. Enter a
* mini main loop until the stopped flag is cleared from the breakpoint
* context.
*
* This handles the parts of the debugger that are common to all CPU's.
* ====================================================================== */
void bedbug_main_loop (unsigned long addr, struct pt_regs *regs)
{
int len; /* Length of command line */
int flag; /* Command flags */
int rc = 0; /* Result from run_command */
char prompt_str[20]; /* Prompt string */
static char lastcommand[CONFIG_SYS_CBSIZE] = { 0 }; /* previous command */
/* -------------------------------------------------- */
if (bug_ctx.clear)
(*bug_ctx.clear) (bug_ctx.current_bp);
printf ("Breakpoint %d: ", bug_ctx.current_bp);
disppc ((unsigned char *) addr, 0, 1, bedbug_puts, F_RADHEX);
bug_ctx.stopped = 1;
bug_ctx.regs = regs;
sprintf (prompt_str, "BEDBUG.%d =>", bug_ctx.current_bp);
/* A miniature main loop */
while (bug_ctx.stopped) {
len = readline (prompt_str);
flag = 0; /* assume no special flags for now */
if (len > 0)
strcpy (lastcommand, console_buffer);
else if (len == 0)
flag |= CMD_FLAG_REPEAT;
if (len == -1)
printf ("<INTERRUPT>\n");
else
rc = run_command (lastcommand, flag);
if (rc <= 0) {
/* invalid command or not repeatable, forget it */
lastcommand[0] = 0;
}
}
bug_ctx.regs = NULL;
bug_ctx.current_bp = 0;
return;
} /* bedbug_main_loop */
/* ======================================================================
* Interpreter command to continue from a breakpoint. Just clears the
* stopped flag in the context so that the breakpoint routine will
* return.
* ====================================================================== */
int do_bedbug_continue (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
/* -------------------------------------------------- */
if (!bug_ctx.stopped) {
printf ("Not at a breakpoint\n");
return 1;
}
bug_ctx.stopped = 0;
return 0;
} /* do_bedbug_continue */
U_BOOT_CMD (continue, 1, 0, do_bedbug_continue,
"continue from a breakpoint",
"");
/* ======================================================================
* Interpreter command to continue to the next instruction, stepping into
* subroutines. Works by calling the find_next_addr() routine to compute
* the address passes control to the CPU-specific set breakpoint routine
* for the current breakpoint number.
* ====================================================================== */
int do_bedbug_step (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned long addr; /* Address to stop at */
/* -------------------------------------------------- */
if (!bug_ctx.stopped) {
printf ("Not at a breakpoint\n");
return 1;
}
if (!find_next_address ((unsigned char *) &addr, FALSE, bug_ctx.regs))
return 1;
if (bug_ctx.set)
(*bug_ctx.set) (bug_ctx.current_bp, addr);
bug_ctx.stopped = 0;
return 0;
} /* do_bedbug_step */
U_BOOT_CMD (step, 1, 1, do_bedbug_step,
"single step execution.",
"");
/* ======================================================================
* Interpreter command to continue to the next instruction, stepping over
* subroutines. Works by calling the find_next_addr() routine to compute
* the address passes control to the CPU-specific set breakpoint routine
* for the current breakpoint number.
* ====================================================================== */
int do_bedbug_next (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned long addr; /* Address to stop at */
/* -------------------------------------------------- */
if (!bug_ctx.stopped) {
printf ("Not at a breakpoint\n");
return 1;
}
if (!find_next_address ((unsigned char *) &addr, TRUE, bug_ctx.regs))
return 1;
if (bug_ctx.set)
(*bug_ctx.set) (bug_ctx.current_bp, addr);
bug_ctx.stopped = 0;
return 0;
} /* do_bedbug_next */
U_BOOT_CMD (next, 1, 1, do_bedbug_next,
"single step execution, stepping over subroutines.",
"");
/* ======================================================================
* Interpreter command to print the current stack. This assumes an EABI
* architecture, so it starts with GPR R1 and works back up the stack.
* ====================================================================== */
int do_bedbug_stack (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned long sp; /* Stack pointer */
unsigned long func; /* LR from stack */
int depth; /* Stack iteration level */
int skip = 1; /* Flag to skip the first entry */
unsigned long top; /* Top of memory address */
/* -------------------------------------------------- */
if (!bug_ctx.stopped) {
printf ("Not at a breakpoint\n");
return 1;
}
top = gd->bd->bi_memstart + gd->bd->bi_memsize;
depth = 0;
printf ("Depth PC\n");
printf ("----- --------\n");
printf ("%5d %08lx\n", depth++, bug_ctx.regs->nip);
sp = bug_ctx.regs->gpr[1];
func = *(unsigned long *) (sp + 4);
while ((func < top) && (sp < top)) {
if (!skip)
printf ("%5d %08lx\n", depth++, func);
else
--skip;
sp = *(unsigned long *) sp;
func = *(unsigned long *) (sp + 4);
}
return 0;
} /* do_bedbug_stack */
U_BOOT_CMD (where, 1, 1, do_bedbug_stack,
"Print the running stack.",
"");
/* ======================================================================
* Interpreter command to dump the registers. Calls the CPU-specific
* show registers routine.
* ====================================================================== */
int do_bedbug_rdump (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
/* -------------------------------------------------- */
if (!bug_ctx.stopped) {
printf ("Not at a breakpoint\n");
return 1;
}
show_regs (bug_ctx.regs);
return 0;
} /* do_bedbug_rdump */
U_BOOT_CMD (rdump, 1, 1, do_bedbug_rdump,
"Show registers.", "");
/* ====================================================================== */
/*
* Copyright (c) 2001 William L. Pitts
* All rights reserved.
*
* Redistribution and use in source and binary forms are freely
* permitted provided that the above copyright notice and this
* paragraph and the following disclaimer are duplicated in all
* such forms.
*
* This software is provided "AS IS" and without any express or
* implied warranties, including, without limitation, the implied
* warranties of merchantability and fitness for a particular
* purpose.
*/
|
1001-study-uboot
|
common/cmd_bedbug.c
|
C
|
gpl3
| 12,284
|
/*
* (C) Copyright 2000
* Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <config.h>
#include <common.h>
#include <stdarg.h>
#include <malloc.h>
#include <stdio_dev.h>
#include <serial.h>
#ifdef CONFIG_LOGBUFFER
#include <logbuff.h>
#endif
#if defined(CONFIG_HARD_I2C) || defined(CONFIG_SOFT_I2C)
#include <i2c.h>
#endif
DECLARE_GLOBAL_DATA_PTR;
static struct stdio_dev devs;
struct stdio_dev *stdio_devices[] = { NULL, NULL, NULL };
char *stdio_names[MAX_FILES] = { "stdin", "stdout", "stderr" };
#if defined(CONFIG_SPLASH_SCREEN) && !defined(CONFIG_SYS_DEVICE_NULLDEV)
#define CONFIG_SYS_DEVICE_NULLDEV 1
#endif
#ifdef CONFIG_SYS_DEVICE_NULLDEV
void nulldev_putc(const char c)
{
/* nulldev is empty! */
}
void nulldev_puts(const char *s)
{
/* nulldev is empty! */
}
int nulldev_input(void)
{
/* nulldev is empty! */
return 0;
}
#endif
/**************************************************************************
* SYSTEM DRIVERS
**************************************************************************
*/
static void drv_system_init (void)
{
struct stdio_dev dev;
memset (&dev, 0, sizeof (dev));
strcpy (dev.name, "serial");
dev.flags = DEV_FLAGS_OUTPUT | DEV_FLAGS_INPUT | DEV_FLAGS_SYSTEM;
dev.putc = serial_putc;
dev.puts = serial_puts;
dev.getc = serial_getc;
dev.tstc = serial_tstc;
stdio_register (&dev);
#ifdef CONFIG_SYS_DEVICE_NULLDEV
memset (&dev, 0, sizeof (dev));
strcpy (dev.name, "nulldev");
dev.flags = DEV_FLAGS_OUTPUT | DEV_FLAGS_INPUT | DEV_FLAGS_SYSTEM;
dev.putc = nulldev_putc;
dev.puts = nulldev_puts;
dev.getc = nulldev_input;
dev.tstc = nulldev_input;
stdio_register (&dev);
#endif
}
/**************************************************************************
* DEVICES
**************************************************************************
*/
struct list_head* stdio_get_list(void)
{
return &(devs.list);
}
struct stdio_dev* stdio_get_by_name(const char *name)
{
struct list_head *pos;
struct stdio_dev *dev;
if(!name)
return NULL;
list_for_each(pos, &(devs.list)) {
dev = list_entry(pos, struct stdio_dev, list);
if(strcmp(dev->name, name) == 0)
return dev;
}
return NULL;
}
struct stdio_dev* stdio_clone(struct stdio_dev *dev)
{
struct stdio_dev *_dev;
if(!dev)
return NULL;
_dev = calloc(1, sizeof(struct stdio_dev));
if(!_dev)
return NULL;
memcpy(_dev, dev, sizeof(struct stdio_dev));
strncpy(_dev->name, dev->name, 16);
return _dev;
}
int stdio_register (struct stdio_dev * dev)
{
struct stdio_dev *_dev;
_dev = stdio_clone(dev);
if(!_dev)
return -1;
list_add_tail(&(_dev->list), &(devs.list));
return 0;
}
/* deregister the device "devname".
* returns 0 if success, -1 if device is assigned and 1 if devname not found
*/
#ifdef CONFIG_SYS_STDIO_DEREGISTER
int stdio_deregister(const char *devname)
{
int l;
struct list_head *pos;
struct stdio_dev *dev;
char temp_names[3][16];
dev = stdio_get_by_name(devname);
if(!dev) /* device not found */
return -1;
/* get stdio devices (ListRemoveItem changes the dev list) */
for (l=0 ; l< MAX_FILES; l++) {
if (stdio_devices[l] == dev) {
/* Device is assigned -> report error */
return -1;
}
memcpy (&temp_names[l][0],
stdio_devices[l]->name,
sizeof(temp_names[l]));
}
list_del(&(dev->list));
/* reassign Device list */
list_for_each(pos, &(devs.list)) {
dev = list_entry(pos, struct stdio_dev, list);
for (l=0 ; l< MAX_FILES; l++) {
if(strcmp(dev->name, temp_names[l]) == 0)
stdio_devices[l] = dev;
}
}
return 0;
}
#endif /* CONFIG_SYS_STDIO_DEREGISTER */
int stdio_init (void)
{
#if defined(CONFIG_NEEDS_MANUAL_RELOC)
/* already relocated for current ARM implementation */
ulong relocation_offset = gd->reloc_off;
int i;
/* relocate device name pointers */
for (i = 0; i < (sizeof (stdio_names) / sizeof (char *)); ++i) {
stdio_names[i] = (char *) (((ulong) stdio_names[i]) +
relocation_offset);
}
#endif /* CONFIG_NEEDS_MANUAL_RELOC */
/* Initialize the list */
INIT_LIST_HEAD(&(devs.list));
#ifdef CONFIG_ARM_DCC_MULTI
drv_arm_dcc_init ();
#endif
#if defined(CONFIG_HARD_I2C) || defined(CONFIG_SOFT_I2C)
i2c_init (CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE);
#endif
#ifdef CONFIG_LCD
drv_lcd_init ();
#endif
#if defined(CONFIG_VIDEO) || defined(CONFIG_CFB_CONSOLE)
drv_video_init ();
#endif
#ifdef CONFIG_KEYBOARD
drv_keyboard_init ();
#endif
#ifdef CONFIG_LOGBUFFER
drv_logbuff_init ();
#endif
drv_system_init ();
#ifdef CONFIG_SERIAL_MULTI
serial_stdio_init ();
#endif
#ifdef CONFIG_USB_TTY
drv_usbtty_init ();
#endif
#ifdef CONFIG_NETCONSOLE
drv_nc_init ();
#endif
#ifdef CONFIG_JTAG_CONSOLE
drv_jtag_console_init ();
#endif
return (0);
}
|
1001-study-uboot
|
common/stdio.c
|
C
|
gpl3
| 5,529
|