code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* (C) Copyright 2011 Freescale Semiconductor, Inc
* Andy Fleming
*
* 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
*/
/*
* MDIO Commands
*/
#include <common.h>
#include <command.h>
#include <miiphy.h>
#include <phy.h>
static char last_op[2];
static uint last_data;
static uint last_addr_lo;
static uint last_addr_hi;
static uint last_devad_lo;
static uint last_devad_hi;
static uint last_reg_lo;
static uint last_reg_hi;
static int extract_range(char *input, int *plo, int *phi)
{
char *end;
*plo = simple_strtol(input, &end, 0);
if (end == input)
return -1;
if ((*end == '-') && *(++end))
*phi = simple_strtol(end, NULL, 0);
else if (*end == '\0')
*phi = *plo;
else
return -1;
return 0;
}
int mdio_write_ranges(struct mii_dev *bus, int addrlo,
int addrhi, int devadlo, int devadhi,
int reglo, int reghi, unsigned short data)
{
int addr, devad, reg;
int err = 0;
for (addr = addrlo; addr <= addrhi; addr++) {
for (devad = devadlo; devad <= devadhi; devad++) {
for (reg = reglo; reg <= reghi; reg++) {
err = bus->write(bus, addr, devad, reg, data);
if (err)
goto err_out;
}
}
}
err_out:
return err;
}
int mdio_read_ranges(struct mii_dev *bus, int addrlo,
int addrhi, int devadlo, int devadhi,
int reglo, int reghi)
{
int addr, devad, reg;
printf("Reading from bus %s\n", bus->name);
for (addr = addrlo; addr <= addrhi; addr++) {
printf("PHY at address %d:\n", addr);
for (devad = devadlo; devad <= devadhi; devad++) {
for (reg = reglo; reg <= reghi; reg++) {
int val;
val = bus->read(bus, addr, devad, reg);
if (val < 0) {
printf("Error\n");
return val;
}
if (devad >= 0)
printf("%d.", devad);
printf("%d - 0x%x\n", reg, val & 0xffff);
}
}
}
return 0;
}
/* The register will be in the form [a[-b].]x[-y] */
int extract_reg_range(char *input, int *devadlo, int *devadhi,
int *reglo, int *reghi)
{
char *regstr;
/* use strrchr to find the last string after a '.' */
regstr = strrchr(input, '.');
/* If it exists, extract the devad(s) */
if (regstr) {
char devadstr[32];
strncpy(devadstr, input, regstr - input);
devadstr[regstr - input] = '\0';
if (extract_range(devadstr, devadlo, devadhi))
return -1;
regstr++;
} else {
/* Otherwise, we have no devad, and we just got regs */
*devadlo = *devadhi = MDIO_DEVAD_NONE;
regstr = input;
}
return extract_range(regstr, reglo, reghi);
}
int extract_phy_range(char *const argv[], int argc, struct mii_dev **bus,
int *addrlo, int *addrhi)
{
struct phy_device *phydev;
if ((argc < 1) || (argc > 2))
return -1;
/* If there are two arguments, it's busname addr */
if (argc == 2) {
*bus = miiphy_get_dev_by_name(argv[0]);
if (!*bus)
return -1;
return extract_range(argv[1], addrlo, addrhi);
}
/* It must be one argument, here */
/*
* This argument can be one of two things:
* 1) Ethernet device name
* 2) Just an address (use the previously-used bus)
*
* We check all buses for a PHY which is connected to an ethernet
* device by the given name. If none are found, we call
* extract_range() on the string, and see if it's an address range.
*/
phydev = mdio_phydev_for_ethname(argv[0]);
if (phydev) {
*addrlo = *addrhi = phydev->addr;
*bus = phydev->bus;
return 0;
}
/* It's an address or nothing useful */
return extract_range(argv[0], addrlo, addrhi);
}
/* ---------------------------------------------------------------- */
static int do_mdio(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char op[2];
int addrlo, addrhi, reglo, reghi, devadlo, devadhi;
unsigned short data;
int pos = argc - 1;
struct mii_dev *bus;
if (argc < 2)
return cmd_usage(cmdtp);
/*
* We use the last specified parameters, unless new ones are
* entered.
*/
op[0] = argv[1][0];
addrlo = last_addr_lo;
addrhi = last_addr_hi;
devadlo = last_devad_lo;
devadhi = last_devad_hi;
reglo = last_reg_lo;
reghi = last_reg_hi;
data = last_data;
bus = mdio_get_current_dev();
if (flag & CMD_FLAG_REPEAT)
op[0] = last_op[0];
switch (op[0]) {
case 'w':
if (pos > 1)
data = simple_strtoul(argv[pos--], NULL, 16);
case 'r':
if (pos > 1)
if (extract_reg_range(argv[pos--], &devadlo, &devadhi,
®lo, ®hi))
return -1;
default:
if (pos > 1)
if (extract_phy_range(&(argv[2]), pos - 1, &bus,
&addrlo, &addrhi))
return -1;
break;
}
if (op[0] == 'l') {
mdio_list_devices();
return 0;
}
/* Save the chosen bus */
miiphy_set_current_dev(bus->name);
switch (op[0]) {
case 'w':
mdio_write_ranges(bus, addrlo, addrhi, devadlo, devadhi,
reglo, reghi, data);
break;
case 'r':
mdio_read_ranges(bus, addrlo, addrhi, devadlo, devadhi,
reglo, reghi);
break;
}
/*
* Save the parameters for repeats.
*/
last_op[0] = op[0];
last_addr_lo = addrlo;
last_addr_hi = addrhi;
last_devad_lo = devadlo;
last_devad_hi = devadhi;
last_reg_lo = reglo;
last_reg_hi = reghi;
last_data = data;
return 0;
}
/***************************************************/
U_BOOT_CMD(
mdio, 6, 1, do_mdio,
"MDIO utility commands",
"list - List MDIO buses\n"
"mdio read <phydev> [<devad>.]<reg> - "
"read PHY's register at <devad>.<reg>\n"
"mdio write <phydev> [<devad>.]<reg> <data> - "
"write PHY's register at <devad>.<reg>\n"
"<phydev> may be:\n"
" <busname> <addr>\n"
" <addr>\n"
" <eth name>\n"
"<addr> <devad>, and <reg> may be ranges, e.g. 1-5.4-0x1f.\n"
);
|
1001-study-uboot
|
common/cmd_mdio.c
|
C
|
gpl3
| 6,266
|
/*
* (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>
static int do_unzip(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unsigned long src, dst;
unsigned long src_len = ~0UL, dst_len = ~0UL;
char buf[32];
switch (argc) {
case 4:
dst_len = simple_strtoul(argv[3], NULL, 16);
/* fall through */
case 3:
src = simple_strtoul(argv[1], NULL, 16);
dst = simple_strtoul(argv[2], NULL, 16);
break;
default:
return cmd_usage(cmdtp);
}
if (gunzip((void *) dst, dst_len, (void *) src, &src_len) != 0)
return 1;
printf("Uncompressed size: %ld = 0x%lX\n", src_len, src_len);
sprintf(buf, "%lX", src_len);
setenv("filesize", buf);
return 0;
}
U_BOOT_CMD(
unzip, 4, 1, do_unzip,
"unzip a memory region",
"srcaddr dstaddr [dstsize]"
);
|
1001-study-uboot
|
common/cmd_unzip.c
|
C
|
gpl3
| 1,648
|
/*
* (C) Copyright 2001
* Denis Peter, MPL AG Switzerland
*
* Part 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 <malloc.h>
#include <stdio_dev.h>
#include <asm/byteorder.h>
#include <usb.h>
#ifdef USB_KBD_DEBUG
#define USB_KBD_PRINTF(fmt, args...) printf(fmt, ##args)
#else
#define USB_KBD_PRINTF(fmt, args...)
#endif
/*
* 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);
#else
int overwrite_console(void)
{
return 0;
}
#endif
/* Keyboard sampling rate */
#define REPEAT_RATE (40 / 4) /* 40msec -> 25cps */
#define REPEAT_DELAY 10 /* 10 x REPEAT_RATE = 400msec */
#define NUM_LOCK 0x53
#define CAPS_LOCK 0x39
#define SCROLL_LOCK 0x47
/* Modifier bits */
#define LEFT_CNTR (1 << 0)
#define LEFT_SHIFT (1 << 1)
#define LEFT_ALT (1 << 2)
#define LEFT_GUI (1 << 3)
#define RIGHT_CNTR (1 << 4)
#define RIGHT_SHIFT (1 << 5)
#define RIGHT_ALT (1 << 6)
#define RIGHT_GUI (1 << 7)
/* Size of the keyboard buffer */
#define USB_KBD_BUFFER_LEN 0x20
/* Device name */
#define DEVNAME "usbkbd"
/* Keyboard maps */
static const unsigned char usb_kbd_numkey[] = {
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'\r', 0x1b, '\b', '\t', ' ', '-', '=', '[', ']',
'\\', '#', ';', '\'', '`', ',', '.', '/'
};
static const unsigned char usb_kbd_numkey_shifted[] = {
'!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
'\r', 0x1b, '\b', '\t', ' ', '_', '+', '{', '}',
'|', '~', ':', '"', '~', '<', '>', '?'
};
/*
* NOTE: It's important for the NUM, CAPS, SCROLL-lock bits to be in this
* order. See usb_kbd_setled() function!
*/
#define USB_KBD_NUMLOCK (1 << 0)
#define USB_KBD_CAPSLOCK (1 << 1)
#define USB_KBD_SCROLLLOCK (1 << 2)
#define USB_KBD_CTRL (1 << 3)
#define USB_KBD_LEDMASK \
(USB_KBD_NUMLOCK | USB_KBD_CAPSLOCK | USB_KBD_SCROLLLOCK)
struct usb_kbd_pdata {
uint32_t repeat_delay;
uint32_t usb_in_pointer;
uint32_t usb_out_pointer;
uint8_t usb_kbd_buffer[USB_KBD_BUFFER_LEN];
uint8_t new[8];
uint8_t old[8];
uint8_t flags;
};
/* Generic keyboard event polling. */
void usb_kbd_generic_poll(void)
{
struct stdio_dev *dev;
struct usb_device *usb_kbd_dev;
struct usb_kbd_pdata *data;
struct usb_interface *iface;
struct usb_endpoint_descriptor *ep;
int pipe;
int maxp;
/* Get the pointer to USB Keyboard device pointer */
dev = stdio_get_by_name(DEVNAME);
usb_kbd_dev = (struct usb_device *)dev->priv;
data = usb_kbd_dev->privptr;
iface = &usb_kbd_dev->config.if_desc[0];
ep = &iface->ep_desc[0];
pipe = usb_rcvintpipe(usb_kbd_dev, ep->bEndpointAddress);
/* Submit a interrupt transfer request */
maxp = usb_maxpacket(usb_kbd_dev, pipe);
usb_submit_int_msg(usb_kbd_dev, pipe, data->new,
maxp > 8 ? 8 : maxp, ep->bInterval);
}
/* Puts character in the queue and sets up the in and out pointer. */
static void usb_kbd_put_queue(struct usb_kbd_pdata *data, char c)
{
if (data->usb_in_pointer == USB_KBD_BUFFER_LEN - 1) {
/* Check for buffer full. */
if (data->usb_out_pointer == 0)
return;
data->usb_in_pointer = 0;
} else {
/* Check for buffer full. */
if (data->usb_in_pointer == data->usb_out_pointer - 1)
return;
data->usb_in_pointer++;
}
data->usb_kbd_buffer[data->usb_in_pointer] = c;
}
/*
* Set the LEDs. Since this is used in the irq routine, the control job is
* issued with a timeout of 0. This means, that the job is queued without
* waiting for job completion.
*/
static void usb_kbd_setled(struct usb_device *dev)
{
struct usb_interface *iface = &dev->config.if_desc[0];
struct usb_kbd_pdata *data = dev->privptr;
uint32_t leds = data->flags & USB_KBD_LEDMASK;
usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0x200, iface->desc.bInterfaceNumber, (void *)&leds, 1, 0);
}
#define CAPITAL_MASK 0x20
/* Translate the scancode in ASCII */
static int usb_kbd_translate(struct usb_kbd_pdata *data, unsigned char scancode,
unsigned char modifier, int pressed)
{
uint8_t keycode = 0;
/* Key released */
if (pressed == 0) {
data->repeat_delay = 0;
return 0;
}
if (pressed == 2) {
data->repeat_delay++;
if (data->repeat_delay < REPEAT_DELAY)
return 0;
data->repeat_delay = REPEAT_DELAY;
}
/* Alphanumeric values */
if ((scancode > 3) && (scancode <= 0x1d)) {
keycode = scancode - 4 + 'a';
if (data->flags & USB_KBD_CAPSLOCK)
keycode &= ~CAPITAL_MASK;
if (modifier & (LEFT_SHIFT | RIGHT_SHIFT)) {
/* Handle CAPSLock + Shift pressed simultaneously */
if (keycode & CAPITAL_MASK)
keycode &= ~CAPITAL_MASK;
else
keycode |= CAPITAL_MASK;
}
}
if ((scancode > 0x1d) && (scancode < 0x3a)) {
/* Shift pressed */
if (modifier & (LEFT_SHIFT | RIGHT_SHIFT))
keycode = usb_kbd_numkey_shifted[scancode - 0x1e];
else
keycode = usb_kbd_numkey[scancode - 0x1e];
}
if (data->flags & USB_KBD_CTRL)
keycode = scancode - 0x3;
if (pressed == 1) {
if (scancode == NUM_LOCK) {
data->flags ^= USB_KBD_NUMLOCK;
return 1;
}
if (scancode == CAPS_LOCK) {
data->flags ^= USB_KBD_CAPSLOCK;
return 1;
}
if (scancode == SCROLL_LOCK) {
data->flags ^= USB_KBD_SCROLLLOCK;
return 1;
}
}
/* Report keycode if any */
if (keycode) {
USB_KBD_PRINTF("%c", keycode);
usb_kbd_put_queue(data, keycode);
}
return 0;
}
static uint32_t usb_kbd_service_key(struct usb_device *dev, int i, int up)
{
uint32_t res = 0;
struct usb_kbd_pdata *data = dev->privptr;
uint8_t *new;
uint8_t *old;
if (up) {
new = data->old;
old = data->new;
} else {
new = data->new;
old = data->old;
}
if ((old[i] > 3) && (memscan(new + 2, old[i], 6) == new + 8))
res |= usb_kbd_translate(data, old[i], data->new[0], up);
return res;
}
/* Interrupt service routine */
static int usb_kbd_irq_worker(struct usb_device *dev)
{
struct usb_kbd_pdata *data = dev->privptr;
int i, res = 0;
/* No combo key pressed */
if (data->new[0] == 0x00)
data->flags &= ~USB_KBD_CTRL;
/* Left or Right Ctrl pressed */
else if ((data->new[0] == LEFT_CNTR) || (data->new[0] == RIGHT_CNTR))
data->flags |= USB_KBD_CTRL;
for (i = 2; i < 8; i++) {
res |= usb_kbd_service_key(dev, i, 0);
res |= usb_kbd_service_key(dev, i, 1);
}
/* Key is still pressed */
if ((data->new[2] > 3) && (data->old[2] == data->new[2]))
res |= usb_kbd_translate(data, data->new[2], data->new[0], 2);
if (res == 1)
usb_kbd_setled(dev);
memcpy(data->old, data->new, 8);
return 1;
}
/* Keyboard interrupt handler */
static int usb_kbd_irq(struct usb_device *dev)
{
if ((dev->irq_status != 0) || (dev->irq_act_len != 8)) {
USB_KBD_PRINTF("USB KBD: Error %lX, len %d\n",
dev->irq_status, dev->irq_act_len);
return 1;
}
return usb_kbd_irq_worker(dev);
}
/* Interrupt polling */
static inline void usb_kbd_poll_for_event(struct usb_device *dev)
{
#if defined(CONFIG_SYS_USB_EVENT_POLL)
usb_event_poll();
usb_kbd_irq_worker(dev);
#elif defined(CONFIG_SYS_USB_EVENT_POLL_VIA_CONTROL_EP)
struct usb_interface *iface;
struct usb_kbd_pdata *data = dev->privptr;
iface = &dev->config.if_desc[0];
usb_get_report(dev, iface->desc.bInterfaceNumber,
1, 1, data->new, sizeof(data->new));
if (memcmp(data->old, data->new, sizeof(data->new)))
usb_kbd_irq_worker(dev);
#endif
}
/* test if a character is in the queue */
static int usb_kbd_testc(void)
{
struct stdio_dev *dev;
struct usb_device *usb_kbd_dev;
struct usb_kbd_pdata *data;
dev = stdio_get_by_name(DEVNAME);
usb_kbd_dev = (struct usb_device *)dev->priv;
data = usb_kbd_dev->privptr;
usb_kbd_poll_for_event(usb_kbd_dev);
return !(data->usb_in_pointer == data->usb_out_pointer);
}
/* gets the character from the queue */
static int usb_kbd_getc(void)
{
struct stdio_dev *dev;
struct usb_device *usb_kbd_dev;
struct usb_kbd_pdata *data;
dev = stdio_get_by_name(DEVNAME);
usb_kbd_dev = (struct usb_device *)dev->priv;
data = usb_kbd_dev->privptr;
while (data->usb_in_pointer == data->usb_out_pointer)
usb_kbd_poll_for_event(usb_kbd_dev);
if (data->usb_out_pointer == USB_KBD_BUFFER_LEN - 1)
data->usb_out_pointer = 0;
else
data->usb_out_pointer++;
return data->usb_kbd_buffer[data->usb_out_pointer];
}
/* probes the USB device dev for keyboard type. */
static int usb_kbd_probe(struct usb_device *dev, unsigned int ifnum)
{
struct usb_interface *iface;
struct usb_endpoint_descriptor *ep;
struct usb_kbd_pdata *data;
int pipe, maxp;
if (dev->descriptor.bNumConfigurations != 1)
return 0;
iface = &dev->config.if_desc[ifnum];
if (iface->desc.bInterfaceClass != 3)
return 0;
if (iface->desc.bInterfaceSubClass != 1)
return 0;
if (iface->desc.bInterfaceProtocol != 1)
return 0;
if (iface->desc.bNumEndpoints != 1)
return 0;
ep = &iface->ep_desc[0];
/* Check if endpoint 1 is interrupt endpoint */
if (!(ep->bEndpointAddress & 0x80))
return 0;
if ((ep->bmAttributes & 3) != 3)
return 0;
USB_KBD_PRINTF("USB KBD: found set protocol...\n");
data = malloc(sizeof(struct usb_kbd_pdata));
if (!data) {
printf("USB KBD: Error allocating private data\n");
return 0;
}
/* Clear private data */
memset(data, 0, sizeof(struct usb_kbd_pdata));
/* Insert private data into USB device structure */
dev->privptr = data;
/* Set IRQ handler */
dev->irq_handle = usb_kbd_irq;
pipe = usb_rcvintpipe(dev, ep->bEndpointAddress);
maxp = usb_maxpacket(dev, pipe);
/* We found a USB Keyboard, install it. */
usb_set_protocol(dev, iface->desc.bInterfaceNumber, 0);
USB_KBD_PRINTF("USB KBD: found set idle...\n");
usb_set_idle(dev, iface->desc.bInterfaceNumber, REPEAT_RATE, 0);
USB_KBD_PRINTF("USB KBD: enable interrupt pipe...\n");
usb_submit_int_msg(dev, pipe, data->new, maxp > 8 ? 8 : maxp,
ep->bInterval);
/* Success. */
return 1;
}
/* Search for keyboard and register it if found. */
int drv_usb_kbd_init(void)
{
struct stdio_dev usb_kbd_dev, *old_dev;
struct usb_device *dev;
char *stdinname = getenv("stdin");
int error, i;
/* Scan all USB Devices */
for (i = 0; i < USB_MAX_DEVICE; i++) {
/* Get USB device. */
dev = usb_get_dev_index(i);
if (!dev)
return -1;
if (dev->devnum == -1)
continue;
/* Try probing the keyboard */
if (usb_kbd_probe(dev, 0) != 1)
continue;
/* We found a keyboard, check if it is already registered. */
USB_KBD_PRINTF("USB KBD: found set up device.\n");
old_dev = stdio_get_by_name(DEVNAME);
if (old_dev) {
/* Already registered, just return ok. */
USB_KBD_PRINTF("USB KBD: is already registered.\n");
return 1;
}
/* Register the keyboard */
USB_KBD_PRINTF("USB KBD: register.\n");
memset(&usb_kbd_dev, 0, sizeof(struct stdio_dev));
strcpy(usb_kbd_dev.name, DEVNAME);
usb_kbd_dev.flags = DEV_FLAGS_INPUT | DEV_FLAGS_SYSTEM;
usb_kbd_dev.putc = NULL;
usb_kbd_dev.puts = NULL;
usb_kbd_dev.getc = usb_kbd_getc;
usb_kbd_dev.tstc = usb_kbd_testc;
usb_kbd_dev.priv = (void *)dev;
error = stdio_register(&usb_kbd_dev);
if (error)
return error;
/* Check if this is the standard input device. */
if (strcmp(stdinname, DEVNAME))
return 1;
/* Reassign the console */
if (overwrite_console())
return 1;
error = console_assign(stdin, DEVNAME);
if (error)
return error;
return 1;
}
/* No USB Keyboard found */
return -1;
}
/* Deregister the keyboard. */
int usb_kbd_deregister(void)
{
#ifdef CONFIG_SYS_STDIO_DEREGISTER
return stdio_deregister(DEVNAME);
#else
return 1;
#endif
}
|
1001-study-uboot
|
common/usb_kbd.c
|
C
|
gpl3
| 12,402
|
/*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* FLASH support
*/
#include <common.h>
#include <command.h>
#ifdef CONFIG_HAS_DATAFLASH
#include <dataflash.h>
#endif
#if defined(CONFIG_CMD_MTDPARTS)
#include <jffs2/jffs2.h>
/* partition handling routines */
int mtdparts_init(void);
int mtd_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
#ifndef CONFIG_SYS_NO_FLASH
#include <flash.h>
#include <mtd/cfi_flash.h>
extern flash_info_t flash_info[]; /* info for FLASH chips */
/*
* The user interface starts numbering for Flash banks with 1
* for historical reasons.
*/
/*
* this routine looks for an abbreviated flash range specification.
* the syntax is B:SF[-SL], where B is the bank number, SF is the first
* sector to erase, and SL is the last sector to erase (defaults to SF).
* bank numbers start at 1 to be consistent with other specs, sector numbers
* start at zero.
*
* returns: 1 - correct spec; *pinfo, *psf and *psl are
* set appropriately
* 0 - doesn't look like an abbreviated spec
* -1 - looks like an abbreviated spec, but got
* a parsing error, a number out of range,
* or an invalid flash bank.
*/
static int
abbrev_spec (char *str, flash_info_t ** pinfo, int *psf, int *psl)
{
flash_info_t *fp;
int bank, first, last;
char *p, *ep;
if ((p = strchr (str, ':')) == NULL)
return 0;
*p++ = '\0';
bank = simple_strtoul (str, &ep, 10);
if (ep == str || *ep != '\0' ||
bank < 1 || bank > CONFIG_SYS_MAX_FLASH_BANKS ||
(fp = &flash_info[bank - 1])->flash_id == FLASH_UNKNOWN)
return -1;
str = p;
if ((p = strchr (str, '-')) != NULL)
*p++ = '\0';
first = simple_strtoul (str, &ep, 10);
if (ep == str || *ep != '\0' || first >= fp->sector_count)
return -1;
if (p != NULL) {
last = simple_strtoul (p, &ep, 10);
if (ep == p || *ep != '\0' ||
last < first || last >= fp->sector_count)
return -1;
} else {
last = first;
}
*pinfo = fp;
*psf = first;
*psl = last;
return 1;
}
/*
* Take *addr in Flash and adjust it to fall on the end of its sector
*/
int flash_sect_roundb (ulong *addr)
{
flash_info_t *info;
ulong bank, sector_end_addr;
char found;
int i;
/* find the end addr of the sector where the *addr is */
found = 0;
for (bank = 0; bank < CONFIG_SYS_MAX_FLASH_BANKS && !found; ++bank) {
info = &flash_info[bank];
for (i = 0; i < info->sector_count && !found; ++i) {
/* get the end address of the sector */
if (i == info->sector_count - 1) {
sector_end_addr = info->start[0] +
info->size - 1;
} else {
sector_end_addr = info->start[i+1] - 1;
}
if (*addr <= sector_end_addr &&
*addr >= info->start[i]) {
found = 1;
/* adjust *addr if necessary */
if (*addr < sector_end_addr)
*addr = sector_end_addr;
} /* sector */
} /* bank */
}
if (!found) {
/* error, address not in flash */
printf("Error: end address (0x%08lx) not in flash!\n", *addr);
return 1;
}
return 0;
}
/*
* This function computes the start and end addresses for both
* erase and protect commands. The range of the addresses on which
* either of the commands is to operate can be given in two forms:
* 1. <cmd> start end - operate on <'start', 'end')
* 2. <cmd> start +length - operate on <'start', start + length)
* If the second form is used and the end address doesn't fall on the
* sector boundary, than it will be adjusted to the next sector boundary.
* If it isn't in the flash, the function will fail (return -1).
* Input:
* arg1, arg2: address specification (i.e. both command arguments)
* Output:
* addr_first, addr_last: computed address range
* Return:
* 1: success
* -1: failure (bad format, bad address).
*/
static int
addr_spec(char *arg1, char *arg2, ulong *addr_first, ulong *addr_last)
{
char *ep;
char len_used; /* indicates if the "start +length" form used */
*addr_first = simple_strtoul(arg1, &ep, 16);
if (ep == arg1 || *ep != '\0')
return -1;
len_used = 0;
if (arg2 && *arg2 == '+'){
len_used = 1;
++arg2;
}
*addr_last = simple_strtoul(arg2, &ep, 16);
if (ep == arg2 || *ep != '\0')
return -1;
if (len_used){
/*
* *addr_last has the length, compute correct *addr_last
* XXX watch out for the integer overflow! Right now it is
* checked for in both the callers.
*/
*addr_last = *addr_first + *addr_last - 1;
/*
* It may happen that *addr_last doesn't fall on the sector
* boundary. We want to round such an address to the next
* sector boundary, so that the commands don't fail later on.
*/
if (flash_sect_roundb(addr_last) > 0)
return -1;
} /* "start +length" from used */
return 1;
}
static int
flash_fill_sect_ranges (ulong addr_first, ulong addr_last,
int *s_first, int *s_last,
int *s_count )
{
flash_info_t *info;
ulong bank;
int rcode = 0;
*s_count = 0;
for (bank=0; bank < CONFIG_SYS_MAX_FLASH_BANKS; ++bank) {
s_first[bank] = -1; /* first sector to erase */
s_last [bank] = -1; /* last sector to erase */
}
for (bank=0,info = &flash_info[0];
(bank < CONFIG_SYS_MAX_FLASH_BANKS) && (addr_first <= addr_last);
++bank, ++info) {
ulong b_end;
int sect;
short s_end;
if (info->flash_id == FLASH_UNKNOWN) {
continue;
}
b_end = info->start[0] + info->size - 1; /* bank end addr */
s_end = info->sector_count - 1; /* last sector */
for (sect=0; sect < info->sector_count; ++sect) {
ulong end; /* last address in current sect */
end = (sect == s_end) ? b_end : info->start[sect + 1] - 1;
if (addr_first > end)
continue;
if (addr_last < info->start[sect])
continue;
if (addr_first == info->start[sect]) {
s_first[bank] = sect;
}
if (addr_last == end) {
s_last[bank] = sect;
}
}
if (s_first[bank] >= 0) {
if (s_last[bank] < 0) {
if (addr_last > b_end) {
s_last[bank] = s_end;
} else {
puts ("Error: end address"
" not on sector boundary\n");
rcode = 1;
break;
}
}
if (s_last[bank] < s_first[bank]) {
puts ("Error: end sector"
" precedes start sector\n");
rcode = 1;
break;
}
sect = s_last[bank];
addr_first = (sect == s_end) ? b_end + 1: info->start[sect + 1];
(*s_count) += s_last[bank] - s_first[bank] + 1;
} else if (addr_first >= info->start[0] && addr_first < b_end) {
puts ("Error: start address not on sector boundary\n");
rcode = 1;
break;
} else if (s_last[bank] >= 0) {
puts ("Error: cannot span across banks when they are"
" mapped in reverse order\n");
rcode = 1;
break;
}
}
return rcode;
}
#endif /* CONFIG_SYS_NO_FLASH */
int do_flinfo ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
#ifndef CONFIG_SYS_NO_FLASH
ulong bank;
#endif
#ifdef CONFIG_HAS_DATAFLASH
dataflash_print_info();
#endif
#ifndef CONFIG_SYS_NO_FLASH
if (argc == 1) { /* print info for all FLASH banks */
for (bank=0; bank <CONFIG_SYS_MAX_FLASH_BANKS; ++bank) {
printf ("\nBank # %ld: ", bank+1);
flash_print_info (&flash_info[bank]);
}
return 0;
}
bank = simple_strtoul(argv[1], NULL, 16);
if ((bank < 1) || (bank > CONFIG_SYS_MAX_FLASH_BANKS)) {
printf ("Only FLASH Banks # 1 ... # %d supported\n",
CONFIG_SYS_MAX_FLASH_BANKS);
return 1;
}
printf ("\nBank # %ld: ", bank);
flash_print_info (&flash_info[bank-1]);
#endif /* CONFIG_SYS_NO_FLASH */
return 0;
}
int do_flerase (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
#ifndef CONFIG_SYS_NO_FLASH
flash_info_t *info = NULL;
ulong bank, addr_first, addr_last;
int n, sect_first = 0, sect_last = 0;
#if defined(CONFIG_CMD_MTDPARTS)
struct mtd_device *dev;
struct part_info *part;
u8 dev_type, dev_num, pnum;
#endif
int rcode = 0;
if (argc < 2)
return cmd_usage(cmdtp);
if (strcmp(argv[1], "all") == 0) {
for (bank=1; bank<=CONFIG_SYS_MAX_FLASH_BANKS; ++bank) {
printf ("Erase Flash Bank # %ld ", bank);
info = &flash_info[bank-1];
rcode = flash_erase (info, 0, info->sector_count-1);
}
return rcode;
}
if ((n = abbrev_spec(argv[1], &info, §_first, §_last)) != 0) {
if (n < 0) {
puts ("Bad sector specification\n");
return 1;
}
printf ("Erase Flash Sectors %d-%d in Bank # %zu ",
sect_first, sect_last, (info-flash_info)+1);
rcode = flash_erase(info, sect_first, sect_last);
return rcode;
}
#if defined(CONFIG_CMD_MTDPARTS)
/* erase <part-id> - erase partition */
if ((argc == 2) && (mtd_id_parse(argv[1], NULL, &dev_type, &dev_num) == 0)) {
mtdparts_init();
if (find_dev_and_part(argv[1], &dev, &pnum, &part) == 0) {
if (dev->id->type == MTD_DEV_TYPE_NOR) {
bank = dev->id->num;
info = &flash_info[bank];
addr_first = part->offset + info->start[0];
addr_last = addr_first + part->size - 1;
printf ("Erase Flash Partition %s, "
"bank %ld, 0x%08lx - 0x%08lx ",
argv[1], bank, addr_first,
addr_last);
rcode = flash_sect_erase(addr_first, addr_last);
return rcode;
}
printf("cannot erase, not a NOR device\n");
return 1;
}
}
#endif
if (argc != 3)
return cmd_usage(cmdtp);
if (strcmp(argv[1], "bank") == 0) {
bank = simple_strtoul(argv[2], NULL, 16);
if ((bank < 1) || (bank > CONFIG_SYS_MAX_FLASH_BANKS)) {
printf ("Only FLASH Banks # 1 ... # %d supported\n",
CONFIG_SYS_MAX_FLASH_BANKS);
return 1;
}
printf ("Erase Flash Bank # %ld ", bank);
info = &flash_info[bank-1];
rcode = flash_erase (info, 0, info->sector_count-1);
return rcode;
}
if (addr_spec(argv[1], argv[2], &addr_first, &addr_last) < 0){
printf ("Bad address format\n");
return 1;
}
if (addr_first >= addr_last)
return cmd_usage(cmdtp);
rcode = flash_sect_erase(addr_first, addr_last);
return rcode;
#else
return 0;
#endif /* CONFIG_SYS_NO_FLASH */
}
#ifndef CONFIG_SYS_NO_FLASH
int flash_sect_erase (ulong addr_first, ulong addr_last)
{
flash_info_t *info;
ulong bank;
int s_first[CONFIG_SYS_MAX_FLASH_BANKS], s_last[CONFIG_SYS_MAX_FLASH_BANKS];
int erased = 0;
int planned;
int rcode = 0;
rcode = flash_fill_sect_ranges (addr_first, addr_last,
s_first, s_last, &planned );
if (planned && (rcode == 0)) {
for (bank=0,info = &flash_info[0];
(bank < CONFIG_SYS_MAX_FLASH_BANKS) && (rcode == 0);
++bank, ++info) {
if (s_first[bank]>=0) {
erased += s_last[bank] - s_first[bank] + 1;
debug ("Erase Flash from 0x%08lx to 0x%08lx "
"in Bank # %ld ",
info->start[s_first[bank]],
(s_last[bank] == info->sector_count) ?
info->start[0] + info->size - 1:
info->start[s_last[bank]+1] - 1,
bank+1);
rcode = flash_erase (info, s_first[bank], s_last[bank]);
}
}
printf ("Erased %d sectors\n", erased);
} else if (rcode == 0) {
puts ("Error: start and/or end address"
" not on sector boundary\n");
rcode = 1;
}
return rcode;
}
#endif /* CONFIG_SYS_NO_FLASH */
int do_protect (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int rcode = 0;
#ifndef CONFIG_SYS_NO_FLASH
flash_info_t *info = NULL;
ulong bank;
int i, n, sect_first = 0, sect_last = 0;
#if defined(CONFIG_CMD_MTDPARTS)
struct mtd_device *dev;
struct part_info *part;
u8 dev_type, dev_num, pnum;
#endif
#endif /* CONFIG_SYS_NO_FLASH */
#ifdef CONFIG_HAS_DATAFLASH
int status;
#endif
#if !defined(CONFIG_SYS_NO_FLASH) || defined(CONFIG_HAS_DATAFLASH)
int p;
ulong addr_first, addr_last;
#endif
if (argc < 3)
return cmd_usage(cmdtp);
#if !defined(CONFIG_SYS_NO_FLASH) || defined(CONFIG_HAS_DATAFLASH)
if (strcmp(argv[1], "off") == 0)
p = 0;
else if (strcmp(argv[1], "on") == 0)
p = 1;
else
return cmd_usage(cmdtp);
#endif
#ifdef CONFIG_HAS_DATAFLASH
if ((strcmp(argv[2], "all") != 0) && (strcmp(argv[2], "bank") != 0)) {
addr_first = simple_strtoul(argv[2], NULL, 16);
addr_last = simple_strtoul(argv[3], NULL, 16);
if (addr_dataflash(addr_first) && addr_dataflash(addr_last)) {
status = dataflash_real_protect(p,addr_first,addr_last);
if (status < 0){
puts ("Bad DataFlash sector specification\n");
return 1;
}
printf("%sProtect %d DataFlash Sectors\n",
p ? "" : "Un-", status);
return 0;
}
}
#endif
#ifndef CONFIG_SYS_NO_FLASH
if (strcmp(argv[2], "all") == 0) {
for (bank=1; bank<=CONFIG_SYS_MAX_FLASH_BANKS; ++bank) {
info = &flash_info[bank-1];
if (info->flash_id == FLASH_UNKNOWN) {
continue;
}
printf ("%sProtect Flash Bank # %ld\n",
p ? "" : "Un-", bank);
for (i=0; i<info->sector_count; ++i) {
#if defined(CONFIG_SYS_FLASH_PROTECTION)
if (flash_real_protect(info, i, p))
rcode = 1;
putc ('.');
#else
info->protect[i] = p;
#endif /* CONFIG_SYS_FLASH_PROTECTION */
}
#if defined(CONFIG_SYS_FLASH_PROTECTION)
if (!rcode) puts (" done\n");
#endif /* CONFIG_SYS_FLASH_PROTECTION */
}
return rcode;
}
if ((n = abbrev_spec(argv[2], &info, §_first, §_last)) != 0) {
if (n < 0) {
puts ("Bad sector specification\n");
return 1;
}
printf("%sProtect Flash Sectors %d-%d in Bank # %zu\n",
p ? "" : "Un-", sect_first, sect_last,
(info-flash_info)+1);
for (i = sect_first; i <= sect_last; i++) {
#if defined(CONFIG_SYS_FLASH_PROTECTION)
if (flash_real_protect(info, i, p))
rcode = 1;
putc ('.');
#else
info->protect[i] = p;
#endif /* CONFIG_SYS_FLASH_PROTECTION */
}
#if defined(CONFIG_SYS_FLASH_PROTECTION)
if (!rcode) puts (" done\n");
#endif /* CONFIG_SYS_FLASH_PROTECTION */
return rcode;
}
#if defined(CONFIG_CMD_MTDPARTS)
/* protect on/off <part-id> */
if ((argc == 3) && (mtd_id_parse(argv[2], NULL, &dev_type, &dev_num) == 0)) {
mtdparts_init();
if (find_dev_and_part(argv[2], &dev, &pnum, &part) == 0) {
if (dev->id->type == MTD_DEV_TYPE_NOR) {
bank = dev->id->num;
info = &flash_info[bank];
addr_first = part->offset + info->start[0];
addr_last = addr_first + part->size - 1;
printf ("%sProtect Flash Partition %s, "
"bank %ld, 0x%08lx - 0x%08lx\n",
p ? "" : "Un", argv[1],
bank, addr_first, addr_last);
rcode = flash_sect_protect (p, addr_first, addr_last);
return rcode;
}
printf("cannot %sprotect, not a NOR device\n",
p ? "" : "un");
return 1;
}
}
#endif
if (argc != 4)
return cmd_usage(cmdtp);
if (strcmp(argv[2], "bank") == 0) {
bank = simple_strtoul(argv[3], NULL, 16);
if ((bank < 1) || (bank > CONFIG_SYS_MAX_FLASH_BANKS)) {
printf ("Only FLASH Banks # 1 ... # %d supported\n",
CONFIG_SYS_MAX_FLASH_BANKS);
return 1;
}
printf ("%sProtect Flash Bank # %ld\n",
p ? "" : "Un-", bank);
info = &flash_info[bank-1];
if (info->flash_id == FLASH_UNKNOWN) {
puts ("missing or unknown FLASH type\n");
return 1;
}
for (i=0; i<info->sector_count; ++i) {
#if defined(CONFIG_SYS_FLASH_PROTECTION)
if (flash_real_protect(info, i, p))
rcode = 1;
putc ('.');
#else
info->protect[i] = p;
#endif /* CONFIG_SYS_FLASH_PROTECTION */
}
#if defined(CONFIG_SYS_FLASH_PROTECTION)
if (!rcode) puts (" done\n");
#endif /* CONFIG_SYS_FLASH_PROTECTION */
return rcode;
}
if (addr_spec(argv[2], argv[3], &addr_first, &addr_last) < 0){
printf("Bad address format\n");
return 1;
}
if (addr_first >= addr_last)
return cmd_usage(cmdtp);
rcode = flash_sect_protect (p, addr_first, addr_last);
#endif /* CONFIG_SYS_NO_FLASH */
return rcode;
}
#ifndef CONFIG_SYS_NO_FLASH
int flash_sect_protect (int p, ulong addr_first, ulong addr_last)
{
flash_info_t *info;
ulong bank;
int s_first[CONFIG_SYS_MAX_FLASH_BANKS], s_last[CONFIG_SYS_MAX_FLASH_BANKS];
int protected, i;
int planned;
int rcode;
rcode = flash_fill_sect_ranges( addr_first, addr_last, s_first, s_last, &planned );
protected = 0;
if (planned && (rcode == 0)) {
for (bank=0,info = &flash_info[0]; bank < CONFIG_SYS_MAX_FLASH_BANKS; ++bank, ++info) {
if (info->flash_id == FLASH_UNKNOWN) {
continue;
}
if (s_first[bank]>=0 && s_first[bank]<=s_last[bank]) {
debug ("%sProtecting sectors %d..%d in bank %ld\n",
p ? "" : "Un-",
s_first[bank], s_last[bank], bank+1);
protected += s_last[bank] - s_first[bank] + 1;
for (i=s_first[bank]; i<=s_last[bank]; ++i) {
#if defined(CONFIG_SYS_FLASH_PROTECTION)
if (flash_real_protect(info, i, p))
rcode = 1;
putc ('.');
#else
info->protect[i] = p;
#endif /* CONFIG_SYS_FLASH_PROTECTION */
}
}
}
#if defined(CONFIG_SYS_FLASH_PROTECTION)
puts (" done\n");
#endif /* CONFIG_SYS_FLASH_PROTECTION */
printf ("%sProtected %d sectors\n",
p ? "" : "Un-", protected);
} else if (rcode == 0) {
puts ("Error: start and/or end address"
" not on sector boundary\n");
rcode = 1;
}
return rcode;
}
#endif /* CONFIG_SYS_NO_FLASH */
/**************************************************/
#if defined(CONFIG_CMD_MTDPARTS)
# define TMP_ERASE "erase <part-id>\n - erase partition\n"
# define TMP_PROT_ON "protect on <part-id>\n - protect partition\n"
# define TMP_PROT_OFF "protect off <part-id>\n - make partition writable\n"
#else
# define TMP_ERASE /* empty */
# define TMP_PROT_ON /* empty */
# define TMP_PROT_OFF /* empty */
#endif
U_BOOT_CMD(
flinfo, 2, 1, do_flinfo,
"print FLASH memory information",
"\n - print information for all FLASH memory banks\n"
"flinfo N\n - print information for FLASH memory bank # N"
);
U_BOOT_CMD(
erase, 3, 0, do_flerase,
"erase FLASH memory",
"start end\n"
" - erase FLASH from addr 'start' to addr 'end'\n"
"erase start +len\n"
" - erase FLASH from addr 'start' to the end of sect "
"w/addr 'start'+'len'-1\n"
"erase N:SF[-SL]\n - erase sectors SF-SL in FLASH bank # N\n"
"erase bank N\n - erase FLASH bank # N\n"
TMP_ERASE
"erase all\n - erase all FLASH banks"
);
U_BOOT_CMD(
protect, 4, 0, do_protect,
"enable or disable FLASH write protection",
"on start end\n"
" - protect FLASH from addr 'start' to addr 'end'\n"
"protect on start +len\n"
" - protect FLASH from addr 'start' to end of sect "
"w/addr 'start'+'len'-1\n"
"protect on N:SF[-SL]\n"
" - protect sectors SF-SL in FLASH bank # N\n"
"protect on bank N\n - protect FLASH bank # N\n"
TMP_PROT_ON
"protect on all\n - protect all FLASH banks\n"
"protect off start end\n"
" - make FLASH from addr 'start' to addr 'end' writable\n"
"protect off start +len\n"
" - make FLASH from addr 'start' to end of sect "
"w/addr 'start'+'len'-1 wrtable\n"
"protect off N:SF[-SL]\n"
" - make sectors SF-SL writable in FLASH bank # N\n"
"protect off bank N\n - make FLASH bank # N writable\n"
TMP_PROT_OFF
"protect off all\n - make all FLASH banks writable"
);
#undef TMP_ERASE
#undef TMP_PROT_ON
#undef TMP_PROT_OFF
|
1001-study-uboot
|
common/cmd_flash.c
|
C
|
gpl3
| 19,637
|
/*
* (C) Copyright 2008-2011 Freescale Semiconductor, Inc.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/* #define DEBUG */
#include <common.h>
#include <command.h>
#include <environment.h>
#include <linux/stddef.h>
#include <malloc.h>
#include <mmc.h>
#include <search.h>
#include <errno.h>
char *env_name_spec = "MMC";
#ifdef ENV_IS_EMBEDDED
env_t *env_ptr = &environment;
#else /* ! ENV_IS_EMBEDDED */
env_t *env_ptr;
#endif /* ENV_IS_EMBEDDED */
DECLARE_GLOBAL_DATA_PTR;
#if !defined(CONFIG_ENV_OFFSET)
#define CONFIG_ENV_OFFSET 0
#endif
static int __mmc_get_env_addr(struct mmc *mmc, u32 *env_addr)
{
*env_addr = CONFIG_ENV_OFFSET;
return 0;
}
int mmc_get_env_addr(struct mmc *mmc, u32 *env_addr)
__attribute__((weak, alias("__mmc_get_env_addr")));
uchar env_get_char_spec(int index)
{
return *((uchar *)(gd->env_addr + index));
}
int env_init(void)
{
/* use default */
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 1;
return 0;
}
static int init_mmc_for_env(struct mmc *mmc)
{
if (!mmc) {
puts("No MMC card found\n");
return -1;
}
if (mmc_init(mmc)) {
puts("MMC init failed\n");
return -1;
}
return 0;
}
#ifdef CONFIG_CMD_SAVEENV
static inline int write_env(struct mmc *mmc, unsigned long size,
unsigned long offset, const void *buffer)
{
uint blk_start, blk_cnt, n;
blk_start = ALIGN(offset, mmc->write_bl_len) / mmc->write_bl_len;
blk_cnt = ALIGN(size, mmc->write_bl_len) / mmc->write_bl_len;
n = mmc->block_dev.block_write(CONFIG_SYS_MMC_ENV_DEV, blk_start,
blk_cnt, (u_char *)buffer);
return (n == blk_cnt) ? 0 : -1;
}
int saveenv(void)
{
env_t env_new;
ssize_t len;
char *res;
struct mmc *mmc = find_mmc_device(CONFIG_SYS_MMC_ENV_DEV);
u32 offset;
if (init_mmc_for_env(mmc) || mmc_get_env_addr(mmc, &offset))
return 1;
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);
printf("Writing to MMC(%d)... ", CONFIG_SYS_MMC_ENV_DEV);
if (write_env(mmc, CONFIG_ENV_SIZE, offset, (u_char *)&env_new)) {
puts("failed\n");
return 1;
}
puts("done\n");
return 0;
}
#endif /* CONFIG_CMD_SAVEENV */
static inline int read_env(struct mmc *mmc, unsigned long size,
unsigned long offset, const void *buffer)
{
uint blk_start, blk_cnt, n;
blk_start = ALIGN(offset, mmc->read_bl_len) / mmc->read_bl_len;
blk_cnt = ALIGN(size, mmc->read_bl_len) / mmc->read_bl_len;
n = mmc->block_dev.block_read(CONFIG_SYS_MMC_ENV_DEV, blk_start,
blk_cnt, (uchar *)buffer);
return (n == blk_cnt) ? 0 : -1;
}
void env_relocate_spec(void)
{
#if !defined(ENV_IS_EMBEDDED)
char buf[CONFIG_ENV_SIZE];
struct mmc *mmc = find_mmc_device(CONFIG_SYS_MMC_ENV_DEV);
u32 offset;
if (init_mmc_for_env(mmc) || mmc_get_env_addr(mmc, &offset))
return set_default_env(NULL);
if (read_env(mmc, CONFIG_ENV_SIZE, offset, buf))
return set_default_env(NULL);
env_import(buf, 1);
#endif
}
|
1001-study-uboot
|
common/env_mmc.c
|
C
|
gpl3
| 3,804
|
/*
* U-Boot command for OneNAND support
*
* Copyright (C) 2005-2008 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.
*/
#include <common.h>
#include <command.h>
#include <malloc.h>
#include <linux/mtd/compat.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/onenand.h>
#include <asm/io.h>
static struct mtd_info *mtd;
static loff_t next_ofs;
static loff_t skip_ofs;
static inline int str2long(char *p, ulong *num)
{
char *endptr;
*num = simple_strtoul(p, &endptr, 16);
return (*p != '\0' && *endptr == '\0') ? 1 : 0;
}
static int arg_off_size(int argc, char * const argv[], ulong *off, size_t *size)
{
if (argc >= 1) {
if (!(str2long(argv[0], off))) {
printf("'%s' is not a number\n", argv[0]);
return -1;
}
} else {
*off = 0;
}
if (argc >= 2) {
if (!(str2long(argv[1], (ulong *)size))) {
printf("'%s' is not a number\n", argv[1]);
return -1;
}
} else {
*size = mtd->size - *off;
}
if ((*off + *size) > mtd->size) {
printf("total chip size (0x%llx) exceeded!\n", mtd->size);
return -1;
}
if (*size == mtd->size)
puts("whole chip\n");
else
printf("offset 0x%lx, size 0x%x\n", *off, *size);
return 0;
}
static int onenand_block_read(loff_t from, size_t len,
size_t *retlen, u_char *buf, int oob)
{
struct onenand_chip *this = mtd->priv;
int blocks = (int) len >> this->erase_shift;
int blocksize = (1 << this->erase_shift);
loff_t ofs = from;
struct mtd_oob_ops ops = {
.retlen = 0,
};
int ret;
if (oob)
ops.ooblen = blocksize;
else
ops.len = blocksize;
while (blocks) {
ret = mtd->block_isbad(mtd, ofs);
if (ret) {
printk("Bad blocks %d at 0x%x\n",
(u32)(ofs >> this->erase_shift), (u32)ofs);
ofs += blocksize;
continue;
}
if (oob)
ops.oobbuf = buf;
else
ops.datbuf = buf;
ops.retlen = 0;
ret = mtd->read_oob(mtd, ofs, &ops);
if (ret) {
printk("Read failed 0x%x, %d\n", (u32)ofs, ret);
ofs += blocksize;
continue;
}
ofs += blocksize;
buf += blocksize;
blocks--;
*retlen += ops.retlen;
}
return 0;
}
static int onenand_write_oneblock_withoob(loff_t to, const u_char * buf,
size_t *retlen)
{
struct mtd_oob_ops ops = {
.len = mtd->writesize,
.ooblen = mtd->oobsize,
.mode = MTD_OOB_AUTO,
};
int page, ret = 0;
for (page = 0; page < (mtd->erasesize / mtd->writesize); page ++) {
ops.datbuf = (u_char *)buf;
buf += mtd->writesize;
ops.oobbuf = (u_char *)buf;
buf += mtd->oobsize;
ret = mtd->write_oob(mtd, to, &ops);
if (ret)
break;
to += mtd->writesize;
}
*retlen = (ret) ? 0 : mtd->erasesize;
return ret;
}
static int onenand_block_write(loff_t to, size_t len,
size_t *retlen, const u_char * buf, int withoob)
{
struct onenand_chip *this = mtd->priv;
int blocks = len >> this->erase_shift;
int blocksize = (1 << this->erase_shift);
loff_t ofs;
size_t _retlen = 0;
int ret;
if (to == next_ofs) {
next_ofs = to + len;
to += skip_ofs;
} else {
next_ofs = to + len;
skip_ofs = 0;
}
ofs = to;
while (blocks) {
ret = mtd->block_isbad(mtd, ofs);
if (ret) {
printk("Bad blocks %d at 0x%x\n",
(u32)(ofs >> this->erase_shift), (u32)ofs);
skip_ofs += blocksize;
goto next;
}
if (!withoob)
ret = mtd->write(mtd, ofs, blocksize, &_retlen, buf);
else
ret = onenand_write_oneblock_withoob(ofs, buf, &_retlen);
if (ret) {
printk("Write failed 0x%x, %d", (u32)ofs, ret);
skip_ofs += blocksize;
goto next;
}
buf += blocksize;
blocks--;
*retlen += _retlen;
next:
ofs += blocksize;
}
return 0;
}
static int onenand_block_erase(u32 start, u32 size, int force)
{
struct onenand_chip *this = mtd->priv;
struct erase_info instr = {
.callback = NULL,
};
loff_t ofs;
int ret;
int blocksize = 1 << this->erase_shift;
for (ofs = start; ofs < (start + size); ofs += blocksize) {
ret = mtd->block_isbad(mtd, ofs);
if (ret && !force) {
printf("Skip erase bad block %d at 0x%x\n",
(u32)(ofs >> this->erase_shift), (u32)ofs);
continue;
}
instr.addr = ofs;
instr.len = blocksize;
instr.priv = force;
instr.mtd = mtd;
ret = mtd->erase(mtd, &instr);
if (ret) {
printf("erase failed block %d at 0x%x\n",
(u32)(ofs >> this->erase_shift), (u32)ofs);
continue;
}
}
return 0;
}
static int onenand_block_test(u32 start, u32 size)
{
struct onenand_chip *this = mtd->priv;
struct erase_info instr = {
.callback = NULL,
.priv = 0,
};
int blocks;
loff_t ofs;
int blocksize = 1 << this->erase_shift;
int start_block, end_block;
size_t retlen;
u_char *buf;
u_char *verify_buf;
int ret;
buf = malloc(blocksize);
if (!buf) {
printf("Not enough malloc space available!\n");
return -1;
}
verify_buf = malloc(blocksize);
if (!verify_buf) {
printf("Not enough malloc space available!\n");
return -1;
}
start_block = start >> this->erase_shift;
end_block = (start + size) >> this->erase_shift;
/* Protect boot-loader from badblock testing */
if (start_block < 2)
start_block = 2;
if (end_block > (mtd->size >> this->erase_shift))
end_block = mtd->size >> this->erase_shift;
blocks = start_block;
ofs = start;
while (blocks < end_block) {
printf("\rTesting block %d at 0x%x", (u32)(ofs >> this->erase_shift), (u32)ofs);
ret = mtd->block_isbad(mtd, ofs);
if (ret) {
printf("Skip erase bad block %d at 0x%x\n",
(u32)(ofs >> this->erase_shift), (u32)ofs);
goto next;
}
instr.addr = ofs;
instr.len = blocksize;
ret = mtd->erase(mtd, &instr);
if (ret) {
printk("Erase failed 0x%x, %d\n", (u32)ofs, ret);
goto next;
}
ret = mtd->write(mtd, ofs, blocksize, &retlen, buf);
if (ret) {
printk("Write failed 0x%x, %d\n", (u32)ofs, ret);
goto next;
}
ret = mtd->read(mtd, ofs, blocksize, &retlen, verify_buf);
if (ret) {
printk("Read failed 0x%x, %d\n", (u32)ofs, ret);
goto next;
}
if (memcmp(buf, verify_buf, blocksize))
printk("\nRead/Write test failed at 0x%x\n", (u32)ofs);
next:
ofs += blocksize;
blocks++;
}
printf("...Done\n");
free(buf);
free(verify_buf);
return 0;
}
static int onenand_dump(struct mtd_info *mtd, ulong off, int only_oob)
{
int i;
u_char *datbuf, *oobbuf, *p;
struct mtd_oob_ops ops;
loff_t addr;
datbuf = malloc(mtd->writesize + mtd->oobsize);
oobbuf = malloc(mtd->oobsize);
if (!datbuf || !oobbuf) {
puts("No memory for page buffer\n");
return 1;
}
off &= ~(mtd->writesize - 1);
addr = (loff_t) off;
memset(&ops, 0, sizeof(ops));
ops.datbuf = datbuf;
ops.oobbuf = oobbuf;
ops.len = mtd->writesize;
ops.ooblen = mtd->oobsize;
ops.retlen = 0;
i = mtd->read_oob(mtd, 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 = mtd->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 = mtd->oobsize >> 3;
p = oobbuf;
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 do_onenand_info(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
printf("%s\n", mtd->name);
return 0;
}
static int do_onenand_bad(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong ofs;
mtd = &onenand_mtd;
/* Currently only one OneNAND device is supported */
printf("\nDevice %d bad blocks:\n", 0);
for (ofs = 0; ofs < mtd->size; ofs += mtd->erasesize) {
if (mtd->block_isbad(mtd, ofs))
printf(" %08x\n", (u32)ofs);
}
return 0;
}
static int do_onenand_read(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
char *s;
int oob = 0;
ulong addr, ofs;
size_t len;
int ret = 0;
size_t retlen = 0;
if (argc < 3)
return cmd_usage(cmdtp);
s = strchr(argv[0], '.');
if ((s != NULL) && (!strcmp(s, ".oob")))
oob = 1;
addr = (ulong)simple_strtoul(argv[1], NULL, 16);
printf("\nOneNAND read: ");
if (arg_off_size(argc - 2, argv + 2, &ofs, &len) != 0)
return 1;
ret = onenand_block_read(ofs, len, &retlen, (u8 *)addr, oob);
printf(" %d bytes read: %s\n", retlen, ret ? "ERROR" : "OK");
return ret == 0 ? 0 : 1;
}
static int do_onenand_write(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, ofs;
size_t len;
int ret = 0, withoob = 0;
size_t retlen = 0;
if (argc < 3)
return cmd_usage(cmdtp);
if (strncmp(argv[0] + 6, "yaffs", 5) == 0)
withoob = 1;
addr = (ulong)simple_strtoul(argv[1], NULL, 16);
printf("\nOneNAND write: ");
if (arg_off_size(argc - 2, argv + 2, &ofs, &len) != 0)
return 1;
ret = onenand_block_write(ofs, len, &retlen, (u8 *)addr, withoob);
printf(" %d bytes written: %s\n", retlen, ret ? "ERROR" : "OK");
return ret == 0 ? 0 : 1;
}
static int do_onenand_erase(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong ofs;
int ret = 0;
size_t len;
int force;
/*
* Syntax is:
* 0 1 2 3 4
* onenand erase [force] [off size]
*/
argc--;
argv++;
if (argc)
{
if (!strcmp("force", argv[0]))
{
force = 1;
argc--;
argv++;
}
}
printf("\nOneNAND erase: ");
/* skip first two or three arguments, look for offset and size */
if (arg_off_size(argc, argv, &ofs, &len) != 0)
return 1;
ret = onenand_block_erase(ofs, len, force);
printf("%s\n", ret ? "ERROR" : "OK");
return ret == 0 ? 0 : 1;
}
static int do_onenand_test(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong ofs;
int ret = 0;
size_t len;
/*
* Syntax is:
* 0 1 2 3 4
* onenand test [force] [off size]
*/
printf("\nOneNAND test: ");
/* skip first two or three arguments, look for offset and size */
if (arg_off_size(argc - 1, argv + 1, &ofs, &len) != 0)
return 1;
ret = onenand_block_test(ofs, len);
printf("%s\n", ret ? "ERROR" : "OK");
return ret == 0 ? 0 : 1;
}
static int do_onenand_dump(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong ofs;
int ret = 0;
char *s;
if (argc < 2)
return cmd_usage(cmdtp);
s = strchr(argv[0], '.');
ofs = (int)simple_strtoul(argv[1], NULL, 16);
if (s != NULL && strcmp(s, ".oob") == 0)
ret = onenand_dump(mtd, ofs, 1);
else
ret = onenand_dump(mtd, ofs, 0);
return ret == 0 ? 1 : 0;
}
static int do_onenand_markbad(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
int ret = 0;
ulong addr;
argc -= 2;
argv += 2;
if (argc <= 0)
return cmd_usage(cmdtp);
while (argc > 0) {
addr = simple_strtoul(*argv, NULL, 16);
if (mtd->block_markbad(mtd, 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;
}
static cmd_tbl_t cmd_onenand_sub[] = {
U_BOOT_CMD_MKENT(info, 1, 0, do_onenand_info, "", ""),
U_BOOT_CMD_MKENT(bad, 1, 0, do_onenand_bad, "", ""),
U_BOOT_CMD_MKENT(read, 4, 0, do_onenand_read, "", ""),
U_BOOT_CMD_MKENT(write, 4, 0, do_onenand_write, "", ""),
U_BOOT_CMD_MKENT(write.yaffs, 4, 0, do_onenand_write, "", ""),
U_BOOT_CMD_MKENT(erase, 3, 0, do_onenand_erase, "", ""),
U_BOOT_CMD_MKENT(test, 3, 0, do_onenand_test, "", ""),
U_BOOT_CMD_MKENT(dump, 2, 0, do_onenand_dump, "", ""),
U_BOOT_CMD_MKENT(markbad, CONFIG_SYS_MAXARGS, 0, do_onenand_markbad, "", ""),
};
#ifdef CONFIG_NEEDS_MANUAL_RELOC
void onenand_reloc(void) {
fixup_cmdtable(cmd_onenand_sub, ARRAY_SIZE(cmd_onenand_sub));
}
#endif
static int do_onenand(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
cmd_tbl_t *c;
if (argc < 2)
return cmd_usage(cmdtp);
mtd = &onenand_mtd;
/* Strip off leading 'onenand' command argument */
argc--;
argv++;
c = find_cmd_tbl(argv[0], &cmd_onenand_sub[0], ARRAY_SIZE(cmd_onenand_sub));
if (c)
return c->cmd(cmdtp, flag, argc, argv);
else
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
onenand, CONFIG_SYS_MAXARGS, 1, do_onenand,
"OneNAND sub-system",
"info - show available OneNAND devices\n"
"onenand bad - show bad blocks\n"
"onenand read[.oob] addr off size\n"
"onenand write[.yaffs] addr off size\n"
" read/write 'size' bytes starting at offset 'off'\n"
" to/from memory address 'addr', skipping bad blocks.\n"
"onenand erase [force] [off size] - erase 'size' bytes from\n"
"onenand test [off size] - test 'size' bytes from\n"
" offset 'off' (entire device if not specified)\n"
"onenand dump[.oob] off - dump page\n"
"onenand markbad off [...] - mark bad block(s) at offset (UNSAFE)"
);
|
1001-study-uboot
|
common/cmd_onenand.c
|
C
|
gpl3
| 13,048
|
/*
* (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 <environment.h>
#include <linux/stddef.h>
#include <mg_disk.h>
char *env_name_spec = "MG_DISK";
env_t *env_ptr;
DECLARE_GLOBAL_DATA_PTR;
uchar env_get_char_spec(int index)
{
return *((uchar *)(gd->env_addr + index));
}
void env_relocate_spec(void)
{
char buf[CONFIG_ENV_SIZE];
unsigned int err, rc;
err = mg_disk_init();
if (err) {
set_default_env("!mg_disk_init error");
return;
}
err = mg_disk_read(CONFIG_ENV_ADDR, buf, CONFIG_ENV_SIZE);
if (err) {
set_default_env("!mg_disk_read error");
return;
}
env_import(buf, 1);
}
int saveenv(void)
{
unsigned int err;
env_ptr->crc = crc32(0, env_ptr->data, ENV_SIZE);
err = mg_disk_write(CONFIG_ENV_ADDR, (u_char *)env_ptr,
CONFIG_ENV_SIZE);
if (err)
puts("*** Warning - mg_disk_write error\n\n");
return err;
}
int env_init(void)
{
/* use default */
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 1;
return 0;
}
|
1001-study-uboot
|
common/env_mgdisk.c
|
C
|
gpl3
| 1,837
|
/*
*==========================================================================
*
* xyzModem.c
*
* RedBoot stream handler for xyzModem protocol
*
*==========================================================================
*####ECOSGPLCOPYRIGHTBEGIN####
* -------------------------------------------
* This file is part of eCos, the Embedded Configurable Operating System.
* Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
* Copyright (C) 2002 Gary Thomas
*
* eCos 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 or (at your option) any later version.
*
* eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* As a special exception, if other files instantiate templates or use macros
* or inline functions from this file, or you compile this file and link it
* with other works to produce a work based on this file, this file does not
* by itself cause the resulting work to be covered by the GNU General Public
* License. However the source code for this file must still be made available
* in accordance with section (3) of the GNU General Public License.
*
* This exception does not invalidate any other reasons why a work based on
* this file might be covered by the GNU General Public License.
*
* Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
* at http: *sources.redhat.com/ecos/ecos-license/
* -------------------------------------------
*####ECOSGPLCOPYRIGHTEND####
*==========================================================================
*#####DESCRIPTIONBEGIN####
*
* Author(s): gthomas
* Contributors: gthomas, tsmith, Yoshinori Sato
* Date: 2000-07-14
* Purpose:
* Description:
*
* This code is part of RedBoot (tm).
*
*####DESCRIPTIONEND####
*
*==========================================================================
*/
#include <common.h>
#include <xyzModem.h>
#include <stdarg.h>
#include <crc.h>
/* Assumption - run xyzModem protocol over the console port */
/* Values magic to the protocol */
#define SOH 0x01
#define STX 0x02
#define EOT 0x04
#define ACK 0x06
#define BSP 0x08
#define NAK 0x15
#define CAN 0x18
#define EOF 0x1A /* ^Z for DOS officionados */
#define USE_YMODEM_LENGTH
/* Data & state local to the protocol */
static struct
{
#ifdef REDBOOT
hal_virtual_comm_table_t *__chan;
#else
int *__chan;
#endif
unsigned char pkt[1024], *bufp;
unsigned char blk, cblk, crc1, crc2;
unsigned char next_blk; /* Expected block */
int len, mode, total_retries;
int total_SOH, total_STX, total_CAN;
bool crc_mode, at_eof, tx_ack;
#ifdef USE_YMODEM_LENGTH
unsigned long file_length, read_length;
#endif
} xyz;
#define xyzModem_CHAR_TIMEOUT 2000 /* 2 seconds */
#define xyzModem_MAX_RETRIES 20
#define xyzModem_MAX_RETRIES_WITH_CRC 10
#define xyzModem_CAN_COUNT 3 /* Wait for 3 CAN before quitting */
#ifndef REDBOOT /*SB */
typedef int cyg_int32;
int
CYGACC_COMM_IF_GETC_TIMEOUT (char chan, char *c)
{
#define DELAY 20
unsigned long counter = 0;
while (!tstc () && (counter < xyzModem_CHAR_TIMEOUT * 1000 / DELAY))
{
udelay (DELAY);
counter++;
}
if (tstc ())
{
*c = getc ();
return 1;
}
return 0;
}
void
CYGACC_COMM_IF_PUTC (char x, char y)
{
putc (y);
}
/* Validate a hex character */
__inline__ static bool
_is_hex (char c)
{
return (((c >= '0') && (c <= '9')) ||
((c >= 'A') && (c <= 'F')) || ((c >= 'a') && (c <= 'f')));
}
/* Convert a single hex nibble */
__inline__ static int
_from_hex (char c)
{
int ret = 0;
if ((c >= '0') && (c <= '9'))
{
ret = (c - '0');
}
else if ((c >= 'a') && (c <= 'f'))
{
ret = (c - 'a' + 0x0a);
}
else if ((c >= 'A') && (c <= 'F'))
{
ret = (c - 'A' + 0x0A);
}
return ret;
}
/* Convert a character to lower case */
__inline__ static char
_tolower (char c)
{
if ((c >= 'A') && (c <= 'Z'))
{
c = (c - 'A') + 'a';
}
return c;
}
/* Parse (scan) a number */
bool
parse_num (char *s, unsigned long *val, char **es, char *delim)
{
bool first = true;
int radix = 10;
char c;
unsigned long result = 0;
int digit;
while (*s == ' ')
s++;
while (*s)
{
if (first && (s[0] == '0') && (_tolower (s[1]) == 'x'))
{
radix = 16;
s += 2;
}
first = false;
c = *s++;
if (_is_hex (c) && ((digit = _from_hex (c)) < radix))
{
/* Valid digit */
#ifdef CYGPKG_HAL_MIPS
/* FIXME: tx49 compiler generates 0x2539018 for MUL which */
/* isn't any good. */
if (16 == radix)
result = result << 4;
else
result = 10 * result;
result += digit;
#else
result = (result * radix) + digit;
#endif
}
else
{
if (delim != (char *) 0)
{
/* See if this character is one of the delimiters */
char *dp = delim;
while (*dp && (c != *dp))
dp++;
if (*dp)
break; /* Found a good delimiter */
}
return false; /* Malformatted number */
}
}
*val = result;
if (es != (char **) 0)
{
*es = s;
}
return true;
}
#endif
#define USE_SPRINTF
#ifdef DEBUG
#ifndef USE_SPRINTF
/*
* Note: this debug setup only works if the target platform has two serial ports
* available so that the other one (currently only port 1) can be used for debug
* messages.
*/
static int
zm_dprintf (char *fmt, ...)
{
int cur_console;
va_list args;
va_start (args, fmt);
#ifdef REDBOOT
cur_console =
CYGACC_CALL_IF_SET_CONSOLE_COMM
(CYGNUM_CALL_IF_SET_COMM_ID_QUERY_CURRENT);
CYGACC_CALL_IF_SET_CONSOLE_COMM (1);
#endif
diag_vprintf (fmt, args);
#ifdef REDBOOT
CYGACC_CALL_IF_SET_CONSOLE_COMM (cur_console);
#endif
}
static void
zm_flush (void)
{
}
#else
/*
* Note: this debug setup works by storing the strings in a fixed buffer
*/
#define FINAL
#ifdef FINAL
static char *zm_out = (char *) 0x00380000;
static char *zm_out_start = (char *) 0x00380000;
#else
static char zm_buf[8192];
static char *zm_out = zm_buf;
static char *zm_out_start = zm_buf;
#endif
static int
zm_dprintf (char *fmt, ...)
{
int len;
va_list args;
va_start (args, fmt);
len = diag_vsprintf (zm_out, fmt, args);
zm_out += len;
return len;
}
static void
zm_flush (void)
{
#ifdef REDBOOT
char *p = zm_out_start;
while (*p)
mon_write_char (*p++);
#endif
zm_out = zm_out_start;
}
#endif
static void
zm_dump_buf (void *buf, int len)
{
#ifdef REDBOOT
diag_vdump_buf_with_offset (zm_dprintf, buf, len, 0);
#else
#endif
}
static unsigned char zm_buf[2048];
static unsigned char *zm_bp;
static void
zm_new (void)
{
zm_bp = zm_buf;
}
static void
zm_save (unsigned char c)
{
*zm_bp++ = c;
}
static void
zm_dump (int line)
{
zm_dprintf ("Packet at line: %d\n", line);
zm_dump_buf (zm_buf, zm_bp - zm_buf);
}
#define ZM_DEBUG(x) x
#else
#define ZM_DEBUG(x)
#endif
/* Wait for the line to go idle */
static void
xyzModem_flush (void)
{
int res;
char c;
while (true)
{
res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
if (!res)
return;
}
}
static int
xyzModem_get_hdr (void)
{
char c;
int res;
bool hdr_found = false;
int i, can_total, hdr_chars;
unsigned short cksum;
ZM_DEBUG (zm_new ());
/* Find the start of a header */
can_total = 0;
hdr_chars = 0;
if (xyz.tx_ack)
{
CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
xyz.tx_ack = false;
}
while (!hdr_found)
{
res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
ZM_DEBUG (zm_save (c));
if (res)
{
hdr_chars++;
switch (c)
{
case SOH:
xyz.total_SOH++;
case STX:
if (c == STX)
xyz.total_STX++;
hdr_found = true;
break;
case CAN:
xyz.total_CAN++;
ZM_DEBUG (zm_dump (__LINE__));
if (++can_total == xyzModem_CAN_COUNT)
{
return xyzModem_cancel;
}
else
{
/* Wait for multiple CAN to avoid early quits */
break;
}
case EOT:
/* EOT only supported if no noise */
if (hdr_chars == 1)
{
CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
ZM_DEBUG (zm_dprintf ("ACK on EOT #%d\n", __LINE__));
ZM_DEBUG (zm_dump (__LINE__));
return xyzModem_eof;
}
default:
/* Ignore, waiting for start of header */
;
}
}
else
{
/* Data stream timed out */
xyzModem_flush (); /* Toss any current input */
ZM_DEBUG (zm_dump (__LINE__));
CYGACC_CALL_IF_DELAY_US ((cyg_int32) 250000);
return xyzModem_timeout;
}
}
/* Header found, now read the data */
res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.blk);
ZM_DEBUG (zm_save (xyz.blk));
if (!res)
{
ZM_DEBUG (zm_dump (__LINE__));
return xyzModem_timeout;
}
res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.cblk);
ZM_DEBUG (zm_save (xyz.cblk));
if (!res)
{
ZM_DEBUG (zm_dump (__LINE__));
return xyzModem_timeout;
}
xyz.len = (c == SOH) ? 128 : 1024;
xyz.bufp = xyz.pkt;
for (i = 0; i < xyz.len; i++)
{
res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
ZM_DEBUG (zm_save (c));
if (res)
{
xyz.pkt[i] = c;
}
else
{
ZM_DEBUG (zm_dump (__LINE__));
return xyzModem_timeout;
}
}
res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.crc1);
ZM_DEBUG (zm_save (xyz.crc1));
if (!res)
{
ZM_DEBUG (zm_dump (__LINE__));
return xyzModem_timeout;
}
if (xyz.crc_mode)
{
res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.crc2);
ZM_DEBUG (zm_save (xyz.crc2));
if (!res)
{
ZM_DEBUG (zm_dump (__LINE__));
return xyzModem_timeout;
}
}
ZM_DEBUG (zm_dump (__LINE__));
/* Validate the message */
if ((xyz.blk ^ xyz.cblk) != (unsigned char) 0xFF)
{
ZM_DEBUG (zm_dprintf
("Framing error - blk: %x/%x/%x\n", xyz.blk, xyz.cblk,
(xyz.blk ^ xyz.cblk)));
ZM_DEBUG (zm_dump_buf (xyz.pkt, xyz.len));
xyzModem_flush ();
return xyzModem_frame;
}
/* Verify checksum/CRC */
if (xyz.crc_mode)
{
cksum = cyg_crc16 (xyz.pkt, xyz.len);
if (cksum != ((xyz.crc1 << 8) | xyz.crc2))
{
ZM_DEBUG (zm_dprintf ("CRC error - recvd: %02x%02x, computed: %x\n",
xyz.crc1, xyz.crc2, cksum & 0xFFFF));
return xyzModem_cksum;
}
}
else
{
cksum = 0;
for (i = 0; i < xyz.len; i++)
{
cksum += xyz.pkt[i];
}
if (xyz.crc1 != (cksum & 0xFF))
{
ZM_DEBUG (zm_dprintf
("Checksum error - recvd: %x, computed: %x\n", xyz.crc1,
cksum & 0xFF));
return xyzModem_cksum;
}
}
/* If we get here, the message passes [structural] muster */
return 0;
}
int
xyzModem_stream_open (connection_info_t * info, int *err)
{
#ifdef REDBOOT
int console_chan;
#endif
int stat = 0;
int retries = xyzModem_MAX_RETRIES;
int crc_retries = xyzModem_MAX_RETRIES_WITH_CRC;
/* ZM_DEBUG(zm_out = zm_out_start); */
#ifdef xyzModem_zmodem
if (info->mode == xyzModem_zmodem)
{
*err = xyzModem_noZmodem;
return -1;
}
#endif
#ifdef REDBOOT
/* Set up the I/O channel. Note: this allows for using a different port in the future */
console_chan =
CYGACC_CALL_IF_SET_CONSOLE_COMM
(CYGNUM_CALL_IF_SET_COMM_ID_QUERY_CURRENT);
if (info->chan >= 0)
{
CYGACC_CALL_IF_SET_CONSOLE_COMM (info->chan);
}
else
{
CYGACC_CALL_IF_SET_CONSOLE_COMM (console_chan);
}
xyz.__chan = CYGACC_CALL_IF_CONSOLE_PROCS ();
CYGACC_CALL_IF_SET_CONSOLE_COMM (console_chan);
CYGACC_COMM_IF_CONTROL (*xyz.__chan, __COMMCTL_SET_TIMEOUT,
xyzModem_CHAR_TIMEOUT);
#else
/* TODO: CHECK ! */
int dummy = 0;
xyz.__chan = &dummy;
#endif
xyz.len = 0;
xyz.crc_mode = true;
xyz.at_eof = false;
xyz.tx_ack = false;
xyz.mode = info->mode;
xyz.total_retries = 0;
xyz.total_SOH = 0;
xyz.total_STX = 0;
xyz.total_CAN = 0;
#ifdef USE_YMODEM_LENGTH
xyz.read_length = 0;
xyz.file_length = 0;
#endif
CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
if (xyz.mode == xyzModem_xmodem)
{
/* X-modem doesn't have an information header - exit here */
xyz.next_blk = 1;
return 0;
}
while (retries-- > 0)
{
stat = xyzModem_get_hdr ();
if (stat == 0)
{
/* Y-modem file information header */
if (xyz.blk == 0)
{
#ifdef USE_YMODEM_LENGTH
/* skip filename */
while (*xyz.bufp++);
/* get the length */
parse_num ((char *) xyz.bufp, &xyz.file_length, NULL, " ");
#endif
/* The rest of the file name data block quietly discarded */
xyz.tx_ack = true;
}
xyz.next_blk = 1;
xyz.len = 0;
return 0;
}
else if (stat == xyzModem_timeout)
{
if (--crc_retries <= 0)
xyz.crc_mode = false;
CYGACC_CALL_IF_DELAY_US (5 * 100000); /* Extra delay for startup */
CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
xyz.total_retries++;
ZM_DEBUG (zm_dprintf ("NAK (%d)\n", __LINE__));
}
if (stat == xyzModem_cancel)
{
break;
}
}
*err = stat;
ZM_DEBUG (zm_flush ());
return -1;
}
int
xyzModem_stream_read (char *buf, int size, int *err)
{
int stat, total, len;
int retries;
total = 0;
stat = xyzModem_cancel;
/* Try and get 'size' bytes into the buffer */
while (!xyz.at_eof && (size > 0))
{
if (xyz.len == 0)
{
retries = xyzModem_MAX_RETRIES;
while (retries-- > 0)
{
stat = xyzModem_get_hdr ();
if (stat == 0)
{
if (xyz.blk == xyz.next_blk)
{
xyz.tx_ack = true;
ZM_DEBUG (zm_dprintf
("ACK block %d (%d)\n", xyz.blk, __LINE__));
xyz.next_blk = (xyz.next_blk + 1) & 0xFF;
#if defined(xyzModem_zmodem) || defined(USE_YMODEM_LENGTH)
if (xyz.mode == xyzModem_xmodem || xyz.file_length == 0)
{
#else
if (1)
{
#endif
/* Data blocks can be padded with ^Z (EOF) characters */
/* This code tries to detect and remove them */
if ((xyz.bufp[xyz.len - 1] == EOF) &&
(xyz.bufp[xyz.len - 2] == EOF) &&
(xyz.bufp[xyz.len - 3] == EOF))
{
while (xyz.len
&& (xyz.bufp[xyz.len - 1] == EOF))
{
xyz.len--;
}
}
}
#ifdef USE_YMODEM_LENGTH
/*
* See if accumulated length exceeds that of the file.
* If so, reduce size (i.e., cut out pad bytes)
* Only do this for Y-modem (and Z-modem should it ever
* be supported since it can fall back to Y-modem mode).
*/
if (xyz.mode != xyzModem_xmodem && 0 != xyz.file_length)
{
xyz.read_length += xyz.len;
if (xyz.read_length > xyz.file_length)
{
xyz.len -= (xyz.read_length - xyz.file_length);
}
}
#endif
break;
}
else if (xyz.blk == ((xyz.next_blk - 1) & 0xFF))
{
/* Just re-ACK this so sender will get on with it */
CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
continue; /* Need new header */
}
else
{
stat = xyzModem_sequence;
}
}
if (stat == xyzModem_cancel)
{
break;
}
if (stat == xyzModem_eof)
{
CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
ZM_DEBUG (zm_dprintf ("ACK (%d)\n", __LINE__));
if (xyz.mode == xyzModem_ymodem)
{
CYGACC_COMM_IF_PUTC (*xyz.__chan,
(xyz.crc_mode ? 'C' : NAK));
xyz.total_retries++;
ZM_DEBUG (zm_dprintf ("Reading Final Header\n"));
stat = xyzModem_get_hdr ();
CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
ZM_DEBUG (zm_dprintf ("FINAL ACK (%d)\n", __LINE__));
}
xyz.at_eof = true;
break;
}
CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
xyz.total_retries++;
ZM_DEBUG (zm_dprintf ("NAK (%d)\n", __LINE__));
}
if (stat < 0)
{
*err = stat;
xyz.len = -1;
return total;
}
}
/* Don't "read" data from the EOF protocol package */
if (!xyz.at_eof)
{
len = xyz.len;
if (size < len)
len = size;
memcpy (buf, xyz.bufp, len);
size -= len;
buf += len;
total += len;
xyz.len -= len;
xyz.bufp += len;
}
}
return total;
}
void
xyzModem_stream_close (int *err)
{
diag_printf
("xyzModem - %s mode, %d(SOH)/%d(STX)/%d(CAN) packets, %d retries\n",
xyz.crc_mode ? "CRC" : "Cksum", xyz.total_SOH, xyz.total_STX,
xyz.total_CAN, xyz.total_retries);
ZM_DEBUG (zm_flush ());
}
/* Need to be able to clean out the input buffer, so have to take the */
/* getc */
void
xyzModem_stream_terminate (bool abort, int (*getc) (void))
{
int c;
if (abort)
{
ZM_DEBUG (zm_dprintf ("!!!! TRANSFER ABORT !!!!\n"));
switch (xyz.mode)
{
case xyzModem_xmodem:
case xyzModem_ymodem:
/* The X/YMODEM Spec seems to suggest that multiple CAN followed by an equal */
/* number of Backspaces is a friendly way to get the other end to abort. */
CYGACC_COMM_IF_PUTC (*xyz.__chan, CAN);
CYGACC_COMM_IF_PUTC (*xyz.__chan, CAN);
CYGACC_COMM_IF_PUTC (*xyz.__chan, CAN);
CYGACC_COMM_IF_PUTC (*xyz.__chan, CAN);
CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
/* Now consume the rest of what's waiting on the line. */
ZM_DEBUG (zm_dprintf ("Flushing serial line.\n"));
xyzModem_flush ();
xyz.at_eof = true;
break;
#ifdef xyzModem_zmodem
case xyzModem_zmodem:
/* Might support it some day I suppose. */
#endif
break;
}
}
else
{
ZM_DEBUG (zm_dprintf ("Engaging cleanup mode...\n"));
/*
* Consume any trailing crap left in the inbuffer from
* previous received blocks. Since very few files are an exact multiple
* of the transfer block size, there will almost always be some gunk here.
* If we don't eat it now, RedBoot will think the user typed it.
*/
ZM_DEBUG (zm_dprintf ("Trailing gunk:\n"));
while ((c = (*getc) ()) > -1);
ZM_DEBUG (zm_dprintf ("\n"));
/*
* Make a small delay to give terminal programs like minicom
* time to get control again after their file transfer program
* exits.
*/
CYGACC_CALL_IF_DELAY_US ((cyg_int32) 250000);
}
}
char *
xyzModem_error (int err)
{
switch (err)
{
case xyzModem_access:
return "Can't access file";
break;
case xyzModem_noZmodem:
return "Sorry, zModem not available yet";
break;
case xyzModem_timeout:
return "Timed out";
break;
case xyzModem_eof:
return "End of file";
break;
case xyzModem_cancel:
return "Cancelled";
break;
case xyzModem_frame:
return "Invalid framing";
break;
case xyzModem_cksum:
return "CRC/checksum error";
break;
case xyzModem_sequence:
return "Block sequence error";
break;
default:
return "Unknown error";
break;
}
}
/*
* RedBoot interface
*/
#if 0 /* SB */
GETC_IO_FUNCS (xyzModem_io, xyzModem_stream_open, xyzModem_stream_close,
xyzModem_stream_terminate, xyzModem_stream_read,
xyzModem_error);
RedBoot_load (xmodem, xyzModem_io, false, false, xyzModem_xmodem);
RedBoot_load (ymodem, xyzModem_io, false, false, xyzModem_ymodem);
#endif
|
1001-study-uboot
|
common/xyzModem.c
|
C
|
gpl3
| 19,815
|
/*
* Command for accessing DataFlash.
*
* Copyright (C) 2008 Atmel Corporation
*/
#include <common.h>
#include <df.h>
static int do_df(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
const char *cmd;
/* need at least two arguments */
if (argc < 2)
goto usage;
cmd = argv[1];
if (strcmp(cmd, "init") == 0) {
df_init(0, 0, 1000000);
return 0;
}
if (strcmp(cmd, "info") == 0) {
df_show_info();
return 0;
}
usage:
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
sf, 2, 1, do_serial_flash,
"Serial flash sub-system",
"probe [bus:]cs - init flash device on given SPI bus and CS")
|
1001-study-uboot
|
common/cmd_df.c
|
C
|
gpl3
| 612
|
/*
* Copyright 2008 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 provides a shell like 'expr' function to return.
*/
#include <common.h>
#include <config.h>
#include <command.h>
static ulong get_arg(char *s, int w)
{
ulong *p;
/*
* if the parameter starts with a '*' then assume
* it is a pointer to the value we want
*/
if (s[0] == '*') {
p = (ulong *)simple_strtoul(&s[1], NULL, 16);
switch (w) {
case 1: return((ulong)(*(uchar *)p));
case 2: return((ulong)(*(ushort *)p));
case 4:
default: return(*p);
}
} else {
return simple_strtoul(s, NULL, 16);
}
}
int do_setexpr(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong a, b;
char buf[16];
int w;
/* Validate arguments */
if ((argc != 5) || (strlen(argv[3]) != 1))
return cmd_usage(cmdtp);
w = cmd_get_data_size(argv[0], 4);
a = get_arg(argv[2], w);
b = get_arg(argv[4], w);
switch (argv[3][0]) {
case '|': sprintf(buf, "%lx", (a | b)); break;
case '&': sprintf(buf, "%lx", (a & b)); break;
case '+': sprintf(buf, "%lx", (a + b)); break;
case '^': sprintf(buf, "%lx", (a ^ b)); break;
case '-': sprintf(buf, "%lx", (a - b)); break;
case '*': sprintf(buf, "%lx", (a * b)); break;
case '/': sprintf(buf, "%lx", (a / b)); break;
case '%': sprintf(buf, "%lx", (a % b)); break;
default:
printf("invalid op\n");
return 1;
}
setenv(argv[1], buf);
return 0;
}
U_BOOT_CMD(
setexpr, 5, 0, do_setexpr,
"set environment variable as the result of eval expression",
"[.b, .w, .l] name value1 <op> value2\n"
" - set environment variable 'name' to the result of the evaluated\n"
" express specified by <op>. <op> can be &, |, ^, +, -, *, /, %\n"
" size argument is only meaningful if value1 and/or value2 are memory addresses"
);
|
1001-study-uboot
|
common/cmd_setexpr.c
|
C
|
gpl3
| 2,571
|
/*
* (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>
*
* (C) Copyright 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 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 <environment.h>
#include <malloc.h>
#include <spi_flash.h>
#include <search.h>
#include <errno.h>
#ifndef CONFIG_ENV_SPI_BUS
# define CONFIG_ENV_SPI_BUS 0
#endif
#ifndef CONFIG_ENV_SPI_CS
# define CONFIG_ENV_SPI_CS 0
#endif
#ifndef CONFIG_ENV_SPI_MAX_HZ
# define CONFIG_ENV_SPI_MAX_HZ 1000000
#endif
#ifndef CONFIG_ENV_SPI_MODE
# define CONFIG_ENV_SPI_MODE SPI_MODE_3
#endif
#ifdef CONFIG_ENV_OFFSET_REDUND
static ulong env_offset = CONFIG_ENV_OFFSET;
static ulong env_new_offset = CONFIG_ENV_OFFSET_REDUND;
#define ACTIVE_FLAG 1
#define OBSOLETE_FLAG 0
#endif /* CONFIG_ENV_OFFSET_REDUND */
DECLARE_GLOBAL_DATA_PTR;
char *env_name_spec = "SPI Flash";
static struct spi_flash *env_flash;
uchar env_get_char_spec(int index)
{
return *((uchar *)(gd->env_addr + index));
}
#if defined(CONFIG_ENV_OFFSET_REDUND)
int saveenv(void)
{
env_t env_new;
ssize_t len;
char *res, *saved_buffer = NULL, flag = OBSOLETE_FLAG;
u32 saved_size, saved_offset, sector = 1;
int ret;
if (!env_flash) {
env_flash = spi_flash_probe(CONFIG_ENV_SPI_BUS,
CONFIG_ENV_SPI_CS,
CONFIG_ENV_SPI_MAX_HZ, CONFIG_ENV_SPI_MODE);
if (!env_flash) {
set_default_env("!spi_flash_probe() failed");
return 1;
}
}
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);
env_new.flags = ACTIVE_FLAG;
if (gd->env_valid == 1) {
env_new_offset = CONFIG_ENV_OFFSET_REDUND;
env_offset = CONFIG_ENV_OFFSET;
} else {
env_new_offset = CONFIG_ENV_OFFSET;
env_offset = CONFIG_ENV_OFFSET_REDUND;
}
/* Is the sector larger than the env (i.e. embedded) */
if (CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE) {
saved_size = CONFIG_ENV_SECT_SIZE - CONFIG_ENV_SIZE;
saved_offset = env_new_offset + CONFIG_ENV_SIZE;
saved_buffer = malloc(saved_size);
if (!saved_buffer) {
ret = 1;
goto done;
}
ret = spi_flash_read(env_flash, saved_offset,
saved_size, saved_buffer);
if (ret)
goto done;
}
if (CONFIG_ENV_SIZE > CONFIG_ENV_SECT_SIZE) {
sector = CONFIG_ENV_SIZE / CONFIG_ENV_SECT_SIZE;
if (CONFIG_ENV_SIZE % CONFIG_ENV_SECT_SIZE)
sector++;
}
puts("Erasing SPI flash...");
ret = spi_flash_erase(env_flash, env_new_offset,
sector * CONFIG_ENV_SECT_SIZE);
if (ret)
goto done;
puts("Writing to SPI flash...");
ret = spi_flash_write(env_flash, env_new_offset,
CONFIG_ENV_SIZE, &env_new);
if (ret)
goto done;
if (CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE) {
ret = spi_flash_write(env_flash, saved_offset,
saved_size, saved_buffer);
if (ret)
goto done;
}
ret = spi_flash_write(env_flash, env_offset + offsetof(env_t, flags),
sizeof(env_new.flags), &flag);
if (ret)
goto done;
puts("done\n");
gd->env_valid = gd->env_valid == 2 ? 1 : 2;
printf("Valid environment: %d\n", (int)gd->env_valid);
done:
if (saved_buffer)
free(saved_buffer);
return ret;
}
void env_relocate_spec(void)
{
int ret;
int crc1_ok = 0, crc2_ok = 0;
env_t *tmp_env1 = NULL;
env_t *tmp_env2 = NULL;
env_t *ep = NULL;
tmp_env1 = (env_t *)malloc(CONFIG_ENV_SIZE);
tmp_env2 = (env_t *)malloc(CONFIG_ENV_SIZE);
if (!tmp_env1 || !tmp_env2) {
set_default_env("!malloc() failed");
goto out;
}
env_flash = spi_flash_probe(CONFIG_ENV_SPI_BUS, CONFIG_ENV_SPI_CS,
CONFIG_ENV_SPI_MAX_HZ, CONFIG_ENV_SPI_MODE);
if (!env_flash) {
set_default_env("!spi_flash_probe() failed");
goto out;
}
ret = spi_flash_read(env_flash, CONFIG_ENV_OFFSET,
CONFIG_ENV_SIZE, tmp_env1);
if (ret) {
set_default_env("!spi_flash_read() failed");
goto err_read;
}
if (crc32(0, tmp_env1->data, ENV_SIZE) == tmp_env1->crc)
crc1_ok = 1;
ret = spi_flash_read(env_flash, CONFIG_ENV_OFFSET_REDUND,
CONFIG_ENV_SIZE, tmp_env2);
if (!ret) {
if (crc32(0, tmp_env2->data, ENV_SIZE) == tmp_env2->crc)
crc2_ok = 1;
}
if (!crc1_ok && !crc2_ok) {
set_default_env("!bad CRC");
goto err_read;
} else if (crc1_ok && !crc2_ok) {
gd->env_valid = 1;
} else if (!crc1_ok && crc2_ok) {
gd->env_valid = 2;
} else if (tmp_env1->flags == ACTIVE_FLAG &&
tmp_env2->flags == OBSOLETE_FLAG) {
gd->env_valid = 1;
} else if (tmp_env1->flags == OBSOLETE_FLAG &&
tmp_env2->flags == ACTIVE_FLAG) {
gd->env_valid = 2;
} else if (tmp_env1->flags == tmp_env2->flags) {
gd->env_valid = 2;
} else if (tmp_env1->flags == 0xFF) {
gd->env_valid = 2;
} else {
/*
* this differs from code in env_flash.c, but I think a sane
* default path is desirable.
*/
gd->env_valid = 2;
}
if (gd->env_valid == 1)
ep = tmp_env1;
else
ep = tmp_env2;
ret = env_import((char *)ep, 0);
if (!ret) {
error("Cannot import environment: errno = %d\n", errno);
set_default_env("env_import failed");
}
err_read:
spi_flash_free(env_flash);
env_flash = NULL;
out:
free(tmp_env1);
free(tmp_env2);
}
#else
int saveenv(void)
{
u32 saved_size, saved_offset, sector = 1;
char *res, *saved_buffer = NULL;
int ret = 1;
env_t env_new;
ssize_t len;
if (!env_flash) {
env_flash = spi_flash_probe(CONFIG_ENV_SPI_BUS,
CONFIG_ENV_SPI_CS,
CONFIG_ENV_SPI_MAX_HZ, CONFIG_ENV_SPI_MODE);
if (!env_flash) {
set_default_env("!spi_flash_probe() failed");
return 1;
}
}
/* Is the sector larger than the env (i.e. embedded) */
if (CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE) {
saved_size = CONFIG_ENV_SECT_SIZE - CONFIG_ENV_SIZE;
saved_offset = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
saved_buffer = malloc(saved_size);
if (!saved_buffer)
goto done;
ret = spi_flash_read(env_flash, saved_offset,
saved_size, saved_buffer);
if (ret)
goto done;
}
if (CONFIG_ENV_SIZE > CONFIG_ENV_SECT_SIZE) {
sector = CONFIG_ENV_SIZE / CONFIG_ENV_SECT_SIZE;
if (CONFIG_ENV_SIZE % CONFIG_ENV_SECT_SIZE)
sector++;
}
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 SPI flash...");
ret = spi_flash_erase(env_flash, CONFIG_ENV_OFFSET,
sector * CONFIG_ENV_SECT_SIZE);
if (ret)
goto done;
puts("Writing to SPI flash...");
ret = spi_flash_write(env_flash, CONFIG_ENV_OFFSET,
CONFIG_ENV_SIZE, &env_new);
if (ret)
goto done;
if (CONFIG_ENV_SECT_SIZE > CONFIG_ENV_SIZE) {
ret = spi_flash_write(env_flash, saved_offset,
saved_size, saved_buffer);
if (ret)
goto done;
}
ret = 0;
puts("done\n");
done:
if (saved_buffer)
free(saved_buffer);
return ret;
}
void env_relocate_spec(void)
{
char buf[CONFIG_ENV_SIZE];
int ret;
env_flash = spi_flash_probe(CONFIG_ENV_SPI_BUS, CONFIG_ENV_SPI_CS,
CONFIG_ENV_SPI_MAX_HZ, CONFIG_ENV_SPI_MODE);
if (!env_flash) {
set_default_env("!spi_flash_probe() failed");
return;
}
ret = spi_flash_read(env_flash,
CONFIG_ENV_OFFSET, CONFIG_ENV_SIZE, buf);
if (ret) {
set_default_env("!spi_flash_read() failed");
goto out;
}
ret = env_import(buf, 1);
if (ret)
gd->env_valid = 1;
out:
spi_flash_free(env_flash);
env_flash = NULL;
}
#endif
int env_init(void)
{
/* SPI flash isn't usable before relocation */
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 1;
return 0;
}
|
1001-study-uboot
|
common/env_sf.c
|
C
|
gpl3
| 8,373
|
/*
* Helper functions for working with the builtin symbol table
*
* Copyright (c) 2008-2009 Analog Devices Inc.
* Licensed under the GPL-2 or later.
*/
#include <common.h>
/* We need the weak marking as this symbol is provided specially */
extern const char system_map[] __attribute__((weak));
/* Given an address, return a pointer to the symbol name and store
* the base address in caddr. So if the symbol map had an entry:
* 03fb9b7c_spi_cs_deactivate
* Then the following call:
* unsigned long base;
* const char *sym = symbol_lookup(0x03fb9b80, &base);
* Would end up setting the variables like so:
* base = 0x03fb9b7c;
* sym = "_spi_cs_deactivate";
*/
const char *symbol_lookup(unsigned long addr, unsigned long *caddr)
{
const char *sym, *csym;
char *esym;
unsigned long sym_addr;
sym = system_map;
csym = NULL;
*caddr = 0;
while (*sym) {
sym_addr = simple_strtoul(sym, &esym, 16);
sym = esym;
if (sym_addr > addr)
break;
*caddr = sym_addr;
csym = sym;
sym += strlen(sym) + 1;
}
return csym;
}
|
1001-study-uboot
|
common/kallsyms.c
|
C
|
gpl3
| 1,050
|
/*
* (C) Copyright 2007 OpenMoko, Inc.
* Written by Harald Welte <laforge@openmoko.org>
*
* 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>
#include <serial.h>
int do_terminal(cmd_tbl_t * cmd, int flag, int argc, char * const argv[])
{
int last_tilde = 0;
struct stdio_dev *dev = NULL;
if (argc < 1)
return -1;
/* Scan for selected output/input device */
dev = stdio_get_by_name(argv[1]);
if (!dev)
return -1;
serial_reinit_all();
printf("Entering terminal mode for port %s\n", dev->name);
puts("Use '~.' to leave the terminal and get back to u-boot\n");
while (1) {
int c;
/* read from console and display on serial port */
if (stdio_devices[0]->tstc()) {
c = stdio_devices[0]->getc();
if (last_tilde == 1) {
if (c == '.') {
putc(c);
putc('\n');
break;
} else {
last_tilde = 0;
/* write the delayed tilde */
dev->putc('~');
/* fall-through to print current
* character */
}
}
if (c == '~') {
last_tilde = 1;
puts("[u-boot]");
putc(c);
}
dev->putc(c);
}
/* read from serial port and display on console */
if (dev->tstc()) {
c = dev->getc();
putc(c);
}
}
return 0;
}
/***************************************************/
U_BOOT_CMD(
terminal, 3, 1, do_terminal,
"start terminal emulator",
""
);
|
1001-study-uboot
|
common/cmd_terminal.c
|
C
|
gpl3
| 2,163
|
/*
* (C) Copyright 2000-2003
* 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
*/
/*
* MPC8xx/MPC8260 Internal Memory Map Functions
*/
#include <common.h>
#include <command.h>
#if defined(CONFIG_8xx) || defined(CONFIG_8260)
#if defined(CONFIG_8xx)
#include <asm/8xx_immap.h>
#include <commproc.h>
#include <asm/iopin_8xx.h>
#elif defined(CONFIG_8260)
#include <asm/immap_8260.h>
#include <asm/cpm_8260.h>
#include <asm/iopin_8260.h>
#endif
DECLARE_GLOBAL_DATA_PTR;
static void
unimplemented ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
printf ("Sorry, but the '%s' command has not been implemented\n",
cmdtp->name);
}
int
do_siuinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
volatile immap_t *immap = (immap_t *) CONFIG_SYS_IMMR;
#if defined(CONFIG_8xx)
volatile sysconf8xx_t *sc = &immap->im_siu_conf;
#elif defined(CONFIG_8260)
volatile sysconf8260_t *sc = &immap->im_siu_conf;
#endif
printf ("SIUMCR= %08x SYPCR = %08x\n", sc->sc_siumcr, sc->sc_sypcr);
#if defined(CONFIG_8xx)
printf ("SWT = %08x\n", sc->sc_swt);
printf ("SIPEND= %08x SIMASK= %08x\n", sc->sc_sipend, sc->sc_simask);
printf ("SIEL = %08x SIVEC = %08x\n", sc->sc_siel, sc->sc_sivec);
printf ("TESR = %08x SDCR = %08x\n", sc->sc_tesr, sc->sc_sdcr);
#elif defined(CONFIG_8260)
printf ("BCR = %08x\n", sc->sc_bcr);
printf ("P_ACR = %02x P_ALRH= %08x P_ALRL= %08x\n",
sc->sc_ppc_acr, sc->sc_ppc_alrh, sc->sc_ppc_alrl);
printf ("L_ACR = %02x L_ALRH= %08x L_ALRL= %08x\n",
sc->sc_lcl_acr, sc->sc_lcl_alrh, sc->sc_lcl_alrl);
printf ("PTESR1= %08x PTESR2= %08x\n", sc->sc_tescr1, sc->sc_tescr2);
printf ("LTESR1= %08x LTESR2= %08x\n", sc->sc_ltescr1, sc->sc_ltescr2);
printf ("PDTEA = %08x PDTEM = %02x\n", sc->sc_pdtea, sc->sc_pdtem);
printf ("LDTEA = %08x LDTEM = %02x\n", sc->sc_ldtea, sc->sc_ldtem);
#endif
return 0;
}
int
do_memcinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
volatile immap_t *immap = (immap_t *) CONFIG_SYS_IMMR;
#if defined(CONFIG_8xx)
volatile memctl8xx_t *memctl = &immap->im_memctl;
int nbanks = 8;
#elif defined(CONFIG_8260)
volatile memctl8260_t *memctl = &immap->im_memctl;
int nbanks = 12;
#endif
volatile uint *p = &memctl->memc_br0;
int i;
for (i = 0; i < nbanks; i++, p += 2) {
if (i < 10) {
printf ("BR%d = %08x OR%d = %08x\n",
i, p[0], i, p[1]);
} else {
printf ("BR%d = %08x OR%d = %08x\n",
i, p[0], i, p[1]);
}
}
printf ("MAR = %08x", memctl->memc_mar);
#if defined(CONFIG_8xx)
printf (" MCR = %08x\n", memctl->memc_mcr);
#elif defined(CONFIG_8260)
putc ('\n');
#endif
printf ("MAMR = %08x MBMR = %08x",
memctl->memc_mamr, memctl->memc_mbmr);
#if defined(CONFIG_8xx)
printf ("\nMSTAT = %04x\n", memctl->memc_mstat);
#elif defined(CONFIG_8260)
printf (" MCMR = %08x\n", memctl->memc_mcmr);
#endif
printf ("MPTPR = %04x MDR = %08x\n",
memctl->memc_mptpr, memctl->memc_mdr);
#if defined(CONFIG_8260)
printf ("PSDMR = %08x LSDMR = %08x\n",
memctl->memc_psdmr, memctl->memc_lsdmr);
printf ("PURT = %02x PSRT = %02x\n",
memctl->memc_purt, memctl->memc_psrt);
printf ("LURT = %02x LSRT = %02x\n",
memctl->memc_lurt, memctl->memc_lsrt);
printf ("IMMR = %08x\n", memctl->memc_immr);
#endif
return 0;
}
int
do_sitinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
#ifdef CONFIG_8260
int
do_icinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
#endif
int
do_carinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
volatile immap_t *immap = (immap_t *) CONFIG_SYS_IMMR;
#if defined(CONFIG_8xx)
volatile car8xx_t *car = &immap->im_clkrst;
#elif defined(CONFIG_8260)
volatile car8260_t *car = &immap->im_clkrst;
#endif
#if defined(CONFIG_8xx)
printf ("SCCR = %08x\n", car->car_sccr);
printf ("PLPRCR= %08x\n", car->car_plprcr);
printf ("RSR = %08x\n", car->car_rsr);
#elif defined(CONFIG_8260)
printf ("SCCR = %08x\n", car->car_sccr);
printf ("SCMR = %08x\n", car->car_scmr);
printf ("RSR = %08x\n", car->car_rsr);
printf ("RMR = %08x\n", car->car_rmr);
#endif
return 0;
}
static int counter;
static void
header(void)
{
char *data = "\
-------------------------------- --------------------------------\
00000000001111111111222222222233 00000000001111111111222222222233\
01234567890123456789012345678901 01234567890123456789012345678901\
-------------------------------- --------------------------------\
";
int i;
if (counter % 2)
putc('\n');
counter = 0;
for (i = 0; i < 4; i++, data += 79)
printf("%.79s\n", data);
}
static void binary (char *label, uint value, int nbits)
{
uint mask = 1 << (nbits - 1);
int i, second = (counter++ % 2);
if (second)
putc (' ');
puts (label);
for (i = 32 + 1; i != nbits; i--)
putc (' ');
while (mask != 0) {
if (value & mask)
putc ('1');
else
putc ('0');
mask >>= 1;
}
if (second)
putc ('\n');
}
#if defined(CONFIG_8xx)
#define PA_NBITS 16
#define PA_NB_ODR 8
#define PB_NBITS 18
#define PB_NB_ODR 16
#define PC_NBITS 12
#define PD_NBITS 13
#elif defined(CONFIG_8260)
#define PA_NBITS 32
#define PA_NB_ODR 32
#define PB_NBITS 28
#define PB_NB_ODR 28
#define PC_NBITS 32
#define PD_NBITS 28
#endif
int
do_iopinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
volatile immap_t *immap = (immap_t *) CONFIG_SYS_IMMR;
#if defined(CONFIG_8xx)
volatile iop8xx_t *iop = &immap->im_ioport;
volatile ushort *l, *r;
#elif defined(CONFIG_8260)
volatile iop8260_t *iop = &immap->im_ioport;
volatile uint *l, *r;
#endif
volatile uint *R;
counter = 0;
header ();
/*
* Ports A & B
*/
#if defined(CONFIG_8xx)
l = &iop->iop_padir;
R = &immap->im_cpm.cp_pbdir;
#elif defined(CONFIG_8260)
l = &iop->iop_pdira;
R = &iop->iop_pdirb;
#endif
binary ("PA_DIR", *l++, PA_NBITS);
binary ("PB_DIR", *R++, PB_NBITS);
binary ("PA_PAR", *l++, PA_NBITS);
binary ("PB_PAR", *R++, PB_NBITS);
#if defined(CONFIG_8260)
binary ("PA_SOR", *l++, PA_NBITS);
binary ("PB_SOR", *R++, PB_NBITS);
#endif
binary ("PA_ODR", *l++, PA_NB_ODR);
binary ("PB_ODR", *R++, PB_NB_ODR);
binary ("PA_DAT", *l++, PA_NBITS);
binary ("PB_DAT", *R++, PB_NBITS);
header ();
/*
* Ports C & D
*/
#if defined(CONFIG_8xx)
l = &iop->iop_pcdir;
r = &iop->iop_pddir;
#elif defined(CONFIG_8260)
l = &iop->iop_pdirc;
r = &iop->iop_pdird;
#endif
binary ("PC_DIR", *l++, PC_NBITS);
binary ("PD_DIR", *r++, PD_NBITS);
binary ("PC_PAR", *l++, PC_NBITS);
binary ("PD_PAR", *r++, PD_NBITS);
#if defined(CONFIG_8xx)
binary ("PC_SO ", *l++, PC_NBITS);
binary (" ", 0, 0);
r++;
#elif defined(CONFIG_8260)
binary ("PC_SOR", *l++, PC_NBITS);
binary ("PD_SOR", *r++, PD_NBITS);
binary ("PC_ODR", *l++, PC_NBITS);
binary ("PD_ODR", *r++, PD_NBITS);
#endif
binary ("PC_DAT", *l++, PC_NBITS);
binary ("PD_DAT", *r++, PD_NBITS);
#if defined(CONFIG_8xx)
binary ("PC_INT", *l++, PC_NBITS);
#endif
header ();
return 0;
}
/*
* set the io pins
* this needs a clean up for smaller tighter code
* use *uint and set the address based on cmd + port
*/
int
do_iopset (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
uint rcode = 0;
iopin_t iopin;
static uint port = 0;
static uint pin = 0;
static uint value = 0;
static enum {
DIR,
PAR,
SOR,
ODR,
DAT,
#if defined(CONFIG_8xx)
INT
#endif
} cmd = DAT;
if (argc != 5) {
puts ("iopset PORT PIN CMD VALUE\n");
return 1;
}
port = argv[1][0] - 'A';
if (port > 3)
port -= 0x20;
if (port > 3)
rcode = 1;
pin = simple_strtol (argv[2], NULL, 10);
if (pin > 31)
rcode = 1;
switch (argv[3][0]) {
case 'd':
if (argv[3][1] == 'a')
cmd = DAT;
else if (argv[3][1] == 'i')
cmd = DIR;
else
rcode = 1;
break;
case 'p':
cmd = PAR;
break;
case 'o':
cmd = ODR;
break;
case 's':
cmd = SOR;
break;
#if defined(CONFIG_8xx)
case 'i':
cmd = INT;
break;
#endif
default:
printf ("iopset: unknown command %s\n", argv[3]);
rcode = 1;
}
if (argv[4][0] == '1')
value = 1;
else if (argv[4][0] == '0')
value = 0;
else
rcode = 1;
if (rcode == 0) {
iopin.port = port;
iopin.pin = pin;
iopin.flag = 0;
switch (cmd) {
case DIR:
if (value)
iopin_set_out (&iopin);
else
iopin_set_in (&iopin);
break;
case PAR:
if (value)
iopin_set_ded (&iopin);
else
iopin_set_gen (&iopin);
break;
case SOR:
if (value)
iopin_set_opt2 (&iopin);
else
iopin_set_opt1 (&iopin);
break;
case ODR:
if (value)
iopin_set_odr (&iopin);
else
iopin_set_act (&iopin);
break;
case DAT:
if (value)
iopin_set_high (&iopin);
else
iopin_set_low (&iopin);
break;
#if defined(CONFIG_8xx)
case INT:
if (value)
iopin_set_falledge (&iopin);
else
iopin_set_anyedge (&iopin);
break;
#endif
}
}
return rcode;
}
int
do_dmainfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
int
do_fccinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
static void prbrg (int n, uint val)
{
uint extc = (val >> 14) & 3;
uint cd = (val & CPM_BRG_CD_MASK) >> 1;
uint div16 = (val & CPM_BRG_DIV16) != 0;
#if defined(CONFIG_8xx)
ulong clock = gd->cpu_clk;
#elif defined(CONFIG_8260)
ulong clock = gd->brg_clk;
#endif
printf ("BRG%d:", n);
if (val & CPM_BRG_RST)
puts (" RESET");
else
puts (" ");
if (val & CPM_BRG_EN)
puts (" ENABLED");
else
puts (" DISABLED");
printf (" EXTC=%d", extc);
if (val & CPM_BRG_ATB)
puts (" ATB");
else
puts (" ");
printf (" DIVIDER=%4d", cd);
if (extc == 0 && cd != 0) {
uint baudrate;
if (div16)
baudrate = (clock / 16) / (cd + 1);
else
baudrate = clock / (cd + 1);
printf ("=%6d bps", baudrate);
} else {
puts (" ");
}
if (val & CPM_BRG_DIV16)
puts (" DIV16");
else
puts (" ");
putc ('\n');
}
int
do_brginfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
volatile immap_t *immap = (immap_t *) CONFIG_SYS_IMMR;
#if defined(CONFIG_8xx)
volatile cpm8xx_t *cp = &immap->im_cpm;
volatile uint *p = &cp->cp_brgc1;
#elif defined(CONFIG_8260)
volatile uint *p = &immap->im_brgc1;
#endif
int i = 1;
while (i <= 4)
prbrg (i++, *p++);
#if defined(CONFIG_8260)
p = &immap->im_brgc5;
while (i <= 8)
prbrg (i++, *p++);
#endif
return 0;
}
int
do_i2cinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
volatile immap_t *immap = (immap_t *) CONFIG_SYS_IMMR;
#if defined(CONFIG_8xx)
volatile i2c8xx_t *i2c = &immap->im_i2c;
volatile cpm8xx_t *cp = &immap->im_cpm;
volatile iic_t *iip = (iic_t *) & cp->cp_dparam[PROFF_IIC];
#elif defined(CONFIG_8260)
volatile i2c8260_t *i2c = &immap->im_i2c;
volatile iic_t *iip;
uint dpaddr;
dpaddr = *((unsigned short *) (&immap->im_dprambase[PROFF_I2C_BASE]));
if (dpaddr == 0)
iip = NULL;
else
iip = (iic_t *) & immap->im_dprambase[dpaddr];
#endif
printf ("I2MOD = %02x I2ADD = %02x\n", i2c->i2c_i2mod, i2c->i2c_i2add);
printf ("I2BRG = %02x I2COM = %02x\n", i2c->i2c_i2brg, i2c->i2c_i2com);
printf ("I2CER = %02x I2CMR = %02x\n", i2c->i2c_i2cer, i2c->i2c_i2cmr);
if (iip == NULL)
puts ("i2c parameter ram not allocated\n");
else {
printf ("RBASE = %08x TBASE = %08x\n",
iip->iic_rbase, iip->iic_tbase);
printf ("RFCR = %02x TFCR = %02x\n",
iip->iic_rfcr, iip->iic_tfcr);
printf ("MRBLR = %04x\n", iip->iic_mrblr);
printf ("RSTATE= %08x RDP = %08x\n",
iip->iic_rstate, iip->iic_rdp);
printf ("RBPTR = %04x RBC = %04x\n",
iip->iic_rbptr, iip->iic_rbc);
printf ("RXTMP = %08x\n", iip->iic_rxtmp);
printf ("TSTATE= %08x TDP = %08x\n",
iip->iic_tstate, iip->iic_tdp);
printf ("TBPTR = %04x TBC = %04x\n",
iip->iic_tbptr, iip->iic_tbc);
printf ("TXTMP = %08x\n", iip->iic_txtmp);
}
return 0;
}
int
do_sccinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
int
do_smcinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
int
do_spiinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
int
do_muxinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
int
do_siinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
int
do_mccinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
unimplemented (cmdtp, flag, argc, argv);
return 0;
}
/***************************************************/
U_BOOT_CMD(
siuinfo, 1, 1, do_siuinfo,
"print System Interface Unit (SIU) registers",
""
);
U_BOOT_CMD(
memcinfo, 1, 1, do_memcinfo,
"print Memory Controller registers",
""
);
U_BOOT_CMD(
sitinfo, 1, 1, do_sitinfo,
"print System Integration Timers (SIT) registers",
""
);
#ifdef CONFIG_8260
U_BOOT_CMD(
icinfo, 1, 1, do_icinfo,
"print Interrupt Controller registers",
""
);
#endif
U_BOOT_CMD(
carinfo, 1, 1, do_carinfo,
"print Clocks and Reset registers",
""
);
U_BOOT_CMD(
iopinfo, 1, 1, do_iopinfo,
"print I/O Port registers",
""
);
U_BOOT_CMD(
iopset, 5, 0, do_iopset,
"set I/O Port registers",
"PORT PIN CMD VALUE\nPORT: A-D, PIN: 0-31, CMD: [dat|dir|odr|sor], VALUE: 0|1"
);
U_BOOT_CMD(
dmainfo, 1, 1, do_dmainfo,
"print SDMA/IDMA registers",
""
);
U_BOOT_CMD(
fccinfo, 1, 1, do_fccinfo,
"print FCC registers",
""
);
U_BOOT_CMD(
brginfo, 1, 1, do_brginfo,
"print Baud Rate Generator (BRG) registers",
""
);
U_BOOT_CMD(
i2cinfo, 1, 1, do_i2cinfo,
"print I2C registers",
""
);
U_BOOT_CMD(
sccinfo, 1, 1, do_sccinfo,
"print SCC registers",
""
);
U_BOOT_CMD(
smcinfo, 1, 1, do_smcinfo,
"print SMC registers",
""
);
U_BOOT_CMD(
spiinfo, 1, 1, do_spiinfo,
"print Serial Peripheral Interface (SPI) registers",
""
);
U_BOOT_CMD(
muxinfo, 1, 1, do_muxinfo,
"print CPM Multiplexing registers",
""
);
U_BOOT_CMD(
siinfo, 1, 1, do_siinfo,
"print Serial Interface (SI) registers",
""
);
U_BOOT_CMD(
mccinfo, 1, 1, do_mccinfo,
"print MCC registers",
""
);
#endif
|
1001-study-uboot
|
common/cmd_immap.c
|
C
|
gpl3
| 15,309
|
/*
* (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
*/
/*
* 09-18-2001 Andreas Heppel, Sysgo RTS GmbH <aheppel@sysgo.de>
*
* It might not be possible in all cases to use 'memcpy()' to copy
* the environment to NVRAM, as the NVRAM might not be mapped into
* the memory space. (I.e. this is the case for the BAB750). In those
* cases it might be possible to access the NVRAM using a different
* method. For example, the RTC on the BAB750 is accessible in IO
* space using its address and data registers. To enable usage of
* NVRAM in those cases I invented the functions 'nvram_read()' and
* 'nvram_write()', which will be activated upon the configuration
* #define CONFIG_SYS_NVRAM_ACCESS_ROUTINE. Note, that those functions are
* strongly dependent on the used HW, and must be redefined for each
* board that wants to use them.
*/
#include <common.h>
#include <command.h>
#include <environment.h>
#include <linux/stddef.h>
#include <search.h>
#include <errno.h>
DECLARE_GLOBAL_DATA_PTR;
#ifdef CONFIG_SYS_NVRAM_ACCESS_ROUTINE
extern void *nvram_read(void *dest, const long src, size_t count);
extern void nvram_write(long dest, const void *src, size_t count);
env_t *env_ptr;
#else
env_t *env_ptr = (env_t *)CONFIG_ENV_ADDR;
#endif
char *env_name_spec = "NVRAM";
uchar env_get_char_spec(int index)
{
#ifdef CONFIG_SYS_NVRAM_ACCESS_ROUTINE
uchar c;
nvram_read(&c, CONFIG_ENV_ADDR + index, 1);
return c;
#else
return *((uchar *)(gd->env_addr + index));
#endif
}
void env_relocate_spec(void)
{
char buf[CONFIG_ENV_SIZE];
#if defined(CONFIG_SYS_NVRAM_ACCESS_ROUTINE)
nvram_read(buf, CONFIG_ENV_ADDR, CONFIG_ENV_SIZE);
#else
memcpy(buf, (void *)CONFIG_ENV_ADDR, CONFIG_ENV_SIZE);
#endif
env_import(buf, 1);
}
int saveenv(void)
{
env_t env_new;
ssize_t len;
char *res;
int rcode = 0;
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_SYS_NVRAM_ACCESS_ROUTINE
nvram_write(CONFIG_ENV_ADDR, &env_new, CONFIG_ENV_SIZE);
#else
if (memcpy((char *)CONFIG_ENV_ADDR, &env_new, CONFIG_ENV_SIZE) == NULL)
rcode = 1;
#endif
return rcode;
}
/*
* Initialize Environment use
*
* We are still running from ROM, so data use is limited
*/
int env_init(void)
{
#if defined(CONFIG_SYS_NVRAM_ACCESS_ROUTINE)
ulong crc;
uchar data[ENV_SIZE];
nvram_read(&crc, CONFIG_ENV_ADDR, sizeof(ulong));
nvram_read(data, CONFIG_ENV_ADDR + sizeof(ulong), ENV_SIZE);
if (crc32(0, data, ENV_SIZE) == crc) {
gd->env_addr = (ulong)CONFIG_ENV_ADDR + sizeof(long);
#else
if (crc32(0, env_ptr->data, ENV_SIZE) == env_ptr->crc) {
gd->env_addr = (ulong)&env_ptr->data;
#endif
gd->env_valid = 1;
} else {
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 0;
}
return 0;
}
|
1001-study-uboot
|
common/env_nvram.c
|
C
|
gpl3
| 3,838
|
/*
* (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
*/
/*
* Serial up- and download support
*/
#include <common.h>
#include <command.h>
#include <s_record.h>
#include <net.h>
#include <exports.h>
#include <xyzModem.h>
DECLARE_GLOBAL_DATA_PTR;
#if defined(CONFIG_CMD_LOADB)
static ulong load_serial_ymodem (ulong offset);
#endif
#if defined(CONFIG_CMD_LOADS)
static ulong load_serial (long offset);
static int read_record (char *buf, ulong len);
# if defined(CONFIG_CMD_SAVES)
static int save_serial (ulong offset, ulong size);
static int write_record (char *buf);
#endif
static int do_echo = 1;
#endif
/* -------------------------------------------------------------------- */
#if defined(CONFIG_CMD_LOADS)
int do_load_serial (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
long offset = 0;
ulong addr;
int i;
char *env_echo;
int rcode = 0;
#ifdef CONFIG_SYS_LOADS_BAUD_CHANGE
int load_baudrate, current_baudrate;
load_baudrate = current_baudrate = gd->baudrate;
#endif
if (((env_echo = getenv("loads_echo")) != NULL) && (*env_echo == '1')) {
do_echo = 1;
} else {
do_echo = 0;
}
#ifdef CONFIG_SYS_LOADS_BAUD_CHANGE
if (argc >= 2) {
offset = simple_strtol(argv[1], NULL, 16);
}
if (argc == 3) {
load_baudrate = (int)simple_strtoul(argv[2], NULL, 10);
/* default to current baudrate */
if (load_baudrate == 0)
load_baudrate = current_baudrate;
}
if (load_baudrate != current_baudrate) {
printf ("## Switch baudrate to %d bps and press ENTER ...\n",
load_baudrate);
udelay(50000);
gd->baudrate = load_baudrate;
serial_setbrg ();
udelay(50000);
for (;;) {
if (getc() == '\r')
break;
}
}
#else /* ! CONFIG_SYS_LOADS_BAUD_CHANGE */
if (argc == 2) {
offset = simple_strtol(argv[1], NULL, 16);
}
#endif /* CONFIG_SYS_LOADS_BAUD_CHANGE */
printf ("## Ready for S-Record download ...\n");
addr = load_serial (offset);
/*
* Gather any trailing characters (for instance, the ^D which
* is sent by 'cu' after sending a file), and give the
* box some time (100 * 1 ms)
*/
for (i=0; i<100; ++i) {
if (tstc()) {
(void) getc();
}
udelay(1000);
}
if (addr == ~0) {
printf ("## S-Record download aborted\n");
rcode = 1;
} else {
printf ("## Start Addr = 0x%08lX\n", addr);
load_addr = addr;
}
#ifdef CONFIG_SYS_LOADS_BAUD_CHANGE
if (load_baudrate != current_baudrate) {
printf ("## Switch baudrate to %d bps and press ESC ...\n",
current_baudrate);
udelay (50000);
gd->baudrate = current_baudrate;
serial_setbrg ();
udelay (50000);
for (;;) {
if (getc() == 0x1B) /* ESC */
break;
}
}
#endif
return rcode;
}
static ulong
load_serial (long offset)
{
char record[SREC_MAXRECLEN + 1]; /* buffer for one S-Record */
char binbuf[SREC_MAXBINLEN]; /* buffer for binary data */
int binlen; /* no. of data bytes in S-Rec. */
int type; /* return code for record type */
ulong addr; /* load address from S-Record */
ulong size; /* number of bytes transferred */
char buf[32];
ulong store_addr;
ulong start_addr = ~0;
ulong end_addr = 0;
int line_count = 0;
while (read_record(record, SREC_MAXRECLEN + 1) >= 0) {
type = srec_decode (record, &binlen, &addr, binbuf);
if (type < 0) {
return (~0); /* Invalid S-Record */
}
switch (type) {
case SREC_DATA2:
case SREC_DATA3:
case SREC_DATA4:
store_addr = addr + offset;
#ifndef CONFIG_SYS_NO_FLASH
if (addr2info(store_addr)) {
int rc;
rc = flash_write((char *)binbuf,store_addr,binlen);
if (rc != 0) {
flash_perror (rc);
return (~0);
}
} else
#endif
{
memcpy ((char *)(store_addr), binbuf, binlen);
}
if ((store_addr) < start_addr)
start_addr = store_addr;
if ((store_addr + binlen - 1) > end_addr)
end_addr = store_addr + binlen - 1;
break;
case SREC_END2:
case SREC_END3:
case SREC_END4:
udelay (10000);
size = end_addr - start_addr + 1;
printf ("\n"
"## First Load Addr = 0x%08lX\n"
"## Last Load Addr = 0x%08lX\n"
"## Total Size = 0x%08lX = %ld Bytes\n",
start_addr, end_addr, size, size
);
flush_cache (start_addr, size);
sprintf(buf, "%lX", size);
setenv("filesize", buf);
return (addr);
case SREC_START:
break;
default:
break;
}
if (!do_echo) { /* print a '.' every 100 lines */
if ((++line_count % 100) == 0)
putc ('.');
}
}
return (~0); /* Download aborted */
}
static int
read_record (char *buf, ulong len)
{
char *p;
char c;
--len; /* always leave room for terminating '\0' byte */
for (p=buf; p < buf+len; ++p) {
c = getc(); /* read character */
if (do_echo)
putc (c); /* ... and echo it */
switch (c) {
case '\r':
case '\n':
*p = '\0';
return (p - buf);
case '\0':
case 0x03: /* ^C - Control C */
return (-1);
default:
*p = c;
}
/* Check for the console hangup (if any different from serial) */
if (gd->jt[XF_getc] != getc) {
if (ctrlc()) {
return (-1);
}
}
}
/* line too long - truncate */
*p = '\0';
return (p - buf);
}
#if defined(CONFIG_CMD_SAVES)
int do_save_serial (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong offset = 0;
ulong size = 0;
#ifdef CONFIG_SYS_LOADS_BAUD_CHANGE
int save_baudrate, current_baudrate;
save_baudrate = current_baudrate = gd->baudrate;
#endif
if (argc >= 2) {
offset = simple_strtoul(argv[1], NULL, 16);
}
#ifdef CONFIG_SYS_LOADS_BAUD_CHANGE
if (argc >= 3) {
size = simple_strtoul(argv[2], NULL, 16);
}
if (argc == 4) {
save_baudrate = (int)simple_strtoul(argv[3], NULL, 10);
/* default to current baudrate */
if (save_baudrate == 0)
save_baudrate = current_baudrate;
}
if (save_baudrate != current_baudrate) {
printf ("## Switch baudrate to %d bps and press ENTER ...\n",
save_baudrate);
udelay(50000);
gd->baudrate = save_baudrate;
serial_setbrg ();
udelay(50000);
for (;;) {
if (getc() == '\r')
break;
}
}
#else /* ! CONFIG_SYS_LOADS_BAUD_CHANGE */
if (argc == 3) {
size = simple_strtoul(argv[2], NULL, 16);
}
#endif /* CONFIG_SYS_LOADS_BAUD_CHANGE */
printf ("## Ready for S-Record upload, press ENTER to proceed ...\n");
for (;;) {
if (getc() == '\r')
break;
}
if(save_serial (offset, size)) {
printf ("## S-Record upload aborted\n");
} else {
printf ("## S-Record upload complete\n");
}
#ifdef CONFIG_SYS_LOADS_BAUD_CHANGE
if (save_baudrate != current_baudrate) {
printf ("## Switch baudrate to %d bps and press ESC ...\n",
(int)current_baudrate);
udelay (50000);
gd->baudrate = current_baudrate;
serial_setbrg ();
udelay (50000);
for (;;) {
if (getc() == 0x1B) /* ESC */
break;
}
}
#endif
return 0;
}
#define SREC3_START "S0030000FC\n"
#define SREC3_FORMAT "S3%02X%08lX%s%02X\n"
#define SREC3_END "S70500000000FA\n"
#define SREC_BYTES_PER_RECORD 16
static int save_serial (ulong address, ulong count)
{
int i, c, reclen, checksum, length;
char *hex = "0123456789ABCDEF";
char record[2*SREC_BYTES_PER_RECORD+16]; /* buffer for one S-Record */
char data[2*SREC_BYTES_PER_RECORD+1]; /* buffer for hex data */
reclen = 0;
checksum = 0;
if(write_record(SREC3_START)) /* write the header */
return (-1);
do {
if(count) { /* collect hex data in the buffer */
c = *(volatile uchar*)(address + reclen); /* get one byte */
checksum += c; /* accumulate checksum */
data[2*reclen] = hex[(c>>4)&0x0f];
data[2*reclen+1] = hex[c & 0x0f];
data[2*reclen+2] = '\0';
++reclen;
--count;
}
if(reclen == SREC_BYTES_PER_RECORD || count == 0) {
/* enough data collected for one record: dump it */
if(reclen) { /* build & write a data record: */
/* address + data + checksum */
length = 4 + reclen + 1;
/* accumulate length bytes into checksum */
for(i = 0; i < 2; i++)
checksum += (length >> (8*i)) & 0xff;
/* accumulate address bytes into checksum: */
for(i = 0; i < 4; i++)
checksum += (address >> (8*i)) & 0xff;
/* make proper checksum byte: */
checksum = ~checksum & 0xff;
/* output one record: */
sprintf(record, SREC3_FORMAT, length, address, data, checksum);
if(write_record(record))
return (-1);
}
address += reclen; /* increment address */
checksum = 0;
reclen = 0;
}
}
while(count);
if(write_record(SREC3_END)) /* write the final record */
return (-1);
return(0);
}
static int
write_record (char *buf)
{
char c;
while((c = *buf++))
putc(c);
/* Check for the console hangup (if any different from serial) */
if (ctrlc()) {
return (-1);
}
return (0);
}
# endif
#endif
#if defined(CONFIG_CMD_LOADB)
/*
* loadb command (load binary) included
*/
#define XON_CHAR 17
#define XOFF_CHAR 19
#define START_CHAR 0x01
#define ETX_CHAR 0x03
#define END_CHAR 0x0D
#define SPACE 0x20
#define K_ESCAPE 0x23
#define SEND_TYPE 'S'
#define DATA_TYPE 'D'
#define ACK_TYPE 'Y'
#define NACK_TYPE 'N'
#define BREAK_TYPE 'B'
#define tochar(x) ((char) (((x) + SPACE) & 0xff))
#define untochar(x) ((int) (((x) - SPACE) & 0xff))
static void set_kerm_bin_mode(unsigned long *);
static int k_recv(void);
static ulong load_serial_bin (ulong offset);
char his_eol; /* character he needs at end of packet */
int his_pad_count; /* number of pad chars he needs */
char his_pad_char; /* pad chars he needs */
char his_quote; /* quote chars he'll use */
int do_load_serial_bin (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong offset = 0;
ulong addr;
int load_baudrate, current_baudrate;
int rcode = 0;
char *s;
/* pre-set offset from CONFIG_SYS_LOAD_ADDR */
offset = CONFIG_SYS_LOAD_ADDR;
/* pre-set offset from $loadaddr */
if ((s = getenv("loadaddr")) != NULL) {
offset = simple_strtoul(s, NULL, 16);
}
load_baudrate = current_baudrate = gd->baudrate;
if (argc >= 2) {
offset = simple_strtoul(argv[1], NULL, 16);
}
if (argc == 3) {
load_baudrate = (int)simple_strtoul(argv[2], NULL, 10);
/* default to current baudrate */
if (load_baudrate == 0)
load_baudrate = current_baudrate;
}
if (load_baudrate != current_baudrate) {
printf ("## Switch baudrate to %d bps and press ENTER ...\n",
load_baudrate);
udelay(50000);
gd->baudrate = load_baudrate;
serial_setbrg ();
udelay(50000);
for (;;) {
if (getc() == '\r')
break;
}
}
if (strcmp(argv[0],"loady")==0) {
printf ("## Ready for binary (ymodem) download "
"to 0x%08lX at %d bps...\n",
offset,
load_baudrate);
addr = load_serial_ymodem (offset);
} else {
printf ("## Ready for binary (kermit) download "
"to 0x%08lX at %d bps...\n",
offset,
load_baudrate);
addr = load_serial_bin (offset);
if (addr == ~0) {
load_addr = 0;
printf ("## Binary (kermit) download aborted\n");
rcode = 1;
} else {
printf ("## Start Addr = 0x%08lX\n", addr);
load_addr = addr;
}
}
if (load_baudrate != current_baudrate) {
printf ("## Switch baudrate to %d bps and press ESC ...\n",
current_baudrate);
udelay (50000);
gd->baudrate = current_baudrate;
serial_setbrg ();
udelay (50000);
for (;;) {
if (getc() == 0x1B) /* ESC */
break;
}
}
return rcode;
}
static ulong load_serial_bin (ulong offset)
{
int size, i;
char buf[32];
set_kerm_bin_mode ((ulong *) offset);
size = k_recv ();
/*
* Gather any trailing characters (for instance, the ^D which
* is sent by 'cu' after sending a file), and give the
* box some time (100 * 1 ms)
*/
for (i=0; i<100; ++i) {
if (tstc()) {
(void) getc();
}
udelay(1000);
}
flush_cache (offset, size);
printf("## Total Size = 0x%08x = %d Bytes\n", size, size);
sprintf(buf, "%X", size);
setenv("filesize", buf);
return offset;
}
void send_pad (void)
{
int count = his_pad_count;
while (count-- > 0)
putc (his_pad_char);
}
/* converts escaped kermit char to binary char */
char ktrans (char in)
{
if ((in & 0x60) == 0x40) {
return (char) (in & ~0x40);
} else if ((in & 0x7f) == 0x3f) {
return (char) (in | 0x40);
} else
return in;
}
int chk1 (char *buffer)
{
int total = 0;
while (*buffer) {
total += *buffer++;
}
return (int) ((total + ((total >> 6) & 0x03)) & 0x3f);
}
void s1_sendpacket (char *packet)
{
send_pad ();
while (*packet) {
putc (*packet++);
}
}
static char a_b[24];
void send_ack (int n)
{
a_b[0] = START_CHAR;
a_b[1] = tochar (3);
a_b[2] = tochar (n);
a_b[3] = ACK_TYPE;
a_b[4] = '\0';
a_b[4] = tochar (chk1 (&a_b[1]));
a_b[5] = his_eol;
a_b[6] = '\0';
s1_sendpacket (a_b);
}
void send_nack (int n)
{
a_b[0] = START_CHAR;
a_b[1] = tochar (3);
a_b[2] = tochar (n);
a_b[3] = NACK_TYPE;
a_b[4] = '\0';
a_b[4] = tochar (chk1 (&a_b[1]));
a_b[5] = his_eol;
a_b[6] = '\0';
s1_sendpacket (a_b);
}
void (*os_data_init) (void);
void (*os_data_char) (char new_char);
static int os_data_state, os_data_state_saved;
static char *os_data_addr, *os_data_addr_saved;
static char *bin_start_address;
static void bin_data_init (void)
{
os_data_state = 0;
os_data_addr = bin_start_address;
}
static void os_data_save (void)
{
os_data_state_saved = os_data_state;
os_data_addr_saved = os_data_addr;
}
static void os_data_restore (void)
{
os_data_state = os_data_state_saved;
os_data_addr = os_data_addr_saved;
}
static void bin_data_char (char new_char)
{
switch (os_data_state) {
case 0: /* data */
*os_data_addr++ = new_char;
break;
}
}
static void set_kerm_bin_mode (unsigned long *addr)
{
bin_start_address = (char *) addr;
os_data_init = bin_data_init;
os_data_char = bin_data_char;
}
/* k_data_* simply handles the kermit escape translations */
static int k_data_escape, k_data_escape_saved;
void k_data_init (void)
{
k_data_escape = 0;
os_data_init ();
}
void k_data_save (void)
{
k_data_escape_saved = k_data_escape;
os_data_save ();
}
void k_data_restore (void)
{
k_data_escape = k_data_escape_saved;
os_data_restore ();
}
void k_data_char (char new_char)
{
if (k_data_escape) {
/* last char was escape - translate this character */
os_data_char (ktrans (new_char));
k_data_escape = 0;
} else {
if (new_char == his_quote) {
/* this char is escape - remember */
k_data_escape = 1;
} else {
/* otherwise send this char as-is */
os_data_char (new_char);
}
}
}
#define SEND_DATA_SIZE 20
char send_parms[SEND_DATA_SIZE];
char *send_ptr;
/* handle_send_packet interprits the protocol info and builds and
sends an appropriate ack for what we can do */
void handle_send_packet (int n)
{
int length = 3;
int bytes;
/* initialize some protocol parameters */
his_eol = END_CHAR; /* default end of line character */
his_pad_count = 0;
his_pad_char = '\0';
his_quote = K_ESCAPE;
/* ignore last character if it filled the buffer */
if (send_ptr == &send_parms[SEND_DATA_SIZE - 1])
--send_ptr;
bytes = send_ptr - send_parms; /* how many bytes we'll process */
do {
if (bytes-- <= 0)
break;
/* handle MAXL - max length */
/* ignore what he says - most I'll take (here) is 94 */
a_b[++length] = tochar (94);
if (bytes-- <= 0)
break;
/* handle TIME - time you should wait for my packets */
/* ignore what he says - don't wait for my ack longer than 1 second */
a_b[++length] = tochar (1);
if (bytes-- <= 0)
break;
/* handle NPAD - number of pad chars I need */
/* remember what he says - I need none */
his_pad_count = untochar (send_parms[2]);
a_b[++length] = tochar (0);
if (bytes-- <= 0)
break;
/* handle PADC - pad chars I need */
/* remember what he says - I need none */
his_pad_char = ktrans (send_parms[3]);
a_b[++length] = 0x40; /* He should ignore this */
if (bytes-- <= 0)
break;
/* handle EOL - end of line he needs */
/* remember what he says - I need CR */
his_eol = untochar (send_parms[4]);
a_b[++length] = tochar (END_CHAR);
if (bytes-- <= 0)
break;
/* handle QCTL - quote control char he'll use */
/* remember what he says - I'll use '#' */
his_quote = send_parms[5];
a_b[++length] = '#';
if (bytes-- <= 0)
break;
/* handle QBIN - 8-th bit prefixing */
/* ignore what he says - I refuse */
a_b[++length] = 'N';
if (bytes-- <= 0)
break;
/* handle CHKT - the clock check type */
/* ignore what he says - I do type 1 (for now) */
a_b[++length] = '1';
if (bytes-- <= 0)
break;
/* handle REPT - the repeat prefix */
/* ignore what he says - I refuse (for now) */
a_b[++length] = 'N';
if (bytes-- <= 0)
break;
/* handle CAPAS - the capabilities mask */
/* ignore what he says - I only do long packets - I don't do windows */
a_b[++length] = tochar (2); /* only long packets */
a_b[++length] = tochar (0); /* no windows */
a_b[++length] = tochar (94); /* large packet msb */
a_b[++length] = tochar (94); /* large packet lsb */
} while (0);
a_b[0] = START_CHAR;
a_b[1] = tochar (length);
a_b[2] = tochar (n);
a_b[3] = ACK_TYPE;
a_b[++length] = '\0';
a_b[length] = tochar (chk1 (&a_b[1]));
a_b[++length] = his_eol;
a_b[++length] = '\0';
s1_sendpacket (a_b);
}
/* k_recv receives a OS Open image file over kermit line */
static int k_recv (void)
{
char new_char;
char k_state, k_state_saved;
int sum;
int done;
int length;
int n, last_n;
int len_lo, len_hi;
/* initialize some protocol parameters */
his_eol = END_CHAR; /* default end of line character */
his_pad_count = 0;
his_pad_char = '\0';
his_quote = K_ESCAPE;
/* initialize the k_recv and k_data state machine */
done = 0;
k_state = 0;
k_data_init ();
k_state_saved = k_state;
k_data_save ();
n = 0; /* just to get rid of a warning */
last_n = -1;
/* expect this "type" sequence (but don't check):
S: send initiate
F: file header
D: data (multiple)
Z: end of file
B: break transmission
*/
/* enter main loop */
while (!done) {
/* set the send packet pointer to begining of send packet parms */
send_ptr = send_parms;
/* With each packet, start summing the bytes starting with the length.
Save the current sequence number.
Note the type of the packet.
If a character less than SPACE (0x20) is received - error.
*/
#if 0
/* OLD CODE, Prior to checking sequence numbers */
/* first have all state machines save current states */
k_state_saved = k_state;
k_data_save ();
#endif
/* get a packet */
/* wait for the starting character or ^C */
for (;;) {
switch (getc ()) {
case START_CHAR: /* start packet */
goto START;
case ETX_CHAR: /* ^C waiting for packet */
return (0);
default:
;
}
}
START:
/* get length of packet */
sum = 0;
new_char = getc ();
if ((new_char & 0xE0) == 0)
goto packet_error;
sum += new_char & 0xff;
length = untochar (new_char);
/* get sequence number */
new_char = getc ();
if ((new_char & 0xE0) == 0)
goto packet_error;
sum += new_char & 0xff;
n = untochar (new_char);
--length;
/* NEW CODE - check sequence numbers for retried packets */
/* Note - this new code assumes that the sequence number is correctly
* received. Handling an invalid sequence number adds another layer
* of complexity that may not be needed - yet! At this time, I'm hoping
* that I don't need to buffer the incoming data packets and can write
* the data into memory in real time.
*/
if (n == last_n) {
/* same sequence number, restore the previous state */
k_state = k_state_saved;
k_data_restore ();
} else {
/* new sequence number, checkpoint the download */
last_n = n;
k_state_saved = k_state;
k_data_save ();
}
/* END NEW CODE */
/* get packet type */
new_char = getc ();
if ((new_char & 0xE0) == 0)
goto packet_error;
sum += new_char & 0xff;
k_state = new_char;
--length;
/* check for extended length */
if (length == -2) {
/* (length byte was 0, decremented twice) */
/* get the two length bytes */
new_char = getc ();
if ((new_char & 0xE0) == 0)
goto packet_error;
sum += new_char & 0xff;
len_hi = untochar (new_char);
new_char = getc ();
if ((new_char & 0xE0) == 0)
goto packet_error;
sum += new_char & 0xff;
len_lo = untochar (new_char);
length = len_hi * 95 + len_lo;
/* check header checksum */
new_char = getc ();
if ((new_char & 0xE0) == 0)
goto packet_error;
if (new_char != tochar ((sum + ((sum >> 6) & 0x03)) & 0x3f))
goto packet_error;
sum += new_char & 0xff;
/* --length; */ /* new length includes only data and block check to come */
}
/* bring in rest of packet */
while (length > 1) {
new_char = getc ();
if ((new_char & 0xE0) == 0)
goto packet_error;
sum += new_char & 0xff;
--length;
if (k_state == DATA_TYPE) {
/* pass on the data if this is a data packet */
k_data_char (new_char);
} else if (k_state == SEND_TYPE) {
/* save send pack in buffer as is */
*send_ptr++ = new_char;
/* if too much data, back off the pointer */
if (send_ptr >= &send_parms[SEND_DATA_SIZE])
--send_ptr;
}
}
/* get and validate checksum character */
new_char = getc ();
if ((new_char & 0xE0) == 0)
goto packet_error;
if (new_char != tochar ((sum + ((sum >> 6) & 0x03)) & 0x3f))
goto packet_error;
/* get END_CHAR */
new_char = getc ();
if (new_char != END_CHAR) {
packet_error:
/* restore state machines */
k_state = k_state_saved;
k_data_restore ();
/* send a negative acknowledge packet in */
send_nack (n);
} else if (k_state == SEND_TYPE) {
/* crack the protocol parms, build an appropriate ack packet */
handle_send_packet (n);
} else {
/* send simple acknowledge packet in */
send_ack (n);
/* quit if end of transmission */
if (k_state == BREAK_TYPE)
done = 1;
}
}
return ((ulong) os_data_addr - (ulong) bin_start_address);
}
static int getcxmodem(void) {
if (tstc())
return (getc());
return -1;
}
static ulong load_serial_ymodem (ulong offset)
{
int size;
char buf[32];
int err;
int res;
connection_info_t info;
char ymodemBuf[1024];
ulong store_addr = ~0;
ulong addr = 0;
size = 0;
info.mode = xyzModem_ymodem;
res = xyzModem_stream_open (&info, &err);
if (!res) {
while ((res =
xyzModem_stream_read (ymodemBuf, 1024, &err)) > 0) {
store_addr = addr + offset;
size += res;
addr += res;
#ifndef CONFIG_SYS_NO_FLASH
if (addr2info (store_addr)) {
int rc;
rc = flash_write ((char *) ymodemBuf,
store_addr, res);
if (rc != 0) {
flash_perror (rc);
return (~0);
}
} else
#endif
{
memcpy ((char *) (store_addr), ymodemBuf,
res);
}
}
} else {
printf ("%s\n", xyzModem_error (err));
}
xyzModem_stream_close (&err);
xyzModem_stream_terminate (false, &getcxmodem);
flush_cache (offset, size);
printf ("## Total Size = 0x%08x = %d Bytes\n", size, size);
sprintf (buf, "%X", size);
setenv ("filesize", buf);
return offset;
}
#endif
/* -------------------------------------------------------------------- */
#if defined(CONFIG_CMD_LOADS)
#ifdef CONFIG_SYS_LOADS_BAUD_CHANGE
U_BOOT_CMD(
loads, 3, 0, do_load_serial,
"load S-Record file over serial line",
"[ off ] [ baud ]\n"
" - load S-Record file over serial line"
" with offset 'off' and baudrate 'baud'"
);
#else /* ! CONFIG_SYS_LOADS_BAUD_CHANGE */
U_BOOT_CMD(
loads, 2, 0, do_load_serial,
"load S-Record file over serial line",
"[ off ]\n"
" - load S-Record file over serial line with offset 'off'"
);
#endif /* CONFIG_SYS_LOADS_BAUD_CHANGE */
/*
* SAVES always requires LOADS support, but not vice versa
*/
#if defined(CONFIG_CMD_SAVES)
#ifdef CONFIG_SYS_LOADS_BAUD_CHANGE
U_BOOT_CMD(
saves, 4, 0, do_save_serial,
"save S-Record file over serial line",
"[ off ] [size] [ baud ]\n"
" - save S-Record file over serial line"
" with offset 'off', size 'size' and baudrate 'baud'"
);
#else /* ! CONFIG_SYS_LOADS_BAUD_CHANGE */
U_BOOT_CMD(
saves, 3, 0, do_save_serial,
"save S-Record file over serial line",
"[ off ] [size]\n"
" - save S-Record file over serial line with offset 'off' and size 'size'"
);
#endif /* CONFIG_SYS_LOADS_BAUD_CHANGE */
#endif
#endif
#if defined(CONFIG_CMD_LOADB)
U_BOOT_CMD(
loadb, 3, 0, do_load_serial_bin,
"load binary file over serial line (kermit mode)",
"[ off ] [ baud ]\n"
" - load binary file over serial line"
" with offset 'off' and baudrate 'baud'"
);
U_BOOT_CMD(
loady, 3, 0, do_load_serial_bin,
"load binary file over serial line (ymodem mode)",
"[ off ] [ baud ]\n"
" - load binary file over serial line"
" with offset 'off' and baudrate 'baud'"
);
#endif
/* -------------------------------------------------------------------- */
#if defined(CONFIG_CMD_HWFLOW)
int do_hwflow (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
extern int hwflow_onoff(int);
if (argc == 2) {
if (strcmp(argv[1], "off") == 0)
hwflow_onoff(-1);
else
if (strcmp(argv[1], "on") == 0)
hwflow_onoff(1);
else
return cmd_usage(cmdtp);
}
printf("RTS/CTS hardware flow control: %s\n", hwflow_onoff(0) ? "on" : "off");
return 0;
}
/* -------------------------------------------------------------------- */
U_BOOT_CMD(
hwflow, 2, 0, do_hwflow,
"turn RTS/CTS hardware flow control in serial line on/off",
"[on|off]"
);
#endif
|
1001-study-uboot
|
common/cmd_load.c
|
C
|
gpl3
| 26,241
|
/*
* (C) Copyright 2008 Semihalf
*
* Written by: Rafal Czubak <rcz@semihalf.com>
* Bartlomiej Sieka <tur@semihalf.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>
#if !(defined(CONFIG_FIT) && defined(CONFIG_OF_LIBFDT))
#error "CONFIG_FIT and CONFIG_OF_LIBFDT are required for auto-update feature"
#endif
#if defined(CONFIG_SYS_NO_FLASH)
#error "CONFIG_SYS_NO_FLASH defined, but FLASH is required for auto-update feature"
#endif
#include <command.h>
#include <flash.h>
#include <net.h>
#include <malloc.h>
/* env variable holding the location of the update file */
#define UPDATE_FILE_ENV "updatefile"
/* set configuration defaults if needed */
#ifndef CONFIG_UPDATE_LOAD_ADDR
#define CONFIG_UPDATE_LOAD_ADDR 0x100000
#endif
#ifndef CONFIG_UPDATE_TFTP_MSEC_MAX
#define CONFIG_UPDATE_TFTP_MSEC_MAX 100
#endif
#ifndef CONFIG_UPDATE_TFTP_CNT_MAX
#define CONFIG_UPDATE_TFTP_CNT_MAX 0
#endif
extern ulong TftpRRQTimeoutMSecs;
extern int TftpRRQTimeoutCountMax;
extern flash_info_t flash_info[];
extern ulong load_addr;
static uchar *saved_prot_info;
static int update_load(char *filename, ulong msec_max, int cnt_max, ulong addr)
{
int size, rv;
ulong saved_timeout_msecs;
int saved_timeout_count;
char *saved_netretry, *saved_bootfile;
rv = 0;
/* save used globals and env variable */
saved_timeout_msecs = TftpRRQTimeoutMSecs;
saved_timeout_count = TftpRRQTimeoutCountMax;
saved_netretry = strdup(getenv("netretry"));
saved_bootfile = strdup(BootFile);
/* set timeouts for auto-update */
TftpRRQTimeoutMSecs = msec_max;
TftpRRQTimeoutCountMax = cnt_max;
/* we don't want to retry the connection if errors occur */
setenv("netretry", "no");
/* download the update file */
load_addr = addr;
copy_filename(BootFile, filename, sizeof(BootFile));
size = NetLoop(TFTPGET);
if (size < 0)
rv = 1;
else if (size > 0)
flush_cache(addr, size);
/* restore changed globals and env variable */
TftpRRQTimeoutMSecs = saved_timeout_msecs;
TftpRRQTimeoutCountMax = saved_timeout_count;
setenv("netretry", saved_netretry);
if (saved_netretry != NULL)
free(saved_netretry);
if (saved_bootfile != NULL) {
copy_filename(BootFile, saved_bootfile, sizeof(BootFile));
free(saved_bootfile);
}
return rv;
}
static int update_flash_protect(int prot, ulong addr_first, ulong addr_last)
{
uchar *sp_info_ptr;
ulong s;
int i, bank, cnt;
flash_info_t *info;
sp_info_ptr = NULL;
if (prot == 0) {
saved_prot_info =
calloc(CONFIG_SYS_MAX_FLASH_BANKS * CONFIG_SYS_MAX_FLASH_SECT, 1);
if (!saved_prot_info)
return 1;
}
for (bank = 0; bank < CONFIG_SYS_MAX_FLASH_BANKS; ++bank) {
cnt = 0;
info = &flash_info[bank];
/* Nothing to do if the bank doesn't exist */
if (info->sector_count == 0)
return 0;
/* Point to current bank protection information */
sp_info_ptr = saved_prot_info + (bank * CONFIG_SYS_MAX_FLASH_SECT);
/*
* Adjust addr_first or addr_last if we are on bank boundary.
* Address space between banks must be continuous for other
* flash functions (like flash_sect_erase or flash_write) to
* succeed. Banks must also be numbered in correct order,
* according to increasing addresses.
*/
if (addr_last > info->start[0] + info->size - 1)
addr_last = info->start[0] + info->size - 1;
if (addr_first < info->start[0])
addr_first = info->start[0];
for (i = 0; i < info->sector_count; i++) {
/* Save current information about protected sectors */
if (prot == 0) {
s = info->start[i];
if ((s >= addr_first) && (s <= addr_last))
sp_info_ptr[i] = info->protect[i];
}
/* Protect/unprotect sectors */
if (sp_info_ptr[i] == 1) {
#if defined(CONFIG_SYS_FLASH_PROTECTION)
if (flash_real_protect(info, i, prot))
return 1;
#else
info->protect[i] = prot;
#endif
cnt++;
}
}
if (cnt) {
printf("%sProtected %d sectors\n",
prot ? "": "Un-", cnt);
}
}
if((prot == 1) && saved_prot_info)
free(saved_prot_info);
return 0;
}
static int update_flash(ulong addr_source, ulong addr_first, ulong size)
{
ulong addr_last = addr_first + size - 1;
/* round last address to the sector boundary */
if (flash_sect_roundb(&addr_last) > 0)
return 1;
if (addr_first >= addr_last) {
printf("Error: end address exceeds addressing space\n");
return 1;
}
/* remove protection on processed sectors */
if (update_flash_protect(0, addr_first, addr_last) > 0) {
printf("Error: could not unprotect flash sectors\n");
return 1;
}
printf("Erasing 0x%08lx - 0x%08lx", addr_first, addr_last);
if (flash_sect_erase(addr_first, addr_last) > 0) {
printf("Error: could not erase flash\n");
return 1;
}
printf("Copying to flash...");
if (flash_write((char *)addr_source, addr_first, size) > 0) {
printf("Error: could not copy to flash\n");
return 1;
}
printf("done\n");
/* enable protection on processed sectors */
if (update_flash_protect(1, addr_first, addr_last) > 0) {
printf("Error: could not protect flash sectors\n");
return 1;
}
return 0;
}
static int update_fit_getparams(const void *fit, int noffset, ulong *addr,
ulong *fladdr, ulong *size)
{
const void *data;
if (fit_image_get_data(fit, noffset, &data, (size_t *)size))
return 1;
if (fit_image_get_load(fit, noffset, (ulong *)fladdr))
return 1;
*addr = (ulong)data;
return 0;
}
int update_tftp(ulong addr)
{
char *filename, *env_addr;
int images_noffset, ndepth, noffset;
ulong update_addr, update_fladdr, update_size;
void *fit;
int ret = 0;
/* use already present image */
if (addr)
goto got_update_file;
printf("Auto-update from TFTP: ");
/* get the file name of the update file */
filename = getenv(UPDATE_FILE_ENV);
if (filename == NULL) {
printf("failed, env. variable '%s' not found\n",
UPDATE_FILE_ENV);
return 1;
}
printf("trying update file '%s'\n", filename);
/* get load address of downloaded update file */
if ((env_addr = getenv("loadaddr")) != NULL)
addr = simple_strtoul(env_addr, NULL, 16);
else
addr = CONFIG_UPDATE_LOAD_ADDR;
if (update_load(filename, CONFIG_UPDATE_TFTP_MSEC_MAX,
CONFIG_UPDATE_TFTP_CNT_MAX, addr)) {
printf("Can't load update file, aborting auto-update\n");
return 1;
}
got_update_file:
fit = (void *)addr;
if (!fit_check_format((void *)fit)) {
printf("Bad FIT format of the update file, aborting "
"auto-update\n");
return 1;
}
/* process updates */
images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
ndepth = 0;
noffset = fdt_next_node(fit, images_noffset, &ndepth);
while (noffset >= 0 && ndepth > 0) {
if (ndepth != 1)
goto next_node;
printf("Processing update '%s' :",
fit_get_name(fit, noffset, NULL));
if (!fit_image_check_hashes(fit, noffset)) {
printf("Error: invalid update hash, aborting\n");
ret = 1;
goto next_node;
}
printf("\n");
if (update_fit_getparams(fit, noffset, &update_addr,
&update_fladdr, &update_size)) {
printf("Error: can't get update parameteres, "
"aborting\n");
ret = 1;
goto next_node;
}
if (update_flash(update_addr, update_fladdr, update_size)) {
printf("Error: can't flash update, aborting\n");
ret = 1;
goto next_node;
}
next_node:
noffset = fdt_next_node(fit, noffset, &ndepth);
}
return ret;
}
|
1001-study-uboot
|
common/update.c
|
C
|
gpl3
| 8,068
|
/*
* 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 <malloc.h>
#include <errno.h>
#include <linux/list.h>
#include "menu.h"
/*
* Internally, each item in a menu is represented by a struct menu_item.
*
* These items will be alloc'd and initialized by menu_item_add and destroyed
* by menu_item_destroy, and the consumer of the interface never sees that
* this struct is used at all.
*/
struct menu_item {
char *key;
void *data;
struct list_head list;
};
/*
* The menu is composed of a list of items along with settings and callbacks
* provided by the user. An incomplete definition of this struct is available
* in menu.h, but the full definition is here to prevent consumers from
* relying on its contents.
*/
struct menu {
struct menu_item *default_item;
int timeout;
char *title;
int prompt;
void (*item_data_print)(void *);
struct list_head items;
};
/*
* An iterator function for menu items. callback will be called for each item
* in m, with m, a pointer to the item, and extra being passed to callback. If
* callback returns a value other than NULL, iteration stops and the value
* return by callback is returned from menu_items_iter. This allows it to be
* used for search type operations. It is also safe for callback to remove the
* item from the list of items.
*/
static inline void *menu_items_iter(struct menu *m,
void *(*callback)(struct menu *, struct menu_item *, void *),
void *extra)
{
struct list_head *pos, *n;
struct menu_item *item;
void *ret;
list_for_each_safe(pos, n, &m->items) {
item = list_entry(pos, struct menu_item, list);
ret = callback(m, item, extra);
if (ret)
return ret;
}
return NULL;
}
/*
* Print a menu_item. If the consumer provided an item_data_print function
* when creating the menu, call it with a pointer to the item's private data.
* Otherwise, print the key of the item.
*/
static inline void *menu_item_print(struct menu *m,
struct menu_item *item,
void *extra)
{
if (!m->item_data_print) {
puts(item->key);
putc('\n');
} else {
m->item_data_print(item->data);
}
return NULL;
}
/*
* Free the memory used by a menu item. This includes the memory used by its
* key.
*/
static inline void *menu_item_destroy(struct menu *m,
struct menu_item *item,
void *extra)
{
if (item->key)
free(item->key);
free(item);
return NULL;
}
/*
* Display a menu so the user can make a choice of an item. First display its
* title, if any, and then each item in the menu.
*/
static inline void menu_display(struct menu *m)
{
if (m->title) {
puts(m->title);
putc('\n');
}
menu_items_iter(m, menu_item_print, NULL);
}
/*
* Check if an item's key matches a provided string, pointed to by extra. If
* extra is NULL, an item with a NULL key will match. Otherwise, the item's
* key has to match according to strcmp.
*
* This is called via menu_items_iter, so it returns a pointer to the item if
* the key matches, and returns NULL otherwise.
*/
static inline void *menu_item_key_match(struct menu *m,
struct menu_item *item, void *extra)
{
char *item_key = extra;
if (!item_key || !item->key) {
if (item_key == item->key)
return item;
return NULL;
}
if (strcmp(item->key, item_key) == 0)
return item;
return NULL;
}
/*
* Find the first item with a key matching item_key, if any exists.
*/
static inline struct menu_item *menu_item_by_key(struct menu *m,
char *item_key)
{
return menu_items_iter(m, menu_item_key_match, item_key);
}
/*
* Wait for the user to hit a key according to the timeout set for the menu.
* Returns 1 if the user hit a key, or 0 if the timeout expired.
*/
static inline int menu_interrupted(struct menu *m)
{
if (!m->timeout)
return 0;
if (abortboot(m->timeout/10))
return 1;
return 0;
}
/*
* Checks whether or not the default menu item should be used without
* prompting for a user choice. If the menu is set to always prompt, or the
* user hits a key during the timeout period, return 0. Otherwise, return 1 to
* indicate we should use the default menu item.
*/
static inline int menu_use_default(struct menu *m)
{
return !m->prompt && !menu_interrupted(m);
}
/*
* Set *choice to point to the default item's data, if any default item was
* set, and returns 1. If no default item was set, returns -ENOENT.
*/
static inline int menu_default_choice(struct menu *m, void **choice)
{
if (m->default_item) {
*choice = m->default_item->data;
return 1;
}
return -ENOENT;
}
/*
* Displays the menu and asks the user to choose an item. *choice will point
* to the private data of the item the user chooses. The user makes a choice
* by inputting a string matching the key of an item. Invalid choices will
* cause the user to be prompted again, repeatedly, until the user makes a
* valid choice. The user can exit the menu without making a choice via ^c.
*
* Returns 1 if the user made a choice, or -EINTR if they bail via ^c.
*/
static inline int menu_interactive_choice(struct menu *m, void **choice)
{
char cbuf[CONFIG_SYS_CBSIZE];
struct menu_item *choice_item = NULL;
int readret;
while (!choice_item) {
cbuf[0] = '\0';
menu_display(m);
readret = readline_into_buffer("Enter choice: ", cbuf);
if (readret >= 0) {
choice_item = menu_item_by_key(m, cbuf);
if (!choice_item)
printf("%s not found\n", cbuf);
} else {
puts("^C\n");
return -EINTR;
}
}
*choice = choice_item->data;
return 1;
}
/*
* menu_default_set() - Sets the default choice for the menu. This is safe to
* call more than once on a menu.
*
* m - Points to a menu created by menu_create().
*
* item_key - Points to a string that, when compared using strcmp, matches the
* key for an existing item in the menu.
*
* Returns 1 if successful, -EINVAL if m is NULL, or -ENOENT if no item with a
* key matching item_key is found.
*/
int menu_default_set(struct menu *m, char *item_key)
{
struct menu_item *item;
if (!m)
return -EINVAL;
item = menu_item_by_key(m, item_key);
if (!item)
return -ENOENT;
m->default_item = item;
return 1;
}
/*
* menu_get_choice() - Returns the user's selected menu entry, or the default
* if the menu is set to not prompt or the timeout expires. This is safe to
* call more than once.
*
* m - Points to a menu created by menu_create().
*
* choice - Points to a location that will store a pointer to the selected
* menu item. If no item is selected or there is an error, no value will be
* written at the location it points to.
*
* Returns 1 if successful, -EINVAL if m or choice is NULL, -ENOENT if no
* default has been set and the menu is set to not prompt or the timeout
* expires, or -EINTR if the user exits the menu via ^c.
*/
int menu_get_choice(struct menu *m, void **choice)
{
if (!m || !choice)
return -EINVAL;
if (menu_use_default(m))
return menu_default_choice(m, choice);
return menu_interactive_choice(m, choice);
}
/*
* menu_item_add() - Adds or replaces a menu item. Note that this replaces the
* data of an item if it already exists, but doesn't change the order of the
* item.
*
* m - Points to a menu created by menu_create().
*
* item_key - Points to a string that will uniquely identify the item. The
* string will be copied to internal storage, and is safe to discard after
* passing to menu_item_add.
*
* item_data - An opaque pointer associated with an item. It is never
* dereferenced internally, but will be passed to the item_data_print, and
* will be returned from menu_get_choice if the menu item is selected.
*
* Returns 1 if successful, -EINVAL if m is NULL, or -ENOMEM if there is
* insufficient memory to add the menu item.
*/
int menu_item_add(struct menu *m, char *item_key, void *item_data)
{
struct menu_item *item;
if (!m)
return -EINVAL;
item = menu_item_by_key(m, item_key);
if (item) {
item->data = item_data;
return 1;
}
item = malloc(sizeof *item);
if (!item)
return -ENOMEM;
item->key = strdup(item_key);
if (!item->key) {
free(item);
return -ENOMEM;
}
item->data = item_data;
list_add_tail(&item->list, &m->items);
return 1;
}
/*
* menu_create() - Creates a menu handle with default settings
*
* title - If not NULL, points to a string that will be displayed before the
* list of menu items. It will be copied to internal storage, and is safe to
* discard after passing to menu_create().
*
* timeout - A delay in seconds to wait for user input. If 0, timeout is
* disabled, and the default choice will be returned unless prompt is 1.
*
* prompt - If 0, don't ask for user input unless there is an interrupted
* timeout. If 1, the user will be prompted for input regardless of the value
* of timeout.
*
* item_data_print - If not NULL, will be called for each item when the menu
* is displayed, with the pointer to the item's data passed as the argument.
* If NULL, each item's key will be printed instead. Since an item's key is
* what must be entered to select an item, the item_data_print function should
* make it obvious what the key for each entry is.
*
* Returns a pointer to the menu if successful, or NULL if there is
* insufficient memory available to create the menu.
*/
struct menu *menu_create(char *title, int timeout, int prompt,
void (*item_data_print)(void *))
{
struct menu *m;
m = malloc(sizeof *m);
if (!m)
return NULL;
m->default_item = NULL;
m->prompt = prompt;
m->timeout = timeout;
m->item_data_print = item_data_print;
if (title) {
m->title = strdup(title);
if (!m->title) {
free(m);
return NULL;
}
} else
m->title = NULL;
INIT_LIST_HEAD(&m->items);
return m;
}
/*
* menu_destroy() - frees the memory used by a menu and its items.
*
* m - Points to a menu created by menu_create().
*
* Returns 1 if successful, or -EINVAL if m is NULL.
*/
int menu_destroy(struct menu *m)
{
if (!m)
return -EINVAL;
menu_items_iter(m, menu_item_destroy, NULL);
if (m->title)
free(m->title);
free(m);
return 1;
}
|
1001-study-uboot
|
common/menu.c
|
C
|
gpl3
| 10,667
|
/*
* (C) Copyright 2003 - 2004
* Sysgo Real-Time Solutions, AG <www.elinos.com>
* Pavel Bartusek <pba@sysgo.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
*
*/
/*
* Reiserfs support
*/
#include <common.h>
#include <config.h>
#include <command.h>
#include <image.h>
#include <linux/ctype.h>
#include <asm/byteorder.h>
#include <reiserfs.h>
#include <part.h>
#ifndef CONFIG_DOS_PARTITION
#error DOS partition support must be selected
#endif
/* #define REISER_DEBUG */
#ifdef REISER_DEBUG
#define PRINTF(fmt,args...) printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif
int do_reiserls (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = "/";
int dev=0;
int part=1;
char *ep;
block_dev_desc_t *dev_desc=NULL;
int part_length;
if (argc < 3)
return cmd_usage(cmdtp);
dev = (int)simple_strtoul (argv[2], &ep, 16);
dev_desc = get_dev(argv[1],dev);
if (dev_desc == NULL) {
printf ("\n** Block device %s %d not supported\n", argv[1], dev);
return 1;
}
if (*ep) {
if (*ep != ':') {
puts ("\n** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = (int)simple_strtoul(++ep, NULL, 16);
}
if (argc == 4) {
filename = argv[3];
}
PRINTF("Using device %s %d:%d, directory: %s\n", argv[1], dev, part, filename);
if ((part_length = reiserfs_set_blk_dev(dev_desc, part)) == 0) {
printf ("** Bad partition - %s %d:%d **\n", argv[1], dev, part);
return 1;
}
if (!reiserfs_mount(part_length)) {
printf ("** Bad Reiserfs partition or disk - %s %d:%d **\n", argv[1], dev, part);
return 1;
}
if (reiserfs_ls (filename)) {
printf ("** Error reiserfs_ls() **\n");
return 1;
};
return 0;
}
U_BOOT_CMD(
reiserls, 4, 1, do_reiserls,
"list files in a directory (default /)",
"<interface> <dev[:part]> [directory]\n"
" - list files from 'dev' on 'interface' in a 'directory'"
);
/******************************************************************************
* Reiserfs boot command intepreter. Derived from diskboot
*/
int do_reiserload (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = NULL;
char *ep;
int dev, part = 0;
ulong addr = 0, part_length, filelen;
disk_partition_t info;
block_dev_desc_t *dev_desc = NULL;
char buf [12];
unsigned long count;
char *addr_str;
switch (argc) {
case 3:
addr_str = getenv("loadaddr");
if (addr_str != NULL) {
addr = simple_strtoul (addr_str, NULL, 16);
} else {
addr = CONFIG_SYS_LOAD_ADDR;
}
filename = getenv ("bootfile");
count = 0;
break;
case 4:
addr = simple_strtoul (argv[3], NULL, 16);
filename = getenv ("bootfile");
count = 0;
break;
case 5:
addr = simple_strtoul (argv[3], NULL, 16);
filename = argv[4];
count = 0;
break;
case 6:
addr = simple_strtoul (argv[3], NULL, 16);
filename = argv[4];
count = simple_strtoul (argv[5], NULL, 16);
break;
default:
return cmd_usage(cmdtp);
}
if (!filename) {
puts ("\n** No boot file defined **\n");
return 1;
}
dev = (int)simple_strtoul (argv[2], &ep, 16);
dev_desc = get_dev(argv[1],dev);
if (dev_desc==NULL) {
printf ("\n** Block device %s %d not supported\n", argv[1], dev);
return 1;
}
if (*ep) {
if (*ep != ':') {
puts ("\n** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = (int)simple_strtoul(++ep, NULL, 16);
}
PRINTF("Using device %s%d, partition %d\n", argv[1], dev, part);
if (part != 0) {
if (get_partition_info (dev_desc, part, &info)) {
printf ("** Bad partition %d **\n", part);
return 1;
}
if (strncmp((char *)info.type, BOOT_PART_TYPE, sizeof(info.type)) != 0) {
printf ("\n** Invalid partition type \"%.32s\""
" (expect \"" BOOT_PART_TYPE "\")\n",
info.type);
return 1;
}
PRINTF ("\nLoading from block device %s device %d, partition %d: "
"Name: %.32s Type: %.32s File:%s\n",
argv[1], dev, part, info.name, info.type, filename);
} else {
PRINTF ("\nLoading from block device %s device %d, File:%s\n",
argv[1], dev, filename);
}
if ((part_length = reiserfs_set_blk_dev(dev_desc, part)) == 0) {
printf ("** Bad partition - %s %d:%d **\n", argv[1], dev, part);
return 1;
}
if (!reiserfs_mount(part_length)) {
printf ("** Bad Reiserfs partition or disk - %s %d:%d **\n", argv[1], dev, part);
return 1;
}
filelen = reiserfs_open(filename);
if (filelen < 0) {
printf("** File not found %s\n", filename);
return 1;
}
if ((count < filelen) && (count != 0)) {
filelen = count;
}
if (reiserfs_read((char *)addr, filelen) != filelen) {
printf("\n** Unable to read \"%s\" from %s %d:%d **\n", filename, argv[1], dev, part);
return 1;
}
/* Loading ok, update default load address */
load_addr = addr;
printf ("\n%ld bytes read\n", filelen);
sprintf(buf, "%lX", filelen);
setenv("filesize", buf);
return filelen;
}
U_BOOT_CMD(
reiserload, 6, 0, do_reiserload,
"load binary file from a Reiser filesystem",
"<interface> <dev[:part]> [addr] [filename] [bytes]\n"
" - load binary file 'filename' from 'dev' on 'interface'\n"
" to address 'addr' from dos filesystem"
);
|
1001-study-uboot
|
common/cmd_reiser.c
|
C
|
gpl3
| 5,873
|
/*
* (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
*/
/*
* Cache support: switch on or off, get status
*/
#include <common.h>
#include <command.h>
#include <linux/compiler.h>
static int parse_argv(const char *);
void __weak flush_icache(void)
{
/* please define arch specific flush_icache */
puts("No arch specific flush_icache available!\n");
}
int do_icache ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
switch (argc) {
case 2: /* on / off */
switch (parse_argv(argv[1])) {
case 0: icache_disable();
break;
case 1: icache_enable ();
break;
case 2: flush_icache();
break;
}
/* FALL TROUGH */
case 1: /* get status */
printf ("Instruction Cache is %s\n",
icache_status() ? "ON" : "OFF");
return 0;
default:
return cmd_usage(cmdtp);
}
return 0;
}
void __weak flush_dcache(void)
{
puts("No arch specific flush_dcache available!\n");
/* please define arch specific flush_dcache */
}
int do_dcache ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
switch (argc) {
case 2: /* on / off */
switch (parse_argv(argv[1])) {
case 0: dcache_disable();
break;
case 1: dcache_enable ();
break;
case 2: flush_dcache();
break;
}
/* FALL TROUGH */
case 1: /* get status */
printf ("Data (writethrough) Cache is %s\n",
dcache_status() ? "ON" : "OFF");
return 0;
default:
return cmd_usage(cmdtp);
}
return 0;
}
static int parse_argv(const char *s)
{
if (strcmp(s, "flush") == 0) {
return (2);
} else if (strcmp(s, "on") == 0) {
return (1);
} else if (strcmp(s, "off") == 0) {
return (0);
}
return (-1);
}
U_BOOT_CMD(
icache, 2, 1, do_icache,
"enable or disable instruction cache",
"[on, off, flush]\n"
" - enable, disable, or flush instruction cache"
);
U_BOOT_CMD(
dcache, 2, 1, do_dcache,
"enable or disable data cache",
"[on, off, flush]\n"
" - enable, disable, or flush data (writethrough) cache"
);
|
1001-study-uboot
|
common/cmd_cache.c
|
C
|
gpl3
| 2,780
|
/*
* (C) Copyright 2003 Stefan Roese, stefan.roese@esd-electronics.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 <malloc.h>
#include <asm/io.h>
#include <pci.h>
#include <universe.h>
#define PCI_VENDOR PCI_VENDOR_ID_TUNDRA
#define PCI_DEVICE PCI_DEVICE_ID_TUNDRA_CA91C042
typedef struct _UNI_DEV UNI_DEV;
struct _UNI_DEV {
int bus;
pci_dev_t busdevfn;
UNIVERSE *uregs;
unsigned int pci_bs;
};
static UNI_DEV *dev;
int universe_init(void)
{
int j, result;
pci_dev_t busdevfn;
unsigned int val;
busdevfn = pci_find_device(PCI_VENDOR, PCI_DEVICE, 0);
if (busdevfn == -1) {
puts("No Tundra Universe found!\n");
return -1;
}
/* Lets turn Latency off */
pci_write_config_dword(busdevfn, 0x0c, 0);
dev = malloc(sizeof(*dev));
if (NULL == dev) {
puts("UNIVERSE: No memory!\n");
result = -1;
goto break_20;
}
memset(dev, 0, sizeof(*dev));
dev->busdevfn = busdevfn;
pci_read_config_dword(busdevfn, PCI_BASE_ADDRESS_1, &val);
if (val & 1) {
pci_read_config_dword(busdevfn, PCI_BASE_ADDRESS_0, &val);
}
val &= ~0xf;
dev->uregs = (UNIVERSE *)val;
debug ("UNIVERSE-Base : %p\n", dev->uregs);
/* check mapping */
debug (" Read via mapping, PCI_ID = %08X\n", readl(&dev->uregs->pci_id));
if (((PCI_DEVICE <<16) | PCI_VENDOR) != readl(&dev->uregs->pci_id)) {
printf ("UNIVERSE: Cannot read PCI-ID via Mapping: %08x\n",
readl(&dev->uregs->pci_id));
result = -1;
goto break_30;
}
debug ("PCI_BS = %08X\n", readl(&dev->uregs->pci_bs));
dev->pci_bs = readl(&dev->uregs->pci_bs);
/* turn off windows */
for (j=0; j <4; j ++) {
writel(0x00800000, &dev->uregs->lsi[j].ctl);
writel(0x00800000, &dev->uregs->vsi[j].ctl);
}
/*
* Write to Misc Register
* Set VME Bus Time-out
* Arbitration Mode
* DTACK Enable
*/
writel(0x15040000 | (readl(&dev->uregs->misc_ctl) & 0x00020000), &dev->uregs->misc_ctl);
if (readl(&dev->uregs->misc_ctl) & 0x00020000) {
debug ("System Controller!\n"); /* test-only */
} else {
debug ("Not System Controller!\n"); /* test-only */
}
/*
* Lets turn off interrupts
*/
writel(0x00000000,&dev->uregs->lint_en); /* Disable interrupts in the Universe first */
writel(0x0000FFFF,&dev->uregs->lint_stat); /* Clear Any Pending Interrupts */
eieio();
writel(0x0000, &dev->uregs->lint_map0); /* Map all ints to 0 */
writel(0x0000, &dev->uregs->lint_map1); /* Map all ints to 0 */
eieio();
return 0;
break_30:
free(dev);
break_20:
return result;
}
/*
* Create pci slave window (access: pci -> vme)
*/
int universe_pci_slave_window(unsigned int pciAddr, unsigned int vmeAddr, int size, int vam, int pms, int vdw)
{
int result, i;
unsigned int ctl = 0;
if (NULL == dev) {
result = -1;
goto exit_10;
}
for (i = 0; i < 4; i++) {
if (0x00800000 == readl(&dev->uregs->lsi[i].ctl))
break;
}
if (i == 4) {
printf ("universe: No Image available\n");
result = -1;
goto exit_10;
}
debug ("universe: Using image %d\n", i);
writel(pciAddr , &dev->uregs->lsi[i].bs);
writel((pciAddr + size), &dev->uregs->lsi[i].bd);
writel((vmeAddr - pciAddr), &dev->uregs->lsi[i].to);
switch (vam & VME_AM_Axx) {
case VME_AM_A16:
ctl = 0x00000000;
break;
case VME_AM_A24:
ctl = 0x00010000;
break;
case VME_AM_A32:
ctl = 0x00020000;
break;
}
switch (vam & VME_AM_Mxx) {
case VME_AM_DATA:
ctl |= 0x00000000;
break;
case VME_AM_PROG:
ctl |= 0x00008000;
break;
}
if (vam & VME_AM_SUP) {
ctl |= 0x00001000;
}
switch (vdw & VME_FLAG_Dxx) {
case VME_FLAG_D8:
ctl |= 0x00000000;
break;
case VME_FLAG_D16:
ctl |= 0x00400000;
break;
case VME_FLAG_D32:
ctl |= 0x00800000;
break;
}
switch (pms & PCI_MS_Mxx) {
case PCI_MS_MEM:
ctl |= 0x00000000;
break;
case PCI_MS_IO:
ctl |= 0x00000001;
break;
case PCI_MS_CONFIG:
ctl |= 0x00000002;
break;
}
ctl |= 0x80000000; /* enable */
writel(ctl, &dev->uregs->lsi[i].ctl);
debug ("universe: window-addr=%p\n", &dev->uregs->lsi[i].ctl);
debug ("universe: pci slave window[%d] ctl=%08x\n", i, readl(&dev->uregs->lsi[i].ctl));
debug ("universe: pci slave window[%d] bs=%08x\n", i, readl(&dev->uregs->lsi[i].bs));
debug ("universe: pci slave window[%d] bd=%08x\n", i, readl(&dev->uregs->lsi[i].bd));
debug ("universe: pci slave window[%d] to=%08x\n", i, readl(&dev->uregs->lsi[i].to));
return 0;
exit_10:
return -result;
}
/*
* Create vme slave window (access: vme -> pci)
*/
int universe_vme_slave_window(unsigned int vmeAddr, unsigned int pciAddr, int size, int vam, int pms)
{
int result, i;
unsigned int ctl = 0;
if (NULL == dev) {
result = -1;
goto exit_10;
}
for (i = 0; i < 4; i++) {
if (0x00800000 == readl(&dev->uregs->vsi[i].ctl))
break;
}
if (i == 4) {
printf ("universe: No Image available\n");
result = -1;
goto exit_10;
}
debug ("universe: Using image %d\n", i);
writel(vmeAddr , &dev->uregs->vsi[i].bs);
writel((vmeAddr + size), &dev->uregs->vsi[i].bd);
writel((pciAddr - vmeAddr), &dev->uregs->vsi[i].to);
switch (vam & VME_AM_Axx) {
case VME_AM_A16:
ctl = 0x00000000;
break;
case VME_AM_A24:
ctl = 0x00010000;
break;
case VME_AM_A32:
ctl = 0x00020000;
break;
}
switch (vam & VME_AM_Mxx) {
case VME_AM_DATA:
ctl |= 0x00000000;
break;
case VME_AM_PROG:
ctl |= 0x00800000;
break;
}
if (vam & VME_AM_SUP) {
ctl |= 0x00100000;
}
switch (pms & PCI_MS_Mxx) {
case PCI_MS_MEM:
ctl |= 0x00000000;
break;
case PCI_MS_IO:
ctl |= 0x00000001;
break;
case PCI_MS_CONFIG:
ctl |= 0x00000002;
break;
}
ctl |= 0x80f00000; /* enable */
writel(ctl, &dev->uregs->vsi[i].ctl);
debug ("universe: window-addr=%p\n", &dev->uregs->vsi[i].ctl);
debug ("universe: vme slave window[%d] ctl=%08x\n", i, readl(&dev->uregs->vsi[i].ctl));
debug ("universe: vme slave window[%d] bs=%08x\n", i, readl(&dev->uregs->vsi[i].bs));
debug ("universe: vme slave window[%d] bd=%08x\n", i, readl(&dev->uregs->vsi[i].bd));
debug ("universe: vme slave window[%d] to=%08x\n", i, readl(&dev->uregs->vsi[i].to));
return 0;
exit_10:
return -result;
}
/*
* Tundra Universe configuration
*/
int do_universe(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr1 = 0, addr2 = 0, size = 0, vam = 0, pms = 0, vdw = 0;
char cmd = 'x';
/* get parameter */
if (argc > 1)
cmd = argv[1][0];
if (argc > 2)
addr1 = simple_strtoul(argv[2], NULL, 16);
if (argc > 3)
addr2 = simple_strtoul(argv[3], NULL, 16);
if (argc > 4)
size = simple_strtoul(argv[4], NULL, 16);
if (argc > 5)
vam = simple_strtoul(argv[5], NULL, 16);
if (argc > 6)
pms = simple_strtoul(argv[6], NULL, 16);
if (argc > 7)
vdw = simple_strtoul(argv[7], NULL, 16);
switch (cmd) {
case 'i': /* init */
universe_init();
break;
case 'v': /* vme */
printf("Configuring Universe VME Slave Window (VME->PCI):\n");
printf(" vme=%08lx pci=%08lx size=%08lx vam=%02lx pms=%02lx\n",
addr1, addr2, size, vam, pms);
universe_vme_slave_window(addr1, addr2, size, vam, pms);
break;
case 'p': /* pci */
printf("Configuring Universe PCI Slave Window (PCI->VME):\n");
printf(" pci=%08lx vme=%08lx size=%08lx vam=%02lx pms=%02lx vdw=%02lx\n",
addr1, addr2, size, vam, pms, vdw);
universe_pci_slave_window(addr1, addr2, size, vam, pms, vdw);
break;
default:
printf("Universe command %s not supported!\n", argv[1]);
}
return 0;
}
U_BOOT_CMD(
universe, 8, 1, do_universe,
"initialize and configure Turndra Universe",
"init\n"
" - initialize universe\n"
"universe vme [vme_addr] [pci_addr] [size] [vam] [pms]\n"
" - create vme slave window (access: vme->pci)\n"
"universe pci [pci_addr] [vme_addr] [size] [vam] [pms] [vdw]\n"
" - create pci slave window (access: pci->vme)\n"
" [vam] = VMEbus Address-Modifier: 01 -> A16 Address Space\n"
" 02 -> A24 Address Space\n"
" 03 -> A32 Address Space\n"
" 04 -> Supervisor AM Code\n"
" 10 -> Data AM Code\n"
" 20 -> Program AM Code\n"
" [pms] = PCI Memory Space: 01 -> Memory Space\n"
" 02 -> I/O Space\n"
" 03 -> Configuration Space\n"
" [vdw] = VMEbus Maximum Datawidth: 01 -> D8 Data Width\n"
" 02 -> D16 Data Width\n"
" 03 -> D32 Data Width"
);
|
1001-study-uboot
|
common/cmd_universe.c
|
C
|
gpl3
| 9,352
|
/*
* (C) Copyright 2002
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* Diagnostics support
*/
#include <common.h>
#include <command.h>
#include <post.h>
int do_diag (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned int i;
if (argc == 1 || strcmp (argv[1], "run") != 0) {
/* List test info */
if (argc == 1) {
puts ("Available hardware tests:\n");
post_info (NULL);
puts ("Use 'diag [<test1> [<test2> ...]]'"
" to get more info.\n");
puts ("Use 'diag run [<test1> [<test2> ...]]'"
" to run tests.\n");
} else {
for (i = 1; i < argc; i++) {
if (post_info (argv[i]) != 0)
printf ("%s - no such test\n", argv[i]);
}
}
} else {
/* Run tests */
if (argc == 2) {
post_run (NULL, POST_RAM | POST_MANUAL);
} else {
for (i = 2; i < argc; i++) {
if (post_run (argv[i], POST_RAM | POST_MANUAL) != 0)
printf ("%s - unable to execute the test\n",
argv[i]);
}
}
}
return 0;
}
/***************************************************/
U_BOOT_CMD(
diag, CONFIG_SYS_MAXARGS, 0, do_diag,
"perform board diagnostics",
" - print list of available tests\n"
"diag [test1 [test2]]\n"
" - print information about specified tests\n"
"diag run - run all available tests\n"
"diag run [test1 [test2]]\n"
" - run specified tests"
);
|
1001-study-uboot
|
common/cmd_diag.c
|
C
|
gpl3
| 2,160
|
/*
* Copyright 2008 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 <config.h>
#include <command.h>
int do_interrupts(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc != 2)
return cmd_usage(cmdtp);
/* on */
if (strncmp(argv[1], "on", 2) == 0)
enable_interrupts();
else
disable_interrupts();
return 0;
}
U_BOOT_CMD(
interrupts, 5, 0, do_interrupts,
"enable or disable interrupts",
"[on, off]"
);
/* Implemented in $(CPU)/interrupts.c */
int do_irqinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
U_BOOT_CMD(
irqinfo, 1, 1, do_irqinfo,
"print information about IRQs",
""
);
|
1001-study-uboot
|
common/cmd_irq.c
|
C
|
gpl3
| 1,456
|
/*
* (C) Copyright 2007
* Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
* Based on code written by:
* Pantelis Antoniou <pantelis.antoniou@gmail.com> and
* Matthew McClintock <msm@freescale.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 <linux/ctype.h>
#include <linux/types.h>
#include <asm/global_data.h>
#include <fdt.h>
#include <libfdt.h>
#include <fdt_support.h>
#define MAX_LEVEL 32 /* how deeply nested we will go */
#define SCRATCHPAD 1024 /* bytes of scratchpad memory */
/*
* Global data (for the gd->bd)
*/
DECLARE_GLOBAL_DATA_PTR;
static int fdt_valid(void);
static int fdt_parse_prop(char *const*newval, int count, char *data, int *len);
static int fdt_print(const char *pathp, char *prop, int depth);
/*
* The working_fdt points to our working flattened device tree.
*/
struct fdt_header *working_fdt;
void set_working_fdt_addr(void *addr)
{
char buf[17];
working_fdt = addr;
sprintf(buf, "%lx", (unsigned long)addr);
setenv("fdtaddr", buf);
}
/*
* Flattened Device Tree command, see the help for parameter definitions.
*/
int do_fdt (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
if (argc < 2)
return cmd_usage(cmdtp);
/*
* Set the address of the fdt
*/
if (argv[1][0] == 'a') {
unsigned long addr;
/*
* Set the address [and length] of the fdt.
*/
if (argc == 2) {
if (!fdt_valid()) {
return 1;
}
printf("The address of the fdt is %p\n", working_fdt);
return 0;
}
addr = simple_strtoul(argv[2], NULL, 16);
set_working_fdt_addr((void *)addr);
if (!fdt_valid()) {
return 1;
}
if (argc >= 4) {
int len;
int err;
/*
* Optional new length
*/
len = simple_strtoul(argv[3], NULL, 16);
if (len < fdt_totalsize(working_fdt)) {
printf ("New length %d < existing length %d, "
"ignoring.\n",
len, fdt_totalsize(working_fdt));
} else {
/*
* Open in place with a new length.
*/
err = fdt_open_into(working_fdt, working_fdt, len);
if (err != 0) {
printf ("libfdt fdt_open_into(): %s\n",
fdt_strerror(err));
}
}
}
/*
* Move the working_fdt
*/
} else if (strncmp(argv[1], "mo", 2) == 0) {
struct fdt_header *newaddr;
int len;
int err;
if (argc < 4)
return cmd_usage(cmdtp);
/*
* Set the address and length of the fdt.
*/
working_fdt = (struct fdt_header *)simple_strtoul(argv[2], NULL, 16);
if (!fdt_valid()) {
return 1;
}
newaddr = (struct fdt_header *)simple_strtoul(argv[3],NULL,16);
/*
* If the user specifies a length, use that. Otherwise use the
* current length.
*/
if (argc <= 4) {
len = fdt_totalsize(working_fdt);
} else {
len = simple_strtoul(argv[4], NULL, 16);
if (len < fdt_totalsize(working_fdt)) {
printf ("New length 0x%X < existing length "
"0x%X, aborting.\n",
len, fdt_totalsize(working_fdt));
return 1;
}
}
/*
* Copy to the new location.
*/
err = fdt_open_into(working_fdt, newaddr, len);
if (err != 0) {
printf ("libfdt fdt_open_into(): %s\n",
fdt_strerror(err));
return 1;
}
working_fdt = newaddr;
/*
* Make a new node
*/
} else if (strncmp(argv[1], "mk", 2) == 0) {
char *pathp; /* path */
char *nodep; /* new node to add */
int nodeoffset; /* node offset from libfdt */
int err;
/*
* Parameters: Node path, new node to be appended to the path.
*/
if (argc < 4)
return cmd_usage(cmdtp);
pathp = argv[2];
nodep = argv[3];
nodeoffset = fdt_path_offset (working_fdt, pathp);
if (nodeoffset < 0) {
/*
* Not found or something else bad happened.
*/
printf ("libfdt fdt_path_offset() returned %s\n",
fdt_strerror(nodeoffset));
return 1;
}
err = fdt_add_subnode(working_fdt, nodeoffset, nodep);
if (err < 0) {
printf ("libfdt fdt_add_subnode(): %s\n",
fdt_strerror(err));
return 1;
}
/*
* Set the value of a property in the working_fdt.
*/
} else if (argv[1][0] == 's') {
char *pathp; /* path */
char *prop; /* property */
int nodeoffset; /* node offset from libfdt */
static char data[SCRATCHPAD]; /* storage for the property */
int len; /* new length of the property */
int ret; /* return value */
/*
* Parameters: Node path, property, optional value.
*/
if (argc < 4)
return cmd_usage(cmdtp);
pathp = argv[2];
prop = argv[3];
if (argc == 4) {
len = 0;
} else {
ret = fdt_parse_prop(&argv[4], argc - 4, data, &len);
if (ret != 0)
return ret;
}
nodeoffset = fdt_path_offset (working_fdt, pathp);
if (nodeoffset < 0) {
/*
* Not found or something else bad happened.
*/
printf ("libfdt fdt_path_offset() returned %s\n",
fdt_strerror(nodeoffset));
return 1;
}
ret = fdt_setprop(working_fdt, nodeoffset, prop, data, len);
if (ret < 0) {
printf ("libfdt fdt_setprop(): %s\n", fdt_strerror(ret));
return 1;
}
/*
* Print (recursive) / List (single level)
*/
} else if ((argv[1][0] == 'p') || (argv[1][0] == 'l')) {
int depth = MAX_LEVEL; /* how deep to print */
char *pathp; /* path */
char *prop; /* property */
int ret; /* return value */
static char root[2] = "/";
/*
* list is an alias for print, but limited to 1 level
*/
if (argv[1][0] == 'l') {
depth = 1;
}
/*
* Get the starting path. The root node is an oddball,
* the offset is zero and has no name.
*/
if (argc == 2)
pathp = root;
else
pathp = argv[2];
if (argc > 3)
prop = argv[3];
else
prop = NULL;
ret = fdt_print(pathp, prop, depth);
if (ret != 0)
return ret;
/*
* Remove a property/node
*/
} else if (strncmp(argv[1], "rm", 2) == 0) {
int nodeoffset; /* node offset from libfdt */
int err;
/*
* Get the path. The root node is an oddball, the offset
* is zero and has no name.
*/
nodeoffset = fdt_path_offset (working_fdt, argv[2]);
if (nodeoffset < 0) {
/*
* Not found or something else bad happened.
*/
printf ("libfdt fdt_path_offset() returned %s\n",
fdt_strerror(nodeoffset));
return 1;
}
/*
* Do the delete. A fourth parameter means delete a property,
* otherwise delete the node.
*/
if (argc > 3) {
err = fdt_delprop(working_fdt, nodeoffset, argv[3]);
if (err < 0) {
printf("libfdt fdt_delprop(): %s\n",
fdt_strerror(err));
return err;
}
} else {
err = fdt_del_node(working_fdt, nodeoffset);
if (err < 0) {
printf("libfdt fdt_del_node(): %s\n",
fdt_strerror(err));
return err;
}
}
/*
* Display header info
*/
} else if (argv[1][0] == 'h') {
u32 version = fdt_version(working_fdt);
printf("magic:\t\t\t0x%x\n", fdt_magic(working_fdt));
printf("totalsize:\t\t0x%x (%d)\n", fdt_totalsize(working_fdt),
fdt_totalsize(working_fdt));
printf("off_dt_struct:\t\t0x%x\n",
fdt_off_dt_struct(working_fdt));
printf("off_dt_strings:\t\t0x%x\n",
fdt_off_dt_strings(working_fdt));
printf("off_mem_rsvmap:\t\t0x%x\n",
fdt_off_mem_rsvmap(working_fdt));
printf("version:\t\t%d\n", version);
printf("last_comp_version:\t%d\n",
fdt_last_comp_version(working_fdt));
if (version >= 2)
printf("boot_cpuid_phys:\t0x%x\n",
fdt_boot_cpuid_phys(working_fdt));
if (version >= 3)
printf("size_dt_strings:\t0x%x\n",
fdt_size_dt_strings(working_fdt));
if (version >= 17)
printf("size_dt_struct:\t\t0x%x\n",
fdt_size_dt_struct(working_fdt));
printf("number mem_rsv:\t\t0x%x\n",
fdt_num_mem_rsv(working_fdt));
printf("\n");
/*
* Set boot cpu id
*/
} else if (strncmp(argv[1], "boo", 3) == 0) {
unsigned long tmp = simple_strtoul(argv[2], NULL, 16);
fdt_set_boot_cpuid_phys(working_fdt, tmp);
/*
* memory command
*/
} else if (strncmp(argv[1], "me", 2) == 0) {
uint64_t addr, size;
int err;
addr = simple_strtoull(argv[2], NULL, 16);
size = simple_strtoull(argv[3], NULL, 16);
err = fdt_fixup_memory(working_fdt, addr, size);
if (err < 0)
return err;
/*
* mem reserve commands
*/
} else if (strncmp(argv[1], "rs", 2) == 0) {
if (argv[2][0] == 'p') {
uint64_t addr, size;
int total = fdt_num_mem_rsv(working_fdt);
int j, err;
printf("index\t\t start\t\t size\n");
printf("-------------------------------"
"-----------------\n");
for (j = 0; j < total; j++) {
err = fdt_get_mem_rsv(working_fdt, j, &addr, &size);
if (err < 0) {
printf("libfdt fdt_get_mem_rsv(): %s\n",
fdt_strerror(err));
return err;
}
printf(" %x\t%08x%08x\t%08x%08x\n", j,
(u32)(addr >> 32),
(u32)(addr & 0xffffffff),
(u32)(size >> 32),
(u32)(size & 0xffffffff));
}
} else if (argv[2][0] == 'a') {
uint64_t addr, size;
int err;
addr = simple_strtoull(argv[3], NULL, 16);
size = simple_strtoull(argv[4], NULL, 16);
err = fdt_add_mem_rsv(working_fdt, addr, size);
if (err < 0) {
printf("libfdt fdt_add_mem_rsv(): %s\n",
fdt_strerror(err));
return err;
}
} else if (argv[2][0] == 'd') {
unsigned long idx = simple_strtoul(argv[3], NULL, 16);
int err = fdt_del_mem_rsv(working_fdt, idx);
if (err < 0) {
printf("libfdt fdt_del_mem_rsv(): %s\n",
fdt_strerror(err));
return err;
}
} else {
/* Unrecognized command */
return cmd_usage(cmdtp);
}
}
#ifdef CONFIG_OF_BOARD_SETUP
/* Call the board-specific fixup routine */
else if (strncmp(argv[1], "boa", 3) == 0)
ft_board_setup(working_fdt, gd->bd);
#endif
/* Create a chosen node */
else if (argv[1][0] == 'c') {
unsigned long initrd_start = 0, initrd_end = 0;
if ((argc != 2) && (argc != 4))
return cmd_usage(cmdtp);
if (argc == 4) {
initrd_start = simple_strtoul(argv[2], NULL, 16);
initrd_end = simple_strtoul(argv[3], NULL, 16);
}
fdt_chosen(working_fdt, 1);
fdt_initrd(working_fdt, initrd_start, initrd_end, 1);
}
/* resize the fdt */
else if (strncmp(argv[1], "re", 2) == 0) {
fdt_resize(working_fdt);
}
else {
/* Unrecognized command */
return cmd_usage(cmdtp);
}
return 0;
}
/****************************************************************************/
static int fdt_valid(void)
{
int err;
if (working_fdt == NULL) {
printf ("The address of the fdt is invalid (NULL).\n");
return 0;
}
err = fdt_check_header(working_fdt);
if (err == 0)
return 1; /* valid */
if (err < 0) {
printf("libfdt fdt_check_header(): %s", fdt_strerror(err));
/*
* Be more informative on bad version.
*/
if (err == -FDT_ERR_BADVERSION) {
if (fdt_version(working_fdt) <
FDT_FIRST_SUPPORTED_VERSION) {
printf (" - too old, fdt %d < %d",
fdt_version(working_fdt),
FDT_FIRST_SUPPORTED_VERSION);
working_fdt = NULL;
}
if (fdt_last_comp_version(working_fdt) >
FDT_LAST_SUPPORTED_VERSION) {
printf (" - too new, fdt %d > %d",
fdt_version(working_fdt),
FDT_LAST_SUPPORTED_VERSION);
working_fdt = NULL;
}
return 0;
}
printf("\n");
return 0;
}
return 1;
}
/****************************************************************************/
/*
* Parse the user's input, partially heuristic. Valid formats:
* <0x00112233 4 05> - an array of cells. Numbers follow standard
* C conventions.
* [00 11 22 .. nn] - byte stream
* "string" - If the the value doesn't start with "<" or "[", it is
* treated as a string. Note that the quotes are
* stripped by the parser before we get the string.
* newval: An array of strings containing the new property as specified
* on the command line
* count: The number of strings in the array
* data: A bytestream to be placed in the property
* len: The length of the resulting bytestream
*/
static int fdt_parse_prop(char * const *newval, int count, char *data, int *len)
{
char *cp; /* temporary char pointer */
char *newp; /* temporary newval char pointer */
unsigned long tmp; /* holds converted values */
int stridx = 0;
*len = 0;
newp = newval[0];
/* An array of cells */
if (*newp == '<') {
newp++;
while ((*newp != '>') && (stridx < count)) {
/*
* Keep searching until we find that last ">"
* That way users don't have to escape the spaces
*/
if (*newp == '\0') {
newp = newval[++stridx];
continue;
}
cp = newp;
tmp = simple_strtoul(cp, &newp, 0);
*(uint32_t *)data = __cpu_to_be32(tmp);
data += 4;
*len += 4;
/* If the ptr didn't advance, something went wrong */
if ((newp - cp) <= 0) {
printf("Sorry, I could not convert \"%s\"\n",
cp);
return 1;
}
while (*newp == ' ')
newp++;
}
if (*newp != '>') {
printf("Unexpected character '%c'\n", *newp);
return 1;
}
} else if (*newp == '[') {
/*
* Byte stream. Convert the values.
*/
newp++;
while ((stridx < count) && (*newp != ']')) {
while (*newp == ' ')
newp++;
if (*newp == '\0') {
newp = newval[++stridx];
continue;
}
if (!isxdigit(*newp))
break;
tmp = simple_strtoul(newp, &newp, 16);
*data++ = tmp & 0xFF;
*len = *len + 1;
}
if (*newp != ']') {
printf("Unexpected character '%c'\n", *newp);
return 1;
}
} else {
/*
* Assume it is one or more strings. Copy it into our
* data area for convenience (including the
* terminating '\0's).
*/
while (stridx < count) {
size_t length = strlen(newp) + 1;
strcpy(data, newp);
data += length;
*len += length;
newp = newval[++stridx];
}
}
return 0;
}
/****************************************************************************/
/*
* Heuristic to guess if this is a string or concatenated strings.
*/
static int is_printable_string(const void *data, int len)
{
const char *s = data;
/* zero length is not */
if (len == 0)
return 0;
/* must terminate with zero */
if (s[len - 1] != '\0')
return 0;
/* printable or a null byte (concatenated strings) */
while (((*s == '\0') || isprint(*s)) && (len > 0)) {
/*
* If we see a null, there are three possibilities:
* 1) If len == 1, it is the end of the string, printable
* 2) Next character also a null, not printable.
* 3) Next character not a null, continue to check.
*/
if (s[0] == '\0') {
if (len == 1)
return 1;
if (s[1] == '\0')
return 0;
}
s++;
len--;
}
/* Not the null termination, or not done yet: not printable */
if (*s != '\0' || (len != 0))
return 0;
return 1;
}
/*
* Print the property in the best format, a heuristic guess. Print as
* a string, concatenated strings, a byte, word, double word, or (if all
* else fails) it is printed as a stream of bytes.
*/
static void print_data(const void *data, int len)
{
int j;
/* no data, don't print */
if (len == 0)
return;
/*
* It is a string, but it may have multiple strings (embedded '\0's).
*/
if (is_printable_string(data, len)) {
puts("\"");
j = 0;
while (j < len) {
if (j > 0)
puts("\", \"");
puts(data);
j += strlen(data) + 1;
data += strlen(data) + 1;
}
puts("\"");
return;
}
if ((len %4) == 0) {
const u32 *p;
printf("<");
for (j = 0, p = data; j < len/4; j ++)
printf("0x%x%s", fdt32_to_cpu(p[j]), j < (len/4 - 1) ? " " : "");
printf(">");
} else { /* anything else... hexdump */
const u8 *s;
printf("[");
for (j = 0, s = data; j < len; j++)
printf("%02x%s", s[j], j < len - 1 ? " " : "");
printf("]");
}
}
/****************************************************************************/
/*
* Recursively print (a portion of) the working_fdt. The depth parameter
* determines how deeply nested the fdt is printed.
*/
static int fdt_print(const char *pathp, char *prop, int depth)
{
static char tabs[MAX_LEVEL+1] =
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
const void *nodep; /* property node pointer */
int nodeoffset; /* node offset from libfdt */
int nextoffset; /* next node offset from libfdt */
uint32_t tag; /* tag */
int len; /* length of the property */
int level = 0; /* keep track of nesting level */
const struct fdt_property *fdt_prop;
nodeoffset = fdt_path_offset (working_fdt, pathp);
if (nodeoffset < 0) {
/*
* Not found or something else bad happened.
*/
printf ("libfdt fdt_path_offset() returned %s\n",
fdt_strerror(nodeoffset));
return 1;
}
/*
* The user passed in a property as well as node path.
* Print only the given property and then return.
*/
if (prop) {
nodep = fdt_getprop (working_fdt, nodeoffset, prop, &len);
if (len == 0) {
/* no property value */
printf("%s %s\n", pathp, prop);
return 0;
} else if (len > 0) {
printf("%s = ", prop);
print_data (nodep, len);
printf("\n");
return 0;
} else {
printf ("libfdt fdt_getprop(): %s\n",
fdt_strerror(len));
return 1;
}
}
/*
* The user passed in a node path and no property,
* print the node and all subnodes.
*/
while(level >= 0) {
tag = fdt_next_tag(working_fdt, nodeoffset, &nextoffset);
switch(tag) {
case FDT_BEGIN_NODE:
pathp = fdt_get_name(working_fdt, nodeoffset, NULL);
if (level <= depth) {
if (pathp == NULL)
pathp = "/* NULL pointer error */";
if (*pathp == '\0')
pathp = "/"; /* root is nameless */
printf("%s%s {\n",
&tabs[MAX_LEVEL - level], pathp);
}
level++;
if (level >= MAX_LEVEL) {
printf("Nested too deep, aborting.\n");
return 1;
}
break;
case FDT_END_NODE:
level--;
if (level <= depth)
printf("%s};\n", &tabs[MAX_LEVEL - level]);
if (level == 0) {
level = -1; /* exit the loop */
}
break;
case FDT_PROP:
fdt_prop = fdt_offset_ptr(working_fdt, nodeoffset,
sizeof(*fdt_prop));
pathp = fdt_string(working_fdt,
fdt32_to_cpu(fdt_prop->nameoff));
len = fdt32_to_cpu(fdt_prop->len);
nodep = fdt_prop->data;
if (len < 0) {
printf ("libfdt fdt_getprop(): %s\n",
fdt_strerror(len));
return 1;
} else if (len == 0) {
/* the property has no value */
if (level <= depth)
printf("%s%s;\n",
&tabs[MAX_LEVEL - level],
pathp);
} else {
if (level <= depth) {
printf("%s%s = ",
&tabs[MAX_LEVEL - level],
pathp);
print_data (nodep, len);
printf(";\n");
}
}
break;
case FDT_NOP:
printf("%s/* NOP */\n", &tabs[MAX_LEVEL - level]);
break;
case FDT_END:
return 1;
default:
if (level <= depth)
printf("Unknown tag 0x%08X\n", tag);
return 1;
}
nodeoffset = nextoffset;
}
return 0;
}
/********************************************************************/
U_BOOT_CMD(
fdt, 255, 0, do_fdt,
"flattened device tree utility commands",
"addr <addr> [<length>] - Set the fdt location to <addr>\n"
#ifdef CONFIG_OF_BOARD_SETUP
"fdt boardsetup - Do board-specific set up\n"
#endif
"fdt move <fdt> <newaddr> <length> - Copy the fdt to <addr> and make it active\n"
"fdt resize - Resize fdt to size + padding to 4k addr\n"
"fdt print <path> [<prop>] - Recursive print starting at <path>\n"
"fdt list <path> [<prop>] - Print one level starting at <path>\n"
"fdt set <path> <prop> [<val>] - Set <property> [to <val>]\n"
"fdt mknode <path> <node> - Create a new node after <path>\n"
"fdt rm <path> [<prop>] - Delete the node or <property>\n"
"fdt header - Display header info\n"
"fdt bootcpu <id> - Set boot cpuid\n"
"fdt memory <addr> <size> - Add/Update memory node\n"
"fdt rsvmem print - Show current mem reserves\n"
"fdt rsvmem add <addr> <size> - Add a mem reserve\n"
"fdt rsvmem delete <index> - Delete a mem reserves\n"
"fdt chosen [<start> <end>] - Add/update the /chosen branch in the tree\n"
" <start>/<end> - initrd start/end addr\n"
"NOTE: Dereference aliases by omiting the leading '/', "
"e.g. fdt print ethernet0."
);
|
1001-study-uboot
|
common/cmd_fdt.c
|
C
|
gpl3
| 20,845
|
/*
* Copyright (C) 2000-2005, DENX Software Engineering
* Wolfgang Denk <wd@denx.de>
* Copyright (C) Procsys. All rights reserved.
* Mushtaq Khan <mushtaq_k@procsys.com>
* <mushtaqk_921@yahoo.co.in>
* Copyright (C) 2008 Freescale Semiconductor, Inc.
* Dave Liu <daveliu@freescale.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <part.h>
#include <sata.h>
int sata_curr_device = -1;
block_dev_desc_t sata_dev_desc[CONFIG_SYS_SATA_MAX_DEVICE];
int __sata_initialize(void)
{
int rc;
int i;
for (i = 0; i < CONFIG_SYS_SATA_MAX_DEVICE; i++) {
memset(&sata_dev_desc[i], 0, sizeof(struct block_dev_desc));
sata_dev_desc[i].if_type = IF_TYPE_SATA;
sata_dev_desc[i].dev = i;
sata_dev_desc[i].part_type = PART_TYPE_UNKNOWN;
sata_dev_desc[i].type = DEV_TYPE_HARDDISK;
sata_dev_desc[i].lba = 0;
sata_dev_desc[i].blksz = 512;
sata_dev_desc[i].block_read = sata_read;
sata_dev_desc[i].block_write = sata_write;
rc = init_sata(i);
rc = scan_sata(i);
if ((sata_dev_desc[i].lba > 0) && (sata_dev_desc[i].blksz > 0))
init_part(&sata_dev_desc[i]);
}
sata_curr_device = 0;
return rc;
}
int sata_initialize(void) __attribute__((weak,alias("__sata_initialize")));
#ifdef CONFIG_PARTITIONS
block_dev_desc_t *sata_get_dev(int dev)
{
return (dev < CONFIG_SYS_SATA_MAX_DEVICE) ? &sata_dev_desc[dev] : NULL;
}
#endif
int do_sata(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int rc = 0;
if (argc == 2 && strcmp(argv[1], "init") == 0)
return sata_initialize();
/* If the user has not yet run `sata init`, do it now */
if (sata_curr_device == -1)
if (sata_initialize())
return 1;
switch (argc) {
case 0:
case 1:
return cmd_usage(cmdtp);
case 2:
if (strncmp(argv[1],"inf", 3) == 0) {
int i;
putc('\n');
for (i = 0; i < CONFIG_SYS_SATA_MAX_DEVICE; ++i) {
if (sata_dev_desc[i].type == DEV_TYPE_UNKNOWN)
continue;
printf ("SATA device %d: ", i);
dev_print(&sata_dev_desc[i]);
}
return 0;
} else if (strncmp(argv[1],"dev", 3) == 0) {
if ((sata_curr_device < 0) || (sata_curr_device >= CONFIG_SYS_SATA_MAX_DEVICE)) {
puts("\nno SATA devices available\n");
return 1;
}
printf("\nSATA device %d: ", sata_curr_device);
dev_print(&sata_dev_desc[sata_curr_device]);
return 0;
} else if (strncmp(argv[1],"part",4) == 0) {
int dev, ok;
for (ok = 0, dev = 0; dev < CONFIG_SYS_SATA_MAX_DEVICE; ++dev) {
if (sata_dev_desc[dev].part_type != PART_TYPE_UNKNOWN) {
++ok;
if (dev)
putc ('\n');
print_part(&sata_dev_desc[dev]);
}
}
if (!ok) {
puts("\nno SATA devices available\n");
rc ++;
}
return rc;
}
return cmd_usage(cmdtp);
case 3:
if (strncmp(argv[1], "dev", 3) == 0) {
int dev = (int)simple_strtoul(argv[2], NULL, 10);
printf("\nSATA device %d: ", dev);
if (dev >= CONFIG_SYS_SATA_MAX_DEVICE) {
puts ("unknown device\n");
return 1;
}
dev_print(&sata_dev_desc[dev]);
if (sata_dev_desc[dev].type == DEV_TYPE_UNKNOWN)
return 1;
sata_curr_device = dev;
puts("... is now current device\n");
return 0;
} else if (strncmp(argv[1], "part", 4) == 0) {
int dev = (int)simple_strtoul(argv[2], NULL, 10);
if (sata_dev_desc[dev].part_type != PART_TYPE_UNKNOWN) {
print_part(&sata_dev_desc[dev]);
} else {
printf("\nSATA device %d not available\n", dev);
rc = 1;
}
return rc;
}
return cmd_usage(cmdtp);
default: /* at least 4 args */
if (strcmp(argv[1], "read") == 0) {
ulong addr = simple_strtoul(argv[2], NULL, 16);
ulong cnt = simple_strtoul(argv[4], NULL, 16);
ulong n;
lbaint_t blk = simple_strtoul(argv[3], NULL, 16);
printf("\nSATA read: device %d block # %ld, count %ld ... ",
sata_curr_device, blk, cnt);
n = sata_read(sata_curr_device, blk, cnt, (u32 *)addr);
/* flush cache after read */
flush_cache(addr, cnt * sata_dev_desc[sata_curr_device].blksz);
printf("%ld blocks read: %s\n",
n, (n==cnt) ? "OK" : "ERROR");
return (n == cnt) ? 0 : 1;
} else if (strcmp(argv[1], "write") == 0) {
ulong addr = simple_strtoul(argv[2], NULL, 16);
ulong cnt = simple_strtoul(argv[4], NULL, 16);
ulong n;
lbaint_t blk = simple_strtoul(argv[3], NULL, 16);
printf("\nSATA write: device %d block # %ld, count %ld ... ",
sata_curr_device, blk, cnt);
n = sata_write(sata_curr_device, blk, cnt, (u32 *)addr);
printf("%ld blocks written: %s\n",
n, (n == cnt) ? "OK" : "ERROR");
return (n == cnt) ? 0 : 1;
} else {
return cmd_usage(cmdtp);
}
return rc;
}
}
U_BOOT_CMD(
sata, 5, 1, do_sata,
"SATA sub system",
"sata init - init SATA sub system\n"
"sata info - show available SATA devices\n"
"sata device [dev] - show or set current device\n"
"sata part [dev] - print partition table\n"
"sata read addr blk# cnt\n"
"sata write addr blk# cnt"
);
|
1001-study-uboot
|
common/cmd_sata.c
|
C
|
gpl3
| 5,594
|
/*
* cmd_otp.c - interface to Blackfin on-chip One-Time-Programmable memory
*
* Copyright (c) 2007-2008 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
/* There are 512 128-bit "pages" (0x000 through 0x1FF).
* The pages are accessable as 64-bit "halfpages" (an upper and lower half).
* The pages are not part of the memory map. There is an OTP controller which
* handles scanning in/out of bits. While access is done through OTP MMRs,
* the bootrom provides C-callable helper functions to handle the interaction.
*/
#include <config.h>
#include <common.h>
#include <command.h>
#include <asm/blackfin.h>
#include <asm/mach-common/bits/otp.h>
static const char *otp_strerror(uint32_t err)
{
switch (err) {
case 0: return "no error";
case OTP_WRITE_ERROR: return "OTP fuse write error";
case OTP_READ_ERROR: return "OTP fuse read error";
case OTP_ACC_VIO_ERROR: return "invalid OTP address";
case OTP_DATA_MULT_ERROR: return "multiple bad bits detected";
case OTP_ECC_MULT_ERROR: return "error in ECC bits";
case OTP_PREV_WR_ERROR: return "space already written";
case OTP_DATA_SB_WARN: return "single bad bit in half page";
case OTP_ECC_SB_WARN: return "single bad bit in ECC";
default: return "unknown error";
}
}
#define lowup(x) ((x) % 2 ? "upper" : "lower")
static int check_voltage(void)
{
/* Make sure voltage limits are within datasheet spec */
uint16_t vr_ctl = bfin_read_VR_CTL();
#ifdef __ADSPBF54x__
/* 0.9V <= VDDINT <= 1.1V */
if ((vr_ctl & 0xc) && (vr_ctl & 0xc0) == 0xc0)
return 1;
#else
/* for the parts w/out qualification yet */
(void)vr_ctl;
#endif
return 0;
}
static void set_otp_timing(bool write)
{
static uint32_t timing;
if (!timing) {
uint32_t tp1, tp2, tp3;
/* OTP_TP1 = 1000 / sclk_period (in nanoseconds)
* OTP_TP1 = 1000 / (1 / get_sclk() * 10^9)
* OTP_TP1 = (1000 * get_sclk()) / 10^9
* OTP_TP1 = get_sclk() / 10^6
*/
tp1 = get_sclk() / 1000000;
/* OTP_TP2 = 400 / (2 * sclk_period)
* OTP_TP2 = 400 / (2 * 1 / get_sclk() * 10^9)
* OTP_TP2 = (400 * get_sclk()) / (2 * 10^9)
* OTP_TP2 = (2 * get_sclk()) / 10^7
*/
tp2 = (2 * get_sclk() / 10000000) << 8;
/* OTP_TP3 = magic constant */
tp3 = (0x1401) << 15;
timing = tp1 | tp2 | tp3;
}
bfrom_OtpCommand(OTP_INIT, write ? timing : timing & ~(-1 << 15));
}
int do_otp(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *cmd;
uint32_t ret, base_flags;
bool prompt_user, force_read;
uint32_t (*otp_func)(uint32_t page, uint32_t flags, uint64_t *page_content);
if (argc < 4) {
usage:
return cmd_usage(cmdtp);
}
prompt_user = false;
base_flags = 0;
cmd = argv[1];
if (!strcmp(cmd, "read"))
otp_func = bfrom_OtpRead;
else if (!strcmp(cmd, "dump")) {
otp_func = bfrom_OtpRead;
force_read = true;
} else if (!strcmp(cmd, "write")) {
otp_func = bfrom_OtpWrite;
base_flags = OTP_CHECK_FOR_PREV_WRITE;
if (!strcmp(argv[2], "--force")) {
argv++;
--argc;
} else
prompt_user = false;
} else if (!strcmp(cmd, "lock")) {
if (argc != 4)
goto usage;
otp_func = bfrom_OtpWrite;
base_flags = OTP_LOCK;
} else
goto usage;
uint64_t *addr = (uint64_t *)simple_strtoul(argv[2], NULL, 16);
uint32_t page = simple_strtoul(argv[3], NULL, 16);
uint32_t flags;
size_t i, count;
ulong half;
if (argc > 4)
count = simple_strtoul(argv[4], NULL, 16);
else
count = 2;
if (argc > 5) {
half = simple_strtoul(argv[5], NULL, 16);
if (half != 0 && half != 1) {
puts("Error: 'half' can only be '0' or '1'\n");
goto usage;
}
} else
half = 0;
/* "otp lock" has slightly different semantics */
if (base_flags & OTP_LOCK) {
count = page;
page = (uint32_t)addr;
addr = NULL;
}
/* do to the nature of OTP, make sure users are sure */
if (prompt_user) {
printf(
"Writing one time programmable memory\n"
"Make sure your operating voltages and temperature are within spec\n"
" source address: 0x%p\n"
" OTP destination: %s page 0x%03X - %s page 0x%03lX\n"
" number to write: %lu halfpages\n"
" type \"YES\" (no quotes) to confirm: ",
addr,
lowup(half), page,
lowup(half + count - 1), page + (half + count - 1) / 2,
half + count
);
i = 0;
while (1) {
if (tstc()) {
const char exp_ans[] = "YES\r";
char c;
putc(c = getc());
if (exp_ans[i++] != c) {
printf(" Aborting\n");
return 1;
} else if (!exp_ans[i]) {
puts("\n");
break;
}
}
}
}
printf("OTP memory %s: addr 0x%p page 0x%03X count %zu ... ",
cmd, addr, page, count);
set_otp_timing(otp_func == bfrom_OtpWrite);
if (otp_func == bfrom_OtpWrite && check_voltage()) {
puts("ERROR: VDDINT voltage is out of spec for writing\n");
return -1;
}
/* Do the actual reading/writing stuff */
ret = 0;
for (i = half; i < count + half; ++i) {
flags = base_flags | (i % 2 ? OTP_UPPER_HALF : OTP_LOWER_HALF);
try_again:
ret = otp_func(page, flags, addr);
if (ret & OTP_MASTER_ERROR) {
if (force_read) {
if (flags & OTP_NO_ECC)
break;
else
flags |= OTP_NO_ECC;
puts("E");
goto try_again;
} else
break;
} else if (ret)
puts("W");
else
puts(".");
if (!(base_flags & OTP_LOCK)) {
++addr;
if (i % 2)
++page;
} else
++page;
}
if (ret & 0x1)
printf("\nERROR at page 0x%03X (%s-halfpage): 0x%03X: %s\n",
page, lowup(i), ret, otp_strerror(ret));
else
puts(" done\n");
/* Make sure we disable writing */
set_otp_timing(false);
bfrom_OtpCommand(OTP_CLOSE, 0);
return ret;
}
U_BOOT_CMD(
otp, 7, 0, do_otp,
"One-Time-Programmable sub-system",
"read <addr> <page> [count] [half]\n"
" - read 'count' half-pages starting at 'page' (offset 'half') to 'addr'\n"
"otp dump <addr> <page> [count] [half]\n"
" - like 'otp read', but skip read errors\n"
"otp write [--force] <addr> <page> [count] [half]\n"
" - write 'count' half-pages starting at 'page' (offset 'half') from 'addr'\n"
"otp lock <page> <count>\n"
" - lock 'count' pages starting at 'page'"
);
|
1001-study-uboot
|
common/cmd_otp.c
|
C
|
gpl3
| 6,082
|
/*
* (C) Copyright 2008
* Gary Jennejohn, DENX Software Engineering GmbH, garyj@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 <malloc.h>
#ifdef CONFIG_CONSOLE_MUX
void iomux_printdevs(const int console)
{
int i;
struct stdio_dev *dev;
for (i = 0; i < cd_count[console]; i++) {
dev = console_devices[console][i];
printf("%s ", dev->name);
}
printf("\n");
}
/* This tries to preserve the old list if an error occurs. */
int iomux_doenv(const int console, const char *arg)
{
char *console_args, *temp, **start;
int i, j, k, io_flag, cs_idx, repeat;
struct stdio_dev *dev;
struct stdio_dev **cons_set;
console_args = strdup(arg);
if (console_args == NULL)
return 1;
/*
* Check whether a comma separated list of devices was
* entered and count how many devices were entered.
* The array start[] has pointers to the beginning of
* each device name (up to MAX_CONSARGS devices).
*
* Have to do this twice - once to count the number of
* commas and then again to populate start.
*/
i = 0;
temp = console_args;
for (;;) {
temp = strchr(temp, ',');
if (temp != NULL) {
i++;
temp++;
continue;
}
/* There's always one entry more than the number of commas. */
i++;
break;
}
start = (char **)malloc(i * sizeof(char *));
if (start == NULL) {
free(console_args);
return 1;
}
i = 0;
start[0] = console_args;
for (;;) {
temp = strchr(start[i++], ',');
if (temp == NULL)
break;
*temp = '\0';
start[i] = temp + 1;
}
cons_set = (struct stdio_dev **)calloc(i, sizeof(struct stdio_dev *));
if (cons_set == NULL) {
free(start);
free(console_args);
return 1;
}
switch (console) {
case stdin:
io_flag = DEV_FLAGS_INPUT;
break;
case stdout:
case stderr:
io_flag = DEV_FLAGS_OUTPUT;
break;
default:
free(start);
free(console_args);
free(cons_set);
return 1;
}
cs_idx = 0;
for (j = 0; j < i; j++) {
/*
* Check whether the device exists and is valid.
* console_assign() also calls search_device(),
* but I need the pointer to the device.
*/
dev = search_device(io_flag, start[j]);
if (dev == NULL)
continue;
/*
* Prevent multiple entries for a device.
*/
repeat = 0;
for (k = 0; k < cs_idx; k++) {
if (dev == cons_set[k]) {
repeat++;
break;
}
}
if (repeat)
continue;
/*
* Try assigning the specified device.
* This could screw up the console settings for apps.
*/
if (console_assign(console, start[j]) < 0)
continue;
#ifdef CONFIG_SERIAL_MULTI
/*
* This was taken from common/cmd_nvedit.c.
* This will never work because serial_assign() returns
* 1 upon error, not -1.
* This would almost always return an error anyway because
* serial_assign() expects the name of a serial device, like
* serial_smc, but the user generally only wants to set serial.
*/
if (serial_assign(start[j]) < 0)
continue;
#endif
cons_set[cs_idx++] = dev;
}
free(console_args);
free(start);
/* failed to set any console */
if (cs_idx == 0) {
free(cons_set);
return 1;
} else {
/* Works even if console_devices[console] is NULL. */
console_devices[console] =
(struct stdio_dev **)realloc(console_devices[console],
cs_idx * sizeof(struct stdio_dev *));
if (console_devices[console] == NULL) {
free(cons_set);
return 1;
}
memcpy(console_devices[console], cons_set, cs_idx *
sizeof(struct stdio_dev *));
cd_count[console] = cs_idx;
}
free(cons_set);
return 0;
}
#endif /* CONFIG_CONSOLE_MUX */
|
1001-study-uboot
|
common/iomux.c
|
C
|
gpl3
| 4,312
|
/* $Id$ */
#include <common.h>
#include <linux/ctype.h>
#include <bedbug/bedbug.h>
#include <bedbug/ppc.h>
#include <bedbug/regs.h>
#include <bedbug/tables.h>
#define Elf32_Word unsigned long
/* USE_SOURCE_CODE enables some symbolic debugging functions of this
code. This is only useful if the program will have access to the
source code for the binary being examined.
*/
/* #define USE_SOURCE_CODE 1 */
#ifdef USE_SOURCE_CODE
extern int line_info_from_addr __P ((Elf32_Word, char *, char *, int *));
extern struct symreflist *symByAddr;
extern char *symbol_name_from_addr __P ((Elf32_Word, int, int *));
#endif /* USE_SOURCE_CODE */
int print_operands __P ((struct ppc_ctx *));
int get_operand_value __P ((struct opcode *, unsigned long,
enum OP_FIELD, unsigned long *));
struct opcode *find_opcode __P ((unsigned long));
struct opcode *find_opcode_by_name __P ((char *));
char *spr_name __P ((int));
int spr_value __P ((char *));
char *tbr_name __P ((int));
int tbr_value __P ((char *));
int parse_operand __P ((unsigned long, struct opcode *,
struct operand *, char *, int *));
int get_word __P ((char **, char *));
long read_number __P ((char *));
int downstring __P ((char *));
/*======================================================================
* Entry point for the PPC disassembler.
*
* Arguments:
* memaddr The address to start disassembling from.
*
* virtual If this value is non-zero, then this will be
* used as the base address for the output and
* symbol lookups. If this value is zero then
* memaddr is used as the absolute address.
*
* num_instr The number of instructions to disassemble. Since
* each instruction is 32 bits long, this can be
* computed if you know the total size of the region.
*
* pfunc The address of a function that is called to print
* each line of output. The function should take a
* single character pointer as its parameters a la puts.
*
* flags Sets options for the output. This is a
* bitwise-inclusive-OR of the following
* values. Note that only one of the radix
* options may be set.
*
* F_RADOCTAL - output radix is unsigned base 8.
* F_RADUDECIMAL - output radix is unsigned base 10.
* F_RADSDECIMAL - output radix is signed base 10.
* F_RADHEX - output radix is unsigned base 16.
* F_SIMPLE - use simplified mnemonics.
* F_SYMBOL - lookup symbols for addresses.
* F_INSTR - output raw instruction.
* F_LINENO - show line # info if available.
*
* Returns TRUE if the area was successfully disassembled or FALSE if
* a problem was encountered with accessing the memory.
*/
int disppc (unsigned char *memaddr, unsigned char *virtual, int num_instr,
int (*pfunc) (const char *), unsigned long flags)
{
int i;
struct ppc_ctx ctx;
#ifdef USE_SOURCE_CODE
int line_no = 0;
int last_line_no = 0;
char funcname[128] = { 0 };
char filename[256] = { 0 };
char last_funcname[128] = { 0 };
int symoffset;
char *symname;
char *cursym = (char *) 0;
#endif /* USE_SOURCE_CODE */
/*------------------------------------------------------------*/
ctx.flags = flags;
ctx.virtual = virtual;
/* Figure out the output radix before we go any further */
if (ctx.flags & F_RADOCTAL) {
/* Unsigned octal output */
strcpy (ctx.radix_fmt, "O%o");
} else if (ctx.flags & F_RADUDECIMAL) {
/* Unsigned decimal output */
strcpy (ctx.radix_fmt, "%u");
} else if (ctx.flags & F_RADSDECIMAL) {
/* Signed decimal output */
strcpy (ctx.radix_fmt, "%d");
} else {
/* Unsigned hex output */
strcpy (ctx.radix_fmt, "0x%x");
}
if (ctx.virtual == 0) {
ctx.virtual = memaddr;
}
#ifdef USE_SOURCE_CODE
if (ctx.flags & F_SYMBOL) {
if (symByAddr == 0) /* no symbols loaded */
ctx.flags &= ~F_SYMBOL;
else {
cursym = (char *) 0;
symoffset = 0;
}
}
#endif /* USE_SOURCE_CODE */
/* format each line as "XXXXXXXX: <symbol> IIIIIIII disassembly" where,
XXXXXXXX is the memory address in hex,
<symbol> is the symbolic location if F_SYMBOL is set.
IIIIIIII is the raw machine code in hex if F_INSTR is set,
and disassembly is the disassembled machine code with numbers
formatted according to the 'radix' parameter */
for (i = 0; i < num_instr; ++i, memaddr += 4, ctx.virtual += 4) {
#ifdef USE_SOURCE_CODE
if (ctx.flags & F_LINENO) {
if ((line_info_from_addr ((Elf32_Word) ctx.virtual, filename,
funcname, &line_no) == TRUE) &&
((line_no != last_line_no) ||
(strcmp (last_funcname, funcname) != 0))) {
print_source_line (filename, funcname, line_no, pfunc);
}
last_line_no = line_no;
strcpy (last_funcname, funcname);
}
#endif /* USE_SOURCE_CODE */
sprintf (ctx.data, "%08lx: ", (unsigned long) ctx.virtual);
ctx.datalen = 10;
#ifdef USE_SOURCE_CODE
if (ctx.flags & F_SYMBOL) {
if ((symname =
symbol_name_from_addr ((Elf32_Word) ctx.virtual,
TRUE, 0)) != 0) {
cursym = symname;
symoffset = 0;
} else {
if ((cursym == 0) &&
((symname =
symbol_name_from_addr ((Elf32_Word) ctx.virtual,
FALSE, &symoffset)) != 0)) {
cursym = symname;
} else {
symoffset += 4;
}
}
if (cursym != 0) {
sprintf (&ctx.data[ctx.datalen], "<%s+", cursym);
ctx.datalen = strlen (ctx.data);
sprintf (&ctx.data[ctx.datalen], ctx.radix_fmt, symoffset);
strcat (ctx.data, ">");
ctx.datalen = strlen (ctx.data);
}
}
#endif /* USE_SOURCE_CODE */
ctx.instr = INSTRUCTION (memaddr);
if (ctx.flags & F_INSTR) {
/* Find the opcode structure for this opcode. If one is not found
then it must be an illegal instruction */
sprintf (&ctx.data[ctx.datalen],
" %02lx %02lx %02lx %02lx ",
((ctx.instr >> 24) & 0xff),
((ctx.instr >> 16) & 0xff), ((ctx.instr >> 8) & 0xff),
(ctx.instr & 0xff));
ctx.datalen += 18;
} else {
strcat (ctx.data, " ");
ctx.datalen += 3;
}
if ((ctx.op = find_opcode (ctx.instr)) == 0) {
/* Illegal Opcode */
sprintf (&ctx.data[ctx.datalen], " .long 0x%08lx",
ctx.instr);
ctx.datalen += 24;
(*pfunc) (ctx.data);
continue;
}
if (((ctx.flags & F_SIMPLE) == 0) ||
(ctx.op->hfunc == 0) || ((*ctx.op->hfunc) (&ctx) == FALSE)) {
sprintf (&ctx.data[ctx.datalen], "%-7s ", ctx.op->name);
ctx.datalen += 8;
print_operands (&ctx);
}
(*pfunc) (ctx.data);
}
return TRUE;
} /* disppc */
/*======================================================================
* Called by the disassembler to print the operands for an instruction.
*
* Arguments:
* ctx A pointer to the disassembler context record.
*
* always returns 0.
*/
int print_operands (struct ppc_ctx *ctx)
{
int open_parens = 0;
int field;
unsigned long operand;
struct operand *opr;
#ifdef USE_SOURCE_CODE
char *symname;
int offset;
#endif /* USE_SOURCE_CODE */
/*------------------------------------------------------------*/
/* Walk through the operands and list each in order */
for (field = 0; ctx->op->fields[field] != 0; ++field) {
if (ctx->op->fields[field] > n_operands) {
continue; /* bad operand ?! */
}
opr = &operands[ctx->op->fields[field] - 1];
if (opr->hint & OH_SILENT) {
continue;
}
if ((field > 0) && !open_parens) {
strcat (ctx->data, ",");
ctx->datalen++;
}
operand = (ctx->instr >> opr->shift) & ((1 << opr->bits) - 1);
if (opr->hint & OH_ADDR) {
if ((operand & (1 << (opr->bits - 1))) != 0) {
operand = operand - (1 << opr->bits);
}
if (ctx->op->hint & H_RELATIVE)
operand = (operand << 2) + (unsigned long) ctx->virtual;
else
operand = (operand << 2);
sprintf (&ctx->data[ctx->datalen], "0x%lx", operand);
ctx->datalen = strlen (ctx->data);
#ifdef USE_SOURCE_CODE
if ((ctx->flags & F_SYMBOL) &&
((symname =
symbol_name_from_addr (operand, 0, &offset)) != 0)) {
sprintf (&ctx->data[ctx->datalen], " <%s", symname);
if (offset != 0) {
strcat (ctx->data, "+");
ctx->datalen = strlen (ctx->data);
sprintf (&ctx->data[ctx->datalen], ctx->radix_fmt,
offset);
}
strcat (ctx->data, ">");
}
#endif /* USE_SOURCE_CODE */
}
else if (opr->hint & OH_REG) {
if ((operand == 0) &&
(opr->field == O_rA) && (ctx->op->hint & H_RA0_IS_0)) {
strcat (ctx->data, "0");
} else {
sprintf (&ctx->data[ctx->datalen], "r%d", (short) operand);
}
if (open_parens) {
strcat (ctx->data, ")");
open_parens--;
}
}
else if (opr->hint & OH_SPR) {
strcat (ctx->data, spr_name (operand));
}
else if (opr->hint & OH_TBR) {
strcat (ctx->data, tbr_name (operand));
}
else if (opr->hint & OH_LITERAL) {
switch (opr->field) {
case O_cr2:
strcat (ctx->data, "cr2");
ctx->datalen += 3;
break;
default:
break;
}
}
else {
sprintf (&ctx->data[ctx->datalen], ctx->radix_fmt,
(unsigned short) operand);
if (open_parens) {
strcat (ctx->data, ")");
open_parens--;
}
else if (opr->hint & OH_OFFSET) {
strcat (ctx->data, "(");
open_parens++;
}
}
ctx->datalen = strlen (ctx->data);
}
return 0;
} /* print_operands */
/*======================================================================
* Called to get the value of an arbitrary operand with in an instruction.
*
* Arguments:
* op The pointer to the opcode structure to which
* the operands belong.
*
* instr The instruction (32 bits) containing the opcode
* and the operands to print. By the time that
* this routine is called the operand has already
* been added to the output.
*
* field The field (operand) to get the value of.
*
* value The address of an unsigned long to be filled in
* with the value of the operand if it is found. This
* will only be filled in if the function returns
* TRUE. This may be passed as 0 if the value is
* not required.
*
* Returns TRUE if the operand was found or FALSE if it was not.
*/
int get_operand_value (struct opcode *op, unsigned long instr,
enum OP_FIELD field, unsigned long *value)
{
int i;
struct operand *opr;
/*------------------------------------------------------------*/
if (field > n_operands) {
return FALSE; /* bad operand ?! */
}
/* Walk through the operands and list each in order */
for (i = 0; op->fields[i] != 0; ++i) {
if (op->fields[i] != field) {
continue;
}
opr = &operands[op->fields[i] - 1];
if (value) {
*value = (instr >> opr->shift) & ((1 << opr->bits) - 1);
}
return TRUE;
}
return FALSE;
} /* operand_value */
/*======================================================================
* Called by the disassembler to match an opcode value to an opcode structure.
*
* Arguments:
* instr The instruction (32 bits) to match. This value
* may contain operand values as well as the opcode
* since they will be masked out anyway for this
* search.
*
* Returns the address of an opcode struct (from the opcode table) if the
* operand successfully matched an entry, or 0 if no match was found.
*/
struct opcode *find_opcode (unsigned long instr)
{
struct opcode *ptr;
int top = 0;
int bottom = n_opcodes - 1;
int idx;
/*------------------------------------------------------------*/
while (top <= bottom) {
idx = (top + bottom) >> 1;
ptr = &opcodes[idx];
if ((instr & ptr->mask) < ptr->opcode) {
bottom = idx - 1;
} else if ((instr & ptr->mask) > ptr->opcode) {
top = idx + 1;
} else {
return ptr;
}
}
return (struct opcode *) 0;
} /* find_opcode */
/*======================================================================
* Called by the assembler to match an opcode name to an opcode structure.
*
* Arguments:
* name The text name of the opcode, e.g. "b", "mtspr", etc.
*
* The opcodes are sorted numerically by their instruction binary code
* so a search for the name cannot use the binary search used by the
* other find routine.
*
* Returns the address of an opcode struct (from the opcode table) if the
* name successfully matched an entry, or 0 if no match was found.
*/
struct opcode *find_opcode_by_name (char *name)
{
int idx;
/*------------------------------------------------------------*/
downstring (name);
for (idx = 0; idx < n_opcodes; ++idx) {
if (!strcmp (name, opcodes[idx].name))
return &opcodes[idx];
}
return (struct opcode *) 0;
} /* find_opcode_by_name */
/*======================================================================
* Convert the 'spr' operand from its numeric value to its symbolic name.
*
* Arguments:
* value The value of the 'spr' operand. This value should
* be unmodified from its encoding in the instruction.
* the split-field computations will be performed
* here before the switch.
*
* Returns the address of a character array containing the name of the
* special purpose register defined by the 'value' parameter, or the
* address of a character array containing "???" if no match was found.
*/
char *spr_name (int value)
{
unsigned short spr;
static char other[10];
int i;
/*------------------------------------------------------------*/
/* spr is a 10 bit field whose interpretation has the high and low
five-bit fields reversed from their encoding in the operand */
spr = ((value >> 5) & 0x1f) | ((value & 0x1f) << 5);
for (i = 0; i < n_sprs; ++i) {
if (spr == spr_map[i].spr_val)
return spr_map[i].spr_name;
}
sprintf (other, "%d", spr);
return other;
} /* spr_name */
/*======================================================================
* Convert the 'spr' operand from its symbolic name to its numeric value
*
* Arguments:
* name The symbolic name of the 'spr' operand. The
* split-field encoding will be done by this routine.
* NOTE: name can be a number.
*
* Returns the numeric value for the spr appropriate for encoding a machine
* instruction. Returns 0 if unable to find the SPR.
*/
int spr_value (char *name)
{
struct spr_info *sprp;
int spr;
int i;
/*------------------------------------------------------------*/
if (!name || !*name)
return 0;
if (isdigit ((int) name[0])) {
i = htonl (read_number (name));
spr = ((i >> 5) & 0x1f) | ((i & 0x1f) << 5);
return spr;
}
downstring (name);
for (i = 0; i < n_sprs; ++i) {
sprp = &spr_map[i];
if (strcmp (name, sprp->spr_name) == 0) {
/* spr is a 10 bit field whose interpretation has the high and low
five-bit fields reversed from their encoding in the operand */
i = htonl (sprp->spr_val);
spr = ((i >> 5) & 0x1f) | ((i & 0x1f) << 5);
return spr;
}
}
return 0;
} /* spr_value */
/*======================================================================
* Convert the 'tbr' operand from its numeric value to its symbolic name.
*
* Arguments:
* value The value of the 'tbr' operand. This value should
* be unmodified from its encoding in the instruction.
* the split-field computations will be performed
* here before the switch.
*
* Returns the address of a character array containing the name of the
* time base register defined by the 'value' parameter, or the address
* of a character array containing "???" if no match was found.
*/
char *tbr_name (int value)
{
unsigned short tbr;
/*------------------------------------------------------------*/
/* tbr is a 10 bit field whose interpretation has the high and low
five-bit fields reversed from their encoding in the operand */
tbr = ((value >> 5) & 0x1f) | ((value & 0x1f) << 5);
if (tbr == 268)
return "TBL";
else if (tbr == 269)
return "TBU";
return "???";
} /* tbr_name */
/*======================================================================
* Convert the 'tbr' operand from its symbolic name to its numeric value.
*
* Arguments:
* name The symbolic name of the 'tbr' operand. The
* split-field encoding will be done by this routine.
*
* Returns the numeric value for the spr appropriate for encoding a machine
* instruction. Returns 0 if unable to find the TBR.
*/
int tbr_value (char *name)
{
int tbr;
int val;
/*------------------------------------------------------------*/
if (!name || !*name)
return 0;
downstring (name);
if (isdigit ((int) name[0])) {
val = read_number (name);
if (val != 268 && val != 269)
return 0;
} else if (strcmp (name, "tbl") == 0)
val = 268;
else if (strcmp (name, "tbu") == 0)
val = 269;
else
return 0;
/* tbr is a 10 bit field whose interpretation has the high and low
five-bit fields reversed from their encoding in the operand */
val = htonl (val);
tbr = ((val >> 5) & 0x1f) | ((val & 0x1f) << 5);
return tbr;
} /* tbr_name */
/*======================================================================
* The next several functions (handle_xxx) are the routines that handle
* disassembling the opcodes with simplified mnemonics.
*
* Arguments:
* ctx A pointer to the disassembler context record.
*
* Returns TRUE if the simpler form was printed or FALSE if it was not.
*/
int handle_bc (struct ppc_ctx *ctx)
{
unsigned long bo;
unsigned long bi;
static struct opcode blt = { B_OPCODE (16, 0, 0), B_MASK, {O_BD, 0},
0, "blt", H_RELATIVE
};
static struct opcode bne =
{ B_OPCODE (16, 0, 0), B_MASK, {O_cr2, O_BD, 0},
0, "bne", H_RELATIVE
};
static struct opcode bdnz = { B_OPCODE (16, 0, 0), B_MASK, {O_BD, 0},
0, "bdnz", H_RELATIVE
};
/*------------------------------------------------------------*/
if (get_operand_value (ctx->op, ctx->instr, O_BO, &bo) == FALSE)
return FALSE;
if (get_operand_value (ctx->op, ctx->instr, O_BI, &bi) == FALSE)
return FALSE;
if ((bo == 12) && (bi == 0)) {
ctx->op = &blt;
sprintf (&ctx->data[ctx->datalen], "%-7s ", ctx->op->name);
ctx->datalen += 8;
print_operands (ctx);
return TRUE;
} else if ((bo == 4) && (bi == 10)) {
ctx->op = =⃥
sprintf (&ctx->data[ctx->datalen], "%-7s ", ctx->op->name);
ctx->datalen += 8;
print_operands (ctx);
return TRUE;
} else if ((bo == 16) && (bi == 0)) {
ctx->op = &bdnz;
sprintf (&ctx->data[ctx->datalen], "%-7s ", ctx->op->name);
ctx->datalen += 8;
print_operands (ctx);
return TRUE;
}
return FALSE;
} /* handle_blt */
/*======================================================================
* Outputs source line information for the disassembler. This should
* be modified in the future to lookup the actual line of source code
* from the file, but for now this will do.
*
* Arguments:
* filename The address of a character array containing the
* absolute path and file name of the source file.
*
* funcname The address of a character array containing the
* name of the function (not C++ demangled (yet))
* to which this code belongs.
*
* line_no An integer specifying the source line number that
* generated this code.
*
* pfunc The address of a function to call to print the output.
*
*
* Returns TRUE if it was able to output the line info, or false if it was
* not.
*/
int print_source_line (char *filename, char *funcname,
int line_no, int (*pfunc) (const char *))
{
char out_buf[256];
/*------------------------------------------------------------*/
(*pfunc) (""); /* output a newline */
sprintf (out_buf, "%s %s(): line %d", filename, funcname, line_no);
(*pfunc) (out_buf);
return TRUE;
} /* print_source_line */
/*======================================================================
* Entry point for the PPC assembler.
*
* Arguments:
* asm_buf An array of characters containing the assembly opcode
* and operands to convert to a POWERPC machine
* instruction.
*
* Returns the machine instruction or zero.
*/
unsigned long asmppc (unsigned long memaddr, char *asm_buf, int *err)
{
struct opcode *opc;
struct operand *oper[MAX_OPERANDS];
unsigned long instr;
unsigned long param;
char *ptr = asm_buf;
char scratch[20];
int i;
int w_operands = 0; /* wanted # of operands */
int n_operands = 0; /* # of operands read */
int asm_debug = 0;
/*------------------------------------------------------------*/
if (err)
*err = 0;
if (get_word (&ptr, scratch) == 0)
return 0;
/* Lookup the opcode structure based on the opcode name */
if ((opc = find_opcode_by_name (scratch)) == (struct opcode *) 0) {
if (err)
*err = E_ASM_BAD_OPCODE;
return 0;
}
if (asm_debug) {
printf ("asmppc: Opcode = \"%s\"\n", opc->name);
}
for (i = 0; i < 8; ++i) {
if (opc->fields[i] == 0)
break;
++w_operands;
}
if (asm_debug) {
printf ("asmppc: Expecting %d operands\n", w_operands);
}
instr = opc->opcode;
/* read each operand */
while (n_operands < w_operands) {
oper[n_operands] = &operands[opc->fields[n_operands] - 1];
if (oper[n_operands]->hint & OH_SILENT) {
/* Skip silent operands, they are covered in opc->opcode */
if (asm_debug) {
printf ("asmppc: Operand %d \"%s\" SILENT\n", n_operands,
oper[n_operands]->name);
}
++n_operands;
continue;
}
if (get_word (&ptr, scratch) == 0)
break;
if (asm_debug) {
printf ("asmppc: Operand %d \"%s\" : \"%s\"\n", n_operands,
oper[n_operands]->name, scratch);
}
if ((param = parse_operand (memaddr, opc, oper[n_operands],
scratch, err)) == -1)
return 0;
instr |= param;
++n_operands;
}
if (n_operands < w_operands) {
if (err)
*err = E_ASM_NUM_OPERANDS;
return 0;
}
if (asm_debug) {
printf ("asmppc: Instruction = 0x%08lx\n", instr);
}
return instr;
} /* asmppc */
/*======================================================================
* Called by the assembler to interpret a single operand
*
* Arguments:
* ctx A pointer to the disassembler context record.
*
* Returns 0 if the operand is ok, or -1 if it is bad.
*/
int parse_operand (unsigned long memaddr, struct opcode *opc,
struct operand *oper, char *txt, int *err)
{
long data;
long mask;
int is_neg = 0;
/*------------------------------------------------------------*/
mask = (1 << oper->bits) - 1;
if (oper->hint & OH_ADDR) {
data = read_number (txt);
if (opc->hint & H_RELATIVE)
data = data - memaddr;
if (data < 0)
is_neg = 1;
data >>= 2;
data &= (mask >> 1);
if (is_neg)
data |= 1 << (oper->bits - 1);
}
else if (oper->hint & OH_REG) {
if (txt[0] == 'r' || txt[0] == 'R')
txt++;
else if (txt[0] == '%' && (txt[1] == 'r' || txt[1] == 'R'))
txt += 2;
data = read_number (txt);
if (data > 31) {
if (err)
*err = E_ASM_BAD_REGISTER;
return -1;
}
data = htonl (data);
}
else if (oper->hint & OH_SPR) {
if ((data = spr_value (txt)) == 0) {
if (err)
*err = E_ASM_BAD_SPR;
return -1;
}
}
else if (oper->hint & OH_TBR) {
if ((data = tbr_value (txt)) == 0) {
if (err)
*err = E_ASM_BAD_TBR;
return -1;
}
}
else {
data = htonl (read_number (txt));
}
return (data & mask) << oper->shift;
} /* parse_operand */
char *asm_error_str (int err)
{
switch (err) {
case E_ASM_BAD_OPCODE:
return "Bad opcode";
case E_ASM_NUM_OPERANDS:
return "Bad number of operands";
case E_ASM_BAD_REGISTER:
return "Bad register number";
case E_ASM_BAD_SPR:
return "Bad SPR name or number";
case E_ASM_BAD_TBR:
return "Bad TBR name or number";
}
return "";
} /* asm_error_str */
/*======================================================================
* Copy a word from one buffer to another, ignores leading white spaces.
*
* Arguments:
* src The address of a character pointer to the
* source buffer.
* dest A pointer to a character buffer to write the word
* into.
*
* Returns the number of non-white space characters copied, or zero.
*/
int get_word (char **src, char *dest)
{
char *ptr = *src;
int nchars = 0;
/*------------------------------------------------------------*/
/* Eat white spaces */
while (*ptr && isblank (*ptr))
ptr++;
if (*ptr == 0) {
*src = ptr;
return 0;
}
/* Find the text of the word */
while (*ptr && !isblank (*ptr) && (*ptr != ','))
dest[nchars++] = *ptr++;
ptr = (*ptr == ',') ? ptr + 1 : ptr;
dest[nchars] = 0;
*src = ptr;
return nchars;
} /* get_word */
/*======================================================================
* Convert a numeric string to a number, be aware of base notations.
*
* Arguments:
* txt The numeric string.
*
* Returns the converted numeric value.
*/
long read_number (char *txt)
{
long val;
int is_neg = 0;
/*------------------------------------------------------------*/
if (txt == 0 || *txt == 0)
return 0;
if (*txt == '-') {
is_neg = 1;
++txt;
}
if (txt[0] == '0' && (txt[1] == 'x' || txt[1] == 'X')) /* hex */
val = simple_strtoul (&txt[2], NULL, 16);
else /* decimal */
val = simple_strtoul (txt, NULL, 10);
if (is_neg)
val = -val;
return val;
} /* read_number */
int downstring (char *s)
{
if (!s || !*s)
return 0;
while (*s) {
if (isupper (*s))
*s = tolower (*s);
s++;
}
return 0;
} /* downstring */
/*======================================================================
* Examines the instruction at the current address and determines the
* next address to be executed. This will take into account branches
* of different types so that a "step" and "next" operations can be
* supported.
*
* Arguments:
* nextaddr The address (to be filled in) of the next
* instruction to execute. This will only be a valid
* address if TRUE is returned.
*
* step_over A flag indicating how to compute addresses for
* branch statements:
* TRUE = Step over the branch (next)
* FALSE = step into the branch (step)
*
* Returns TRUE if it was able to compute the address. Returns FALSE if
* it has a problem reading the current instruction or one of the registers.
*/
int find_next_address (unsigned char *nextaddr, int step_over,
struct pt_regs *regs)
{
unsigned long pc; /* SRR0 register from PPC */
unsigned long ctr; /* CTR register from PPC */
unsigned long cr; /* CR register from PPC */
unsigned long lr; /* LR register from PPC */
unsigned long instr; /* instruction at SRR0 */
unsigned long next; /* computed instruction for 'next' */
unsigned long step; /* computed instruction for 'step' */
unsigned long addr = 0; /* target address operand */
unsigned long aa = 0; /* AA operand */
unsigned long lk = 0; /* LK operand */
unsigned long bo = 0; /* BO operand */
unsigned long bi = 0; /* BI operand */
struct opcode *op = 0; /* opcode structure for 'instr' */
int ctr_ok = 0;
int cond_ok = 0;
int conditional = 0;
int branch = 0;
/*------------------------------------------------------------*/
if (nextaddr == 0 || regs == 0) {
printf ("find_next_address: bad args");
return FALSE;
}
pc = regs->nip & 0xfffffffc;
instr = INSTRUCTION (pc);
if ((op = find_opcode (instr)) == (struct opcode *) 0) {
printf ("find_next_address: can't parse opcode 0x%lx", instr);
return FALSE;
}
ctr = regs->ctr;
cr = regs->ccr;
lr = regs->link;
switch (op->opcode) {
case B_OPCODE (16, 0, 0): /* bc */
case B_OPCODE (16, 0, 1): /* bcl */
case B_OPCODE (16, 1, 0): /* bca */
case B_OPCODE (16, 1, 1): /* bcla */
if (!get_operand_value (op, instr, O_BD, &addr) ||
!get_operand_value (op, instr, O_BO, &bo) ||
!get_operand_value (op, instr, O_BI, &bi) ||
!get_operand_value (op, instr, O_AA, &aa) ||
!get_operand_value (op, instr, O_LK, &lk))
return FALSE;
if ((addr & (1 << 13)) != 0)
addr = addr - (1 << 14);
addr <<= 2;
conditional = 1;
branch = 1;
break;
case I_OPCODE (18, 0, 0): /* b */
case I_OPCODE (18, 0, 1): /* bl */
case I_OPCODE (18, 1, 0): /* ba */
case I_OPCODE (18, 1, 1): /* bla */
if (!get_operand_value (op, instr, O_LI, &addr) ||
!get_operand_value (op, instr, O_AA, &aa) ||
!get_operand_value (op, instr, O_LK, &lk))
return FALSE;
if ((addr & (1 << 23)) != 0)
addr = addr - (1 << 24);
addr <<= 2;
conditional = 0;
branch = 1;
break;
case XL_OPCODE (19, 528, 0): /* bcctr */
case XL_OPCODE (19, 528, 1): /* bcctrl */
if (!get_operand_value (op, instr, O_BO, &bo) ||
!get_operand_value (op, instr, O_BI, &bi) ||
!get_operand_value (op, instr, O_LK, &lk))
return FALSE;
addr = ctr;
aa = 1;
conditional = 1;
branch = 1;
break;
case XL_OPCODE (19, 16, 0): /* bclr */
case XL_OPCODE (19, 16, 1): /* bclrl */
if (!get_operand_value (op, instr, O_BO, &bo) ||
!get_operand_value (op, instr, O_BI, &bi) ||
!get_operand_value (op, instr, O_LK, &lk))
return FALSE;
addr = lr;
aa = 1;
conditional = 1;
branch = 1;
break;
default:
conditional = 0;
branch = 0;
break;
}
if (conditional) {
switch ((bo & 0x1e) >> 1) {
case 0: /* 0000y */
if (--ctr != 0)
ctr_ok = 1;
cond_ok = !(cr & (1 << (31 - bi)));
break;
case 1: /* 0001y */
if (--ctr == 0)
ctr_ok = 1;
cond_ok = !(cr & (1 << (31 - bi)));
break;
case 2: /* 001zy */
ctr_ok = 1;
cond_ok = !(cr & (1 << (31 - bi)));
break;
case 4: /* 0100y */
if (--ctr != 0)
ctr_ok = 1;
cond_ok = cr & (1 << (31 - bi));
break;
case 5: /* 0101y */
if (--ctr == 0)
ctr_ok = 1;
cond_ok = cr & (1 << (31 - bi));
break;
case 6: /* 011zy */
ctr_ok = 1;
cond_ok = cr & (1 << (31 - bi));
break;
case 8: /* 1z00y */
if (--ctr != 0)
ctr_ok = cond_ok = 1;
break;
case 9: /* 1z01y */
if (--ctr == 0)
ctr_ok = cond_ok = 1;
break;
case 10: /* 1z1zz */
ctr_ok = cond_ok = 1;
break;
}
}
if (branch && (!conditional || (ctr_ok && cond_ok))) {
if (aa)
step = addr;
else
step = addr + pc;
if (lk)
next = pc + 4;
else
next = step;
} else {
step = next = pc + 4;
}
if (step_over == TRUE)
*(unsigned long *) nextaddr = next;
else
*(unsigned long *) nextaddr = step;
return TRUE;
} /* find_next_address */
/*
* Copyright (c) 2000 William L. Pitts and W. Gerald Hicks
* 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/bedbug.c
|
C
|
gpl3
| 30,617
|
/*
* (C) Copyright 2002
* 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
*/
/*
* SPI Read/Write Utilities
*/
#include <common.h>
#include <command.h>
#include <spi.h>
/*-----------------------------------------------------------------------
* Definitions
*/
#ifndef MAX_SPI_BYTES
# define MAX_SPI_BYTES 32 /* Maximum number of bytes we can handle */
#endif
#ifndef CONFIG_DEFAULT_SPI_BUS
# define CONFIG_DEFAULT_SPI_BUS 0
#endif
#ifndef CONFIG_DEFAULT_SPI_MODE
# define CONFIG_DEFAULT_SPI_MODE SPI_MODE_0
#endif
/*
* Values from last command.
*/
static unsigned int bus;
static unsigned int cs;
static unsigned int mode;
static int bitlen;
static uchar dout[MAX_SPI_BYTES];
static uchar din[MAX_SPI_BYTES];
/*
* SPI read/write
*
* Syntax:
* spi {dev} {num_bits} {dout}
* {dev} is the device number for controlling chip select (see TBD)
* {num_bits} is the number of bits to send & receive (base 10)
* {dout} is a hexadecimal string of data to send
* The command prints out the hexadecimal string received via SPI.
*/
int do_spi (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
struct spi_slave *slave;
char *cp = 0;
uchar tmp;
int j;
int rcode = 0;
/*
* We use the last specified parameters, unless new ones are
* entered.
*/
if ((flag & CMD_FLAG_REPEAT) == 0)
{
if (argc >= 2) {
mode = CONFIG_DEFAULT_SPI_MODE;
bus = simple_strtoul(argv[1], &cp, 10);
if (*cp == ':') {
cs = simple_strtoul(cp+1, &cp, 10);
} else {
cs = bus;
bus = CONFIG_DEFAULT_SPI_BUS;
}
if (*cp == '.');
mode = simple_strtoul(cp+1, NULL, 10);
}
if (argc >= 3)
bitlen = simple_strtoul(argv[2], NULL, 10);
if (argc >= 4) {
cp = argv[3];
for(j = 0; *cp; j++, cp++) {
tmp = *cp - '0';
if(tmp > 9)
tmp -= ('A' - '0') - 10;
if(tmp > 15)
tmp -= ('a' - 'A');
if(tmp > 15) {
printf("Hex conversion error on %c\n", *cp);
return 1;
}
if((j % 2) == 0)
dout[j / 2] = (tmp << 4);
else
dout[j / 2] |= tmp;
}
}
}
if ((bitlen < 0) || (bitlen > (MAX_SPI_BYTES * 8))) {
printf("Invalid bitlen %d\n", bitlen);
return 1;
}
slave = spi_setup_slave(bus, cs, 1000000, mode);
if (!slave) {
printf("Invalid device %d:%d\n", bus, cs);
return 1;
}
spi_claim_bus(slave);
if(spi_xfer(slave, bitlen, dout, din,
SPI_XFER_BEGIN | SPI_XFER_END) != 0) {
printf("Error during SPI transaction\n");
rcode = 1;
} else {
for(j = 0; j < ((bitlen + 7) / 8); j++) {
printf("%02X", din[j]);
}
printf("\n");
}
spi_release_bus(slave);
spi_free_slave(slave);
return rcode;
}
/***************************************************/
U_BOOT_CMD(
sspi, 5, 1, do_spi,
"SPI utility command",
"[<bus>:]<cs>[.<mode>] <bit_len> <dout> - Send and receive bits\n"
"<bus> - Identifies the SPI bus\n"
"<cs> - Identifies the chip select\n"
"<mode> - Identifies the SPI mode to use\n"
"<bit_len> - Number of bits to send (base 10)\n"
"<dout> - Hexadecimal string that gets sent"
);
|
1001-study-uboot
|
common/cmd_spi.c
|
C
|
gpl3
| 3,858
|
/*
* (C) Copyright 2007 by OpenMoko, Inc.
* Author: Harald Welte <laforge@openmoko.org>
*
* 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>
/* COPYING is currently 15951 bytes in size */
#define LICENSE_MAX 20480
#include <command.h>
#include <malloc.h>
#include <license.h>
int do_license(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *tok, *dst = malloc(LICENSE_MAX);
unsigned long len = LICENSE_MAX;
if (!dst)
return -1;
if (gunzip(dst, LICENSE_MAX, license_gz, &len) != 0) {
printf("Error uncompressing license text\n");
free(dst);
return -1;
}
puts(dst);
free(dst);
return 0;
}
U_BOOT_CMD(
license, 1, 1, do_license,
"print GPL license text",
""
);
|
1001-study-uboot
|
common/cmd_license.c
|
C
|
gpl3
| 1,470
|
/*
* (C) Copyright 2000, 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
*
*/
/*
* Support for read and write access to EEPROM like memory devices. This
* includes regular EEPROM as well as FRAM (ferroelectic nonvolaile RAM).
* FRAM devices read and write data at bus speed. In particular, there is no
* write delay. Also, there is no limit imposed on the numer of bytes that can
* be transferred with a single read or write.
*
* Use the following configuration options to ensure no unneeded performance
* degradation (typical for EEPROM) is incured for FRAM memory:
*
* #define CONFIG_SYS_I2C_FRAM
* #undef CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS
*
*/
#include <common.h>
#include <config.h>
#include <command.h>
#include <i2c.h>
extern void eeprom_init (void);
extern int eeprom_read (unsigned dev_addr, unsigned offset,
uchar *buffer, unsigned cnt);
extern int eeprom_write (unsigned dev_addr, unsigned offset,
uchar *buffer, unsigned cnt);
#if defined(CONFIG_SYS_EEPROM_WREN)
extern int eeprom_write_enable (unsigned dev_addr, int state);
#endif
#if defined(CONFIG_SYS_EEPROM_X40430)
/* Maximum number of times to poll for acknowledge after write */
#define MAX_ACKNOWLEDGE_POLLS 10
#endif
/* ------------------------------------------------------------------------- */
#if defined(CONFIG_CMD_EEPROM)
int do_eeprom ( cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
const char *const fmt =
"\nEEPROM @0x%lX %s: addr %08lx off %04lx count %ld ... ";
#if defined(CONFIG_SYS_I2C_MULTI_EEPROMS)
if (argc == 6) {
ulong dev_addr = simple_strtoul (argv[2], NULL, 16);
ulong addr = simple_strtoul (argv[3], NULL, 16);
ulong off = simple_strtoul (argv[4], NULL, 16);
ulong cnt = simple_strtoul (argv[5], NULL, 16);
#else
if (argc == 5) {
ulong dev_addr = CONFIG_SYS_DEF_EEPROM_ADDR;
ulong addr = simple_strtoul (argv[2], NULL, 16);
ulong off = simple_strtoul (argv[3], NULL, 16);
ulong cnt = simple_strtoul (argv[4], NULL, 16);
#endif /* CONFIG_SYS_I2C_MULTI_EEPROMS */
# if !defined(CONFIG_SPI) || defined(CONFIG_ENV_EEPROM_IS_ON_I2C)
eeprom_init ();
# endif /* !CONFIG_SPI */
if (strcmp (argv[1], "read") == 0) {
int rcode;
printf (fmt, dev_addr, argv[1], addr, off, cnt);
rcode = eeprom_read (dev_addr, off, (uchar *) addr, cnt);
puts ("done\n");
return rcode;
} else if (strcmp (argv[1], "write") == 0) {
int rcode;
printf (fmt, dev_addr, argv[1], addr, off, cnt);
rcode = eeprom_write (dev_addr, off, (uchar *) addr, cnt);
puts ("done\n");
return rcode;
}
}
return cmd_usage(cmdtp);
}
#endif
/*-----------------------------------------------------------------------
*
* for CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 2 (16-bit EEPROM address) offset is
* 0x000nxxxx for EEPROM address selectors at n, offset xxxx in EEPROM.
*
* for CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 (8-bit EEPROM page address) offset is
* 0x00000nxx for EEPROM address selectors and page number at n.
*/
#if !defined(CONFIG_SPI) || defined(CONFIG_ENV_EEPROM_IS_ON_I2C)
#if !defined(CONFIG_SYS_I2C_EEPROM_ADDR_LEN) || CONFIG_SYS_I2C_EEPROM_ADDR_LEN < 1 || CONFIG_SYS_I2C_EEPROM_ADDR_LEN > 2
#error CONFIG_SYS_I2C_EEPROM_ADDR_LEN must be 1 or 2
#endif
#endif
int eeprom_read (unsigned dev_addr, unsigned offset, uchar *buffer, unsigned cnt)
{
unsigned end = offset + cnt;
unsigned blk_off;
int rcode = 0;
/* Read data until done or would cross a page boundary.
* We must write the address again when changing pages
* because the next page may be in a different device.
*/
while (offset < end) {
unsigned alen, len;
#if !defined(CONFIG_SYS_I2C_FRAM)
unsigned maxlen;
#endif
#if CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 && !defined(CONFIG_SPI_X)
uchar addr[2];
blk_off = offset & 0xFF; /* block offset */
addr[0] = offset >> 8; /* block number */
addr[1] = blk_off; /* block offset */
alen = 2;
#else
uchar addr[3];
blk_off = offset & 0xFF; /* block offset */
addr[0] = offset >> 16; /* block number */
addr[1] = offset >> 8; /* upper address octet */
addr[2] = blk_off; /* lower address octet */
alen = 3;
#endif /* CONFIG_SYS_I2C_EEPROM_ADDR_LEN, CONFIG_SPI_X */
addr[0] |= dev_addr; /* insert device address */
len = end - offset;
/*
* For a FRAM device there is no limit on the number of the
* bytes that can be ccessed with the single read or write
* operation.
*/
#if !defined(CONFIG_SYS_I2C_FRAM)
maxlen = 0x100 - blk_off;
if (maxlen > I2C_RXTX_LEN)
maxlen = I2C_RXTX_LEN;
if (len > maxlen)
len = maxlen;
#endif
#if defined(CONFIG_SPI) && !defined(CONFIG_ENV_EEPROM_IS_ON_I2C)
spi_read (addr, alen, buffer, len);
#else
if (i2c_read (addr[0], offset, alen-1, buffer, len) != 0)
rcode = 1;
#endif
buffer += len;
offset += len;
}
return rcode;
}
/*-----------------------------------------------------------------------
*
* for CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 2 (16-bit EEPROM address) offset is
* 0x000nxxxx for EEPROM address selectors at n, offset xxxx in EEPROM.
*
* for CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 (8-bit EEPROM page address) offset is
* 0x00000nxx for EEPROM address selectors and page number at n.
*/
int eeprom_write (unsigned dev_addr, unsigned offset, uchar *buffer, unsigned cnt)
{
unsigned end = offset + cnt;
unsigned blk_off;
int rcode = 0;
#if defined(CONFIG_SYS_EEPROM_X40430)
uchar contr_r_addr[2];
uchar addr_void[2];
uchar contr_reg[2];
uchar ctrl_reg_v;
int i;
#endif
#if defined(CONFIG_SYS_EEPROM_WREN)
eeprom_write_enable (dev_addr,1);
#endif
/* Write data until done or would cross a write page boundary.
* We must write the address again when changing pages
* because the address counter only increments within a page.
*/
while (offset < end) {
unsigned alen, len;
#if !defined(CONFIG_SYS_I2C_FRAM)
unsigned maxlen;
#endif
#if CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 && !defined(CONFIG_SPI_X)
uchar addr[2];
blk_off = offset & 0xFF; /* block offset */
addr[0] = offset >> 8; /* block number */
addr[1] = blk_off; /* block offset */
alen = 2;
#else
uchar addr[3];
blk_off = offset & 0xFF; /* block offset */
addr[0] = offset >> 16; /* block number */
addr[1] = offset >> 8; /* upper address octet */
addr[2] = blk_off; /* lower address octet */
alen = 3;
#endif /* CONFIG_SYS_I2C_EEPROM_ADDR_LEN, CONFIG_SPI_X */
addr[0] |= dev_addr; /* insert device address */
len = end - offset;
/*
* For a FRAM device there is no limit on the number of the
* bytes that can be accessed with the single read or write
* operation.
*/
#if !defined(CONFIG_SYS_I2C_FRAM)
#if defined(CONFIG_SYS_EEPROM_PAGE_WRITE_BITS)
#define EEPROM_PAGE_SIZE (1 << CONFIG_SYS_EEPROM_PAGE_WRITE_BITS)
#define EEPROM_PAGE_OFFSET(x) ((x) & (EEPROM_PAGE_SIZE - 1))
maxlen = EEPROM_PAGE_SIZE - EEPROM_PAGE_OFFSET(blk_off);
#else
maxlen = 0x100 - blk_off;
#endif
if (maxlen > I2C_RXTX_LEN)
maxlen = I2C_RXTX_LEN;
if (len > maxlen)
len = maxlen;
#endif
#if defined(CONFIG_SPI) && !defined(CONFIG_ENV_EEPROM_IS_ON_I2C)
spi_write (addr, alen, buffer, len);
#else
#if defined(CONFIG_SYS_EEPROM_X40430)
/* Get the value of the control register.
* Set current address (internal pointer in the x40430)
* to 0x1ff.
*/
contr_r_addr[0] = 9;
contr_r_addr[1] = 0xff;
addr_void[0] = 0;
addr_void[1] = addr[1];
#ifdef CONFIG_SYS_I2C_EEPROM_ADDR
contr_r_addr[0] |= CONFIG_SYS_I2C_EEPROM_ADDR;
addr_void[0] |= CONFIG_SYS_I2C_EEPROM_ADDR;
#endif
contr_reg[0] = 0xff;
if (i2c_read (contr_r_addr[0], contr_r_addr[1], 1, contr_reg, 1) != 0) {
rcode = 1;
}
ctrl_reg_v = contr_reg[0];
/* Are any of the eeprom blocks write protected?
*/
if (ctrl_reg_v & 0x18) {
ctrl_reg_v &= ~0x18; /* reset block protect bits */
ctrl_reg_v |= 0x02; /* set write enable latch */
ctrl_reg_v &= ~0x04; /* clear RWEL */
/* Set write enable latch.
*/
contr_reg[0] = 0x02;
if (i2c_write (contr_r_addr[0], 0xff, 1, contr_reg, 1) != 0) {
rcode = 1;
}
/* Set register write enable latch.
*/
contr_reg[0] = 0x06;
if (i2c_write (contr_r_addr[0], 0xFF, 1, contr_reg, 1) != 0) {
rcode = 1;
}
/* Modify ctrl register.
*/
contr_reg[0] = ctrl_reg_v;
if (i2c_write (contr_r_addr[0], 0xFF, 1, contr_reg, 1) != 0) {
rcode = 1;
}
/* The write (above) is an operation on NV memory.
* These can take some time (~5ms), and the device
* will not respond to further I2C messages till
* it's completed the write.
* So poll device for an I2C acknowledge.
* When we get one we know we can continue with other
* operations.
*/
contr_reg[0] = 0;
for (i = 0; i < MAX_ACKNOWLEDGE_POLLS; i++) {
if (i2c_read (addr_void[0], addr_void[1], 1, contr_reg, 1) == 0)
break; /* got ack */
#if defined(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS)
udelay(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS * 1000);
#endif
}
if (i == MAX_ACKNOWLEDGE_POLLS) {
puts ("EEPROM poll acknowledge failed\n");
rcode = 1;
}
}
/* Is the write enable latch on?.
*/
else if (!(ctrl_reg_v & 0x02)) {
/* Set write enable latch.
*/
contr_reg[0] = 0x02;
if (i2c_write (contr_r_addr[0], 0xFF, 1, contr_reg, 1) != 0) {
rcode = 1;
}
}
/* Write is enabled ... now write eeprom value.
*/
#endif
if (i2c_write (addr[0], offset, alen-1, buffer, len) != 0)
rcode = 1;
#endif
buffer += len;
offset += len;
#if defined(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS)
udelay(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS * 1000);
#endif
}
#if defined(CONFIG_SYS_EEPROM_WREN)
eeprom_write_enable (dev_addr,0);
#endif
return rcode;
}
#if !defined(CONFIG_SPI) || defined(CONFIG_ENV_EEPROM_IS_ON_I2C)
int
eeprom_probe (unsigned dev_addr, unsigned offset)
{
unsigned char chip;
/* Probe the chip address
*/
#if CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 && !defined(CONFIG_SPI_X)
chip = offset >> 8; /* block number */
#else
chip = offset >> 16; /* block number */
#endif /* CONFIG_SYS_I2C_EEPROM_ADDR_LEN, CONFIG_SPI_X */
chip |= dev_addr; /* insert device address */
return (i2c_probe (chip));
}
#endif
/*-----------------------------------------------------------------------
* Set default values
*/
#ifndef CONFIG_SYS_I2C_SPEED
#define CONFIG_SYS_I2C_SPEED 50000
#endif
void eeprom_init (void)
{
#if defined(CONFIG_SPI) && !defined(CONFIG_ENV_EEPROM_IS_ON_I2C)
spi_init_f ();
#endif
#if defined(CONFIG_HARD_I2C) || \
defined(CONFIG_SOFT_I2C)
i2c_init (CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE);
#endif
}
/*-----------------------------------------------------------------------
*/
/***************************************************/
#if defined(CONFIG_CMD_EEPROM)
#ifdef CONFIG_SYS_I2C_MULTI_EEPROMS
U_BOOT_CMD(
eeprom, 6, 1, do_eeprom,
"EEPROM sub-system",
"read devaddr addr off cnt\n"
"eeprom write devaddr addr off cnt\n"
" - read/write `cnt' bytes from `devaddr` EEPROM at offset `off'"
);
#else /* One EEPROM */
U_BOOT_CMD(
eeprom, 5, 1, do_eeprom,
"EEPROM sub-system",
"read addr off cnt\n"
"eeprom write addr off cnt\n"
" - read/write `cnt' bytes at EEPROM offset `off'"
);
#endif /* CONFIG_SYS_I2C_MULTI_EEPROMS */
#endif
|
1001-study-uboot
|
common/cmd_eeprom.c
|
C
|
gpl3
| 12,121
|
/*
* (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
*/
/*
* Boot support
*/
#include <common.h>
#include <watchdog.h>
#include <command.h>
#include <image.h>
#include <malloc.h>
#include <u-boot/zlib.h>
#include <bzlib.h>
#include <environment.h>
#include <lmb.h>
#include <linux/ctype.h>
#include <asm/byteorder.h>
#include <linux/compiler.h>
#if defined(CONFIG_CMD_USB)
#include <usb.h>
#endif
#ifdef CONFIG_SYS_HUSH_PARSER
#include <hush.h>
#endif
#if defined(CONFIG_OF_LIBFDT)
#include <fdt.h>
#include <libfdt.h>
#include <fdt_support.h>
#endif
#ifdef CONFIG_LZMA
#include <lzma/LzmaTypes.h>
#include <lzma/LzmaDec.h>
#include <lzma/LzmaTools.h>
#endif /* CONFIG_LZMA */
#ifdef CONFIG_LZO
#include <linux/lzo.h>
#endif /* CONFIG_LZO */
DECLARE_GLOBAL_DATA_PTR;
#ifndef CONFIG_SYS_BOOTM_LEN
#define CONFIG_SYS_BOOTM_LEN 0x800000 /* use 8MByte as default max gunzip size */
#endif
#ifdef CONFIG_BZIP2
extern void bz_internal_error(int);
#endif
#if defined(CONFIG_CMD_IMI)
static int image_info(unsigned long addr);
#endif
#if defined(CONFIG_CMD_IMLS)
#include <flash.h>
#include <mtd/cfi_flash.h>
extern flash_info_t flash_info[]; /* info for FLASH chips */
static int do_imls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
#endif
#ifdef CONFIG_SILENT_CONSOLE
static void fixup_silent_linux(void);
#endif
static image_header_t *image_get_kernel(ulong img_addr, int verify);
#if defined(CONFIG_FIT)
static int fit_check_kernel(const void *fit, int os_noffset, int verify);
#endif
static void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[], bootm_headers_t *images,
ulong *os_data, ulong *os_len);
/*
* Continue booting an OS image; caller already has:
* - copied image header to global variable `header'
* - checked header magic number, checksums (both header & image),
* - verified image architecture (PPC) and type (KERNEL or MULTI),
* - loaded (first part of) image to header load address,
* - disabled interrupts.
*/
typedef int boot_os_fn(int flag, int argc, char * const argv[],
bootm_headers_t *images); /* pointers to os/initrd/fdt */
#ifdef CONFIG_BOOTM_LINUX
extern boot_os_fn do_bootm_linux;
#endif
#ifdef CONFIG_BOOTM_NETBSD
static boot_os_fn do_bootm_netbsd;
#endif
#if defined(CONFIG_LYNXKDI)
static boot_os_fn do_bootm_lynxkdi;
extern void lynxkdi_boot(image_header_t *);
#endif
#ifdef CONFIG_BOOTM_RTEMS
static boot_os_fn do_bootm_rtems;
#endif
#if defined(CONFIG_BOOTM_OSE)
static boot_os_fn do_bootm_ose;
#endif
#if defined(CONFIG_CMD_ELF)
static boot_os_fn do_bootm_vxworks;
static boot_os_fn do_bootm_qnxelf;
int do_bootvx(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
int do_bootelf(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
#endif
#if defined(CONFIG_INTEGRITY)
static boot_os_fn do_bootm_integrity;
#endif
static boot_os_fn *boot_os[] = {
#ifdef CONFIG_BOOTM_LINUX
[IH_OS_LINUX] = do_bootm_linux,
#endif
#ifdef CONFIG_BOOTM_NETBSD
[IH_OS_NETBSD] = do_bootm_netbsd,
#endif
#ifdef CONFIG_LYNXKDI
[IH_OS_LYNXOS] = do_bootm_lynxkdi,
#endif
#ifdef CONFIG_BOOTM_RTEMS
[IH_OS_RTEMS] = do_bootm_rtems,
#endif
#if defined(CONFIG_BOOTM_OSE)
[IH_OS_OSE] = do_bootm_ose,
#endif
#if defined(CONFIG_CMD_ELF)
[IH_OS_VXWORKS] = do_bootm_vxworks,
[IH_OS_QNX] = do_bootm_qnxelf,
#endif
#ifdef CONFIG_INTEGRITY
[IH_OS_INTEGRITY] = do_bootm_integrity,
#endif
};
bootm_headers_t images; /* pointers to os/initrd/fdt images */
/* Allow for arch specific config before we boot */
void __arch_preboot_os(void)
{
/* please define platform specific arch_preboot_os() */
}
void arch_preboot_os(void) __attribute__((weak, alias("__arch_preboot_os")));
#define IH_INITRD_ARCH IH_ARCH_DEFAULT
static void bootm_start_lmb(void)
{
#ifdef CONFIG_LMB
ulong mem_start;
phys_size_t mem_size;
lmb_init(&images.lmb);
mem_start = getenv_bootm_low();
mem_size = getenv_bootm_size();
lmb_add(&images.lmb, (phys_addr_t)mem_start, mem_size);
arch_lmb_reserve(&images.lmb);
board_lmb_reserve(&images.lmb);
#else
# define lmb_reserve(lmb, base, size)
#endif
}
static int bootm_start(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
void *os_hdr;
int ret;
memset((void *)&images, 0, sizeof(images));
images.verify = getenv_yesno("verify");
bootm_start_lmb();
/* get kernel image header, start address and length */
os_hdr = boot_get_kernel(cmdtp, flag, argc, argv,
&images, &images.os.image_start, &images.os.image_len);
if (images.os.image_len == 0) {
puts("ERROR: can't get kernel image!\n");
return 1;
}
/* get image parameters */
switch (genimg_get_format(os_hdr)) {
case IMAGE_FORMAT_LEGACY:
images.os.type = image_get_type(os_hdr);
images.os.comp = image_get_comp(os_hdr);
images.os.os = image_get_os(os_hdr);
images.os.end = image_get_image_end(os_hdr);
images.os.load = image_get_load(os_hdr);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
if (fit_image_get_type(images.fit_hdr_os,
images.fit_noffset_os, &images.os.type)) {
puts("Can't get image type!\n");
show_boot_progress(-109);
return 1;
}
if (fit_image_get_comp(images.fit_hdr_os,
images.fit_noffset_os, &images.os.comp)) {
puts("Can't get image compression!\n");
show_boot_progress(-110);
return 1;
}
if (fit_image_get_os(images.fit_hdr_os,
images.fit_noffset_os, &images.os.os)) {
puts("Can't get image OS!\n");
show_boot_progress(-111);
return 1;
}
images.os.end = fit_get_end(images.fit_hdr_os);
if (fit_image_get_load(images.fit_hdr_os, images.fit_noffset_os,
&images.os.load)) {
puts("Can't get image load address!\n");
show_boot_progress(-112);
return 1;
}
break;
#endif
default:
puts("ERROR: unknown image format type!\n");
return 1;
}
/* find kernel entry point */
if (images.legacy_hdr_valid) {
images.ep = image_get_ep(&images.legacy_hdr_os_copy);
#if defined(CONFIG_FIT)
} else if (images.fit_uname_os) {
ret = fit_image_get_entry(images.fit_hdr_os,
images.fit_noffset_os, &images.ep);
if (ret) {
puts("Can't get entry point property!\n");
return 1;
}
#endif
} else {
puts("Could not find kernel entry point!\n");
return 1;
}
if (images.os.type == IH_TYPE_KERNEL_NOLOAD) {
images.os.load = images.os.image_start;
images.ep += images.os.load;
}
if (((images.os.type == IH_TYPE_KERNEL) ||
(images.os.type == IH_TYPE_KERNEL_NOLOAD) ||
(images.os.type == IH_TYPE_MULTI)) &&
(images.os.os == IH_OS_LINUX)) {
/* find ramdisk */
ret = boot_get_ramdisk(argc, argv, &images, IH_INITRD_ARCH,
&images.rd_start, &images.rd_end);
if (ret) {
puts("Ramdisk image is corrupt or invalid\n");
return 1;
}
#if defined(CONFIG_OF_LIBFDT)
/* find flattened device tree */
ret = boot_get_fdt(flag, argc, argv, &images,
&images.ft_addr, &images.ft_len);
if (ret) {
puts("Could not find a valid device tree\n");
return 1;
}
set_working_fdt_addr(images.ft_addr);
#endif
}
images.os.start = (ulong)os_hdr;
images.state = BOOTM_STATE_START;
return 0;
}
#define BOOTM_ERR_RESET -1
#define BOOTM_ERR_OVERLAP -2
#define BOOTM_ERR_UNIMPLEMENTED -3
static int bootm_load_os(image_info_t os, ulong *load_end, int boot_progress)
{
uint8_t comp = os.comp;
ulong load = os.load;
ulong blob_start = os.start;
ulong blob_end = os.end;
ulong image_start = os.image_start;
ulong image_len = os.image_len;
__maybe_unused uint unc_len = CONFIG_SYS_BOOTM_LEN;
int no_overlap = 0;
#if defined(CONFIG_LZMA) || defined(CONFIG_LZO)
int ret;
#endif /* defined(CONFIG_LZMA) || defined(CONFIG_LZO) */
const char *type_name = genimg_get_type_name(os.type);
switch (comp) {
case IH_COMP_NONE:
if (load == blob_start || load == image_start) {
printf(" XIP %s ... ", type_name);
no_overlap = 1;
} else {
printf(" Loading %s ... ", type_name);
memmove_wd((void *)load, (void *)image_start,
image_len, CHUNKSZ);
}
*load_end = load + image_len;
puts("OK\n");
break;
#ifdef CONFIG_GZIP
case IH_COMP_GZIP:
printf(" Uncompressing %s ... ", type_name);
if (gunzip((void *)load, unc_len,
(uchar *)image_start, &image_len) != 0) {
puts("GUNZIP: uncompress, out-of-mem or overwrite "
"error - must RESET board to recover\n");
if (boot_progress)
show_boot_progress(-6);
return BOOTM_ERR_RESET;
}
*load_end = load + image_len;
break;
#endif /* CONFIG_GZIP */
#ifdef CONFIG_BZIP2
case IH_COMP_BZIP2:
printf(" Uncompressing %s ... ", type_name);
/*
* If we've got less than 4 MB of malloc() space,
* use slower decompression algorithm which requires
* at most 2300 KB of memory.
*/
int i = BZ2_bzBuffToBuffDecompress((char *)load,
&unc_len, (char *)image_start, image_len,
CONFIG_SYS_MALLOC_LEN < (4096 * 1024), 0);
if (i != BZ_OK) {
printf("BUNZIP2: uncompress or overwrite error %d "
"- must RESET board to recover\n", i);
if (boot_progress)
show_boot_progress(-6);
return BOOTM_ERR_RESET;
}
*load_end = load + unc_len;
break;
#endif /* CONFIG_BZIP2 */
#ifdef CONFIG_LZMA
case IH_COMP_LZMA: {
SizeT lzma_len = unc_len;
printf(" Uncompressing %s ... ", type_name);
ret = lzmaBuffToBuffDecompress(
(unsigned char *)load, &lzma_len,
(unsigned char *)image_start, image_len);
unc_len = lzma_len;
if (ret != SZ_OK) {
printf("LZMA: uncompress or overwrite error %d "
"- must RESET board to recover\n", ret);
show_boot_progress(-6);
return BOOTM_ERR_RESET;
}
*load_end = load + unc_len;
break;
}
#endif /* CONFIG_LZMA */
#ifdef CONFIG_LZO
case IH_COMP_LZO:
printf(" Uncompressing %s ... ", type_name);
ret = lzop_decompress((const unsigned char *)image_start,
image_len, (unsigned char *)load,
&unc_len);
if (ret != LZO_E_OK) {
printf("LZO: uncompress or overwrite error %d "
"- must RESET board to recover\n", ret);
if (boot_progress)
show_boot_progress(-6);
return BOOTM_ERR_RESET;
}
*load_end = load + unc_len;
break;
#endif /* CONFIG_LZO */
default:
printf("Unimplemented compression type %d\n", comp);
return BOOTM_ERR_UNIMPLEMENTED;
}
flush_cache(load, (*load_end - load) * sizeof(ulong));
puts("OK\n");
debug(" kernel loaded at 0x%08lx, end = 0x%08lx\n", load, *load_end);
if (boot_progress)
show_boot_progress(7);
if (!no_overlap && (load < blob_end) && (*load_end > blob_start)) {
debug("images.os.start = 0x%lX, images.os.end = 0x%lx\n",
blob_start, blob_end);
debug("images.os.load = 0x%lx, load_end = 0x%lx\n", load,
*load_end);
return BOOTM_ERR_OVERLAP;
}
return 0;
}
static int bootm_start_standalone(ulong iflag, int argc, char * const argv[])
{
char *s;
int (*appl)(int, char * const []);
/* Don't start if "autostart" is set to "no" */
if (((s = getenv("autostart")) != NULL) && (strcmp(s, "no") == 0)) {
char buf[32];
sprintf(buf, "%lX", images.os.image_len);
setenv("filesize", buf);
return 0;
}
appl = (int (*)(int, char * const []))(ulong)ntohl(images.ep);
(*appl)(argc-1, &argv[1]);
return 0;
}
/* we overload the cmd field with our state machine info instead of a
* function pointer */
static cmd_tbl_t cmd_bootm_sub[] = {
U_BOOT_CMD_MKENT(start, 0, 1, (void *)BOOTM_STATE_START, "", ""),
U_BOOT_CMD_MKENT(loados, 0, 1, (void *)BOOTM_STATE_LOADOS, "", ""),
#ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
U_BOOT_CMD_MKENT(ramdisk, 0, 1, (void *)BOOTM_STATE_RAMDISK, "", ""),
#endif
#ifdef CONFIG_OF_LIBFDT
U_BOOT_CMD_MKENT(fdt, 0, 1, (void *)BOOTM_STATE_FDT, "", ""),
#endif
U_BOOT_CMD_MKENT(cmdline, 0, 1, (void *)BOOTM_STATE_OS_CMDLINE, "", ""),
U_BOOT_CMD_MKENT(bdt, 0, 1, (void *)BOOTM_STATE_OS_BD_T, "", ""),
U_BOOT_CMD_MKENT(prep, 0, 1, (void *)BOOTM_STATE_OS_PREP, "", ""),
U_BOOT_CMD_MKENT(go, 0, 1, (void *)BOOTM_STATE_OS_GO, "", ""),
};
int do_bootm_subcommand(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[])
{
int ret = 0;
long state;
cmd_tbl_t *c;
boot_os_fn *boot_fn;
c = find_cmd_tbl(argv[1], &cmd_bootm_sub[0], ARRAY_SIZE(cmd_bootm_sub));
if (c) {
state = (long)c->cmd;
/* treat start special since it resets the state machine */
if (state == BOOTM_STATE_START) {
argc--;
argv++;
return bootm_start(cmdtp, flag, argc, argv);
}
} else {
/* Unrecognized command */
return cmd_usage(cmdtp);
}
if (images.state >= state) {
printf("Trying to execute a command out of order\n");
return cmd_usage(cmdtp);
}
images.state |= state;
boot_fn = boot_os[images.os.os];
switch (state) {
ulong load_end;
case BOOTM_STATE_START:
/* should never occur */
break;
case BOOTM_STATE_LOADOS:
ret = bootm_load_os(images.os, &load_end, 0);
if (ret)
return ret;
lmb_reserve(&images.lmb, images.os.load,
(load_end - images.os.load));
break;
#ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
case BOOTM_STATE_RAMDISK:
{
ulong rd_len = images.rd_end - images.rd_start;
char str[17];
ret = boot_ramdisk_high(&images.lmb, images.rd_start,
rd_len, &images.initrd_start, &images.initrd_end);
if (ret)
return ret;
sprintf(str, "%lx", images.initrd_start);
setenv("initrd_start", str);
sprintf(str, "%lx", images.initrd_end);
setenv("initrd_end", str);
}
break;
#endif
#if defined(CONFIG_OF_LIBFDT)
case BOOTM_STATE_FDT:
{
boot_fdt_add_mem_rsv_regions(&images.lmb,
images.ft_addr);
ret = boot_relocate_fdt(&images.lmb,
&images.ft_addr, &images.ft_len);
break;
}
#endif
case BOOTM_STATE_OS_CMDLINE:
ret = boot_fn(BOOTM_STATE_OS_CMDLINE, argc, argv, &images);
if (ret)
printf("cmdline subcommand not supported\n");
break;
case BOOTM_STATE_OS_BD_T:
ret = boot_fn(BOOTM_STATE_OS_BD_T, argc, argv, &images);
if (ret)
printf("bdt subcommand not supported\n");
break;
case BOOTM_STATE_OS_PREP:
ret = boot_fn(BOOTM_STATE_OS_PREP, argc, argv, &images);
if (ret)
printf("prep subcommand not supported\n");
break;
case BOOTM_STATE_OS_GO:
disable_interrupts();
arch_preboot_os();
boot_fn(BOOTM_STATE_OS_GO, argc, argv, &images);
break;
}
return ret;
}
/*******************************************************************/
/* bootm - boot application image from image in memory */
/*******************************************************************/
int do_bootm(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong iflag;
ulong load_end = 0;
int ret;
boot_os_fn *boot_fn;
#ifdef CONFIG_NEEDS_MANUAL_RELOC
static int relocated = 0;
/* relocate boot function table */
if (!relocated) {
int i;
for (i = 0; i < ARRAY_SIZE(boot_os); i++)
if (boot_os[i] != NULL)
boot_os[i] += gd->reloc_off;
relocated = 1;
}
#endif
/* determine if we have a sub command */
if (argc > 1) {
char *endp;
simple_strtoul(argv[1], &endp, 16);
/* endp pointing to NULL means that argv[1] was just a
* valid number, pass it along to the normal bootm processing
*
* If endp is ':' or '#' assume a FIT identifier so pass
* along for normal processing.
*
* Right now we assume the first arg should never be '-'
*/
if ((*endp != 0) && (*endp != ':') && (*endp != '#'))
return do_bootm_subcommand(cmdtp, flag, argc, argv);
}
if (bootm_start(cmdtp, flag, argc, argv))
return 1;
/*
* We have reached the point of no return: we are going to
* overwrite all exception vector code, so we cannot easily
* recover from any failures any more...
*/
iflag = disable_interrupts();
#if defined(CONFIG_CMD_USB)
/*
* turn off USB to prevent the host controller from writing to the
* SDRAM while Linux is booting. This could happen (at least for OHCI
* controller), because the HCCA (Host Controller Communication Area)
* lies within the SDRAM and the host controller writes continously to
* this area (as busmaster!). The HccaFrameNumber is for example
* updated every 1 ms within the HCCA structure in SDRAM! For more
* details see the OpenHCI specification.
*/
usb_stop();
#endif
ret = bootm_load_os(images.os, &load_end, 1);
if (ret < 0) {
if (ret == BOOTM_ERR_RESET)
do_reset(cmdtp, flag, argc, argv);
if (ret == BOOTM_ERR_OVERLAP) {
if (images.legacy_hdr_valid) {
image_header_t *hdr;
hdr = &images.legacy_hdr_os_copy;
if (image_get_type(hdr) == IH_TYPE_MULTI)
puts("WARNING: legacy format multi "
"component image "
"overwritten\n");
} else {
puts("ERROR: new format image overwritten - "
"must RESET the board to recover\n");
show_boot_progress(-113);
do_reset(cmdtp, flag, argc, argv);
}
}
if (ret == BOOTM_ERR_UNIMPLEMENTED) {
if (iflag)
enable_interrupts();
show_boot_progress(-7);
return 1;
}
}
lmb_reserve(&images.lmb, images.os.load, (load_end - images.os.load));
if (images.os.type == IH_TYPE_STANDALONE) {
if (iflag)
enable_interrupts();
/* This may return when 'autostart' is 'no' */
bootm_start_standalone(iflag, argc, argv);
return 0;
}
show_boot_progress(8);
#ifdef CONFIG_SILENT_CONSOLE
if (images.os.os == IH_OS_LINUX)
fixup_silent_linux();
#endif
boot_fn = boot_os[images.os.os];
if (boot_fn == NULL) {
if (iflag)
enable_interrupts();
printf("ERROR: booting os '%s' (%d) is not supported\n",
genimg_get_os_name(images.os.os), images.os.os);
show_boot_progress(-8);
return 1;
}
arch_preboot_os();
boot_fn(0, argc, argv, &images);
show_boot_progress(-9);
#ifdef DEBUG
puts("\n## Control returned to monitor - resetting...\n");
#endif
do_reset(cmdtp, flag, argc, argv);
return 1;
}
int bootm_maybe_autostart(cmd_tbl_t *cmdtp, const char *cmd)
{
const char *ep = getenv("autostart");
if (ep && !strcmp(ep, "yes")) {
char *local_args[2];
local_args[0] = (char *)cmd;
local_args[1] = NULL;
printf("Automatic boot of image at addr 0x%08lX ...\n", load_addr);
return do_bootm(cmdtp, 0, 1, local_args);
}
return 0;
}
/**
* image_get_kernel - verify legacy format kernel image
* @img_addr: in RAM address of the legacy format image to be verified
* @verify: data CRC verification flag
*
* image_get_kernel() verifies legacy image integrity and returns pointer to
* legacy image header if image verification was completed successfully.
*
* returns:
* pointer to a legacy image header if valid image was found
* otherwise return NULL
*/
static image_header_t *image_get_kernel(ulong img_addr, int verify)
{
image_header_t *hdr = (image_header_t *)img_addr;
if (!image_check_magic(hdr)) {
puts("Bad Magic Number\n");
show_boot_progress(-1);
return NULL;
}
show_boot_progress(2);
if (!image_check_hcrc(hdr)) {
puts("Bad Header Checksum\n");
show_boot_progress(-2);
return NULL;
}
show_boot_progress(3);
image_print_contents(hdr);
if (verify) {
puts(" Verifying Checksum ... ");
if (!image_check_dcrc(hdr)) {
printf("Bad Data CRC\n");
show_boot_progress(-3);
return NULL;
}
puts("OK\n");
}
show_boot_progress(4);
if (!image_check_target_arch(hdr)) {
printf("Unsupported Architecture 0x%x\n", image_get_arch(hdr));
show_boot_progress(-4);
return NULL;
}
return hdr;
}
/**
* fit_check_kernel - verify FIT format kernel subimage
* @fit_hdr: pointer to the FIT image header
* os_noffset: kernel subimage node offset within FIT image
* @verify: data CRC verification flag
*
* fit_check_kernel() verifies integrity of the kernel subimage and from
* specified FIT image.
*
* returns:
* 1, on success
* 0, on failure
*/
#if defined(CONFIG_FIT)
static int fit_check_kernel(const void *fit, int os_noffset, int verify)
{
fit_image_print(fit, os_noffset, " ");
if (verify) {
puts(" Verifying Hash Integrity ... ");
if (!fit_image_check_hashes(fit, os_noffset)) {
puts("Bad Data Hash\n");
show_boot_progress(-104);
return 0;
}
puts("OK\n");
}
show_boot_progress(105);
if (!fit_image_check_target_arch(fit, os_noffset)) {
puts("Unsupported Architecture\n");
show_boot_progress(-105);
return 0;
}
show_boot_progress(106);
if (!fit_image_check_type(fit, os_noffset, IH_TYPE_KERNEL) &&
!fit_image_check_type(fit, os_noffset, IH_TYPE_KERNEL_NOLOAD)) {
puts("Not a kernel image\n");
show_boot_progress(-106);
return 0;
}
show_boot_progress(107);
return 1;
}
#endif /* CONFIG_FIT */
/**
* boot_get_kernel - find kernel image
* @os_data: pointer to a ulong variable, will hold os data start address
* @os_len: pointer to a ulong variable, will hold os data length
*
* boot_get_kernel() tries to find a kernel image, verifies its integrity
* and locates kernel data.
*
* returns:
* pointer to image header if valid image was found, plus kernel start
* address and length, otherwise NULL
*/
static void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[], bootm_headers_t *images, ulong *os_data,
ulong *os_len)
{
image_header_t *hdr;
ulong img_addr;
#if defined(CONFIG_FIT)
void *fit_hdr;
const char *fit_uname_config = NULL;
const char *fit_uname_kernel = NULL;
const void *data;
size_t len;
int cfg_noffset;
int os_noffset;
#endif
/* find out kernel image address */
if (argc < 2) {
img_addr = load_addr;
debug("* kernel: default image load address = 0x%08lx\n",
load_addr);
#if defined(CONFIG_FIT)
} else if (fit_parse_conf(argv[1], load_addr, &img_addr,
&fit_uname_config)) {
debug("* kernel: config '%s' from image at 0x%08lx\n",
fit_uname_config, img_addr);
} else if (fit_parse_subimage(argv[1], load_addr, &img_addr,
&fit_uname_kernel)) {
debug("* kernel: subimage '%s' from image at 0x%08lx\n",
fit_uname_kernel, img_addr);
#endif
} else {
img_addr = simple_strtoul(argv[1], NULL, 16);
debug("* kernel: cmdline image address = 0x%08lx\n", img_addr);
}
show_boot_progress(1);
/* copy from dataflash if needed */
img_addr = genimg_get_image(img_addr);
/* check image type, for FIT images get FIT kernel node */
*os_data = *os_len = 0;
switch (genimg_get_format((void *)img_addr)) {
case IMAGE_FORMAT_LEGACY:
printf("## Booting kernel from Legacy Image at %08lx ...\n",
img_addr);
hdr = image_get_kernel(img_addr, images->verify);
if (!hdr)
return NULL;
show_boot_progress(5);
/* get os_data and os_len */
switch (image_get_type(hdr)) {
case IH_TYPE_KERNEL:
case IH_TYPE_KERNEL_NOLOAD:
*os_data = image_get_data(hdr);
*os_len = image_get_data_size(hdr);
break;
case IH_TYPE_MULTI:
image_multi_getimg(hdr, 0, os_data, os_len);
break;
case IH_TYPE_STANDALONE:
*os_data = image_get_data(hdr);
*os_len = image_get_data_size(hdr);
break;
default:
printf("Wrong Image Type for %s command\n",
cmdtp->name);
show_boot_progress(-5);
return NULL;
}
/*
* copy image header to allow for image overwrites during
* kernel decompression.
*/
memmove(&images->legacy_hdr_os_copy, hdr,
sizeof(image_header_t));
/* save pointer to image header */
images->legacy_hdr_os = hdr;
images->legacy_hdr_valid = 1;
show_boot_progress(6);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
fit_hdr = (void *)img_addr;
printf("## Booting kernel from FIT Image at %08lx ...\n",
img_addr);
if (!fit_check_format(fit_hdr)) {
puts("Bad FIT kernel image format!\n");
show_boot_progress(-100);
return NULL;
}
show_boot_progress(100);
if (!fit_uname_kernel) {
/*
* no kernel image node unit name, try to get config
* node first. If config unit node name is NULL
* fit_conf_get_node() will try to find default config
* node
*/
show_boot_progress(101);
cfg_noffset = fit_conf_get_node(fit_hdr,
fit_uname_config);
if (cfg_noffset < 0) {
show_boot_progress(-101);
return NULL;
}
/* save configuration uname provided in the first
* bootm argument
*/
images->fit_uname_cfg = fdt_get_name(fit_hdr,
cfg_noffset,
NULL);
printf(" Using '%s' configuration\n",
images->fit_uname_cfg);
show_boot_progress(103);
os_noffset = fit_conf_get_kernel_node(fit_hdr,
cfg_noffset);
fit_uname_kernel = fit_get_name(fit_hdr, os_noffset,
NULL);
} else {
/* get kernel component image node offset */
show_boot_progress(102);
os_noffset = fit_image_get_node(fit_hdr,
fit_uname_kernel);
}
if (os_noffset < 0) {
show_boot_progress(-103);
return NULL;
}
printf(" Trying '%s' kernel subimage\n", fit_uname_kernel);
show_boot_progress(104);
if (!fit_check_kernel(fit_hdr, os_noffset, images->verify))
return NULL;
/* get kernel image data address and length */
if (fit_image_get_data(fit_hdr, os_noffset, &data, &len)) {
puts("Could not find kernel subimage data!\n");
show_boot_progress(-107);
return NULL;
}
show_boot_progress(108);
*os_len = len;
*os_data = (ulong)data;
images->fit_hdr_os = fit_hdr;
images->fit_uname_os = fit_uname_kernel;
images->fit_noffset_os = os_noffset;
break;
#endif
default:
printf("Wrong Image Format for %s command\n", cmdtp->name);
show_boot_progress(-108);
return NULL;
}
debug(" kernel data at 0x%08lx, len = 0x%08lx (%ld)\n",
*os_data, *os_len, *os_len);
return (void *)img_addr;
}
U_BOOT_CMD(
bootm, CONFIG_SYS_MAXARGS, 1, do_bootm,
"boot application image from memory",
"[addr [arg ...]]\n - boot application image stored in memory\n"
"\tpassing arguments 'arg ...'; when booting a Linux kernel,\n"
"\t'arg' can be the address of an initrd image\n"
#if defined(CONFIG_OF_LIBFDT)
"\tWhen booting a Linux kernel which requires a flat device-tree\n"
"\ta third argument is required which is the address of the\n"
"\tdevice-tree blob. To boot that kernel without an initrd image,\n"
"\tuse a '-' for the second argument. If you do not pass a third\n"
"\ta bd_info struct will be passed instead\n"
#endif
#if defined(CONFIG_FIT)
"\t\nFor the new multi component uImage format (FIT) addresses\n"
"\tmust be extened to include component or configuration unit name:\n"
"\taddr:<subimg_uname> - direct component image specification\n"
"\taddr#<conf_uname> - configuration specification\n"
"\tUse iminfo command to get the list of existing component\n"
"\timages and configurations.\n"
#endif
"\nSub-commands to do part of the bootm sequence. The sub-commands "
"must be\n"
"issued in the order below (it's ok to not issue all sub-commands):\n"
"\tstart [addr [arg ...]]\n"
"\tloados - load OS image\n"
#if defined(CONFIG_PPC) || defined(CONFIG_M68K) || defined(CONFIG_SPARC)
"\tramdisk - relocate initrd, set env initrd_start/initrd_end\n"
#endif
#if defined(CONFIG_OF_LIBFDT)
"\tfdt - relocate flat device tree\n"
#endif
"\tcmdline - OS specific command line processing/setup\n"
"\tbdt - OS specific bd_t processing\n"
"\tprep - OS specific prep before relocation or go\n"
"\tgo - start OS"
);
/*******************************************************************/
/* bootd - boot default image */
/*******************************************************************/
#if defined(CONFIG_CMD_BOOTD)
int do_bootd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int rcode = 0;
#ifndef CONFIG_SYS_HUSH_PARSER
if (run_command(getenv("bootcmd"), flag) < 0)
rcode = 1;
#else
if (parse_string_outer(getenv("bootcmd"),
FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP) != 0)
rcode = 1;
#endif
return rcode;
}
U_BOOT_CMD(
boot, 1, 1, do_bootd,
"boot default, i.e., run 'bootcmd'",
""
);
/* keep old command name "bootd" for backward compatibility */
U_BOOT_CMD(
bootd, 1, 1, do_bootd,
"boot default, i.e., run 'bootcmd'",
""
);
#endif
/*******************************************************************/
/* iminfo - print header info for a requested image */
/*******************************************************************/
#if defined(CONFIG_CMD_IMI)
int do_iminfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int arg;
ulong addr;
int rcode = 0;
if (argc < 2) {
return image_info(load_addr);
}
for (arg = 1; arg < argc; ++arg) {
addr = simple_strtoul(argv[arg], NULL, 16);
if (image_info(addr) != 0)
rcode = 1;
}
return rcode;
}
static int image_info(ulong addr)
{
void *hdr = (void *)addr;
printf("\n## Checking Image at %08lx ...\n", addr);
switch (genimg_get_format(hdr)) {
case IMAGE_FORMAT_LEGACY:
puts(" Legacy image found\n");
if (!image_check_magic(hdr)) {
puts(" Bad Magic Number\n");
return 1;
}
if (!image_check_hcrc(hdr)) {
puts(" Bad Header Checksum\n");
return 1;
}
image_print_contents(hdr);
puts(" Verifying Checksum ... ");
if (!image_check_dcrc(hdr)) {
puts(" Bad Data CRC\n");
return 1;
}
puts("OK\n");
return 0;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
puts(" FIT image found\n");
if (!fit_check_format(hdr)) {
puts("Bad FIT image format!\n");
return 1;
}
fit_print_contents(hdr);
if (!fit_all_image_check_hashes(hdr)) {
puts("Bad hash in FIT image!\n");
return 1;
}
return 0;
#endif
default:
puts("Unknown image format!\n");
break;
}
return 1;
}
U_BOOT_CMD(
iminfo, CONFIG_SYS_MAXARGS, 1, do_iminfo,
"print header information for application image",
"addr [addr ...]\n"
" - print header information for application image starting at\n"
" address 'addr' in memory; this includes verification of the\n"
" image contents (magic number, header and payload checksums)"
);
#endif
/*******************************************************************/
/* imls - list all images found in flash */
/*******************************************************************/
#if defined(CONFIG_CMD_IMLS)
int do_imls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
flash_info_t *info;
int i, j;
void *hdr;
for (i = 0, info = &flash_info[0];
i < CONFIG_SYS_MAX_FLASH_BANKS; ++i, ++info) {
if (info->flash_id == FLASH_UNKNOWN)
goto next_bank;
for (j = 0; j < info->sector_count; ++j) {
hdr = (void *)info->start[j];
if (!hdr)
goto next_sector;
switch (genimg_get_format(hdr)) {
case IMAGE_FORMAT_LEGACY:
if (!image_check_hcrc(hdr))
goto next_sector;
printf("Legacy Image at %08lX:\n", (ulong)hdr);
image_print_contents(hdr);
puts(" Verifying Checksum ... ");
if (!image_check_dcrc(hdr)) {
puts("Bad Data CRC\n");
} else {
puts("OK\n");
}
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
if (!fit_check_format(hdr))
goto next_sector;
printf("FIT Image at %08lX:\n", (ulong)hdr);
fit_print_contents(hdr);
break;
#endif
default:
goto next_sector;
}
next_sector: ;
}
next_bank: ;
}
return (0);
}
U_BOOT_CMD(
imls, 1, 1, do_imls,
"list all images found in flash",
"\n"
" - Prints information about all images found at sector\n"
" boundaries in flash."
);
#endif
/*******************************************************************/
/* helper routines */
/*******************************************************************/
#ifdef CONFIG_SILENT_CONSOLE
static void fixup_silent_linux(void)
{
char buf[256], *start, *end;
char *cmdline = getenv("bootargs");
/* Only fix cmdline when requested */
if (!(gd->flags & GD_FLG_SILENT))
return;
debug("before silent fix-up: %s\n", cmdline);
if (cmdline) {
start = strstr(cmdline, "console=");
if (start) {
end = strchr(start, ' ');
strncpy(buf, cmdline, (start - cmdline + 8));
if (end)
strcpy(buf + (start - cmdline + 8), end);
else
buf[start - cmdline + 8] = '\0';
} else {
strcpy(buf, cmdline);
strcat(buf, " console=");
}
} else {
strcpy(buf, "console=");
}
setenv("bootargs", buf);
debug("after silent fix-up: %s\n", buf);
}
#endif /* CONFIG_SILENT_CONSOLE */
/*******************************************************************/
/* OS booting routines */
/*******************************************************************/
#ifdef CONFIG_BOOTM_NETBSD
static int do_bootm_netbsd(int flag, int argc, char * const argv[],
bootm_headers_t *images)
{
void (*loader)(bd_t *, image_header_t *, char *, char *);
image_header_t *os_hdr, *hdr;
ulong kernel_data, kernel_len;
char *consdev;
char *cmdline;
if ((flag != 0) && (flag != BOOTM_STATE_OS_GO))
return 1;
#if defined(CONFIG_FIT)
if (!images->legacy_hdr_valid) {
fit_unsupported_reset("NetBSD");
return 1;
}
#endif
hdr = images->legacy_hdr_os;
/*
* Booting a (NetBSD) kernel image
*
* This process is pretty similar to a standalone application:
* The (first part of an multi-) image must be a stage-2 loader,
* which in turn is responsible for loading & invoking the actual
* kernel. The only differences are the parameters being passed:
* besides the board info strucure, the loader expects a command
* line, the name of the console device, and (optionally) the
* address of the original image header.
*/
os_hdr = NULL;
if (image_check_type(&images->legacy_hdr_os_copy, IH_TYPE_MULTI)) {
image_multi_getimg(hdr, 1, &kernel_data, &kernel_len);
if (kernel_len)
os_hdr = hdr;
}
consdev = "";
#if defined(CONFIG_8xx_CONS_SMC1)
consdev = "smc1";
#elif defined(CONFIG_8xx_CONS_SMC2)
consdev = "smc2";
#elif defined(CONFIG_8xx_CONS_SCC2)
consdev = "scc2";
#elif defined(CONFIG_8xx_CONS_SCC3)
consdev = "scc3";
#endif
if (argc > 2) {
ulong len;
int i;
for (i = 2, len = 0; i < argc; i += 1)
len += strlen(argv[i]) + 1;
cmdline = malloc(len);
for (i = 2, len = 0; i < argc; i += 1) {
if (i > 2)
cmdline[len++] = ' ';
strcpy(&cmdline[len], argv[i]);
len += strlen(argv[i]);
}
} else if ((cmdline = getenv("bootargs")) == NULL) {
cmdline = "";
}
loader = (void (*)(bd_t *, image_header_t *, char *, char *))images->ep;
printf("## Transferring control to NetBSD stage-2 loader "
"(at address %08lx) ...\n",
(ulong)loader);
show_boot_progress(15);
/*
* NetBSD Stage-2 Loader Parameters:
* r3: ptr to board info data
* r4: image address
* r5: console device
* r6: boot args string
*/
(*loader)(gd->bd, os_hdr, consdev, cmdline);
return 1;
}
#endif /* CONFIG_BOOTM_NETBSD*/
#ifdef CONFIG_LYNXKDI
static int do_bootm_lynxkdi(int flag, int argc, char * const argv[],
bootm_headers_t *images)
{
image_header_t *hdr = &images->legacy_hdr_os_copy;
if ((flag != 0) && (flag != BOOTM_STATE_OS_GO))
return 1;
#if defined(CONFIG_FIT)
if (!images->legacy_hdr_valid) {
fit_unsupported_reset("Lynx");
return 1;
}
#endif
lynxkdi_boot((image_header_t *)hdr);
return 1;
}
#endif /* CONFIG_LYNXKDI */
#ifdef CONFIG_BOOTM_RTEMS
static int do_bootm_rtems(int flag, int argc, char * const argv[],
bootm_headers_t *images)
{
void (*entry_point)(bd_t *);
if ((flag != 0) && (flag != BOOTM_STATE_OS_GO))
return 1;
#if defined(CONFIG_FIT)
if (!images->legacy_hdr_valid) {
fit_unsupported_reset("RTEMS");
return 1;
}
#endif
entry_point = (void (*)(bd_t *))images->ep;
printf("## Transferring control to RTEMS (at address %08lx) ...\n",
(ulong)entry_point);
show_boot_progress(15);
/*
* RTEMS Parameters:
* r3: ptr to board info data
*/
(*entry_point)(gd->bd);
return 1;
}
#endif /* CONFIG_BOOTM_RTEMS */
#if defined(CONFIG_BOOTM_OSE)
static int do_bootm_ose(int flag, int argc, char * const argv[],
bootm_headers_t *images)
{
void (*entry_point)(void);
if ((flag != 0) && (flag != BOOTM_STATE_OS_GO))
return 1;
#if defined(CONFIG_FIT)
if (!images->legacy_hdr_valid) {
fit_unsupported_reset("OSE");
return 1;
}
#endif
entry_point = (void (*)(void))images->ep;
printf("## Transferring control to OSE (at address %08lx) ...\n",
(ulong)entry_point);
show_boot_progress(15);
/*
* OSE Parameters:
* None
*/
(*entry_point)();
return 1;
}
#endif /* CONFIG_BOOTM_OSE */
#if defined(CONFIG_CMD_ELF)
static int do_bootm_vxworks(int flag, int argc, char * const argv[],
bootm_headers_t *images)
{
char str[80];
if ((flag != 0) && (flag != BOOTM_STATE_OS_GO))
return 1;
#if defined(CONFIG_FIT)
if (!images->legacy_hdr_valid) {
fit_unsupported_reset("VxWorks");
return 1;
}
#endif
sprintf(str, "%lx", images->ep); /* write entry-point into string */
setenv("loadaddr", str);
do_bootvx(NULL, 0, 0, NULL);
return 1;
}
static int do_bootm_qnxelf(int flag, int argc, char * const argv[],
bootm_headers_t *images)
{
char *local_args[2];
char str[16];
if ((flag != 0) && (flag != BOOTM_STATE_OS_GO))
return 1;
#if defined(CONFIG_FIT)
if (!images->legacy_hdr_valid) {
fit_unsupported_reset("QNX");
return 1;
}
#endif
sprintf(str, "%lx", images->ep); /* write entry-point into string */
local_args[0] = argv[0];
local_args[1] = str; /* and provide it via the arguments */
do_bootelf(NULL, 0, 2, local_args);
return 1;
}
#endif
#ifdef CONFIG_INTEGRITY
static int do_bootm_integrity(int flag, int argc, char * const argv[],
bootm_headers_t *images)
{
void (*entry_point)(void);
if ((flag != 0) && (flag != BOOTM_STATE_OS_GO))
return 1;
#if defined(CONFIG_FIT)
if (!images->legacy_hdr_valid) {
fit_unsupported_reset("INTEGRITY");
return 1;
}
#endif
entry_point = (void (*)(void))images->ep;
printf("## Transferring control to INTEGRITY (at address %08lx) ...\n",
(ulong)entry_point);
show_boot_progress(15);
/*
* INTEGRITY Parameters:
* None
*/
(*entry_point)();
return 1;
}
#endif
|
1001-study-uboot
|
common/cmd_bootm.c
|
C
|
gpl3
| 38,277
|
/*
* (C) Copyright 2008 Semihalf
*
* (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
*/
#ifndef USE_HOSTCC
#include <common.h>
#include <watchdog.h>
#ifdef CONFIG_SHOW_BOOT_PROGRESS
#include <status_led.h>
#endif
#ifdef CONFIG_HAS_DATAFLASH
#include <dataflash.h>
#endif
#ifdef CONFIG_LOGBUFFER
#include <logbuff.h>
#endif
#if defined(CONFIG_TIMESTAMP) || defined(CONFIG_CMD_DATE)
#include <rtc.h>
#endif
#include <image.h>
#if defined(CONFIG_FIT) || defined(CONFIG_OF_LIBFDT)
#include <fdt.h>
#include <libfdt.h>
#include <fdt_support.h>
#endif
#if defined(CONFIG_FIT)
#include <u-boot/md5.h>
#include <sha1.h>
static int fit_check_ramdisk(const void *fit, int os_noffset,
uint8_t arch, int verify);
#endif
#ifdef CONFIG_CMD_BDI
extern int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
#endif
DECLARE_GLOBAL_DATA_PTR;
static const image_header_t *image_get_ramdisk(ulong rd_addr, uint8_t arch,
int verify);
#else
#include "mkimage.h"
#include <u-boot/md5.h>
#include <time.h>
#include <image.h>
#endif /* !USE_HOSTCC*/
static const table_entry_t uimage_arch[] = {
{ IH_ARCH_INVALID, NULL, "Invalid ARCH", },
{ IH_ARCH_ALPHA, "alpha", "Alpha", },
{ IH_ARCH_ARM, "arm", "ARM", },
{ IH_ARCH_I386, "x86", "Intel x86", },
{ IH_ARCH_IA64, "ia64", "IA64", },
{ IH_ARCH_M68K, "m68k", "M68K", },
{ IH_ARCH_MICROBLAZE, "microblaze", "MicroBlaze", },
{ IH_ARCH_MIPS, "mips", "MIPS", },
{ IH_ARCH_MIPS64, "mips64", "MIPS 64 Bit", },
{ IH_ARCH_NIOS2, "nios2", "NIOS II", },
{ IH_ARCH_PPC, "powerpc", "PowerPC", },
{ IH_ARCH_PPC, "ppc", "PowerPC", },
{ IH_ARCH_S390, "s390", "IBM S390", },
{ IH_ARCH_SH, "sh", "SuperH", },
{ IH_ARCH_SPARC, "sparc", "SPARC", },
{ IH_ARCH_SPARC64, "sparc64", "SPARC 64 Bit", },
{ IH_ARCH_BLACKFIN, "blackfin", "Blackfin", },
{ IH_ARCH_AVR32, "avr32", "AVR32", },
{ IH_ARCH_NDS32, "nds32", "NDS32", },
{ -1, "", "", },
};
static const table_entry_t uimage_os[] = {
{ IH_OS_INVALID, NULL, "Invalid OS", },
{ IH_OS_LINUX, "linux", "Linux", },
#if defined(CONFIG_LYNXKDI) || defined(USE_HOSTCC)
{ IH_OS_LYNXOS, "lynxos", "LynxOS", },
#endif
{ IH_OS_NETBSD, "netbsd", "NetBSD", },
{ IH_OS_OSE, "ose", "Enea OSE", },
{ IH_OS_RTEMS, "rtems", "RTEMS", },
{ IH_OS_U_BOOT, "u-boot", "U-Boot", },
#if defined(CONFIG_CMD_ELF) || defined(USE_HOSTCC)
{ IH_OS_QNX, "qnx", "QNX", },
{ IH_OS_VXWORKS, "vxworks", "VxWorks", },
#endif
#if defined(CONFIG_INTEGRITY) || defined(USE_HOSTCC)
{ IH_OS_INTEGRITY,"integrity", "INTEGRITY", },
#endif
#ifdef USE_HOSTCC
{ IH_OS_4_4BSD, "4_4bsd", "4_4BSD", },
{ IH_OS_DELL, "dell", "Dell", },
{ IH_OS_ESIX, "esix", "Esix", },
{ IH_OS_FREEBSD, "freebsd", "FreeBSD", },
{ IH_OS_IRIX, "irix", "Irix", },
{ IH_OS_NCR, "ncr", "NCR", },
{ IH_OS_OPENBSD, "openbsd", "OpenBSD", },
{ IH_OS_PSOS, "psos", "pSOS", },
{ IH_OS_SCO, "sco", "SCO", },
{ IH_OS_SOLARIS, "solaris", "Solaris", },
{ IH_OS_SVR4, "svr4", "SVR4", },
#endif
{ -1, "", "", },
};
static const table_entry_t uimage_type[] = {
{ IH_TYPE_AISIMAGE, "aisimage", "Davinci AIS image",},
{ IH_TYPE_FILESYSTEM, "filesystem", "Filesystem Image", },
{ IH_TYPE_FIRMWARE, "firmware", "Firmware", },
{ IH_TYPE_FLATDT, "flat_dt", "Flat Device Tree", },
{ IH_TYPE_KERNEL, "kernel", "Kernel Image", },
{ IH_TYPE_KERNEL_NOLOAD, "kernel_noload", "Kernel Image (no loading done)", },
{ IH_TYPE_KWBIMAGE, "kwbimage", "Kirkwood Boot Image",},
{ IH_TYPE_IMXIMAGE, "imximage", "Freescale i.MX Boot Image",},
{ IH_TYPE_INVALID, NULL, "Invalid Image", },
{ IH_TYPE_MULTI, "multi", "Multi-File Image", },
{ IH_TYPE_OMAPIMAGE, "omapimage", "TI OMAP SPL With GP CH",},
{ IH_TYPE_RAMDISK, "ramdisk", "RAMDisk Image", },
{ IH_TYPE_SCRIPT, "script", "Script", },
{ IH_TYPE_STANDALONE, "standalone", "Standalone Program", },
{ IH_TYPE_UBLIMAGE, "ublimage", "Davinci UBL image",},
{ -1, "", "", },
};
static const table_entry_t uimage_comp[] = {
{ IH_COMP_NONE, "none", "uncompressed", },
{ IH_COMP_BZIP2, "bzip2", "bzip2 compressed", },
{ IH_COMP_GZIP, "gzip", "gzip compressed", },
{ IH_COMP_LZMA, "lzma", "lzma compressed", },
{ IH_COMP_LZO, "lzo", "lzo compressed", },
{ -1, "", "", },
};
uint32_t crc32(uint32_t, const unsigned char *, uint);
uint32_t crc32_wd(uint32_t, const unsigned char *, uint, uint);
#if defined(CONFIG_TIMESTAMP) || defined(CONFIG_CMD_DATE) || defined(USE_HOSTCC)
static void genimg_print_time(time_t timestamp);
#endif
/*****************************************************************************/
/* Legacy format routines */
/*****************************************************************************/
int image_check_hcrc(const image_header_t *hdr)
{
ulong hcrc;
ulong len = image_get_header_size();
image_header_t header;
/* Copy header so we can blank CRC field for re-calculation */
memmove(&header, (char *)hdr, image_get_header_size());
image_set_hcrc(&header, 0);
hcrc = crc32(0, (unsigned char *)&header, len);
return (hcrc == image_get_hcrc(hdr));
}
int image_check_dcrc(const image_header_t *hdr)
{
ulong data = image_get_data(hdr);
ulong len = image_get_data_size(hdr);
ulong dcrc = crc32_wd(0, (unsigned char *)data, len, CHUNKSZ_CRC32);
return (dcrc == image_get_dcrc(hdr));
}
/**
* image_multi_count - get component (sub-image) count
* @hdr: pointer to the header of the multi component image
*
* image_multi_count() returns number of components in a multi
* component image.
*
* Note: no checking of the image type is done, caller must pass
* a valid multi component image.
*
* returns:
* number of components
*/
ulong image_multi_count(const image_header_t *hdr)
{
ulong i, count = 0;
uint32_t *size;
/* get start of the image payload, which in case of multi
* component images that points to a table of component sizes */
size = (uint32_t *)image_get_data(hdr);
/* count non empty slots */
for (i = 0; size[i]; ++i)
count++;
return count;
}
/**
* image_multi_getimg - get component data address and size
* @hdr: pointer to the header of the multi component image
* @idx: index of the requested component
* @data: pointer to a ulong variable, will hold component data address
* @len: pointer to a ulong variable, will hold component size
*
* image_multi_getimg() returns size and data address for the requested
* component in a multi component image.
*
* Note: no checking of the image type is done, caller must pass
* a valid multi component image.
*
* returns:
* data address and size of the component, if idx is valid
* 0 in data and len, if idx is out of range
*/
void image_multi_getimg(const image_header_t *hdr, ulong idx,
ulong *data, ulong *len)
{
int i;
uint32_t *size;
ulong offset, count, img_data;
/* get number of component */
count = image_multi_count(hdr);
/* get start of the image payload, which in case of multi
* component images that points to a table of component sizes */
size = (uint32_t *)image_get_data(hdr);
/* get address of the proper component data start, which means
* skipping sizes table (add 1 for last, null entry) */
img_data = image_get_data(hdr) + (count + 1) * sizeof(uint32_t);
if (idx < count) {
*len = uimage_to_cpu(size[idx]);
offset = 0;
/* go over all indices preceding requested component idx */
for (i = 0; i < idx; i++) {
/* add up i-th component size, rounding up to 4 bytes */
offset += (uimage_to_cpu(size[i]) + 3) & ~3 ;
}
/* calculate idx-th component data address */
*data = img_data + offset;
} else {
*len = 0;
*data = 0;
}
}
static void image_print_type(const image_header_t *hdr)
{
const char *os, *arch, *type, *comp;
os = genimg_get_os_name(image_get_os(hdr));
arch = genimg_get_arch_name(image_get_arch(hdr));
type = genimg_get_type_name(image_get_type(hdr));
comp = genimg_get_comp_name(image_get_comp(hdr));
printf("%s %s %s (%s)\n", arch, os, type, comp);
}
/**
* image_print_contents - prints out the contents of the legacy format image
* @ptr: pointer to the legacy format image header
* @p: pointer to prefix string
*
* image_print_contents() formats a multi line legacy image contents description.
* The routine prints out all header fields followed by the size/offset data
* for MULTI/SCRIPT images.
*
* returns:
* no returned results
*/
void image_print_contents(const void *ptr)
{
const image_header_t *hdr = (const image_header_t *)ptr;
const char *p;
#ifdef USE_HOSTCC
p = "";
#else
p = " ";
#endif
printf("%sImage Name: %.*s\n", p, IH_NMLEN, image_get_name(hdr));
#if defined(CONFIG_TIMESTAMP) || defined(CONFIG_CMD_DATE) || defined(USE_HOSTCC)
printf("%sCreated: ", p);
genimg_print_time((time_t)image_get_time(hdr));
#endif
printf("%sImage Type: ", p);
image_print_type(hdr);
printf("%sData Size: ", p);
genimg_print_size(image_get_data_size(hdr));
printf("%sLoad Address: %08x\n", p, image_get_load(hdr));
printf("%sEntry Point: %08x\n", p, image_get_ep(hdr));
if (image_check_type(hdr, IH_TYPE_MULTI) ||
image_check_type(hdr, IH_TYPE_SCRIPT)) {
int i;
ulong data, len;
ulong count = image_multi_count(hdr);
printf("%sContents:\n", p);
for (i = 0; i < count; i++) {
image_multi_getimg(hdr, i, &data, &len);
printf("%s Image %d: ", p, i);
genimg_print_size(len);
if (image_check_type(hdr, IH_TYPE_SCRIPT) && i > 0) {
/*
* the user may need to know offsets
* if planning to do something with
* multiple files
*/
printf("%s Offset = 0x%08lx\n", p, data);
}
}
}
}
#ifndef USE_HOSTCC
/**
* image_get_ramdisk - get and verify ramdisk image
* @rd_addr: ramdisk image start address
* @arch: expected ramdisk architecture
* @verify: checksum verification flag
*
* image_get_ramdisk() returns a pointer to the verified ramdisk image
* header. Routine receives image start address and expected architecture
* flag. Verification done covers data and header integrity and os/type/arch
* fields checking.
*
* If dataflash support is enabled routine checks for dataflash addresses
* and handles required dataflash reads.
*
* returns:
* pointer to a ramdisk image header, if image was found and valid
* otherwise, return NULL
*/
static const image_header_t *image_get_ramdisk(ulong rd_addr, uint8_t arch,
int verify)
{
const image_header_t *rd_hdr = (const image_header_t *)rd_addr;
if (!image_check_magic(rd_hdr)) {
puts("Bad Magic Number\n");
show_boot_progress(-10);
return NULL;
}
if (!image_check_hcrc(rd_hdr)) {
puts("Bad Header Checksum\n");
show_boot_progress(-11);
return NULL;
}
show_boot_progress(10);
image_print_contents(rd_hdr);
if (verify) {
puts(" Verifying Checksum ... ");
if (!image_check_dcrc(rd_hdr)) {
puts("Bad Data CRC\n");
show_boot_progress(-12);
return NULL;
}
puts("OK\n");
}
show_boot_progress(11);
if (!image_check_os(rd_hdr, IH_OS_LINUX) ||
!image_check_arch(rd_hdr, arch) ||
!image_check_type(rd_hdr, IH_TYPE_RAMDISK)) {
printf("No Linux %s Ramdisk Image\n",
genimg_get_arch_name(arch));
show_boot_progress(-13);
return NULL;
}
return rd_hdr;
}
#endif /* !USE_HOSTCC */
/*****************************************************************************/
/* Shared dual-format routines */
/*****************************************************************************/
#ifndef USE_HOSTCC
int getenv_yesno(char *var)
{
char *s = getenv(var);
return (s && (*s == 'n')) ? 0 : 1;
}
ulong getenv_bootm_low(void)
{
char *s = getenv("bootm_low");
if (s) {
ulong tmp = simple_strtoul(s, NULL, 16);
return tmp;
}
#if defined(CONFIG_SYS_SDRAM_BASE)
return CONFIG_SYS_SDRAM_BASE;
#elif defined(CONFIG_ARM)
return gd->bd->bi_dram[0].start;
#else
return 0;
#endif
}
phys_size_t getenv_bootm_size(void)
{
phys_size_t tmp;
char *s = getenv("bootm_size");
if (s) {
tmp = (phys_size_t)simple_strtoull(s, NULL, 16);
return tmp;
}
s = getenv("bootm_low");
if (s)
tmp = (phys_size_t)simple_strtoull(s, NULL, 16);
else
tmp = 0;
#if defined(CONFIG_ARM)
return gd->bd->bi_dram[0].size - tmp;
#else
return gd->bd->bi_memsize - tmp;
#endif
}
phys_size_t getenv_bootm_mapsize(void)
{
phys_size_t tmp;
char *s = getenv("bootm_mapsize");
if (s) {
tmp = (phys_size_t)simple_strtoull(s, NULL, 16);
return tmp;
}
#if defined(CONFIG_SYS_BOOTMAPSZ)
return CONFIG_SYS_BOOTMAPSZ;
#else
return getenv_bootm_size();
#endif
}
void memmove_wd(void *to, void *from, size_t len, ulong chunksz)
{
if (to == from)
return;
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
while (len > 0) {
size_t tail = (len > chunksz) ? chunksz : len;
WATCHDOG_RESET();
memmove(to, from, tail);
to += tail;
from += tail;
len -= tail;
}
#else /* !(CONFIG_HW_WATCHDOG || CONFIG_WATCHDOG) */
memmove(to, from, len);
#endif /* CONFIG_HW_WATCHDOG || CONFIG_WATCHDOG */
}
#endif /* !USE_HOSTCC */
void genimg_print_size(uint32_t size)
{
#ifndef USE_HOSTCC
printf("%d Bytes = ", size);
print_size(size, "\n");
#else
printf("%d Bytes = %.2f kB = %.2f MB\n",
size, (double)size / 1.024e3,
(double)size / 1.048576e6);
#endif
}
#if defined(CONFIG_TIMESTAMP) || defined(CONFIG_CMD_DATE) || defined(USE_HOSTCC)
static void genimg_print_time(time_t timestamp)
{
#ifndef USE_HOSTCC
struct rtc_time tm;
to_tm(timestamp, &tm);
printf("%4d-%02d-%02d %2d:%02d:%02d UTC\n",
tm.tm_year, tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
#else
printf("%s", ctime(×tamp));
#endif
}
#endif /* CONFIG_TIMESTAMP || CONFIG_CMD_DATE || USE_HOSTCC */
/**
* get_table_entry_name - translate entry id to long name
* @table: pointer to a translation table for entries of a specific type
* @msg: message to be returned when translation fails
* @id: entry id to be translated
*
* get_table_entry_name() will go over translation table trying to find
* entry that matches given id. If matching entry is found, its long
* name is returned to the caller.
*
* returns:
* long entry name if translation succeeds
* msg otherwise
*/
char *get_table_entry_name(const table_entry_t *table, char *msg, int id)
{
for (; table->id >= 0; ++table) {
if (table->id == id)
#if defined(USE_HOSTCC) || !defined(CONFIG_NEEDS_MANUAL_RELOC)
return table->lname;
#else
return table->lname + gd->reloc_off;
#endif
}
return (msg);
}
const char *genimg_get_os_name(uint8_t os)
{
return (get_table_entry_name(uimage_os, "Unknown OS", os));
}
const char *genimg_get_arch_name(uint8_t arch)
{
return (get_table_entry_name(uimage_arch, "Unknown Architecture",
arch));
}
const char *genimg_get_type_name(uint8_t type)
{
return (get_table_entry_name(uimage_type, "Unknown Image", type));
}
const char *genimg_get_comp_name(uint8_t comp)
{
return (get_table_entry_name(uimage_comp, "Unknown Compression",
comp));
}
/**
* get_table_entry_id - translate short entry name to id
* @table: pointer to a translation table for entries of a specific type
* @table_name: to be used in case of error
* @name: entry short name to be translated
*
* get_table_entry_id() will go over translation table trying to find
* entry that matches given short name. If matching entry is found,
* its id returned to the caller.
*
* returns:
* entry id if translation succeeds
* -1 otherwise
*/
int get_table_entry_id(const table_entry_t *table,
const char *table_name, const char *name)
{
const table_entry_t *t;
#ifdef USE_HOSTCC
int first = 1;
for (t = table; t->id >= 0; ++t) {
if (t->sname && strcasecmp(t->sname, name) == 0)
return(t->id);
}
fprintf(stderr, "\nInvalid %s Type - valid names are", table_name);
for (t = table; t->id >= 0; ++t) {
if (t->sname == NULL)
continue;
fprintf(stderr, "%c %s", (first) ? ':' : ',', t->sname);
first = 0;
}
fprintf(stderr, "\n");
#else
for (t = table; t->id >= 0; ++t) {
#ifdef CONFIG_NEEDS_MANUAL_RELOC
if (t->sname && strcmp(t->sname + gd->reloc_off, name) == 0)
#else
if (t->sname && strcmp(t->sname, name) == 0)
#endif
return (t->id);
}
debug("Invalid %s Type: %s\n", table_name, name);
#endif /* USE_HOSTCC */
return (-1);
}
int genimg_get_os_id(const char *name)
{
return (get_table_entry_id(uimage_os, "OS", name));
}
int genimg_get_arch_id(const char *name)
{
return (get_table_entry_id(uimage_arch, "CPU", name));
}
int genimg_get_type_id(const char *name)
{
return (get_table_entry_id(uimage_type, "Image", name));
}
int genimg_get_comp_id(const char *name)
{
return (get_table_entry_id(uimage_comp, "Compression", name));
}
#ifndef USE_HOSTCC
/**
* genimg_get_format - get image format type
* @img_addr: image start address
*
* genimg_get_format() checks whether provided address points to a valid
* legacy or FIT image.
*
* New uImage format and FDT blob are based on a libfdt. FDT blob
* may be passed directly or embedded in a FIT image. In both situations
* genimg_get_format() must be able to dectect libfdt header.
*
* returns:
* image format type or IMAGE_FORMAT_INVALID if no image is present
*/
int genimg_get_format(void *img_addr)
{
ulong format = IMAGE_FORMAT_INVALID;
const image_header_t *hdr;
#if defined(CONFIG_FIT) || defined(CONFIG_OF_LIBFDT)
char *fit_hdr;
#endif
hdr = (const image_header_t *)img_addr;
if (image_check_magic(hdr))
format = IMAGE_FORMAT_LEGACY;
#if defined(CONFIG_FIT) || defined(CONFIG_OF_LIBFDT)
else {
fit_hdr = (char *)img_addr;
if (fdt_check_header(fit_hdr) == 0)
format = IMAGE_FORMAT_FIT;
}
#endif
return format;
}
/**
* genimg_get_image - get image from special storage (if necessary)
* @img_addr: image start address
*
* genimg_get_image() checks if provided image start adddress is located
* in a dataflash storage. If so, image is moved to a system RAM memory.
*
* returns:
* image start address after possible relocation from special storage
*/
ulong genimg_get_image(ulong img_addr)
{
ulong ram_addr = img_addr;
#ifdef CONFIG_HAS_DATAFLASH
ulong h_size, d_size;
if (addr_dataflash(img_addr)) {
/* ger RAM address */
ram_addr = CONFIG_SYS_LOAD_ADDR;
/* get header size */
h_size = image_get_header_size();
#if defined(CONFIG_FIT)
if (sizeof(struct fdt_header) > h_size)
h_size = sizeof(struct fdt_header);
#endif
/* read in header */
debug(" Reading image header from dataflash address "
"%08lx to RAM address %08lx\n", img_addr, ram_addr);
read_dataflash(img_addr, h_size, (char *)ram_addr);
/* get data size */
switch (genimg_get_format((void *)ram_addr)) {
case IMAGE_FORMAT_LEGACY:
d_size = image_get_data_size(
(const image_header_t *)ram_addr);
debug(" Legacy format image found at 0x%08lx, "
"size 0x%08lx\n",
ram_addr, d_size);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
d_size = fit_get_size((const void *)ram_addr) - h_size;
debug(" FIT/FDT format image found at 0x%08lx, "
"size 0x%08lx\n",
ram_addr, d_size);
break;
#endif
default:
printf(" No valid image found at 0x%08lx\n",
img_addr);
return ram_addr;
}
/* read in image data */
debug(" Reading image remaining data from dataflash address "
"%08lx to RAM address %08lx\n", img_addr + h_size,
ram_addr + h_size);
read_dataflash(img_addr + h_size, d_size,
(char *)(ram_addr + h_size));
}
#endif /* CONFIG_HAS_DATAFLASH */
return ram_addr;
}
/**
* fit_has_config - check if there is a valid FIT configuration
* @images: pointer to the bootm command headers structure
*
* fit_has_config() checks if there is a FIT configuration in use
* (if FTI support is present).
*
* returns:
* 0, no FIT support or no configuration found
* 1, configuration found
*/
int genimg_has_config(bootm_headers_t *images)
{
#if defined(CONFIG_FIT)
if (images->fit_uname_cfg)
return 1;
#endif
return 0;
}
/**
* boot_get_ramdisk - main ramdisk handling routine
* @argc: command argument count
* @argv: command argument list
* @images: pointer to the bootm images structure
* @arch: expected ramdisk architecture
* @rd_start: pointer to a ulong variable, will hold ramdisk start address
* @rd_end: pointer to a ulong variable, will hold ramdisk end
*
* boot_get_ramdisk() is responsible for finding a valid ramdisk image.
* Curently supported are the following ramdisk sources:
* - multicomponent kernel/ramdisk image,
* - commandline provided address of decicated ramdisk image.
*
* returns:
* 0, if ramdisk image was found and valid, or skiped
* rd_start and rd_end are set to ramdisk start/end addresses if
* ramdisk image is found and valid
*
* 1, if ramdisk image is found but corrupted, or invalid
* rd_start and rd_end are set to 0 if no ramdisk exists
*/
int boot_get_ramdisk(int argc, char * const argv[], bootm_headers_t *images,
uint8_t arch, ulong *rd_start, ulong *rd_end)
{
ulong rd_addr, rd_load;
ulong rd_data, rd_len;
const image_header_t *rd_hdr;
#if defined(CONFIG_FIT)
void *fit_hdr;
const char *fit_uname_config = NULL;
const char *fit_uname_ramdisk = NULL;
ulong default_addr;
int rd_noffset;
int cfg_noffset;
const void *data;
size_t size;
#endif
*rd_start = 0;
*rd_end = 0;
/*
* Look for a '-' which indicates to ignore the
* ramdisk argument
*/
if ((argc >= 3) && (strcmp(argv[2], "-") == 0)) {
debug("## Skipping init Ramdisk\n");
rd_len = rd_data = 0;
} else if (argc >= 3 || genimg_has_config(images)) {
#if defined(CONFIG_FIT)
if (argc >= 3) {
/*
* If the init ramdisk comes from the FIT image and
* the FIT image address is omitted in the command
* line argument, try to use os FIT image address or
* default load address.
*/
if (images->fit_uname_os)
default_addr = (ulong)images->fit_hdr_os;
else
default_addr = load_addr;
if (fit_parse_conf(argv[2], default_addr,
&rd_addr, &fit_uname_config)) {
debug("* ramdisk: config '%s' from image at "
"0x%08lx\n",
fit_uname_config, rd_addr);
} else if (fit_parse_subimage(argv[2], default_addr,
&rd_addr, &fit_uname_ramdisk)) {
debug("* ramdisk: subimage '%s' from image at "
"0x%08lx\n",
fit_uname_ramdisk, rd_addr);
} else
#endif
{
rd_addr = simple_strtoul(argv[2], NULL, 16);
debug("* ramdisk: cmdline image address = "
"0x%08lx\n",
rd_addr);
}
#if defined(CONFIG_FIT)
} else {
/* use FIT configuration provided in first bootm
* command argument
*/
rd_addr = (ulong)images->fit_hdr_os;
fit_uname_config = images->fit_uname_cfg;
debug("* ramdisk: using config '%s' from image "
"at 0x%08lx\n",
fit_uname_config, rd_addr);
/*
* Check whether configuration has ramdisk defined,
* if not, don't try to use it, quit silently.
*/
fit_hdr = (void *)rd_addr;
cfg_noffset = fit_conf_get_node(fit_hdr,
fit_uname_config);
if (cfg_noffset < 0) {
debug("* ramdisk: no such config\n");
return 1;
}
rd_noffset = fit_conf_get_ramdisk_node(fit_hdr,
cfg_noffset);
if (rd_noffset < 0) {
debug("* ramdisk: no ramdisk in config\n");
return 0;
}
}
#endif
/* copy from dataflash if needed */
rd_addr = genimg_get_image(rd_addr);
/*
* Check if there is an initrd image at the
* address provided in the second bootm argument
* check image type, for FIT images get FIT node.
*/
switch (genimg_get_format((void *)rd_addr)) {
case IMAGE_FORMAT_LEGACY:
printf("## Loading init Ramdisk from Legacy "
"Image at %08lx ...\n", rd_addr);
show_boot_progress(9);
rd_hdr = image_get_ramdisk(rd_addr, arch,
images->verify);
if (rd_hdr == NULL)
return 1;
rd_data = image_get_data(rd_hdr);
rd_len = image_get_data_size(rd_hdr);
rd_load = image_get_load(rd_hdr);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
fit_hdr = (void *)rd_addr;
printf("## Loading init Ramdisk from FIT "
"Image at %08lx ...\n", rd_addr);
show_boot_progress(120);
if (!fit_check_format(fit_hdr)) {
puts("Bad FIT ramdisk image format!\n");
show_boot_progress(-120);
return 1;
}
show_boot_progress(121);
if (!fit_uname_ramdisk) {
/*
* no ramdisk image node unit name, try to get config
* node first. If config unit node name is NULL
* fit_conf_get_node() will try to find default config node
*/
show_boot_progress(122);
cfg_noffset = fit_conf_get_node(fit_hdr,
fit_uname_config);
if (cfg_noffset < 0) {
puts("Could not find configuration "
"node\n");
show_boot_progress(-122);
return 1;
}
fit_uname_config = fdt_get_name(fit_hdr,
cfg_noffset, NULL);
printf(" Using '%s' configuration\n",
fit_uname_config);
rd_noffset = fit_conf_get_ramdisk_node(fit_hdr,
cfg_noffset);
fit_uname_ramdisk = fit_get_name(fit_hdr,
rd_noffset, NULL);
} else {
/* get ramdisk component image node offset */
show_boot_progress(123);
rd_noffset = fit_image_get_node(fit_hdr,
fit_uname_ramdisk);
}
if (rd_noffset < 0) {
puts("Could not find subimage node\n");
show_boot_progress(-124);
return 1;
}
printf(" Trying '%s' ramdisk subimage\n",
fit_uname_ramdisk);
show_boot_progress(125);
if (!fit_check_ramdisk(fit_hdr, rd_noffset, arch,
images->verify))
return 1;
/* get ramdisk image data address and length */
if (fit_image_get_data(fit_hdr, rd_noffset, &data,
&size)) {
puts("Could not find ramdisk subimage data!\n");
show_boot_progress(-127);
return 1;
}
show_boot_progress(128);
rd_data = (ulong)data;
rd_len = size;
if (fit_image_get_load(fit_hdr, rd_noffset, &rd_load)) {
puts("Can't get ramdisk subimage load "
"address!\n");
show_boot_progress(-129);
return 1;
}
show_boot_progress(129);
images->fit_hdr_rd = fit_hdr;
images->fit_uname_rd = fit_uname_ramdisk;
images->fit_noffset_rd = rd_noffset;
break;
#endif
default:
puts("Wrong Ramdisk Image Format\n");
rd_data = rd_len = rd_load = 0;
return 1;
}
} else if (images->legacy_hdr_valid &&
image_check_type(&images->legacy_hdr_os_copy,
IH_TYPE_MULTI)) {
/*
* Now check if we have a legacy mult-component image,
* get second entry data start address and len.
*/
show_boot_progress(13);
printf("## Loading init Ramdisk from multi component "
"Legacy Image at %08lx ...\n",
(ulong)images->legacy_hdr_os);
image_multi_getimg(images->legacy_hdr_os, 1, &rd_data, &rd_len);
} else {
/*
* no initrd image
*/
show_boot_progress(14);
rd_len = rd_data = 0;
}
if (!rd_data) {
debug("## No init Ramdisk\n");
} else {
*rd_start = rd_data;
*rd_end = rd_data + rd_len;
}
debug(" ramdisk start = 0x%08lx, ramdisk end = 0x%08lx\n",
*rd_start, *rd_end);
return 0;
}
#ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
/**
* boot_ramdisk_high - relocate init ramdisk
* @lmb: pointer to lmb handle, will be used for memory mgmt
* @rd_data: ramdisk data start address
* @rd_len: ramdisk data length
* @initrd_start: pointer to a ulong variable, will hold final init ramdisk
* start address (after possible relocation)
* @initrd_end: pointer to a ulong variable, will hold final init ramdisk
* end address (after possible relocation)
*
* boot_ramdisk_high() takes a relocation hint from "initrd_high" environement
* variable and if requested ramdisk data is moved to a specified location.
*
* Initrd_start and initrd_end are set to final (after relocation) ramdisk
* start/end addresses if ramdisk image start and len were provided,
* otherwise set initrd_start and initrd_end set to zeros.
*
* returns:
* 0 - success
* -1 - failure
*/
int boot_ramdisk_high(struct lmb *lmb, ulong rd_data, ulong rd_len,
ulong *initrd_start, ulong *initrd_end)
{
char *s;
ulong initrd_high;
int initrd_copy_to_ram = 1;
if ((s = getenv("initrd_high")) != NULL) {
/* a value of "no" or a similar string will act like 0,
* turning the "load high" feature off. This is intentional.
*/
initrd_high = simple_strtoul(s, NULL, 16);
if (initrd_high == ~0)
initrd_copy_to_ram = 0;
} else {
/* not set, no restrictions to load high */
initrd_high = ~0;
}
#ifdef CONFIG_LOGBUFFER
/* Prevent initrd from overwriting logbuffer */
lmb_reserve(lmb, logbuffer_base() - LOGBUFF_OVERHEAD, LOGBUFF_RESERVE);
#endif
debug("## initrd_high = 0x%08lx, copy_to_ram = %d\n",
initrd_high, initrd_copy_to_ram);
if (rd_data) {
if (!initrd_copy_to_ram) { /* zero-copy ramdisk support */
debug(" in-place initrd\n");
*initrd_start = rd_data;
*initrd_end = rd_data + rd_len;
lmb_reserve(lmb, rd_data, rd_len);
} else {
if (initrd_high)
*initrd_start = (ulong)lmb_alloc_base(lmb,
rd_len, 0x1000, initrd_high);
else
*initrd_start = (ulong)lmb_alloc(lmb, rd_len,
0x1000);
if (*initrd_start == 0) {
puts("ramdisk - allocation error\n");
goto error;
}
show_boot_progress(12);
*initrd_end = *initrd_start + rd_len;
printf(" Loading Ramdisk to %08lx, end %08lx ... ",
*initrd_start, *initrd_end);
memmove_wd((void *)*initrd_start,
(void *)rd_data, rd_len, CHUNKSZ);
#ifdef CONFIG_MP
/*
* Ensure the image is flushed to memory to handle
* AMP boot scenarios in which we might not be
* HW cache coherent
*/
flush_cache((unsigned long)*initrd_start, rd_len);
#endif
puts("OK\n");
}
} else {
*initrd_start = 0;
*initrd_end = 0;
}
debug(" ramdisk load start = 0x%08lx, ramdisk load end = 0x%08lx\n",
*initrd_start, *initrd_end);
return 0;
error:
return -1;
}
#endif /* CONFIG_SYS_BOOT_RAMDISK_HIGH */
#ifdef CONFIG_OF_LIBFDT
static void fdt_error(const char *msg)
{
puts("ERROR: ");
puts(msg);
puts(" - must RESET the board to recover.\n");
}
static const image_header_t *image_get_fdt(ulong fdt_addr)
{
const image_header_t *fdt_hdr = (const image_header_t *)fdt_addr;
image_print_contents(fdt_hdr);
puts(" Verifying Checksum ... ");
if (!image_check_hcrc(fdt_hdr)) {
fdt_error("fdt header checksum invalid");
return NULL;
}
if (!image_check_dcrc(fdt_hdr)) {
fdt_error("fdt checksum invalid");
return NULL;
}
puts("OK\n");
if (!image_check_type(fdt_hdr, IH_TYPE_FLATDT)) {
fdt_error("uImage is not a fdt");
return NULL;
}
if (image_get_comp(fdt_hdr) != IH_COMP_NONE) {
fdt_error("uImage is compressed");
return NULL;
}
if (fdt_check_header((char *)image_get_data(fdt_hdr)) != 0) {
fdt_error("uImage data is not a fdt");
return NULL;
}
return fdt_hdr;
}
/**
* fit_check_fdt - verify FIT format FDT subimage
* @fit_hdr: pointer to the FIT header
* fdt_noffset: FDT subimage node offset within FIT image
* @verify: data CRC verification flag
*
* fit_check_fdt() verifies integrity of the FDT subimage and from
* specified FIT image.
*
* returns:
* 1, on success
* 0, on failure
*/
#if defined(CONFIG_FIT)
static int fit_check_fdt(const void *fit, int fdt_noffset, int verify)
{
fit_image_print(fit, fdt_noffset, " ");
if (verify) {
puts(" Verifying Hash Integrity ... ");
if (!fit_image_check_hashes(fit, fdt_noffset)) {
fdt_error("Bad Data Hash");
return 0;
}
puts("OK\n");
}
if (!fit_image_check_type(fit, fdt_noffset, IH_TYPE_FLATDT)) {
fdt_error("Not a FDT image");
return 0;
}
if (!fit_image_check_comp(fit, fdt_noffset, IH_COMP_NONE)) {
fdt_error("FDT image is compressed");
return 0;
}
return 1;
}
#endif /* CONFIG_FIT */
#ifndef CONFIG_SYS_FDT_PAD
#define CONFIG_SYS_FDT_PAD 0x3000
#endif
#if defined(CONFIG_OF_LIBFDT)
/**
* boot_fdt_add_mem_rsv_regions - Mark the memreserve sections as unusable
* @lmb: pointer to lmb handle, will be used for memory mgmt
* @fdt_blob: pointer to fdt blob base address
*
* Adds the memreserve regions in the dtb to the lmb block. Adding the
* memreserve regions prevents u-boot from using them to store the initrd
* or the fdt blob.
*/
void boot_fdt_add_mem_rsv_regions(struct lmb *lmb, void *fdt_blob)
{
uint64_t addr, size;
int i, total;
if (fdt_check_header(fdt_blob) != 0)
return;
total = fdt_num_mem_rsv(fdt_blob);
for (i = 0; i < total; i++) {
if (fdt_get_mem_rsv(fdt_blob, i, &addr, &size) != 0)
continue;
printf(" reserving fdt memory region: addr=%llx size=%llx\n",
(unsigned long long)addr, (unsigned long long)size);
lmb_reserve(lmb, addr, size);
}
}
/**
* boot_relocate_fdt - relocate flat device tree
* @lmb: pointer to lmb handle, will be used for memory mgmt
* @of_flat_tree: pointer to a char* variable, will hold fdt start address
* @of_size: pointer to a ulong variable, will hold fdt length
*
* boot_relocate_fdt() allocates a region of memory within the bootmap and
* relocates the of_flat_tree into that region, even if the fdt is already in
* the bootmap. It also expands the size of the fdt by CONFIG_SYS_FDT_PAD
* bytes.
*
* of_flat_tree and of_size are set to final (after relocation) values
*
* returns:
* 0 - success
* 1 - failure
*/
int boot_relocate_fdt(struct lmb *lmb, char **of_flat_tree, ulong *of_size)
{
void *fdt_blob = *of_flat_tree;
void *of_start = 0;
char *fdt_high;
ulong of_len = 0;
int err;
int disable_relocation = 0;
/* nothing to do */
if (*of_size == 0)
return 0;
if (fdt_check_header(fdt_blob) != 0) {
fdt_error("image is not a fdt");
goto error;
}
/* position on a 4K boundary before the alloc_current */
/* Pad the FDT by a specified amount */
of_len = *of_size + CONFIG_SYS_FDT_PAD;
/* If fdt_high is set use it to select the relocation address */
fdt_high = getenv("fdt_high");
if (fdt_high) {
void *desired_addr = (void *)simple_strtoul(fdt_high, NULL, 16);
if (((ulong) desired_addr) == ~0UL) {
/* All ones means use fdt in place */
desired_addr = fdt_blob;
disable_relocation = 1;
}
if (desired_addr) {
of_start =
(void *)(ulong) lmb_alloc_base(lmb, of_len, 0x1000,
((ulong)
desired_addr)
+ of_len);
if (desired_addr && of_start != desired_addr) {
puts("Failed using fdt_high value for Device Tree");
goto error;
}
} else {
of_start =
(void *)(ulong) lmb_alloc(lmb, of_len, 0x1000);
}
} else {
of_start =
(void *)(ulong) lmb_alloc_base(lmb, of_len, 0x1000,
getenv_bootm_mapsize()
+ getenv_bootm_low());
}
if (of_start == 0) {
puts("device tree - allocation error\n");
goto error;
}
if (disable_relocation) {
/* We assume there is space after the existing fdt to use for padding */
fdt_set_totalsize(of_start, of_len);
printf(" Using Device Tree in place at %p, end %p\n",
of_start, of_start + of_len - 1);
} else {
debug("## device tree at %p ... %p (len=%ld [0x%lX])\n",
fdt_blob, fdt_blob + *of_size - 1, of_len, of_len);
printf(" Loading Device Tree to %p, end %p ... ",
of_start, of_start + of_len - 1);
err = fdt_open_into(fdt_blob, of_start, of_len);
if (err != 0) {
fdt_error("fdt move failed");
goto error;
}
puts("OK\n");
}
*of_flat_tree = of_start;
*of_size = of_len;
set_working_fdt_addr(*of_flat_tree);
return 0;
error:
return 1;
}
#endif /* CONFIG_OF_LIBFDT */
/**
* boot_get_fdt - main fdt handling routine
* @argc: command argument count
* @argv: command argument list
* @images: pointer to the bootm images structure
* @of_flat_tree: pointer to a char* variable, will hold fdt start address
* @of_size: pointer to a ulong variable, will hold fdt length
*
* boot_get_fdt() is responsible for finding a valid flat device tree image.
* Curently supported are the following ramdisk sources:
* - multicomponent kernel/ramdisk image,
* - commandline provided address of decicated ramdisk image.
*
* returns:
* 0, if fdt image was found and valid, or skipped
* of_flat_tree and of_size are set to fdt start address and length if
* fdt image is found and valid
*
* 1, if fdt image is found but corrupted
* of_flat_tree and of_size are set to 0 if no fdt exists
*/
int boot_get_fdt(int flag, int argc, char * const argv[],
bootm_headers_t *images, char **of_flat_tree, ulong *of_size)
{
const image_header_t *fdt_hdr;
ulong fdt_addr;
char *fdt_blob = NULL;
ulong image_start, image_end;
ulong load_start, load_end;
#if defined(CONFIG_FIT)
void *fit_hdr;
const char *fit_uname_config = NULL;
const char *fit_uname_fdt = NULL;
ulong default_addr;
int cfg_noffset;
int fdt_noffset;
const void *data;
size_t size;
#endif
*of_flat_tree = NULL;
*of_size = 0;
if (argc > 3 || genimg_has_config(images)) {
#if defined(CONFIG_FIT)
if (argc > 3) {
/*
* If the FDT blob comes from the FIT image and the
* FIT image address is omitted in the command line
* argument, try to use ramdisk or os FIT image
* address or default load address.
*/
if (images->fit_uname_rd)
default_addr = (ulong)images->fit_hdr_rd;
else if (images->fit_uname_os)
default_addr = (ulong)images->fit_hdr_os;
else
default_addr = load_addr;
if (fit_parse_conf(argv[3], default_addr,
&fdt_addr, &fit_uname_config)) {
debug("* fdt: config '%s' from image at "
"0x%08lx\n",
fit_uname_config, fdt_addr);
} else if (fit_parse_subimage(argv[3], default_addr,
&fdt_addr, &fit_uname_fdt)) {
debug("* fdt: subimage '%s' from image at "
"0x%08lx\n",
fit_uname_fdt, fdt_addr);
} else
#endif
{
fdt_addr = simple_strtoul(argv[3], NULL, 16);
debug("* fdt: cmdline image address = "
"0x%08lx\n",
fdt_addr);
}
#if defined(CONFIG_FIT)
} else {
/* use FIT configuration provided in first bootm
* command argument
*/
fdt_addr = (ulong)images->fit_hdr_os;
fit_uname_config = images->fit_uname_cfg;
debug("* fdt: using config '%s' from image "
"at 0x%08lx\n",
fit_uname_config, fdt_addr);
/*
* Check whether configuration has FDT blob defined,
* if not quit silently.
*/
fit_hdr = (void *)fdt_addr;
cfg_noffset = fit_conf_get_node(fit_hdr,
fit_uname_config);
if (cfg_noffset < 0) {
debug("* fdt: no such config\n");
return 0;
}
fdt_noffset = fit_conf_get_fdt_node(fit_hdr,
cfg_noffset);
if (fdt_noffset < 0) {
debug("* fdt: no fdt in config\n");
return 0;
}
}
#endif
debug("## Checking for 'FDT'/'FDT Image' at %08lx\n",
fdt_addr);
/* copy from dataflash if needed */
fdt_addr = genimg_get_image(fdt_addr);
/*
* Check if there is an FDT image at the
* address provided in the second bootm argument
* check image type, for FIT images get a FIT node.
*/
switch (genimg_get_format((void *)fdt_addr)) {
case IMAGE_FORMAT_LEGACY:
/* verify fdt_addr points to a valid image header */
printf("## Flattened Device Tree from Legacy Image "
"at %08lx\n",
fdt_addr);
fdt_hdr = image_get_fdt(fdt_addr);
if (!fdt_hdr)
goto error;
/*
* move image data to the load address,
* make sure we don't overwrite initial image
*/
image_start = (ulong)fdt_hdr;
image_end = image_get_image_end(fdt_hdr);
load_start = image_get_load(fdt_hdr);
load_end = load_start + image_get_data_size(fdt_hdr);
if ((load_start < image_end) && (load_end > image_start)) {
fdt_error("fdt overwritten");
goto error;
}
debug(" Loading FDT from 0x%08lx to 0x%08lx\n",
image_get_data(fdt_hdr), load_start);
memmove((void *)load_start,
(void *)image_get_data(fdt_hdr),
image_get_data_size(fdt_hdr));
fdt_blob = (char *)load_start;
break;
case IMAGE_FORMAT_FIT:
/*
* This case will catch both: new uImage format
* (libfdt based) and raw FDT blob (also libfdt
* based).
*/
#if defined(CONFIG_FIT)
/* check FDT blob vs FIT blob */
if (fit_check_format((const void *)fdt_addr)) {
/*
* FIT image
*/
fit_hdr = (void *)fdt_addr;
printf("## Flattened Device Tree from FIT "
"Image at %08lx\n",
fdt_addr);
if (!fit_uname_fdt) {
/*
* no FDT blob image node unit name,
* try to get config node first. If
* config unit node name is NULL
* fit_conf_get_node() will try to
* find default config node
*/
cfg_noffset = fit_conf_get_node(fit_hdr,
fit_uname_config);
if (cfg_noffset < 0) {
fdt_error("Could not find "
"configuration "
"node\n");
goto error;
}
fit_uname_config = fdt_get_name(fit_hdr,
cfg_noffset, NULL);
printf(" Using '%s' configuration\n",
fit_uname_config);
fdt_noffset = fit_conf_get_fdt_node(
fit_hdr,
cfg_noffset);
fit_uname_fdt = fit_get_name(fit_hdr,
fdt_noffset, NULL);
} else {
/* get FDT component image node offset */
fdt_noffset = fit_image_get_node(
fit_hdr,
fit_uname_fdt);
}
if (fdt_noffset < 0) {
fdt_error("Could not find subimage "
"node\n");
goto error;
}
printf(" Trying '%s' FDT blob subimage\n",
fit_uname_fdt);
if (!fit_check_fdt(fit_hdr, fdt_noffset,
images->verify))
goto error;
/* get ramdisk image data address and length */
if (fit_image_get_data(fit_hdr, fdt_noffset,
&data, &size)) {
fdt_error("Could not find FDT "
"subimage data");
goto error;
}
/* verift that image data is a proper FDT blob */
if (fdt_check_header((char *)data) != 0) {
fdt_error("Subimage data is not a FTD");
goto error;
}
/*
* move image data to the load address,
* make sure we don't overwrite initial image
*/
image_start = (ulong)fit_hdr;
image_end = fit_get_end(fit_hdr);
if (fit_image_get_load(fit_hdr, fdt_noffset,
&load_start) == 0) {
load_end = load_start + size;
if ((load_start < image_end) &&
(load_end > image_start)) {
fdt_error("FDT overwritten");
goto error;
}
printf(" Loading FDT from 0x%08lx "
"to 0x%08lx\n",
(ulong)data,
load_start);
memmove((void *)load_start,
(void *)data, size);
fdt_blob = (char *)load_start;
} else {
fdt_blob = (char *)data;
}
images->fit_hdr_fdt = fit_hdr;
images->fit_uname_fdt = fit_uname_fdt;
images->fit_noffset_fdt = fdt_noffset;
break;
} else
#endif
{
/*
* FDT blob
*/
fdt_blob = (char *)fdt_addr;
debug("* fdt: raw FDT blob\n");
printf("## Flattened Device Tree blob at "
"%08lx\n", (long)fdt_blob);
}
break;
default:
puts("ERROR: Did not find a cmdline Flattened Device "
"Tree\n");
goto error;
}
printf(" Booting using the fdt blob at 0x%p\n", fdt_blob);
} else if (images->legacy_hdr_valid &&
image_check_type(&images->legacy_hdr_os_copy,
IH_TYPE_MULTI)) {
ulong fdt_data, fdt_len;
/*
* Now check if we have a legacy multi-component image,
* get second entry data start address and len.
*/
printf("## Flattened Device Tree from multi "
"component Image at %08lX\n",
(ulong)images->legacy_hdr_os);
image_multi_getimg(images->legacy_hdr_os, 2, &fdt_data,
&fdt_len);
if (fdt_len) {
fdt_blob = (char *)fdt_data;
printf(" Booting using the fdt at 0x%p\n", fdt_blob);
if (fdt_check_header(fdt_blob) != 0) {
fdt_error("image is not a fdt");
goto error;
}
if (fdt_totalsize(fdt_blob) != fdt_len) {
fdt_error("fdt size != image size");
goto error;
}
} else {
debug("## No Flattened Device Tree\n");
return 0;
}
} else {
debug("## No Flattened Device Tree\n");
return 0;
}
*of_flat_tree = fdt_blob;
*of_size = fdt_totalsize(fdt_blob);
debug(" of_flat_tree at 0x%08lx size 0x%08lx\n",
(ulong)*of_flat_tree, *of_size);
return 0;
error:
*of_flat_tree = 0;
*of_size = 0;
return 1;
}
#endif /* CONFIG_OF_LIBFDT */
#ifdef CONFIG_SYS_BOOT_GET_CMDLINE
/**
* boot_get_cmdline - allocate and initialize kernel cmdline
* @lmb: pointer to lmb handle, will be used for memory mgmt
* @cmd_start: pointer to a ulong variable, will hold cmdline start
* @cmd_end: pointer to a ulong variable, will hold cmdline end
*
* boot_get_cmdline() allocates space for kernel command line below
* BOOTMAPSZ + getenv_bootm_low() address. If "bootargs" U-boot environemnt
* variable is present its contents is copied to allocated kernel
* command line.
*
* returns:
* 0 - success
* -1 - failure
*/
int boot_get_cmdline(struct lmb *lmb, ulong *cmd_start, ulong *cmd_end)
{
char *cmdline;
char *s;
cmdline = (char *)(ulong)lmb_alloc_base(lmb, CONFIG_SYS_BARGSIZE, 0xf,
getenv_bootm_mapsize() + getenv_bootm_low());
if (cmdline == NULL)
return -1;
if ((s = getenv("bootargs")) == NULL)
s = "";
strcpy(cmdline, s);
*cmd_start = (ulong) & cmdline[0];
*cmd_end = *cmd_start + strlen(cmdline);
debug("## cmdline at 0x%08lx ... 0x%08lx\n", *cmd_start, *cmd_end);
return 0;
}
#endif /* CONFIG_SYS_BOOT_GET_CMDLINE */
#ifdef CONFIG_SYS_BOOT_GET_KBD
/**
* boot_get_kbd - allocate and initialize kernel copy of board info
* @lmb: pointer to lmb handle, will be used for memory mgmt
* @kbd: double pointer to board info data
*
* boot_get_kbd() allocates space for kernel copy of board info data below
* BOOTMAPSZ + getenv_bootm_low() address and kernel board info is initialized
* with the current u-boot board info data.
*
* returns:
* 0 - success
* -1 - failure
*/
int boot_get_kbd(struct lmb *lmb, bd_t **kbd)
{
*kbd = (bd_t *)(ulong)lmb_alloc_base(lmb, sizeof(bd_t), 0xf,
getenv_bootm_mapsize() + getenv_bootm_low());
if (*kbd == NULL)
return -1;
**kbd = *(gd->bd);
debug("## kernel board info at 0x%08lx\n", (ulong)*kbd);
#if defined(DEBUG) && defined(CONFIG_CMD_BDI)
do_bdinfo(NULL, 0, 0, NULL);
#endif
return 0;
}
#endif /* CONFIG_SYS_BOOT_GET_KBD */
#endif /* !USE_HOSTCC */
#if defined(CONFIG_FIT)
/*****************************************************************************/
/* New uImage format routines */
/*****************************************************************************/
#ifndef USE_HOSTCC
static int fit_parse_spec(const char *spec, char sepc, ulong addr_curr,
ulong *addr, const char **name)
{
const char *sep;
*addr = addr_curr;
*name = NULL;
sep = strchr(spec, sepc);
if (sep) {
if (sep - spec > 0)
*addr = simple_strtoul(spec, NULL, 16);
*name = sep + 1;
return 1;
}
return 0;
}
/**
* fit_parse_conf - parse FIT configuration spec
* @spec: input string, containing configuration spec
* @add_curr: current image address (to be used as a possible default)
* @addr: pointer to a ulong variable, will hold FIT image address of a given
* configuration
* @conf_name double pointer to a char, will hold pointer to a configuration
* unit name
*
* fit_parse_conf() expects configuration spec in the for of [<addr>]#<conf>,
* where <addr> is a FIT image address that contains configuration
* with a <conf> unit name.
*
* Address part is optional, and if omitted default add_curr will
* be used instead.
*
* returns:
* 1 if spec is a valid configuration string,
* addr and conf_name are set accordingly
* 0 otherwise
*/
inline int fit_parse_conf(const char *spec, ulong addr_curr,
ulong *addr, const char **conf_name)
{
return fit_parse_spec(spec, '#', addr_curr, addr, conf_name);
}
/**
* fit_parse_subimage - parse FIT subimage spec
* @spec: input string, containing subimage spec
* @add_curr: current image address (to be used as a possible default)
* @addr: pointer to a ulong variable, will hold FIT image address of a given
* subimage
* @image_name: double pointer to a char, will hold pointer to a subimage name
*
* fit_parse_subimage() expects subimage spec in the for of
* [<addr>]:<subimage>, where <addr> is a FIT image address that contains
* subimage with a <subimg> unit name.
*
* Address part is optional, and if omitted default add_curr will
* be used instead.
*
* returns:
* 1 if spec is a valid subimage string,
* addr and image_name are set accordingly
* 0 otherwise
*/
inline int fit_parse_subimage(const char *spec, ulong addr_curr,
ulong *addr, const char **image_name)
{
return fit_parse_spec(spec, ':', addr_curr, addr, image_name);
}
#endif /* !USE_HOSTCC */
static void fit_get_debug(const void *fit, int noffset,
char *prop_name, int err)
{
debug("Can't get '%s' property from FIT 0x%08lx, "
"node: offset %d, name %s (%s)\n",
prop_name, (ulong)fit, noffset,
fit_get_name(fit, noffset, NULL),
fdt_strerror(err));
}
/**
* fit_print_contents - prints out the contents of the FIT format image
* @fit: pointer to the FIT format image header
* @p: pointer to prefix string
*
* fit_print_contents() formats a multi line FIT image contents description.
* The routine prints out FIT image properties (root node level) follwed by
* the details of each component image.
*
* returns:
* no returned results
*/
void fit_print_contents(const void *fit)
{
char *desc;
char *uname;
int images_noffset;
int confs_noffset;
int noffset;
int ndepth;
int count = 0;
int ret;
const char *p;
#if defined(CONFIG_TIMESTAMP) || defined(CONFIG_CMD_DATE) || defined(USE_HOSTCC)
time_t timestamp;
#endif
#ifdef USE_HOSTCC
p = "";
#else
p = " ";
#endif
/* Root node properties */
ret = fit_get_desc(fit, 0, &desc);
printf("%sFIT description: ", p);
if (ret)
printf("unavailable\n");
else
printf("%s\n", desc);
#if defined(CONFIG_TIMESTAMP) || defined(CONFIG_CMD_DATE) || defined(USE_HOSTCC)
ret = fit_get_timestamp(fit, 0, ×tamp);
printf("%sCreated: ", p);
if (ret)
printf("unavailable\n");
else
genimg_print_time(timestamp);
#endif
/* Find images parent node offset */
images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
if (images_noffset < 0) {
printf("Can't find images parent node '%s' (%s)\n",
FIT_IMAGES_PATH, fdt_strerror(images_noffset));
return;
}
/* Process its subnodes, print out component images details */
for (ndepth = 0, count = 0,
noffset = fdt_next_node(fit, images_noffset, &ndepth);
(noffset >= 0) && (ndepth > 0);
noffset = fdt_next_node(fit, noffset, &ndepth)) {
if (ndepth == 1) {
/*
* Direct child node of the images parent node,
* i.e. component image node.
*/
printf("%s Image %u (%s)\n", p, count++,
fit_get_name(fit, noffset, NULL));
fit_image_print(fit, noffset, p);
}
}
/* Find configurations parent node offset */
confs_noffset = fdt_path_offset(fit, FIT_CONFS_PATH);
if (confs_noffset < 0) {
debug("Can't get configurations parent node '%s' (%s)\n",
FIT_CONFS_PATH, fdt_strerror(confs_noffset));
return;
}
/* get default configuration unit name from default property */
uname = (char *)fdt_getprop(fit, noffset, FIT_DEFAULT_PROP, NULL);
if (uname)
printf("%s Default Configuration: '%s'\n", p, uname);
/* Process its subnodes, print out configurations details */
for (ndepth = 0, count = 0,
noffset = fdt_next_node(fit, confs_noffset, &ndepth);
(noffset >= 0) && (ndepth > 0);
noffset = fdt_next_node(fit, noffset, &ndepth)) {
if (ndepth == 1) {
/*
* Direct child node of the configurations parent node,
* i.e. configuration node.
*/
printf("%s Configuration %u (%s)\n", p, count++,
fit_get_name(fit, noffset, NULL));
fit_conf_print(fit, noffset, p);
}
}
}
/**
* fit_image_print - prints out the FIT component image details
* @fit: pointer to the FIT format image header
* @image_noffset: offset of the component image node
* @p: pointer to prefix string
*
* fit_image_print() lists all mandatory properies for the processed component
* image. If present, hash nodes are printed out as well. Load
* address for images of type firmware is also printed out. Since the load
* address is not mandatory for firmware images, it will be output as
* "unavailable" when not present.
*
* returns:
* no returned results
*/
void fit_image_print(const void *fit, int image_noffset, const char *p)
{
char *desc;
uint8_t type, arch, os, comp;
size_t size;
ulong load, entry;
const void *data;
int noffset;
int ndepth;
int ret;
/* Mandatory properties */
ret = fit_get_desc(fit, image_noffset, &desc);
printf("%s Description: ", p);
if (ret)
printf("unavailable\n");
else
printf("%s\n", desc);
fit_image_get_type(fit, image_noffset, &type);
printf("%s Type: %s\n", p, genimg_get_type_name(type));
fit_image_get_comp(fit, image_noffset, &comp);
printf("%s Compression: %s\n", p, genimg_get_comp_name(comp));
ret = fit_image_get_data(fit, image_noffset, &data, &size);
#ifndef USE_HOSTCC
printf("%s Data Start: ", p);
if (ret)
printf("unavailable\n");
else
printf("0x%08lx\n", (ulong)data);
#endif
printf("%s Data Size: ", p);
if (ret)
printf("unavailable\n");
else
genimg_print_size(size);
/* Remaining, type dependent properties */
if ((type == IH_TYPE_KERNEL) || (type == IH_TYPE_STANDALONE) ||
(type == IH_TYPE_RAMDISK) || (type == IH_TYPE_FIRMWARE) ||
(type == IH_TYPE_FLATDT)) {
fit_image_get_arch(fit, image_noffset, &arch);
printf("%s Architecture: %s\n", p, genimg_get_arch_name(arch));
}
if (type == IH_TYPE_KERNEL) {
fit_image_get_os(fit, image_noffset, &os);
printf("%s OS: %s\n", p, genimg_get_os_name(os));
}
if ((type == IH_TYPE_KERNEL) || (type == IH_TYPE_STANDALONE) ||
(type == IH_TYPE_FIRMWARE)) {
ret = fit_image_get_load(fit, image_noffset, &load);
printf("%s Load Address: ", p);
if (ret)
printf("unavailable\n");
else
printf("0x%08lx\n", load);
}
if ((type == IH_TYPE_KERNEL) || (type == IH_TYPE_STANDALONE)) {
fit_image_get_entry(fit, image_noffset, &entry);
printf("%s Entry Point: ", p);
if (ret)
printf("unavailable\n");
else
printf("0x%08lx\n", entry);
}
/* Process all hash subnodes of the component image node */
for (ndepth = 0, noffset = fdt_next_node(fit, image_noffset, &ndepth);
(noffset >= 0) && (ndepth > 0);
noffset = fdt_next_node(fit, noffset, &ndepth)) {
if (ndepth == 1) {
/* Direct child node of the component image node */
fit_image_print_hash(fit, noffset, p);
}
}
}
/**
* fit_image_print_hash - prints out the hash node details
* @fit: pointer to the FIT format image header
* @noffset: offset of the hash node
* @p: pointer to prefix string
*
* fit_image_print_hash() lists properies for the processed hash node
*
* returns:
* no returned results
*/
void fit_image_print_hash(const void *fit, int noffset, const char *p)
{
char *algo;
uint8_t *value;
int value_len;
int i, ret;
/*
* Check subnode name, must be equal to "hash".
* Multiple hash nodes require unique unit node
* names, e.g. hash@1, hash@2, etc.
*/
if (strncmp(fit_get_name(fit, noffset, NULL),
FIT_HASH_NODENAME,
strlen(FIT_HASH_NODENAME)) != 0)
return;
debug("%s Hash node: '%s'\n", p,
fit_get_name(fit, noffset, NULL));
printf("%s Hash algo: ", p);
if (fit_image_hash_get_algo(fit, noffset, &algo)) {
printf("invalid/unsupported\n");
return;
}
printf("%s\n", algo);
ret = fit_image_hash_get_value(fit, noffset, &value,
&value_len);
printf("%s Hash value: ", p);
if (ret) {
printf("unavailable\n");
} else {
for (i = 0; i < value_len; i++)
printf("%02x", value[i]);
printf("\n");
}
debug("%s Hash len: %d\n", p, value_len);
}
/**
* fit_get_desc - get node description property
* @fit: pointer to the FIT format image header
* @noffset: node offset
* @desc: double pointer to the char, will hold pointer to the descrption
*
* fit_get_desc() reads description property from a given node, if
* description is found pointer to it is returened in third call argument.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_get_desc(const void *fit, int noffset, char **desc)
{
int len;
*desc = (char *)fdt_getprop(fit, noffset, FIT_DESC_PROP, &len);
if (*desc == NULL) {
fit_get_debug(fit, noffset, FIT_DESC_PROP, len);
return -1;
}
return 0;
}
/**
* fit_get_timestamp - get node timestamp property
* @fit: pointer to the FIT format image header
* @noffset: node offset
* @timestamp: pointer to the time_t, will hold read timestamp
*
* fit_get_timestamp() reads timestamp poperty from given node, if timestamp
* is found and has a correct size its value is retured in third call
* argument.
*
* returns:
* 0, on success
* -1, on property read failure
* -2, on wrong timestamp size
*/
int fit_get_timestamp(const void *fit, int noffset, time_t *timestamp)
{
int len;
const void *data;
data = fdt_getprop(fit, noffset, FIT_TIMESTAMP_PROP, &len);
if (data == NULL) {
fit_get_debug(fit, noffset, FIT_TIMESTAMP_PROP, len);
return -1;
}
if (len != sizeof(uint32_t)) {
debug("FIT timestamp with incorrect size of (%u)\n", len);
return -2;
}
*timestamp = uimage_to_cpu(*((uint32_t *)data));
return 0;
}
/**
* fit_image_get_node - get node offset for component image of a given unit name
* @fit: pointer to the FIT format image header
* @image_uname: component image node unit name
*
* fit_image_get_node() finds a component image (withing the '/images'
* node) of a provided unit name. If image is found its node offset is
* returned to the caller.
*
* returns:
* image node offset when found (>=0)
* negative number on failure (FDT_ERR_* code)
*/
int fit_image_get_node(const void *fit, const char *image_uname)
{
int noffset, images_noffset;
images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
if (images_noffset < 0) {
debug("Can't find images parent node '%s' (%s)\n",
FIT_IMAGES_PATH, fdt_strerror(images_noffset));
return images_noffset;
}
noffset = fdt_subnode_offset(fit, images_noffset, image_uname);
if (noffset < 0) {
debug("Can't get node offset for image unit name: '%s' (%s)\n",
image_uname, fdt_strerror(noffset));
}
return noffset;
}
/**
* fit_image_get_os - get os id for a given component image node
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @os: pointer to the uint8_t, will hold os numeric id
*
* fit_image_get_os() finds os property in a given component image node.
* If the property is found, its (string) value is translated to the numeric
* id which is returned to the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_get_os(const void *fit, int noffset, uint8_t *os)
{
int len;
const void *data;
/* Get OS name from property data */
data = fdt_getprop(fit, noffset, FIT_OS_PROP, &len);
if (data == NULL) {
fit_get_debug(fit, noffset, FIT_OS_PROP, len);
*os = -1;
return -1;
}
/* Translate OS name to id */
*os = genimg_get_os_id(data);
return 0;
}
/**
* fit_image_get_arch - get arch id for a given component image node
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @arch: pointer to the uint8_t, will hold arch numeric id
*
* fit_image_get_arch() finds arch property in a given component image node.
* If the property is found, its (string) value is translated to the numeric
* id which is returned to the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_get_arch(const void *fit, int noffset, uint8_t *arch)
{
int len;
const void *data;
/* Get architecture name from property data */
data = fdt_getprop(fit, noffset, FIT_ARCH_PROP, &len);
if (data == NULL) {
fit_get_debug(fit, noffset, FIT_ARCH_PROP, len);
*arch = -1;
return -1;
}
/* Translate architecture name to id */
*arch = genimg_get_arch_id(data);
return 0;
}
/**
* fit_image_get_type - get type id for a given component image node
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @type: pointer to the uint8_t, will hold type numeric id
*
* fit_image_get_type() finds type property in a given component image node.
* If the property is found, its (string) value is translated to the numeric
* id which is returned to the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_get_type(const void *fit, int noffset, uint8_t *type)
{
int len;
const void *data;
/* Get image type name from property data */
data = fdt_getprop(fit, noffset, FIT_TYPE_PROP, &len);
if (data == NULL) {
fit_get_debug(fit, noffset, FIT_TYPE_PROP, len);
*type = -1;
return -1;
}
/* Translate image type name to id */
*type = genimg_get_type_id(data);
return 0;
}
/**
* fit_image_get_comp - get comp id for a given component image node
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @comp: pointer to the uint8_t, will hold comp numeric id
*
* fit_image_get_comp() finds comp property in a given component image node.
* If the property is found, its (string) value is translated to the numeric
* id which is returned to the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_get_comp(const void *fit, int noffset, uint8_t *comp)
{
int len;
const void *data;
/* Get compression name from property data */
data = fdt_getprop(fit, noffset, FIT_COMP_PROP, &len);
if (data == NULL) {
fit_get_debug(fit, noffset, FIT_COMP_PROP, len);
*comp = -1;
return -1;
}
/* Translate compression name to id */
*comp = genimg_get_comp_id(data);
return 0;
}
/**
* fit_image_get_load - get load address property for a given component image node
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @load: pointer to the uint32_t, will hold load address
*
* fit_image_get_load() finds load address property in a given component image node.
* If the property is found, its value is returned to the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_get_load(const void *fit, int noffset, ulong *load)
{
int len;
const uint32_t *data;
data = fdt_getprop(fit, noffset, FIT_LOAD_PROP, &len);
if (data == NULL) {
fit_get_debug(fit, noffset, FIT_LOAD_PROP, len);
return -1;
}
*load = uimage_to_cpu(*data);
return 0;
}
/**
* fit_image_get_entry - get entry point address property for a given component image node
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @entry: pointer to the uint32_t, will hold entry point address
*
* fit_image_get_entry() finds entry point address property in a given component image node.
* If the property is found, its value is returned to the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_get_entry(const void *fit, int noffset, ulong *entry)
{
int len;
const uint32_t *data;
data = fdt_getprop(fit, noffset, FIT_ENTRY_PROP, &len);
if (data == NULL) {
fit_get_debug(fit, noffset, FIT_ENTRY_PROP, len);
return -1;
}
*entry = uimage_to_cpu(*data);
return 0;
}
/**
* fit_image_get_data - get data property and its size for a given component image node
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @data: double pointer to void, will hold data property's data address
* @size: pointer to size_t, will hold data property's data size
*
* fit_image_get_data() finds data property in a given component image node.
* If the property is found its data start address and size are returned to
* the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_get_data(const void *fit, int noffset,
const void **data, size_t *size)
{
int len;
*data = fdt_getprop(fit, noffset, FIT_DATA_PROP, &len);
if (*data == NULL) {
fit_get_debug(fit, noffset, FIT_DATA_PROP, len);
*size = 0;
return -1;
}
*size = len;
return 0;
}
/**
* fit_image_hash_get_algo - get hash algorithm name
* @fit: pointer to the FIT format image header
* @noffset: hash node offset
* @algo: double pointer to char, will hold pointer to the algorithm name
*
* fit_image_hash_get_algo() finds hash algorithm property in a given hash node.
* If the property is found its data start address is returned to the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_hash_get_algo(const void *fit, int noffset, char **algo)
{
int len;
*algo = (char *)fdt_getprop(fit, noffset, FIT_ALGO_PROP, &len);
if (*algo == NULL) {
fit_get_debug(fit, noffset, FIT_ALGO_PROP, len);
return -1;
}
return 0;
}
/**
* fit_image_hash_get_value - get hash value and length
* @fit: pointer to the FIT format image header
* @noffset: hash node offset
* @value: double pointer to uint8_t, will hold address of a hash value data
* @value_len: pointer to an int, will hold hash data length
*
* fit_image_hash_get_value() finds hash value property in a given hash node.
* If the property is found its data start address and size are returned to
* the caller.
*
* returns:
* 0, on success
* -1, on failure
*/
int fit_image_hash_get_value(const void *fit, int noffset, uint8_t **value,
int *value_len)
{
int len;
*value = (uint8_t *)fdt_getprop(fit, noffset, FIT_VALUE_PROP, &len);
if (*value == NULL) {
fit_get_debug(fit, noffset, FIT_VALUE_PROP, len);
*value_len = 0;
return -1;
}
*value_len = len;
return 0;
}
/**
* fit_set_timestamp - set node timestamp property
* @fit: pointer to the FIT format image header
* @noffset: node offset
* @timestamp: timestamp value to be set
*
* fit_set_timestamp() attempts to set timestamp property in the requested
* node and returns operation status to the caller.
*
* returns:
* 0, on success
* -1, on property read failure
*/
int fit_set_timestamp(void *fit, int noffset, time_t timestamp)
{
uint32_t t;
int ret;
t = cpu_to_uimage(timestamp);
ret = fdt_setprop(fit, noffset, FIT_TIMESTAMP_PROP, &t,
sizeof(uint32_t));
if (ret) {
printf("Can't set '%s' property for '%s' node (%s)\n",
FIT_TIMESTAMP_PROP, fit_get_name(fit, noffset, NULL),
fdt_strerror(ret));
return -1;
}
return 0;
}
/**
* calculate_hash - calculate and return hash for provided input data
* @data: pointer to the input data
* @data_len: data length
* @algo: requested hash algorithm
* @value: pointer to the char, will hold hash value data (caller must
* allocate enough free space)
* value_len: length of the calculated hash
*
* calculate_hash() computes input data hash according to the requested algorithm.
* Resulting hash value is placed in caller provided 'value' buffer, length
* of the calculated hash is returned via value_len pointer argument.
*
* returns:
* 0, on success
* -1, when algo is unsupported
*/
static int calculate_hash(const void *data, int data_len, const char *algo,
uint8_t *value, int *value_len)
{
if (strcmp(algo, "crc32") == 0) {
*((uint32_t *)value) = crc32_wd(0, data, data_len,
CHUNKSZ_CRC32);
*((uint32_t *)value) = cpu_to_uimage(*((uint32_t *)value));
*value_len = 4;
} else if (strcmp(algo, "sha1") == 0) {
sha1_csum_wd((unsigned char *) data, data_len,
(unsigned char *) value, CHUNKSZ_SHA1);
*value_len = 20;
} else if (strcmp(algo, "md5") == 0) {
md5_wd((unsigned char *)data, data_len, value, CHUNKSZ_MD5);
*value_len = 16;
} else {
debug("Unsupported hash alogrithm\n");
return -1;
}
return 0;
}
#ifdef USE_HOSTCC
/**
* fit_set_hashes - process FIT component image nodes and calculate hashes
* @fit: pointer to the FIT format image header
*
* fit_set_hashes() adds hash values for all component images in the FIT blob.
* Hashes are calculated for all component images which have hash subnodes
* with algorithm property set to one of the supported hash algorithms.
*
* returns
* 0, on success
* libfdt error code, on failure
*/
int fit_set_hashes(void *fit)
{
int images_noffset;
int noffset;
int ndepth;
int ret;
/* Find images parent node offset */
images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
if (images_noffset < 0) {
printf("Can't find images parent node '%s' (%s)\n",
FIT_IMAGES_PATH, fdt_strerror(images_noffset));
return images_noffset;
}
/* Process its subnodes, print out component images details */
for (ndepth = 0, noffset = fdt_next_node(fit, images_noffset, &ndepth);
(noffset >= 0) && (ndepth > 0);
noffset = fdt_next_node(fit, noffset, &ndepth)) {
if (ndepth == 1) {
/*
* Direct child node of the images parent node,
* i.e. component image node.
*/
ret = fit_image_set_hashes(fit, noffset);
if (ret)
return ret;
}
}
return 0;
}
/**
* fit_image_set_hashes - calculate/set hashes for given component image node
* @fit: pointer to the FIT format image header
* @image_noffset: requested component image node
*
* fit_image_set_hashes() adds hash values for an component image node. All
* existing hash subnodes are checked, if algorithm property is set to one of
* the supported hash algorithms, hash value is computed and corresponding
* hash node property is set, for example:
*
* Input component image node structure:
*
* o image@1 (at image_noffset)
* | - data = [binary data]
* o hash@1
* |- algo = "sha1"
*
* Output component image node structure:
*
* o image@1 (at image_noffset)
* | - data = [binary data]
* o hash@1
* |- algo = "sha1"
* |- value = sha1(data)
*
* returns:
* 0 on sucess
* <0 on failure
*/
int fit_image_set_hashes(void *fit, int image_noffset)
{
const void *data;
size_t size;
char *algo;
uint8_t value[FIT_MAX_HASH_LEN];
int value_len;
int noffset;
int ndepth;
/* Get image data and data length */
if (fit_image_get_data(fit, image_noffset, &data, &size)) {
printf("Can't get image data/size\n");
return -1;
}
/* Process all hash subnodes of the component image node */
for (ndepth = 0, noffset = fdt_next_node(fit, image_noffset, &ndepth);
(noffset >= 0) && (ndepth > 0);
noffset = fdt_next_node(fit, noffset, &ndepth)) {
if (ndepth == 1) {
/* Direct child node of the component image node */
/*
* Check subnode name, must be equal to "hash".
* Multiple hash nodes require unique unit node
* names, e.g. hash@1, hash@2, etc.
*/
if (strncmp(fit_get_name(fit, noffset, NULL),
FIT_HASH_NODENAME,
strlen(FIT_HASH_NODENAME)) != 0) {
/* Not a hash subnode, skip it */
continue;
}
if (fit_image_hash_get_algo(fit, noffset, &algo)) {
printf("Can't get hash algo property for "
"'%s' hash node in '%s' image node\n",
fit_get_name(fit, noffset, NULL),
fit_get_name(fit, image_noffset, NULL));
return -1;
}
if (calculate_hash(data, size, algo, value,
&value_len)) {
printf("Unsupported hash algorithm (%s) for "
"'%s' hash node in '%s' image node\n",
algo, fit_get_name(fit, noffset, NULL),
fit_get_name(fit, image_noffset,
NULL));
return -1;
}
if (fit_image_hash_set_value(fit, noffset, value,
value_len)) {
printf("Can't set hash value for "
"'%s' hash node in '%s' image node\n",
fit_get_name(fit, noffset, NULL),
fit_get_name(fit, image_noffset, NULL));
return -1;
}
}
}
return 0;
}
/**
* fit_image_hash_set_value - set hash value in requested has node
* @fit: pointer to the FIT format image header
* @noffset: hash node offset
* @value: hash value to be set
* @value_len: hash value length
*
* fit_image_hash_set_value() attempts to set hash value in a node at offset
* given and returns operation status to the caller.
*
* returns
* 0, on success
* -1, on failure
*/
int fit_image_hash_set_value(void *fit, int noffset, uint8_t *value,
int value_len)
{
int ret;
ret = fdt_setprop(fit, noffset, FIT_VALUE_PROP, value, value_len);
if (ret) {
printf("Can't set hash '%s' property for '%s' node(%s)\n",
FIT_VALUE_PROP, fit_get_name(fit, noffset, NULL),
fdt_strerror(ret));
return -1;
}
return 0;
}
#endif /* USE_HOSTCC */
/**
* fit_image_check_hashes - verify data intergity
* @fit: pointer to the FIT format image header
* @image_noffset: component image node offset
*
* fit_image_check_hashes() goes over component image hash nodes,
* re-calculates each data hash and compares with the value stored in hash
* node.
*
* returns:
* 1, if all hashes are valid
* 0, otherwise (or on error)
*/
int fit_image_check_hashes(const void *fit, int image_noffset)
{
const void *data;
size_t size;
char *algo;
uint8_t *fit_value;
int fit_value_len;
uint8_t value[FIT_MAX_HASH_LEN];
int value_len;
int noffset;
int ndepth;
char *err_msg = "";
/* Get image data and data length */
if (fit_image_get_data(fit, image_noffset, &data, &size)) {
printf("Can't get image data/size\n");
return 0;
}
/* Process all hash subnodes of the component image node */
for (ndepth = 0, noffset = fdt_next_node(fit, image_noffset, &ndepth);
(noffset >= 0) && (ndepth > 0);
noffset = fdt_next_node(fit, noffset, &ndepth)) {
if (ndepth == 1) {
/* Direct child node of the component image node */
/*
* Check subnode name, must be equal to "hash".
* Multiple hash nodes require unique unit node
* names, e.g. hash@1, hash@2, etc.
*/
if (strncmp(fit_get_name(fit, noffset, NULL),
FIT_HASH_NODENAME,
strlen(FIT_HASH_NODENAME)) != 0)
continue;
if (fit_image_hash_get_algo(fit, noffset, &algo)) {
err_msg = " error!\nCan't get hash algo "
"property";
goto error;
}
printf("%s", algo);
if (fit_image_hash_get_value(fit, noffset, &fit_value,
&fit_value_len)) {
err_msg = " error!\nCan't get hash value "
"property";
goto error;
}
if (calculate_hash(data, size, algo, value,
&value_len)) {
err_msg = " error!\n"
"Unsupported hash algorithm";
goto error;
}
if (value_len != fit_value_len) {
err_msg = " error !\nBad hash value len";
goto error;
} else if (memcmp(value, fit_value, value_len) != 0) {
err_msg = " error!\nBad hash value";
goto error;
}
printf("+ ");
}
}
return 1;
error:
printf("%s for '%s' hash node in '%s' image node\n",
err_msg, fit_get_name(fit, noffset, NULL),
fit_get_name(fit, image_noffset, NULL));
return 0;
}
/**
* fit_all_image_check_hashes - verify data intergity for all images
* @fit: pointer to the FIT format image header
*
* fit_all_image_check_hashes() goes over all images in the FIT and
* for every images checks if all it's hashes are valid.
*
* returns:
* 1, if all hashes of all images are valid
* 0, otherwise (or on error)
*/
int fit_all_image_check_hashes(const void *fit)
{
int images_noffset;
int noffset;
int ndepth;
int count;
/* Find images parent node offset */
images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
if (images_noffset < 0) {
printf("Can't find images parent node '%s' (%s)\n",
FIT_IMAGES_PATH, fdt_strerror(images_noffset));
return 0;
}
/* Process all image subnodes, check hashes for each */
printf("## Checking hash(es) for FIT Image at %08lx ...\n",
(ulong)fit);
for (ndepth = 0, count = 0,
noffset = fdt_next_node(fit, images_noffset, &ndepth);
(noffset >= 0) && (ndepth > 0);
noffset = fdt_next_node(fit, noffset, &ndepth)) {
if (ndepth == 1) {
/*
* Direct child node of the images parent node,
* i.e. component image node.
*/
printf(" Hash(es) for Image %u (%s): ", count++,
fit_get_name(fit, noffset, NULL));
if (!fit_image_check_hashes(fit, noffset))
return 0;
printf("\n");
}
}
return 1;
}
/**
* fit_image_check_os - check whether image node is of a given os type
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @os: requested image os
*
* fit_image_check_os() reads image os property and compares its numeric
* id with the requested os. Comparison result is returned to the caller.
*
* returns:
* 1 if image is of given os type
* 0 otherwise (or on error)
*/
int fit_image_check_os(const void *fit, int noffset, uint8_t os)
{
uint8_t image_os;
if (fit_image_get_os(fit, noffset, &image_os))
return 0;
return (os == image_os);
}
/**
* fit_image_check_arch - check whether image node is of a given arch
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @arch: requested imagearch
*
* fit_image_check_arch() reads image arch property and compares its numeric
* id with the requested arch. Comparison result is returned to the caller.
*
* returns:
* 1 if image is of given arch
* 0 otherwise (or on error)
*/
int fit_image_check_arch(const void *fit, int noffset, uint8_t arch)
{
uint8_t image_arch;
if (fit_image_get_arch(fit, noffset, &image_arch))
return 0;
return (arch == image_arch);
}
/**
* fit_image_check_type - check whether image node is of a given type
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @type: requested image type
*
* fit_image_check_type() reads image type property and compares its numeric
* id with the requested type. Comparison result is returned to the caller.
*
* returns:
* 1 if image is of given type
* 0 otherwise (or on error)
*/
int fit_image_check_type(const void *fit, int noffset, uint8_t type)
{
uint8_t image_type;
if (fit_image_get_type(fit, noffset, &image_type))
return 0;
return (type == image_type);
}
/**
* fit_image_check_comp - check whether image node uses given compression
* @fit: pointer to the FIT format image header
* @noffset: component image node offset
* @comp: requested image compression type
*
* fit_image_check_comp() reads image compression property and compares its
* numeric id with the requested compression type. Comparison result is
* returned to the caller.
*
* returns:
* 1 if image uses requested compression
* 0 otherwise (or on error)
*/
int fit_image_check_comp(const void *fit, int noffset, uint8_t comp)
{
uint8_t image_comp;
if (fit_image_get_comp(fit, noffset, &image_comp))
return 0;
return (comp == image_comp);
}
/**
* fit_check_format - sanity check FIT image format
* @fit: pointer to the FIT format image header
*
* fit_check_format() runs a basic sanity FIT image verification.
* Routine checks for mandatory properties, nodes, etc.
*
* returns:
* 1, on success
* 0, on failure
*/
int fit_check_format(const void *fit)
{
/* mandatory / node 'description' property */
if (fdt_getprop(fit, 0, FIT_DESC_PROP, NULL) == NULL) {
debug("Wrong FIT format: no description\n");
return 0;
}
#if defined(CONFIG_TIMESTAMP) || defined(CONFIG_CMD_DATE) || defined(USE_HOSTCC)
/* mandatory / node 'timestamp' property */
if (fdt_getprop(fit, 0, FIT_TIMESTAMP_PROP, NULL) == NULL) {
debug("Wrong FIT format: no timestamp\n");
return 0;
}
#endif
/* mandatory subimages parent '/images' node */
if (fdt_path_offset(fit, FIT_IMAGES_PATH) < 0) {
debug("Wrong FIT format: no images parent node\n");
return 0;
}
return 1;
}
/**
* fit_conf_get_node - get node offset for configuration of a given unit name
* @fit: pointer to the FIT format image header
* @conf_uname: configuration node unit name
*
* fit_conf_get_node() finds a configuration (withing the '/configurations'
* parant node) of a provided unit name. If configuration is found its node offset
* is returned to the caller.
*
* When NULL is provided in second argument fit_conf_get_node() will search
* for a default configuration node instead. Default configuration node unit name
* is retrived from FIT_DEFAULT_PROP property of the '/configurations' node.
*
* returns:
* configuration node offset when found (>=0)
* negative number on failure (FDT_ERR_* code)
*/
int fit_conf_get_node(const void *fit, const char *conf_uname)
{
int noffset, confs_noffset;
int len;
confs_noffset = fdt_path_offset(fit, FIT_CONFS_PATH);
if (confs_noffset < 0) {
debug("Can't find configurations parent node '%s' (%s)\n",
FIT_CONFS_PATH, fdt_strerror(confs_noffset));
return confs_noffset;
}
if (conf_uname == NULL) {
/* get configuration unit name from the default property */
debug("No configuration specified, trying default...\n");
conf_uname = (char *)fdt_getprop(fit, confs_noffset,
FIT_DEFAULT_PROP, &len);
if (conf_uname == NULL) {
fit_get_debug(fit, confs_noffset, FIT_DEFAULT_PROP,
len);
return len;
}
debug("Found default configuration: '%s'\n", conf_uname);
}
noffset = fdt_subnode_offset(fit, confs_noffset, conf_uname);
if (noffset < 0) {
debug("Can't get node offset for configuration unit name: "
"'%s' (%s)\n",
conf_uname, fdt_strerror(noffset));
}
return noffset;
}
static int __fit_conf_get_prop_node(const void *fit, int noffset,
const char *prop_name)
{
char *uname;
int len;
/* get kernel image unit name from configuration kernel property */
uname = (char *)fdt_getprop(fit, noffset, prop_name, &len);
if (uname == NULL)
return len;
return fit_image_get_node(fit, uname);
}
/**
* fit_conf_get_kernel_node - get kernel image node offset that corresponds to
* a given configuration
* @fit: pointer to the FIT format image header
* @noffset: configuration node offset
*
* fit_conf_get_kernel_node() retrives kernel image node unit name from
* configuration FIT_KERNEL_PROP property and translates it to the node
* offset.
*
* returns:
* image node offset when found (>=0)
* negative number on failure (FDT_ERR_* code)
*/
int fit_conf_get_kernel_node(const void *fit, int noffset)
{
return __fit_conf_get_prop_node(fit, noffset, FIT_KERNEL_PROP);
}
/**
* fit_conf_get_ramdisk_node - get ramdisk image node offset that corresponds to
* a given configuration
* @fit: pointer to the FIT format image header
* @noffset: configuration node offset
*
* fit_conf_get_ramdisk_node() retrives ramdisk image node unit name from
* configuration FIT_KERNEL_PROP property and translates it to the node
* offset.
*
* returns:
* image node offset when found (>=0)
* negative number on failure (FDT_ERR_* code)
*/
int fit_conf_get_ramdisk_node(const void *fit, int noffset)
{
return __fit_conf_get_prop_node(fit, noffset, FIT_RAMDISK_PROP);
}
/**
* fit_conf_get_fdt_node - get fdt image node offset that corresponds to
* a given configuration
* @fit: pointer to the FIT format image header
* @noffset: configuration node offset
*
* fit_conf_get_fdt_node() retrives fdt image node unit name from
* configuration FIT_KERNEL_PROP property and translates it to the node
* offset.
*
* returns:
* image node offset when found (>=0)
* negative number on failure (FDT_ERR_* code)
*/
int fit_conf_get_fdt_node(const void *fit, int noffset)
{
return __fit_conf_get_prop_node(fit, noffset, FIT_FDT_PROP);
}
/**
* fit_conf_print - prints out the FIT configuration details
* @fit: pointer to the FIT format image header
* @noffset: offset of the configuration node
* @p: pointer to prefix string
*
* fit_conf_print() lists all mandatory properies for the processed
* configuration node.
*
* returns:
* no returned results
*/
void fit_conf_print(const void *fit, int noffset, const char *p)
{
char *desc;
char *uname;
int ret;
/* Mandatory properties */
ret = fit_get_desc(fit, noffset, &desc);
printf("%s Description: ", p);
if (ret)
printf("unavailable\n");
else
printf("%s\n", desc);
uname = (char *)fdt_getprop(fit, noffset, FIT_KERNEL_PROP, NULL);
printf("%s Kernel: ", p);
if (uname == NULL)
printf("unavailable\n");
else
printf("%s\n", uname);
/* Optional properties */
uname = (char *)fdt_getprop(fit, noffset, FIT_RAMDISK_PROP, NULL);
if (uname)
printf("%s Init Ramdisk: %s\n", p, uname);
uname = (char *)fdt_getprop(fit, noffset, FIT_FDT_PROP, NULL);
if (uname)
printf("%s FDT: %s\n", p, uname);
}
/**
* fit_check_ramdisk - verify FIT format ramdisk subimage
* @fit_hdr: pointer to the FIT ramdisk header
* @rd_noffset: ramdisk subimage node offset within FIT image
* @arch: requested ramdisk image architecture type
* @verify: data CRC verification flag
*
* fit_check_ramdisk() verifies integrity of the ramdisk subimage and from
* specified FIT image.
*
* returns:
* 1, on success
* 0, on failure
*/
#ifndef USE_HOSTCC
static int fit_check_ramdisk(const void *fit, int rd_noffset, uint8_t arch,
int verify)
{
fit_image_print(fit, rd_noffset, " ");
if (verify) {
puts(" Verifying Hash Integrity ... ");
if (!fit_image_check_hashes(fit, rd_noffset)) {
puts("Bad Data Hash\n");
show_boot_progress(-125);
return 0;
}
puts("OK\n");
}
show_boot_progress(126);
if (!fit_image_check_os(fit, rd_noffset, IH_OS_LINUX) ||
!fit_image_check_arch(fit, rd_noffset, arch) ||
!fit_image_check_type(fit, rd_noffset, IH_TYPE_RAMDISK)) {
printf("No Linux %s Ramdisk Image\n",
genimg_get_arch_name(arch));
show_boot_progress(-126);
return 0;
}
show_boot_progress(127);
return 1;
}
#endif /* USE_HOSTCC */
#endif /* CONFIG_FIT */
|
1001-study-uboot
|
common/image.c
|
C
|
gpl3
| 86,251
|
/*
* (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
*/
/*
* RTC, Date & Time support: get and set date & time
*/
#include <common.h>
#include <command.h>
#include <rtc.h>
#include <i2c.h>
DECLARE_GLOBAL_DATA_PTR;
static const char * const weekdays[] = {
"Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur",
};
#ifdef CONFIG_NEEDS_MANUAL_RELOC
#define RELOC(a) ((typeof(a))((unsigned long)(a) + gd->reloc_off))
#else
#define RELOC(a) a
#endif
int mk_date (const char *, struct rtc_time *);
int do_date (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
struct rtc_time tm;
int rcode = 0;
int old_bus;
/* switch to correct I2C bus */
old_bus = I2C_GET_BUS();
I2C_SET_BUS(CONFIG_SYS_RTC_BUS_NUM);
switch (argc) {
case 2: /* set date & time */
if (strcmp(argv[1],"reset") == 0) {
puts ("Reset RTC...\n");
rtc_reset ();
} else {
/* initialize tm with current time */
rcode = rtc_get (&tm);
if(!rcode) {
/* insert new date & time */
if (mk_date (argv[1], &tm) != 0) {
puts ("## Bad date format\n");
break;
}
/* and write to RTC */
rcode = rtc_set (&tm);
if(rcode)
puts("## Set date failed\n");
} else {
puts("## Get date failed\n");
}
}
/* FALL TROUGH */
case 1: /* get date & time */
rcode = rtc_get (&tm);
if (rcode) {
puts("## Get date failed\n");
break;
}
printf ("Date: %4d-%02d-%02d (%sday) Time: %2d:%02d:%02d\n",
tm.tm_year, tm.tm_mon, tm.tm_mday,
(tm.tm_wday<0 || tm.tm_wday>6) ?
"unknown " : RELOC(weekdays[tm.tm_wday]),
tm.tm_hour, tm.tm_min, tm.tm_sec);
break;
default:
cmd_usage(cmdtp);
rcode = 1;
}
/* switch back to original I2C bus */
I2C_SET_BUS(old_bus);
return rcode;
}
/*
* simple conversion of two-digit string with error checking
*/
static int cnvrt2 (const char *str, int *valp)
{
int val;
if ((*str < '0') || (*str > '9'))
return (-1);
val = *str - '0';
++str;
if ((*str < '0') || (*str > '9'))
return (-1);
*valp = 10 * val + (*str - '0');
return (0);
}
/*
* Convert date string: MMDDhhmm[[CC]YY][.ss]
*
* Some basic checking for valid values is done, but this will not catch
* all possible error conditions.
*/
int mk_date (const char *datestr, struct rtc_time *tmp)
{
int len, val;
char *ptr;
ptr = strchr (datestr,'.');
len = strlen (datestr);
/* Set seconds */
if (ptr) {
int sec;
*ptr++ = '\0';
if ((len - (ptr - datestr)) != 2)
return (-1);
len = strlen (datestr);
if (cnvrt2 (ptr, &sec))
return (-1);
tmp->tm_sec = sec;
} else {
tmp->tm_sec = 0;
}
if (len == 12) { /* MMDDhhmmCCYY */
int year, century;
if (cnvrt2 (datestr+ 8, ¢ury) ||
cnvrt2 (datestr+10, &year) ) {
return (-1);
}
tmp->tm_year = 100 * century + year;
} else if (len == 10) { /* MMDDhhmmYY */
int year, century;
century = tmp->tm_year / 100;
if (cnvrt2 (datestr+ 8, &year))
return (-1);
tmp->tm_year = 100 * century + year;
}
switch (len) {
case 8: /* MMDDhhmm */
/* fall thru */
case 10: /* MMDDhhmmYY */
/* fall thru */
case 12: /* MMDDhhmmCCYY */
if (cnvrt2 (datestr+0, &val) ||
val > 12) {
break;
}
tmp->tm_mon = val;
if (cnvrt2 (datestr+2, &val) ||
val > ((tmp->tm_mon==2) ? 29 : 31)) {
break;
}
tmp->tm_mday = val;
if (cnvrt2 (datestr+4, &val) ||
val > 23) {
break;
}
tmp->tm_hour = val;
if (cnvrt2 (datestr+6, &val) ||
val > 59) {
break;
}
tmp->tm_min = val;
/* calculate day of week */
GregorianDay (tmp);
return (0);
default:
break;
}
return (-1);
}
/***************************************************/
U_BOOT_CMD(
date, 2, 1, do_date,
"get/set/reset date & time",
"[MMDDhhmm[[CC]YY][.ss]]\ndate reset\n"
" - without arguments: print date & time\n"
" - with numeric argument: set the system date & time\n"
" - with 'reset' argument: reset the RTC"
);
|
1001-study-uboot
|
common/cmd_date.c
|
C
|
gpl3
| 4,740
|
/*
* (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
*/
/*
* This provides a bit-banged interface to the ethernet MII management
* channel.
*/
#include <common.h>
#include <miiphy.h>
#include <phy.h>
#include <asm/types.h>
#include <linux/list.h>
#include <malloc.h>
#include <net.h>
/* local debug macro */
#undef MII_DEBUG
#undef debug
#ifdef MII_DEBUG
#define debug(fmt, args...) printf(fmt, ##args)
#else
#define debug(fmt, args...)
#endif /* MII_DEBUG */
static struct list_head mii_devs;
static struct mii_dev *current_mii;
/*
* Lookup the mii_dev struct by the registered device name.
*/
struct mii_dev *miiphy_get_dev_by_name(const char *devname)
{
struct list_head *entry;
struct mii_dev *dev;
if (!devname) {
printf("NULL device name!\n");
return NULL;
}
list_for_each(entry, &mii_devs) {
dev = list_entry(entry, struct mii_dev, link);
if (strcmp(dev->name, devname) == 0)
return dev;
}
return NULL;
}
/*****************************************************************************
*
* Initialize global data. Need to be called before any other miiphy routine.
*/
void miiphy_init(void)
{
INIT_LIST_HEAD(&mii_devs);
current_mii = NULL;
}
static int legacy_miiphy_read(struct mii_dev *bus, int addr, int devad, int reg)
{
unsigned short val;
int ret;
struct legacy_mii_dev *ldev = bus->priv;
ret = ldev->read(bus->name, addr, reg, &val);
return ret ? -1 : (int)val;
}
static int legacy_miiphy_write(struct mii_dev *bus, int addr, int devad,
int reg, u16 val)
{
struct legacy_mii_dev *ldev = bus->priv;
return ldev->write(bus->name, addr, reg, val);
}
/*****************************************************************************
*
* Register read and write MII access routines for the device <name>.
* This API is now deprecated. Please use mdio_alloc and mdio_register, instead.
*/
void miiphy_register(const char *name,
int (*read)(const char *devname, unsigned char addr,
unsigned char reg, unsigned short *value),
int (*write)(const char *devname, unsigned char addr,
unsigned char reg, unsigned short value))
{
struct mii_dev *new_dev;
struct legacy_mii_dev *ldev;
BUG_ON(strlen(name) >= MDIO_NAME_LEN);
/* check if we have unique name */
new_dev = miiphy_get_dev_by_name(name);
if (new_dev) {
printf("miiphy_register: non unique device name '%s'\n", name);
return;
}
/* allocate memory */
new_dev = mdio_alloc();
ldev = malloc(sizeof(*ldev));
if (new_dev == NULL || ldev == NULL) {
printf("miiphy_register: cannot allocate memory for '%s'\n",
name);
return;
}
/* initalize mii_dev struct fields */
new_dev->read = legacy_miiphy_read;
new_dev->write = legacy_miiphy_write;
strncpy(new_dev->name, name, MDIO_NAME_LEN);
new_dev->name[MDIO_NAME_LEN - 1] = 0;
ldev->read = read;
ldev->write = write;
new_dev->priv = ldev;
debug("miiphy_register: added '%s', read=0x%08lx, write=0x%08lx\n",
new_dev->name, ldev->read, ldev->write);
/* add it to the list */
list_add_tail(&new_dev->link, &mii_devs);
if (!current_mii)
current_mii = new_dev;
}
struct mii_dev *mdio_alloc(void)
{
struct mii_dev *bus;
bus = malloc(sizeof(*bus));
if (!bus)
return bus;
memset(bus, 0, sizeof(*bus));
/* initalize mii_dev struct fields */
INIT_LIST_HEAD(&bus->link);
return bus;
}
int mdio_register(struct mii_dev *bus)
{
if (!bus || !bus->name || !bus->read || !bus->write)
return -1;
/* check if we have unique name */
if (miiphy_get_dev_by_name(bus->name)) {
printf("mdio_register: non unique device name '%s'\n",
bus->name);
return -1;
}
/* add it to the list */
list_add_tail(&bus->link, &mii_devs);
if (!current_mii)
current_mii = bus;
return 0;
}
void mdio_list_devices(void)
{
struct list_head *entry;
list_for_each(entry, &mii_devs) {
int i;
struct mii_dev *bus = list_entry(entry, struct mii_dev, link);
printf("%s:\n", bus->name);
for (i = 0; i < PHY_MAX_ADDR; i++) {
struct phy_device *phydev = bus->phymap[i];
if (phydev) {
printf("%d - %s", i, phydev->drv->name);
if (phydev->dev)
printf(" <--> %s\n", phydev->dev->name);
else
printf("\n");
}
}
}
}
int miiphy_set_current_dev(const char *devname)
{
struct mii_dev *dev;
dev = miiphy_get_dev_by_name(devname);
if (dev) {
current_mii = dev;
return 0;
}
printf("No such device: %s\n", devname);
return 1;
}
struct mii_dev *mdio_get_current_dev(void)
{
return current_mii;
}
struct phy_device *mdio_phydev_for_ethname(const char *ethname)
{
struct list_head *entry;
struct mii_dev *bus;
list_for_each(entry, &mii_devs) {
int i;
bus = list_entry(entry, struct mii_dev, link);
for (i = 0; i < PHY_MAX_ADDR; i++) {
if (!bus->phymap[i] || !bus->phymap[i]->dev)
continue;
if (strcmp(bus->phymap[i]->dev->name, ethname) == 0)
return bus->phymap[i];
}
}
printf("%s is not a known ethernet\n", ethname);
return NULL;
}
const char *miiphy_get_current_dev(void)
{
if (current_mii)
return current_mii->name;
return NULL;
}
static struct mii_dev *miiphy_get_active_dev(const char *devname)
{
/* If the current mii is the one we want, return it */
if (current_mii)
if (strcmp(current_mii->name, devname) == 0)
return current_mii;
/* Otherwise, set the active one to the one we want */
if (miiphy_set_current_dev(devname))
return NULL;
else
return current_mii;
}
/*****************************************************************************
*
* Read to variable <value> from the PHY attached to device <devname>,
* use PHY address <addr> and register <reg>.
*
* This API is deprecated. Use phy_read on a phy_device found via phy_connect
*
* Returns:
* 0 on success
*/
int miiphy_read(const char *devname, unsigned char addr, unsigned char reg,
unsigned short *value)
{
struct mii_dev *bus;
int ret;
bus = miiphy_get_active_dev(devname);
if (!bus)
return 1;
ret = bus->read(bus, addr, MDIO_DEVAD_NONE, reg);
if (ret < 0)
return 1;
*value = (unsigned short)ret;
return 0;
}
/*****************************************************************************
*
* Write <value> to the PHY attached to device <devname>,
* use PHY address <addr> and register <reg>.
*
* This API is deprecated. Use phy_write on a phy_device found by phy_connect
*
* Returns:
* 0 on success
*/
int miiphy_write(const char *devname, unsigned char addr, unsigned char reg,
unsigned short value)
{
struct mii_dev *bus;
bus = miiphy_get_active_dev(devname);
if (bus)
return bus->write(bus, addr, MDIO_DEVAD_NONE, reg, value);
return 1;
}
/*****************************************************************************
*
* Print out list of registered MII capable devices.
*/
void miiphy_listdev(void)
{
struct list_head *entry;
struct mii_dev *dev;
puts("MII devices: ");
list_for_each(entry, &mii_devs) {
dev = list_entry(entry, struct mii_dev, link);
printf("'%s' ", dev->name);
}
puts("\n");
if (current_mii)
printf("Current device: '%s'\n", current_mii->name);
}
/*****************************************************************************
*
* Read the OUI, manufacture's model number, and revision number.
*
* OUI: 22 bits (unsigned int)
* Model: 6 bits (unsigned char)
* Revision: 4 bits (unsigned char)
*
* This API is deprecated.
*
* Returns:
* 0 on success
*/
int miiphy_info(const char *devname, unsigned char addr, unsigned int *oui,
unsigned char *model, unsigned char *rev)
{
unsigned int reg = 0;
unsigned short tmp;
if (miiphy_read(devname, addr, MII_PHYSID2, &tmp) != 0) {
debug("PHY ID register 2 read failed\n");
return -1;
}
reg = tmp;
debug("MII_PHYSID2 @ 0x%x = 0x%04x\n", addr, reg);
if (reg == 0xFFFF) {
/* No physical device present at this address */
return -1;
}
if (miiphy_read(devname, addr, MII_PHYSID1, &tmp) != 0) {
debug("PHY ID register 1 read failed\n");
return -1;
}
reg |= tmp << 16;
debug("PHY_PHYIDR[1,2] @ 0x%x = 0x%08x\n", addr, reg);
*oui = (reg >> 10);
*model = (unsigned char)((reg >> 4) & 0x0000003F);
*rev = (unsigned char)(reg & 0x0000000F);
return 0;
}
#ifndef CONFIG_PHYLIB
/*****************************************************************************
*
* Reset the PHY.
*
* This API is deprecated. Use PHYLIB.
*
* Returns:
* 0 on success
*/
int miiphy_reset(const char *devname, unsigned char addr)
{
unsigned short reg;
int timeout = 500;
if (miiphy_read(devname, addr, MII_BMCR, ®) != 0) {
debug("PHY status read failed\n");
return -1;
}
if (miiphy_write(devname, addr, MII_BMCR, reg | BMCR_RESET) != 0) {
debug("PHY reset failed\n");
return -1;
}
#ifdef CONFIG_PHY_RESET_DELAY
udelay(CONFIG_PHY_RESET_DELAY); /* Intel LXT971A needs this */
#endif
/*
* Poll the control register for the reset bit to go to 0 (it is
* auto-clearing). This should happen within 0.5 seconds per the
* IEEE spec.
*/
reg = 0x8000;
while (((reg & 0x8000) != 0) && timeout--) {
if (miiphy_read(devname, addr, MII_BMCR, ®) != 0) {
debug("PHY status read failed\n");
return -1;
}
udelay(1000);
}
if ((reg & 0x8000) == 0) {
return 0;
} else {
puts("PHY reset timed out\n");
return -1;
}
return 0;
}
#endif /* !PHYLIB */
/*****************************************************************************
*
* Determine the ethernet speed (10/100/1000). Return 10 on error.
*/
int miiphy_speed(const char *devname, unsigned char addr)
{
u16 bmcr, anlpar;
#if defined(CONFIG_PHY_GIGE)
u16 btsr;
/*
* Check for 1000BASE-X. If it is supported, then assume that the speed
* is 1000.
*/
if (miiphy_is_1000base_x(devname, addr))
return _1000BASET;
/*
* No 1000BASE-X, so assume 1000BASE-T/100BASE-TX/10BASE-T register set.
*/
/* Check for 1000BASE-T. */
if (miiphy_read(devname, addr, MII_STAT1000, &btsr)) {
printf("PHY 1000BT status");
goto miiphy_read_failed;
}
if (btsr != 0xFFFF &&
(btsr & (PHY_1000BTSR_1000FD | PHY_1000BTSR_1000HD)))
return _1000BASET;
#endif /* CONFIG_PHY_GIGE */
/* Check Basic Management Control Register first. */
if (miiphy_read(devname, addr, MII_BMCR, &bmcr)) {
printf("PHY speed");
goto miiphy_read_failed;
}
/* Check if auto-negotiation is on. */
if (bmcr & BMCR_ANENABLE) {
/* Get auto-negotiation results. */
if (miiphy_read(devname, addr, MII_LPA, &anlpar)) {
printf("PHY AN speed");
goto miiphy_read_failed;
}
return (anlpar & LPA_100) ? _100BASET : _10BASET;
}
/* Get speed from basic control settings. */
return (bmcr & BMCR_SPEED100) ? _100BASET : _10BASET;
miiphy_read_failed:
printf(" read failed, assuming 10BASE-T\n");
return _10BASET;
}
/*****************************************************************************
*
* Determine full/half duplex. Return half on error.
*/
int miiphy_duplex(const char *devname, unsigned char addr)
{
u16 bmcr, anlpar;
#if defined(CONFIG_PHY_GIGE)
u16 btsr;
/* Check for 1000BASE-X. */
if (miiphy_is_1000base_x(devname, addr)) {
/* 1000BASE-X */
if (miiphy_read(devname, addr, MII_LPA, &anlpar)) {
printf("1000BASE-X PHY AN duplex");
goto miiphy_read_failed;
}
}
/*
* No 1000BASE-X, so assume 1000BASE-T/100BASE-TX/10BASE-T register set.
*/
/* Check for 1000BASE-T. */
if (miiphy_read(devname, addr, MII_STAT1000, &btsr)) {
printf("PHY 1000BT status");
goto miiphy_read_failed;
}
if (btsr != 0xFFFF) {
if (btsr & PHY_1000BTSR_1000FD) {
return FULL;
} else if (btsr & PHY_1000BTSR_1000HD) {
return HALF;
}
}
#endif /* CONFIG_PHY_GIGE */
/* Check Basic Management Control Register first. */
if (miiphy_read(devname, addr, MII_BMCR, &bmcr)) {
puts("PHY duplex");
goto miiphy_read_failed;
}
/* Check if auto-negotiation is on. */
if (bmcr & BMCR_ANENABLE) {
/* Get auto-negotiation results. */
if (miiphy_read(devname, addr, MII_LPA, &anlpar)) {
puts("PHY AN duplex");
goto miiphy_read_failed;
}
return (anlpar & (LPA_10FULL | LPA_100FULL)) ?
FULL : HALF;
}
/* Get speed from basic control settings. */
return (bmcr & BMCR_FULLDPLX) ? FULL : HALF;
miiphy_read_failed:
printf(" read failed, assuming half duplex\n");
return HALF;
}
/*****************************************************************************
*
* Return 1 if PHY supports 1000BASE-X, 0 if PHY supports 10BASE-T/100BASE-TX/
* 1000BASE-T, or on error.
*/
int miiphy_is_1000base_x(const char *devname, unsigned char addr)
{
#if defined(CONFIG_PHY_GIGE)
u16 exsr;
if (miiphy_read(devname, addr, MII_ESTATUS, &exsr)) {
printf("PHY extended status read failed, assuming no "
"1000BASE-X\n");
return 0;
}
return 0 != (exsr & (ESTATUS_1000XF | ESTATUS_1000XH));
#else
return 0;
#endif
}
#ifdef CONFIG_SYS_FAULT_ECHO_LINK_DOWN
/*****************************************************************************
*
* Determine link status
*/
int miiphy_link(const char *devname, unsigned char addr)
{
unsigned short reg;
/* dummy read; needed to latch some phys */
(void)miiphy_read(devname, addr, MII_BMSR, ®);
if (miiphy_read(devname, addr, MII_BMSR, ®)) {
puts("MII_BMSR read failed, assuming no link\n");
return 0;
}
/* Determine if a link is active */
if ((reg & BMSR_LSTATUS) != 0) {
return 1;
} else {
return 0;
}
}
#endif
|
1001-study-uboot
|
common/miiphyutil.c
|
C
|
gpl3
| 14,096
|
/*
* (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.
*
* $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)
*
*/
/*
* JFFS2/CRAMFS support
*/
#include <common.h>
#include <command.h>
#include <malloc.h>
#include <jffs2/jffs2.h>
#include <linux/list.h>
#include <linux/ctype.h>
#include <cramfs/cramfs_fs.h>
#if defined(CONFIG_CMD_NAND)
#include <linux/mtd/nand.h>
#include <nand.h>
#endif
#if defined(CONFIG_CMD_ONENAND)
#include <linux/mtd/mtd.h>
#include <linux/mtd/onenand.h>
#include <onenand_uboot.h>
#endif
/* enable/disable debugging messages */
#define DEBUG_JFFS
#undef DEBUG_JFFS
#ifdef DEBUG_JFFS
# define DEBUGF(fmt, args...) printf(fmt ,##args)
#else
# define DEBUGF(fmt, args...)
#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
/* current active device and partition number */
#ifdef CONFIG_CMD_MTDPARTS
/* Use the ones declared in cmd_mtdparts.c */
extern struct mtd_device *current_mtd_dev;
extern u8 current_mtd_partnum;
#else
/* Use local ones */
struct mtd_device *current_mtd_dev = NULL;
u8 current_mtd_partnum = 0;
#endif
#if defined(CONFIG_CMD_CRAMFS)
extern int cramfs_check (struct part_info *info);
extern int cramfs_load (char *loadoffset, struct part_info *info, char *filename);
extern int cramfs_ls (struct part_info *info, char *filename);
extern int cramfs_info (struct part_info *info);
#else
/* defining empty macros for function names is ugly but avoids ifdef clutter
* all over the code */
#define cramfs_check(x) (0)
#define cramfs_load(x,y,z) (-1)
#define cramfs_ls(x,y) (0)
#define cramfs_info(x) (0)
#endif
#ifndef CONFIG_CMD_MTDPARTS
/**
* Check device number to be within valid range for given device type.
*
* @param dev device to validate
* @return 0 if device is valid, 1 otherwise
*/
static int mtd_device_validate(u8 type, u8 num, u32 *size)
{
if (type == MTD_DEV_TYPE_NOR) {
#if defined(CONFIG_CMD_FLASH)
if (num < CONFIG_SYS_MAX_FLASH_BANKS) {
extern flash_info_t flash_info[];
*size = flash_info[num].size;
return 0;
}
printf("no such FLASH device: %s%d (valid range 0 ... %d\n",
MTD_DEV_TYPE(type), num, CONFIG_SYS_MAX_FLASH_BANKS - 1);
#else
printf("support for FLASH devices not present\n");
#endif
} else if (type == MTD_DEV_TYPE_NAND) {
#if defined(CONFIG_JFFS2_NAND) && defined(CONFIG_CMD_NAND)
if (num < CONFIG_SYS_MAX_NAND_DEVICE) {
*size = nand_info[num].size;
return 0;
}
printf("no such NAND device: %s%d (valid range 0 ... %d)\n",
MTD_DEV_TYPE(type), num, CONFIG_SYS_MAX_NAND_DEVICE - 1);
#else
printf("support for NAND devices not present\n");
#endif
} else if (type == MTD_DEV_TYPE_ONENAND) {
#if defined(CONFIG_CMD_ONENAND)
*size = onenand_mtd.size;
return 0;
#else
printf("support for OneNAND devices not present\n");
#endif
} else
printf("Unknown defice type %d\n", type);
return 1;
}
/**
* 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
*/
static 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;
}
/*
* 'Static' version of command line mtdparts_init() routine. Single partition on
* a single device configuration.
*/
/**
* Calculate sector size.
*
* @return sector size
*/
static inline u32 get_part_sector_size_nand(struct mtdids *id)
{
#if defined(CONFIG_JFFS2_NAND) && defined(CONFIG_CMD_NAND)
nand_info_t *nand;
nand = &nand_info[id->num];
return nand->erasesize;
#else
BUG();
return 0;
#endif
}
static inline u32 get_part_sector_size_nor(struct mtdids *id, struct part_info *part)
{
#if defined(CONFIG_CMD_FLASH)
extern flash_info_t flash_info[];
u32 end_phys, start_phys, sector_size = 0, size = 0;
int i;
flash_info_t *flash;
flash = &flash_info[id->num];
start_phys = flash->start[0] + part->offset;
end_phys = start_phys + part->size - 1;
for (i = 0; i < flash->sector_count; i++) {
if (flash->start[i] >= end_phys)
break;
if (flash->start[i] >= start_phys) {
if (i == flash->sector_count - 1) {
size = flash->start[0] + flash->size - flash->start[i];
} else {
size = flash->start[i+1] - flash->start[i];
}
if (sector_size < size)
sector_size = size;
}
}
return sector_size;
#else
BUG();
return 0;
#endif
}
static inline u32 get_part_sector_size_onenand(void)
{
#if defined(CONFIG_CMD_ONENAND)
struct mtd_info *mtd;
mtd = &onenand_mtd;
return mtd->erasesize;
#else
BUG();
return 0;
#endif
}
static inline u32 get_part_sector_size(struct mtdids *id, struct part_info *part)
{
if (id->type == MTD_DEV_TYPE_NAND)
return get_part_sector_size_nand(id);
else if (id->type == MTD_DEV_TYPE_NOR)
return get_part_sector_size_nor(id, part);
else if (id->type == MTD_DEV_TYPE_ONENAND)
return get_part_sector_size_onenand();
else
DEBUGF("Error: Unknown device type.\n");
return 0;
}
/**
* Parse and initialize global mtdids mapping and create global
* device/partition list.
*
* 'Static' version of command line mtdparts_init() routine. Single partition on
* a single device configuration.
*
* @return 0 on success, 1 otherwise
*/
int mtdparts_init(void)
{
static int initialized = 0;
u32 size;
char *dev_name;
DEBUGF("\n---mtdparts_init---\n");
if (!initialized) {
struct mtdids *id;
struct part_info *part;
initialized = 1;
current_mtd_dev = (struct mtd_device *)
malloc(sizeof(struct mtd_device) +
sizeof(struct part_info) +
sizeof(struct mtdids));
if (!current_mtd_dev) {
printf("out of memory\n");
return 1;
}
memset(current_mtd_dev, 0, sizeof(struct mtd_device) +
sizeof(struct part_info) + sizeof(struct mtdids));
id = (struct mtdids *)(current_mtd_dev + 1);
part = (struct part_info *)(id + 1);
/* id */
id->mtd_id = "single part";
#if defined(CONFIG_JFFS2_DEV)
dev_name = CONFIG_JFFS2_DEV;
#else
dev_name = "nor0";
#endif
if ((mtd_id_parse(dev_name, NULL, &id->type, &id->num) != 0) ||
(mtd_device_validate(id->type, id->num, &size) != 0)) {
printf("incorrect device: %s%d\n", MTD_DEV_TYPE(id->type), id->num);
free(current_mtd_dev);
return 1;
}
id->size = size;
INIT_LIST_HEAD(&id->link);
DEBUGF("dev id: type = %d, num = %d, size = 0x%08lx, mtd_id = %s\n",
id->type, id->num, id->size, id->mtd_id);
/* partition */
part->name = "static";
part->auto_name = 0;
#if defined(CONFIG_JFFS2_PART_SIZE)
part->size = CONFIG_JFFS2_PART_SIZE;
#else
part->size = SIZE_REMAINING;
#endif
#if defined(CONFIG_JFFS2_PART_OFFSET)
part->offset = CONFIG_JFFS2_PART_OFFSET;
#else
part->offset = 0x00000000;
#endif
part->dev = current_mtd_dev;
INIT_LIST_HEAD(&part->link);
/* recalculate size if needed */
if (part->size == SIZE_REMAINING)
part->size = id->size - part->offset;
part->sector_size = get_part_sector_size(id, part);
DEBUGF("part : name = %s, size = 0x%08lx, offset = 0x%08lx\n",
part->name, part->size, part->offset);
/* device */
current_mtd_dev->id = id;
INIT_LIST_HEAD(¤t_mtd_dev->link);
current_mtd_dev->num_parts = 1;
INIT_LIST_HEAD(¤t_mtd_dev->parts);
list_add(&part->link, ¤t_mtd_dev->parts);
}
return 0;
}
#endif /* #ifndef CONFIG_CMD_MTDPARTS */
/**
* 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* jffs2_part_info(struct mtd_device *dev, unsigned int part_num)
{
struct list_head *entry;
struct part_info *part;
int num;
if (!dev)
return NULL;
DEBUGF("\n--- jffs2_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 */
/***************************************************/
/**
* Routine implementing fsload u-boot command. This routine tries to load
* a requested file from jffs2/cramfs filesystem on a current partition.
*
* @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_jffs2_fsload(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *fsname;
char *filename;
int size;
struct part_info *part;
ulong offset = load_addr;
/* pre-set Boot file name */
if ((filename = getenv("bootfile")) == NULL) {
filename = "uImage";
}
if (argc == 2) {
filename = argv[1];
}
if (argc == 3) {
offset = simple_strtoul(argv[1], NULL, 16);
load_addr = offset;
filename = argv[2];
}
/* make sure we are in sync with env variables */
if (mtdparts_init() !=0)
return 1;
if ((part = jffs2_part_info(current_mtd_dev, current_mtd_partnum))){
/* check partition type for cramfs */
fsname = (cramfs_check(part) ? "CRAMFS" : "JFFS2");
printf("### %s loading '%s' to 0x%lx\n", fsname, filename, offset);
if (cramfs_check(part)) {
size = cramfs_load ((char *) offset, part, filename);
} else {
/* if this is not cramfs assume jffs2 */
size = jffs2_1pass_load((char *)offset, part, filename);
}
if (size > 0) {
char buf[10];
printf("### %s load complete: %d bytes loaded to 0x%lx\n",
fsname, size, offset);
sprintf(buf, "%x", size);
setenv("filesize", buf);
} else {
printf("### %s LOAD ERROR<%x> for %s!\n", fsname, size, filename);
}
return !(size > 0);
}
return 1;
}
/**
* Routine implementing u-boot ls command which lists content of a given
* directory on a current partition.
*
* @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_jffs2_ls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = "/";
int ret;
struct part_info *part;
if (argc == 2)
filename = argv[1];
/* make sure we are in sync with env variables */
if (mtdparts_init() !=0)
return 1;
if ((part = jffs2_part_info(current_mtd_dev, current_mtd_partnum))){
/* check partition type for cramfs */
if (cramfs_check(part)) {
ret = cramfs_ls (part, filename);
} else {
/* if this is not cramfs assume jffs2 */
ret = jffs2_1pass_ls(part, filename);
}
return ret ? 0 : 1;
}
return 1;
}
/**
* Routine implementing u-boot fsinfo command. This routine prints out
* miscellaneous filesystem informations/statistics.
*
* @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_jffs2_fsinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
struct part_info *part;
char *fsname;
int ret;
/* make sure we are in sync with env variables */
if (mtdparts_init() !=0)
return 1;
if ((part = jffs2_part_info(current_mtd_dev, current_mtd_partnum))){
/* check partition type for cramfs */
fsname = (cramfs_check(part) ? "CRAMFS" : "JFFS2");
printf("### filesystem type is %s\n", fsname);
if (cramfs_check(part)) {
ret = cramfs_info (part);
} else {
/* if this is not cramfs assume jffs2 */
ret = jffs2_1pass_info(part);
}
return ret ? 0 : 1;
}
return 1;
}
/***************************************************/
U_BOOT_CMD(
fsload, 3, 0, do_jffs2_fsload,
"load binary file from a filesystem image",
"[ off ] [ filename ]\n"
" - load binary file from flash bank\n"
" with offset 'off'"
);
U_BOOT_CMD(
ls, 2, 1, do_jffs2_ls,
"list files in a directory (default /)",
"[ directory ]"
);
U_BOOT_CMD(
fsinfo, 1, 1, do_jffs2_fsinfo,
"print information about filesystems",
""
);
/***************************************************/
|
1001-study-uboot
|
common/cmd_jffs2.c
|
C
|
gpl3
| 16,335
|
/*
* Control GPIO pins on the fly
*
* Copyright (c) 2008-2011 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <common.h>
#include <command.h>
#include <asm/gpio.h>
#ifndef name_to_gpio
#define name_to_gpio(name) simple_strtoul(name, NULL, 10)
#endif
enum gpio_cmd {
GPIO_INPUT,
GPIO_SET,
GPIO_CLEAR,
GPIO_TOGGLE,
};
static int do_gpio(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int gpio;
enum gpio_cmd sub_cmd;
ulong value;
const char *str_cmd, *str_gpio;
#ifdef gpio_status
if (argc == 2 && !strcmp(argv[1], "status")) {
gpio_status();
return 0;
}
#endif
if (argc != 3)
show_usage:
return cmd_usage(cmdtp);
str_cmd = argv[1];
str_gpio = argv[2];
/* parse the behavior */
switch (*str_cmd) {
case 'i': sub_cmd = GPIO_INPUT; break;
case 's': sub_cmd = GPIO_SET; break;
case 'c': sub_cmd = GPIO_CLEAR; break;
case 't': sub_cmd = GPIO_TOGGLE; break;
default: goto show_usage;
}
/* turn the gpio name into a gpio number */
gpio = name_to_gpio(str_gpio);
if (gpio < 0)
goto show_usage;
/* grab the pin before we tweak it */
if (gpio_request(gpio, "cmd_gpio")) {
printf("gpio: requesting pin %u failed\n", gpio);
return -1;
}
/* finally, let's do it: set direction and exec command */
if (sub_cmd == GPIO_INPUT) {
gpio_direction_input(gpio);
value = gpio_get_value(gpio);
} else {
switch (sub_cmd) {
case GPIO_SET: value = 1; break;
case GPIO_CLEAR: value = 0; break;
case GPIO_TOGGLE: value = !gpio_get_value(gpio); break;
default: goto show_usage;
}
gpio_direction_output(gpio, value);
}
printf("gpio: pin %s (gpio %i) value is %lu\n",
str_gpio, gpio, value);
gpio_free(gpio);
return value;
}
U_BOOT_CMD(gpio, 3, 0, do_gpio,
"input/set/clear/toggle gpio pins",
"<input|set|clear|toggle> <pin>\n"
" - input/set/clear/toggle the specified pin");
|
1001-study-uboot
|
common/cmd_gpio.c
|
C
|
gpl3
| 1,902
|
/*
* (C) Copyright 2000-2010
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2008
* Stuart Wood, Lab X Technologies <stuart.wood@labxtechnologies.com>
*
* (C) Copyright 2004
* Jian Zhang, Texas Instruments, jzhang@ti.com.
*
* (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 <malloc.h>
#include <nand.h>
#include <search.h>
#include <errno.h>
#if defined(CONFIG_CMD_SAVEENV) && defined(CONFIG_CMD_NAND)
#define CMD_SAVEENV
#elif defined(CONFIG_ENV_OFFSET_REDUND)
#error CONFIG_ENV_OFFSET_REDUND must have CONFIG_CMD_SAVEENV & CONFIG_CMD_NAND
#endif
#if defined(CONFIG_ENV_SIZE_REDUND) && \
(CONFIG_ENV_SIZE_REDUND != CONFIG_ENV_SIZE)
#error CONFIG_ENV_SIZE_REDUND should be the same as CONFIG_ENV_SIZE
#endif
#ifndef CONFIG_ENV_RANGE
#define CONFIG_ENV_RANGE CONFIG_ENV_SIZE
#endif
char *env_name_spec = "NAND";
#if defined(ENV_IS_EMBEDDED)
env_t *env_ptr = &environment;
#elif defined(CONFIG_NAND_ENV_DST)
env_t *env_ptr = (env_t *)CONFIG_NAND_ENV_DST;
#else /* ! ENV_IS_EMBEDDED */
env_t *env_ptr;
#endif /* ENV_IS_EMBEDDED */
DECLARE_GLOBAL_DATA_PTR;
uchar env_get_char_spec(int index)
{
return *((uchar *)(gd->env_addr + index));
}
/*
* This is called before nand_init() so we can't read NAND to
* validate env data.
*
* Mark it OK for now. env_relocate() in env_common.c will call our
* relocate function which does the real validation.
*
* When using a NAND boot image (like sequoia_nand), the environment
* can be embedded or attached to the U-Boot image in NAND flash.
* This way the SPL loads not only the U-Boot image from NAND but
* also the environment.
*/
int env_init(void)
{
#if defined(ENV_IS_EMBEDDED) || defined(CONFIG_NAND_ENV_DST)
int crc1_ok = 0, crc2_ok = 0;
env_t *tmp_env1;
#ifdef CONFIG_ENV_OFFSET_REDUND
env_t *tmp_env2;
tmp_env2 = (env_t *)((ulong)env_ptr + CONFIG_ENV_SIZE);
crc2_ok = crc32(0, tmp_env2->data, ENV_SIZE) == tmp_env2->crc;
#endif
tmp_env1 = env_ptr;
crc1_ok = crc32(0, tmp_env1->data, ENV_SIZE) == tmp_env1->crc;
if (!crc1_ok && !crc2_ok) {
gd->env_addr = 0;
gd->env_valid = 0;
return 0;
} else if (crc1_ok && !crc2_ok) {
gd->env_valid = 1;
}
#ifdef CONFIG_ENV_OFFSET_REDUND
else if (!crc1_ok && crc2_ok) {
gd->env_valid = 2;
} else {
/* both ok - check serial */
if (tmp_env1->flags == 255 && tmp_env2->flags == 0)
gd->env_valid = 2;
else if (tmp_env2->flags == 255 && tmp_env1->flags == 0)
gd->env_valid = 1;
else if (tmp_env1->flags > tmp_env2->flags)
gd->env_valid = 1;
else if (tmp_env2->flags > tmp_env1->flags)
gd->env_valid = 2;
else /* flags are equal - almost impossible */
gd->env_valid = 1;
}
if (gd->env_valid == 2)
env_ptr = tmp_env2;
else
#endif
if (gd->env_valid == 1)
env_ptr = tmp_env1;
gd->env_addr = (ulong)env_ptr->data;
#else /* ENV_IS_EMBEDDED || CONFIG_NAND_ENV_DST */
gd->env_addr = (ulong)&default_environment[0];
gd->env_valid = 1;
#endif /* ENV_IS_EMBEDDED || CONFIG_NAND_ENV_DST */
return 0;
}
#ifdef CMD_SAVEENV
/*
* The legacy NAND code saved the environment in the first NAND device i.e.,
* nand_dev_desc + 0. This is also the behaviour using the new NAND code.
*/
int writeenv(size_t offset, u_char *buf)
{
size_t end = offset + CONFIG_ENV_RANGE;
size_t amount_saved = 0;
size_t blocksize, len;
u_char *char_ptr;
blocksize = nand_info[0].erasesize;
len = min(blocksize, CONFIG_ENV_SIZE);
while (amount_saved < CONFIG_ENV_SIZE && offset < end) {
if (nand_block_isbad(&nand_info[0], offset)) {
offset += blocksize;
} else {
char_ptr = &buf[amount_saved];
if (nand_write(&nand_info[0], offset, &len, char_ptr))
return 1;
offset += blocksize;
amount_saved += len;
}
}
if (amount_saved != CONFIG_ENV_SIZE)
return 1;
return 0;
}
#ifdef CONFIG_ENV_OFFSET_REDUND
static unsigned char env_flags;
int saveenv(void)
{
env_t env_new;
ssize_t len;
char *res;
int ret = 0;
nand_erase_options_t nand_erase_options;
memset(&nand_erase_options, 0, sizeof(nand_erase_options));
nand_erase_options.length = CONFIG_ENV_RANGE;
if (CONFIG_ENV_RANGE < CONFIG_ENV_SIZE)
return 1;
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);
env_new.flags = ++env_flags; /* increase the serial */
if (gd->env_valid == 1) {
puts("Erasing redundant NAND...\n");
nand_erase_options.offset = CONFIG_ENV_OFFSET_REDUND;
if (nand_erase_opts(&nand_info[0], &nand_erase_options))
return 1;
puts("Writing to redundant NAND... ");
ret = writeenv(CONFIG_ENV_OFFSET_REDUND, (u_char *)&env_new);
} else {
puts("Erasing NAND...\n");
nand_erase_options.offset = CONFIG_ENV_OFFSET;
if (nand_erase_opts(&nand_info[0], &nand_erase_options))
return 1;
puts("Writing to NAND... ");
ret = writeenv(CONFIG_ENV_OFFSET, (u_char *)&env_new);
}
if (ret) {
puts("FAILED!\n");
return 1;
}
puts("done\n");
gd->env_valid = gd->env_valid == 2 ? 1 : 2;
return ret;
}
#else /* ! CONFIG_ENV_OFFSET_REDUND */
int saveenv(void)
{
int ret = 0;
env_t env_new;
ssize_t len;
char *res;
nand_erase_options_t nand_erase_options;
memset(&nand_erase_options, 0, sizeof(nand_erase_options));
nand_erase_options.length = CONFIG_ENV_RANGE;
nand_erase_options.offset = CONFIG_ENV_OFFSET;
if (CONFIG_ENV_RANGE < CONFIG_ENV_SIZE)
return 1;
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);
puts("Erasing Nand...\n");
if (nand_erase_opts(&nand_info[0], &nand_erase_options))
return 1;
puts("Writing to Nand... ");
if (writeenv(CONFIG_ENV_OFFSET, (u_char *)&env_new)) {
puts("FAILED!\n");
return 1;
}
puts("done\n");
return ret;
}
#endif /* CONFIG_ENV_OFFSET_REDUND */
#endif /* CMD_SAVEENV */
int readenv(size_t offset, u_char *buf)
{
size_t end = offset + CONFIG_ENV_RANGE;
size_t amount_loaded = 0;
size_t blocksize, len;
u_char *char_ptr;
blocksize = nand_info[0].erasesize;
if (!blocksize)
return 1;
len = min(blocksize, CONFIG_ENV_SIZE);
while (amount_loaded < CONFIG_ENV_SIZE && offset < end) {
if (nand_block_isbad(&nand_info[0], offset)) {
offset += blocksize;
} else {
char_ptr = &buf[amount_loaded];
if (nand_read_skip_bad(&nand_info[0], offset,
&len, char_ptr))
return 1;
offset += blocksize;
amount_loaded += len;
}
}
if (amount_loaded != CONFIG_ENV_SIZE)
return 1;
return 0;
}
#ifdef CONFIG_ENV_OFFSET_OOB
int get_nand_env_oob(nand_info_t *nand, unsigned long *result)
{
struct mtd_oob_ops ops;
uint32_t oob_buf[ENV_OFFSET_SIZE / sizeof(uint32_t)];
int ret;
ops.datbuf = NULL;
ops.mode = MTD_OOB_AUTO;
ops.ooboffs = 0;
ops.ooblen = ENV_OFFSET_SIZE;
ops.oobbuf = (void *)oob_buf;
ret = nand->read_oob(nand, ENV_OFFSET_SIZE, &ops);
if (ret) {
printf("error reading OOB block 0\n");
return ret;
}
if (oob_buf[0] == ENV_OOB_MARKER) {
*result = oob_buf[1] * nand->erasesize;
} else if (oob_buf[0] == ENV_OOB_MARKER_OLD) {
*result = oob_buf[1];
} else {
printf("No dynamic environment marker in OOB block 0\n");
return -ENOENT;
}
return 0;
}
#endif
#ifdef CONFIG_ENV_OFFSET_REDUND
void env_relocate_spec(void)
{
#if !defined(ENV_IS_EMBEDDED)
int crc1_ok = 0, crc2_ok = 0;
env_t *ep, *tmp_env1, *tmp_env2;
tmp_env1 = (env_t *)malloc(CONFIG_ENV_SIZE);
tmp_env2 = (env_t *)malloc(CONFIG_ENV_SIZE);
if (tmp_env1 == NULL || tmp_env2 == NULL) {
puts("Can't allocate buffers for environment\n");
set_default_env("!malloc() failed");
goto done;
}
if (readenv(CONFIG_ENV_OFFSET, (u_char *) tmp_env1))
puts("No Valid Environment Area found\n");
if (readenv(CONFIG_ENV_OFFSET_REDUND, (u_char *) tmp_env2))
puts("No Valid Redundant Environment Area found\n");
crc1_ok = crc32(0, tmp_env1->data, ENV_SIZE) == tmp_env1->crc;
crc2_ok = crc32(0, tmp_env2->data, ENV_SIZE) == tmp_env2->crc;
if (!crc1_ok && !crc2_ok) {
set_default_env("!bad CRC");
goto done;
} else if (crc1_ok && !crc2_ok) {
gd->env_valid = 1;
} else if (!crc1_ok && crc2_ok) {
gd->env_valid = 2;
} else {
/* both ok - check serial */
if (tmp_env1->flags == 255 && tmp_env2->flags == 0)
gd->env_valid = 2;
else if (tmp_env2->flags == 255 && tmp_env1->flags == 0)
gd->env_valid = 1;
else if (tmp_env1->flags > tmp_env2->flags)
gd->env_valid = 1;
else if (tmp_env2->flags > tmp_env1->flags)
gd->env_valid = 2;
else /* flags are equal - almost impossible */
gd->env_valid = 1;
}
free(env_ptr);
if (gd->env_valid == 1)
ep = tmp_env1;
else
ep = tmp_env2;
env_flags = ep->flags;
env_import((char *)ep, 0);
done:
free(tmp_env1);
free(tmp_env2);
#endif /* ! ENV_IS_EMBEDDED */
}
#else /* ! CONFIG_ENV_OFFSET_REDUND */
/*
* The legacy NAND code saved the environment in the first NAND
* device i.e., nand_dev_desc + 0. This is also the behaviour using
* the new NAND code.
*/
void env_relocate_spec(void)
{
#if !defined(ENV_IS_EMBEDDED)
int ret;
char buf[CONFIG_ENV_SIZE];
#if defined(CONFIG_ENV_OFFSET_OOB)
ret = get_nand_env_oob(&nand_info[0], &nand_env_oob_offset);
/*
* If unable to read environment offset from NAND OOB then fall through
* to the normal environment reading code below
*/
if (!ret) {
printf("Found Environment offset in OOB..\n");
} else {
set_default_env("!no env offset in OOB");
return;
}
#endif
ret = readenv(CONFIG_ENV_OFFSET, (u_char *)buf);
if (ret) {
set_default_env("!readenv() failed");
return;
}
env_import(buf, 1);
#endif /* ! ENV_IS_EMBEDDED */
}
#endif /* CONFIG_ENV_OFFSET_REDUND */
|
1001-study-uboot
|
common/env_nand.c
|
C
|
gpl3
| 10,740
|
/*
* (C) Copyright 2007
* Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
*
* Copyright 2010-2011 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 <stdio_dev.h>
#include <linux/ctype.h>
#include <linux/types.h>
#include <asm/global_data.h>
#include <fdt.h>
#include <libfdt.h>
#include <fdt_support.h>
#include <exports.h>
/*
* Global data (for the gd->bd)
*/
DECLARE_GLOBAL_DATA_PTR;
/**
* fdt_getprop_u32_default - Find a node and return it's property or a default
*
* @fdt: ptr to device tree
* @path: path of node
* @prop: property name
* @dflt: default value if the property isn't found
*
* Convenience function to find a node and return it's property or a
* default value if it doesn't exist.
*/
u32 fdt_getprop_u32_default(const void *fdt, const char *path,
const char *prop, const u32 dflt)
{
const u32 *val;
int off;
off = fdt_path_offset(fdt, path);
if (off < 0)
return dflt;
val = fdt_getprop(fdt, off, prop, NULL);
if (val)
return fdt32_to_cpu(*val);
else
return dflt;
}
/**
* fdt_find_and_setprop: Find a node and set it's property
*
* @fdt: ptr to device tree
* @node: path of node
* @prop: property name
* @val: ptr to new value
* @len: length of new property value
* @create: flag to create the property if it doesn't exist
*
* Convenience function to directly set a property given the path to the node.
*/
int fdt_find_and_setprop(void *fdt, const char *node, const char *prop,
const void *val, int len, int create)
{
int nodeoff = fdt_path_offset(fdt, node);
if (nodeoff < 0)
return nodeoff;
if ((!create) && (fdt_get_property(fdt, nodeoff, prop, 0) == NULL))
return 0; /* create flag not set; so exit quietly */
return fdt_setprop(fdt, nodeoff, prop, val, len);
}
#ifdef CONFIG_OF_STDOUT_VIA_ALIAS
#ifdef CONFIG_SERIAL_MULTI
static void fdt_fill_multisername(char *sername, size_t maxlen)
{
const char *outname = stdio_devices[stdout]->name;
if (strcmp(outname, "serial") > 0)
strncpy(sername, outname, maxlen);
/* eserial? */
if (strcmp(outname + 1, "serial") > 0)
strncpy(sername, outname + 1, maxlen);
}
#else
static inline void fdt_fill_multisername(char *sername, size_t maxlen) {}
#endif /* CONFIG_SERIAL_MULTI */
static int fdt_fixup_stdout(void *fdt, int chosenoff)
{
int err = 0;
#ifdef CONFIG_CONS_INDEX
int node;
char sername[9] = { 0 };
const char *path;
fdt_fill_multisername(sername, sizeof(sername) - 1);
if (!sername[0])
sprintf(sername, "serial%d", CONFIG_CONS_INDEX - 1);
err = node = fdt_path_offset(fdt, "/aliases");
if (node >= 0) {
int len;
path = fdt_getprop(fdt, node, sername, &len);
if (path) {
char *p = malloc(len);
err = -FDT_ERR_NOSPACE;
if (p) {
memcpy(p, path, len);
err = fdt_setprop(fdt, chosenoff,
"linux,stdout-path", p, len);
free(p);
}
} else {
err = len;
}
}
#endif
if (err < 0)
printf("WARNING: could not set linux,stdout-path %s.\n",
fdt_strerror(err));
return err;
}
#endif
int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end, int force)
{
int nodeoffset;
int err, j, total;
u32 tmp;
const char *path;
uint64_t addr, size;
/* Find the "chosen" node. */
nodeoffset = fdt_path_offset (fdt, "/chosen");
/* If there is no "chosen" node in the blob return */
if (nodeoffset < 0) {
printf("fdt_initrd: %s\n", fdt_strerror(nodeoffset));
return nodeoffset;
}
/* just return if initrd_start/end aren't valid */
if ((initrd_start == 0) || (initrd_end == 0))
return 0;
total = fdt_num_mem_rsv(fdt);
/*
* Look for an existing entry and update it. If we don't find
* the entry, we will j be the next available slot.
*/
for (j = 0; j < total; j++) {
err = fdt_get_mem_rsv(fdt, j, &addr, &size);
if (addr == initrd_start) {
fdt_del_mem_rsv(fdt, j);
break;
}
}
err = fdt_add_mem_rsv(fdt, initrd_start, initrd_end - initrd_start);
if (err < 0) {
printf("fdt_initrd: %s\n", fdt_strerror(err));
return err;
}
path = fdt_getprop(fdt, nodeoffset, "linux,initrd-start", NULL);
if ((path == NULL) || force) {
tmp = __cpu_to_be32(initrd_start);
err = fdt_setprop(fdt, nodeoffset,
"linux,initrd-start", &tmp, sizeof(tmp));
if (err < 0) {
printf("WARNING: "
"could not set linux,initrd-start %s.\n",
fdt_strerror(err));
return err;
}
tmp = __cpu_to_be32(initrd_end);
err = fdt_setprop(fdt, nodeoffset,
"linux,initrd-end", &tmp, sizeof(tmp));
if (err < 0) {
printf("WARNING: could not set linux,initrd-end %s.\n",
fdt_strerror(err));
return err;
}
}
return 0;
}
int fdt_chosen(void *fdt, int force)
{
int nodeoffset;
int err;
char *str; /* used to set string properties */
const char *path;
err = fdt_check_header(fdt);
if (err < 0) {
printf("fdt_chosen: %s\n", fdt_strerror(err));
return err;
}
/*
* Find the "chosen" node.
*/
nodeoffset = fdt_path_offset (fdt, "/chosen");
/*
* If there is no "chosen" node in the blob, create it.
*/
if (nodeoffset < 0) {
/*
* Create a new node "/chosen" (offset 0 is root level)
*/
nodeoffset = fdt_add_subnode(fdt, 0, "chosen");
if (nodeoffset < 0) {
printf("WARNING: could not create /chosen %s.\n",
fdt_strerror(nodeoffset));
return nodeoffset;
}
}
/*
* Create /chosen properites that don't exist in the fdt.
* If the property exists, update it only if the "force" parameter
* is true.
*/
str = getenv("bootargs");
if (str != NULL) {
path = fdt_getprop(fdt, nodeoffset, "bootargs", NULL);
if ((path == NULL) || force) {
err = fdt_setprop(fdt, nodeoffset,
"bootargs", str, strlen(str)+1);
if (err < 0)
printf("WARNING: could not set bootargs %s.\n",
fdt_strerror(err));
}
}
#ifdef CONFIG_OF_STDOUT_VIA_ALIAS
path = fdt_getprop(fdt, nodeoffset, "linux,stdout-path", NULL);
if ((path == NULL) || force)
err = fdt_fixup_stdout(fdt, nodeoffset);
#endif
#ifdef OF_STDOUT_PATH
path = fdt_getprop(fdt, nodeoffset, "linux,stdout-path", NULL);
if ((path == NULL) || force) {
err = fdt_setprop(fdt, nodeoffset,
"linux,stdout-path", OF_STDOUT_PATH, strlen(OF_STDOUT_PATH)+1);
if (err < 0)
printf("WARNING: could not set linux,stdout-path %s.\n",
fdt_strerror(err));
}
#endif
return err;
}
void do_fixup_by_path(void *fdt, const char *path, const char *prop,
const void *val, int len, int create)
{
#if defined(DEBUG)
int i;
debug("Updating property '%s/%s' = ", path, prop);
for (i = 0; i < len; i++)
debug(" %.2x", *(u8*)(val+i));
debug("\n");
#endif
int rc = fdt_find_and_setprop(fdt, path, prop, val, len, create);
if (rc)
printf("Unable to update property %s:%s, err=%s\n",
path, prop, fdt_strerror(rc));
}
void do_fixup_by_path_u32(void *fdt, const char *path, const char *prop,
u32 val, int create)
{
val = cpu_to_fdt32(val);
do_fixup_by_path(fdt, path, prop, &val, sizeof(val), create);
}
void do_fixup_by_prop(void *fdt,
const char *pname, const void *pval, int plen,
const char *prop, const void *val, int len,
int create)
{
int off;
#if defined(DEBUG)
int i;
debug("Updating property '%s' = ", prop);
for (i = 0; i < len; i++)
debug(" %.2x", *(u8*)(val+i));
debug("\n");
#endif
off = fdt_node_offset_by_prop_value(fdt, -1, pname, pval, plen);
while (off != -FDT_ERR_NOTFOUND) {
if (create || (fdt_get_property(fdt, off, prop, 0) != NULL))
fdt_setprop(fdt, off, prop, val, len);
off = fdt_node_offset_by_prop_value(fdt, off, pname, pval, plen);
}
}
void do_fixup_by_prop_u32(void *fdt,
const char *pname, const void *pval, int plen,
const char *prop, u32 val, int create)
{
val = cpu_to_fdt32(val);
do_fixup_by_prop(fdt, pname, pval, plen, prop, &val, 4, create);
}
void do_fixup_by_compat(void *fdt, const char *compat,
const char *prop, const void *val, int len, int create)
{
int off = -1;
#if defined(DEBUG)
int i;
debug("Updating property '%s' = ", prop);
for (i = 0; i < len; i++)
debug(" %.2x", *(u8*)(val+i));
debug("\n");
#endif
off = fdt_node_offset_by_compatible(fdt, -1, compat);
while (off != -FDT_ERR_NOTFOUND) {
if (create || (fdt_get_property(fdt, off, prop, 0) != NULL))
fdt_setprop(fdt, off, prop, val, len);
off = fdt_node_offset_by_compatible(fdt, off, compat);
}
}
void do_fixup_by_compat_u32(void *fdt, const char *compat,
const char *prop, u32 val, int create)
{
val = cpu_to_fdt32(val);
do_fixup_by_compat(fdt, compat, prop, &val, 4, create);
}
/*
* Get cells len in bytes
* if #NNNN-cells property is 2 then len is 8
* otherwise len is 4
*/
static int get_cells_len(void *blob, char *nr_cells_name)
{
const u32 *cell;
cell = fdt_getprop(blob, 0, nr_cells_name, NULL);
if (cell && fdt32_to_cpu(*cell) == 2)
return 8;
return 4;
}
/*
* Write a 4 or 8 byte big endian cell
*/
static void write_cell(u8 *addr, u64 val, int size)
{
int shift = (size - 1) * 8;
while (size-- > 0) {
*addr++ = (val >> shift) & 0xff;
shift -= 8;
}
}
int fdt_fixup_memory_banks(void *blob, u64 start[], u64 size[], int banks)
{
int err, nodeoffset;
int addr_cell_len, size_cell_len, len;
u8 tmp[banks * 16]; /* Up to 64-bit address + 64-bit size */
int bank;
err = fdt_check_header(blob);
if (err < 0) {
printf("%s: %s\n", __FUNCTION__, fdt_strerror(err));
return err;
}
/* update, or add and update /memory node */
nodeoffset = fdt_path_offset(blob, "/memory");
if (nodeoffset < 0) {
nodeoffset = fdt_add_subnode(blob, 0, "memory");
if (nodeoffset < 0)
printf("WARNING: could not create /memory: %s.\n",
fdt_strerror(nodeoffset));
return nodeoffset;
}
err = fdt_setprop(blob, nodeoffset, "device_type", "memory",
sizeof("memory"));
if (err < 0) {
printf("WARNING: could not set %s %s.\n", "device_type",
fdt_strerror(err));
return err;
}
addr_cell_len = get_cells_len(blob, "#address-cells");
size_cell_len = get_cells_len(blob, "#size-cells");
for (bank = 0, len = 0; bank < banks; bank++) {
write_cell(tmp + len, start[bank], addr_cell_len);
len += addr_cell_len;
write_cell(tmp + len, size[bank], size_cell_len);
len += size_cell_len;
}
err = fdt_setprop(blob, nodeoffset, "reg", tmp, len);
if (err < 0) {
printf("WARNING: could not set %s %s.\n",
"reg", fdt_strerror(err));
return err;
}
return 0;
}
int fdt_fixup_memory(void *blob, u64 start, u64 size)
{
return fdt_fixup_memory_banks(blob, &start, &size, 1);
}
void fdt_fixup_ethernet(void *fdt)
{
int node, i, j;
char enet[16], *tmp, *end;
char mac[16] = "ethaddr";
const char *path;
unsigned char mac_addr[6];
node = fdt_path_offset(fdt, "/aliases");
if (node < 0)
return;
i = 0;
while ((tmp = getenv(mac)) != NULL) {
sprintf(enet, "ethernet%d", i);
path = fdt_getprop(fdt, node, enet, NULL);
if (!path) {
debug("No alias for %s\n", enet);
sprintf(mac, "eth%daddr", ++i);
continue;
}
for (j = 0; j < 6; j++) {
mac_addr[j] = tmp ? simple_strtoul(tmp, &end, 16) : 0;
if (tmp)
tmp = (*end) ? end+1 : end;
}
do_fixup_by_path(fdt, path, "mac-address", &mac_addr, 6, 0);
do_fixup_by_path(fdt, path, "local-mac-address",
&mac_addr, 6, 1);
sprintf(mac, "eth%daddr", ++i);
}
}
/* Resize the fdt to its actual size + a bit of padding */
int fdt_resize(void *blob)
{
int i;
uint64_t addr, size;
int total, ret;
uint actualsize;
if (!blob)
return 0;
total = fdt_num_mem_rsv(blob);
for (i = 0; i < total; i++) {
fdt_get_mem_rsv(blob, i, &addr, &size);
if (addr == (uintptr_t)blob) {
fdt_del_mem_rsv(blob, i);
break;
}
}
/*
* Calculate the actual size of the fdt
* plus the size needed for 5 fdt_add_mem_rsv, one
* for the fdt itself and 4 for a possible initrd
* ((initrd-start + initrd-end) * 2 (name & value))
*/
actualsize = fdt_off_dt_strings(blob) +
fdt_size_dt_strings(blob) + 5 * sizeof(struct fdt_reserve_entry);
/* Make it so the fdt ends on a page boundary */
actualsize = ALIGN(actualsize + ((uintptr_t)blob & 0xfff), 0x1000);
actualsize = actualsize - ((uintptr_t)blob & 0xfff);
/* Change the fdt header to reflect the correct size */
fdt_set_totalsize(blob, actualsize);
/* Add the new reservation */
ret = fdt_add_mem_rsv(blob, (uintptr_t)blob, actualsize);
if (ret < 0)
return ret;
return actualsize;
}
#ifdef CONFIG_PCI
#define CONFIG_SYS_PCI_NR_INBOUND_WIN 4
#define FDT_PCI_PREFETCH (0x40000000)
#define FDT_PCI_MEM32 (0x02000000)
#define FDT_PCI_IO (0x01000000)
#define FDT_PCI_MEM64 (0x03000000)
int fdt_pci_dma_ranges(void *blob, int phb_off, struct pci_controller *hose) {
int addrcell, sizecell, len, r;
u32 *dma_range;
/* sized based on pci addr cells, size-cells, & address-cells */
u32 dma_ranges[(3 + 2 + 2) * CONFIG_SYS_PCI_NR_INBOUND_WIN];
addrcell = fdt_getprop_u32_default(blob, "/", "#address-cells", 1);
sizecell = fdt_getprop_u32_default(blob, "/", "#size-cells", 1);
dma_range = &dma_ranges[0];
for (r = 0; r < hose->region_count; r++) {
u64 bus_start, phys_start, size;
/* skip if !PCI_REGION_SYS_MEMORY */
if (!(hose->regions[r].flags & PCI_REGION_SYS_MEMORY))
continue;
bus_start = (u64)hose->regions[r].bus_start;
phys_start = (u64)hose->regions[r].phys_start;
size = (u64)hose->regions[r].size;
dma_range[0] = 0;
if (size >= 0x100000000ull)
dma_range[0] |= FDT_PCI_MEM64;
else
dma_range[0] |= FDT_PCI_MEM32;
if (hose->regions[r].flags & PCI_REGION_PREFETCH)
dma_range[0] |= FDT_PCI_PREFETCH;
#ifdef CONFIG_SYS_PCI_64BIT
dma_range[1] = bus_start >> 32;
#else
dma_range[1] = 0;
#endif
dma_range[2] = bus_start & 0xffffffff;
if (addrcell == 2) {
dma_range[3] = phys_start >> 32;
dma_range[4] = phys_start & 0xffffffff;
} else {
dma_range[3] = phys_start & 0xffffffff;
}
if (sizecell == 2) {
dma_range[3 + addrcell + 0] = size >> 32;
dma_range[3 + addrcell + 1] = size & 0xffffffff;
} else {
dma_range[3 + addrcell + 0] = size & 0xffffffff;
}
dma_range += (3 + addrcell + sizecell);
}
len = dma_range - &dma_ranges[0];
if (len)
fdt_setprop(blob, phb_off, "dma-ranges", &dma_ranges[0], len*4);
return 0;
}
#endif
#ifdef CONFIG_FDT_FIXUP_NOR_FLASH_SIZE
/*
* Provide a weak default function to return the flash bank size.
* There might be multiple non-identical flash chips connected to one
* chip-select, so we need to pass an index as well.
*/
u32 __flash_get_bank_size(int cs, int idx)
{
extern flash_info_t flash_info[];
/*
* As default, a simple 1:1 mapping is provided. Boards with
* a different mapping need to supply a board specific mapping
* routine.
*/
return flash_info[cs].size;
}
u32 flash_get_bank_size(int cs, int idx)
__attribute__((weak, alias("__flash_get_bank_size")));
/*
* This function can be used to update the size in the "reg" property
* of all NOR FLASH device nodes. This is necessary for boards with
* non-fixed NOR FLASH sizes.
*/
int fdt_fixup_nor_flash_size(void *blob)
{
char compat[][16] = { "cfi-flash", "jedec-flash" };
int off;
int len;
struct fdt_property *prop;
u32 *reg, *reg2;
int i;
for (i = 0; i < 2; i++) {
off = fdt_node_offset_by_compatible(blob, -1, compat[i]);
while (off != -FDT_ERR_NOTFOUND) {
int idx;
/*
* Found one compatible node, so fixup the size
* int its reg properties
*/
prop = fdt_get_property_w(blob, off, "reg", &len);
if (prop) {
int tuple_size = 3 * sizeof(reg);
/*
* There might be multiple reg-tuples,
* so loop through them all
*/
reg = reg2 = (u32 *)&prop->data[0];
for (idx = 0; idx < (len / tuple_size); idx++) {
/*
* Update size in reg property
*/
reg[2] = flash_get_bank_size(reg[0],
idx);
/*
* Point to next reg tuple
*/
reg += 3;
}
fdt_setprop(blob, off, "reg", reg2, len);
}
/* Move to next compatible node */
off = fdt_node_offset_by_compatible(blob, off,
compat[i]);
}
}
return 0;
}
#endif
int fdt_increase_size(void *fdt, int add_len)
{
int newlen;
newlen = fdt_totalsize(fdt) + add_len;
/* Open in place with a new len */
return fdt_open_into(fdt, fdt, newlen);
}
#ifdef CONFIG_FDT_FIXUP_PARTITIONS
#include <jffs2/load_kernel.h>
#include <mtd_node.h>
struct reg_cell {
unsigned int r0;
unsigned int r1;
};
int fdt_del_subnodes(const void *blob, int parent_offset)
{
int off, ndepth;
int ret;
for (ndepth = 0, off = fdt_next_node(blob, parent_offset, &ndepth);
(off >= 0) && (ndepth > 0);
off = fdt_next_node(blob, off, &ndepth)) {
if (ndepth == 1) {
debug("delete %s: offset: %x\n",
fdt_get_name(blob, off, 0), off);
ret = fdt_del_node((void *)blob, off);
if (ret < 0) {
printf("Can't delete node: %s\n",
fdt_strerror(ret));
return ret;
} else {
ndepth = 0;
off = parent_offset;
}
}
}
return 0;
}
int fdt_del_partitions(void *blob, int parent_offset)
{
const void *prop;
int ndepth = 0;
int off;
int ret;
off = fdt_next_node(blob, parent_offset, &ndepth);
if (off > 0 && ndepth == 1) {
prop = fdt_getprop(blob, off, "label", NULL);
if (prop == NULL) {
/*
* Could not find label property, nand {}; node?
* Check subnode, delete partitions there if any.
*/
return fdt_del_partitions(blob, off);
} else {
ret = fdt_del_subnodes(blob, parent_offset);
if (ret < 0) {
printf("Can't remove subnodes: %s\n",
fdt_strerror(ret));
return ret;
}
}
}
return 0;
}
int fdt_node_set_part_info(void *blob, int parent_offset,
struct mtd_device *dev)
{
struct list_head *pentry;
struct part_info *part;
struct reg_cell cell;
int off, ndepth = 0;
int part_num, ret;
char buf[64];
ret = fdt_del_partitions(blob, parent_offset);
if (ret < 0)
return ret;
/*
* Check if it is nand {}; subnode, adjust
* the offset in this case
*/
off = fdt_next_node(blob, parent_offset, &ndepth);
if (off > 0 && ndepth == 1)
parent_offset = off;
part_num = 0;
list_for_each_prev(pentry, &dev->parts) {
int newoff;
part = list_entry(pentry, struct part_info, link);
debug("%2d: %-20s0x%08x\t0x%08x\t%d\n",
part_num, part->name, part->size,
part->offset, part->mask_flags);
sprintf(buf, "partition@%x", part->offset);
add_sub:
ret = fdt_add_subnode(blob, parent_offset, buf);
if (ret == -FDT_ERR_NOSPACE) {
ret = fdt_increase_size(blob, 512);
if (!ret)
goto add_sub;
else
goto err_size;
} else if (ret < 0) {
printf("Can't add partition node: %s\n",
fdt_strerror(ret));
return ret;
}
newoff = ret;
/* Check MTD_WRITEABLE_CMD flag */
if (part->mask_flags & 1) {
add_ro:
ret = fdt_setprop(blob, newoff, "read_only", NULL, 0);
if (ret == -FDT_ERR_NOSPACE) {
ret = fdt_increase_size(blob, 512);
if (!ret)
goto add_ro;
else
goto err_size;
} else if (ret < 0)
goto err_prop;
}
cell.r0 = cpu_to_fdt32(part->offset);
cell.r1 = cpu_to_fdt32(part->size);
add_reg:
ret = fdt_setprop(blob, newoff, "reg", &cell, sizeof(cell));
if (ret == -FDT_ERR_NOSPACE) {
ret = fdt_increase_size(blob, 512);
if (!ret)
goto add_reg;
else
goto err_size;
} else if (ret < 0)
goto err_prop;
add_label:
ret = fdt_setprop_string(blob, newoff, "label", part->name);
if (ret == -FDT_ERR_NOSPACE) {
ret = fdt_increase_size(blob, 512);
if (!ret)
goto add_label;
else
goto err_size;
} else if (ret < 0)
goto err_prop;
part_num++;
}
return 0;
err_size:
printf("Can't increase blob size: %s\n", fdt_strerror(ret));
return ret;
err_prop:
printf("Can't add property: %s\n", fdt_strerror(ret));
return ret;
}
/*
* Update partitions in nor/nand nodes using info from
* mtdparts environment variable. The nodes to update are
* specified by node_info structure which contains mtd device
* type and compatible string: E. g. the board code in
* ft_board_setup() could use:
*
* struct node_info nodes[] = {
* { "fsl,mpc5121-nfc", MTD_DEV_TYPE_NAND, },
* { "cfi-flash", MTD_DEV_TYPE_NOR, },
* };
*
* fdt_fixup_mtdparts(blob, nodes, ARRAY_SIZE(nodes));
*/
void fdt_fixup_mtdparts(void *blob, void *node_info, int node_info_size)
{
struct node_info *ni = node_info;
struct mtd_device *dev;
char *parts;
int i, idx;
int noff;
parts = getenv("mtdparts");
if (!parts)
return;
if (mtdparts_init() != 0)
return;
for (i = 0; i < node_info_size; i++) {
idx = 0;
noff = fdt_node_offset_by_compatible(blob, -1, ni[i].compat);
while (noff != -FDT_ERR_NOTFOUND) {
debug("%s: %s, mtd dev type %d\n",
fdt_get_name(blob, noff, 0),
ni[i].compat, ni[i].type);
dev = device_find(ni[i].type, idx++);
if (dev) {
if (fdt_node_set_part_info(blob, noff, dev))
return; /* return on error */
}
/* Jump to next flash node */
noff = fdt_node_offset_by_compatible(blob, noff,
ni[i].compat);
}
}
}
#endif
void fdt_del_node_and_alias(void *blob, const char *alias)
{
int off = fdt_path_offset(blob, alias);
if (off < 0)
return;
fdt_del_node(blob, off);
off = fdt_path_offset(blob, "/aliases");
fdt_delprop(blob, off, alias);
}
/* Helper to read a big number; size is in cells (not bytes) */
static inline u64 of_read_number(const __be32 *cell, int size)
{
u64 r = 0;
while (size--)
r = (r << 32) | be32_to_cpu(*(cell++));
return r;
}
#define PRu64 "%llx"
/* Max address size we deal with */
#define OF_MAX_ADDR_CELLS 4
#define OF_BAD_ADDR ((u64)-1)
#define OF_CHECK_COUNTS(na, ns) ((na) > 0 && (na) <= OF_MAX_ADDR_CELLS && \
(ns) > 0)
/* Debug utility */
#ifdef DEBUG
static void of_dump_addr(const char *s, const u32 *addr, int na)
{
printf("%s", s);
while(na--)
printf(" %08x", *(addr++));
printf("\n");
}
#else
static void of_dump_addr(const char *s, const u32 *addr, int na) { }
#endif
/* Callbacks for bus specific translators */
struct of_bus {
const char *name;
const char *addresses;
void (*count_cells)(void *blob, int parentoffset,
int *addrc, int *sizec);
u64 (*map)(u32 *addr, const u32 *range,
int na, int ns, int pna);
int (*translate)(u32 *addr, u64 offset, int na);
};
/* Default translator (generic bus) */
static void of_bus_default_count_cells(void *blob, int parentoffset,
int *addrc, int *sizec)
{
const u32 *prop;
if (addrc) {
prop = fdt_getprop(blob, parentoffset, "#address-cells", NULL);
if (prop)
*addrc = be32_to_cpup((u32 *)prop);
else
*addrc = 2;
}
if (sizec) {
prop = fdt_getprop(blob, parentoffset, "#size-cells", NULL);
if (prop)
*sizec = be32_to_cpup((u32 *)prop);
else
*sizec = 1;
}
}
static u64 of_bus_default_map(u32 *addr, const u32 *range,
int na, int ns, int pna)
{
u64 cp, s, da;
cp = of_read_number(range, na);
s = of_read_number(range + na + pna, ns);
da = of_read_number(addr, na);
debug("OF: default map, cp="PRu64", s="PRu64", da="PRu64"\n",
cp, s, da);
if (da < cp || da >= (cp + s))
return OF_BAD_ADDR;
return da - cp;
}
static int of_bus_default_translate(u32 *addr, u64 offset, int na)
{
u64 a = of_read_number(addr, na);
memset(addr, 0, na * 4);
a += offset;
if (na > 1)
addr[na - 2] = a >> 32;
addr[na - 1] = a & 0xffffffffu;
return 0;
}
/* Array of bus specific translators */
static struct of_bus of_busses[] = {
/* Default */
{
.name = "default",
.addresses = "reg",
.count_cells = of_bus_default_count_cells,
.map = of_bus_default_map,
.translate = of_bus_default_translate,
},
};
static int of_translate_one(void * blob, int parent, struct of_bus *bus,
struct of_bus *pbus, u32 *addr,
int na, int ns, int pna, const char *rprop)
{
const u32 *ranges;
int rlen;
int rone;
u64 offset = OF_BAD_ADDR;
/* Normally, an absence of a "ranges" property means we are
* crossing a non-translatable boundary, and thus the addresses
* below the current not cannot be converted to CPU physical ones.
* Unfortunately, while this is very clear in the spec, it's not
* what Apple understood, and they do have things like /uni-n or
* /ht nodes with no "ranges" property and a lot of perfectly
* useable mapped devices below them. Thus we treat the absence of
* "ranges" as equivalent to an empty "ranges" property which means
* a 1:1 translation at that level. It's up to the caller not to try
* to translate addresses that aren't supposed to be translated in
* the first place. --BenH.
*/
ranges = (u32 *)fdt_getprop(blob, parent, rprop, &rlen);
if (ranges == NULL || rlen == 0) {
offset = of_read_number(addr, na);
memset(addr, 0, pna * 4);
debug("OF: no ranges, 1:1 translation\n");
goto finish;
}
debug("OF: walking ranges...\n");
/* Now walk through the ranges */
rlen /= 4;
rone = na + pna + ns;
for (; rlen >= rone; rlen -= rone, ranges += rone) {
offset = bus->map(addr, ranges, na, ns, pna);
if (offset != OF_BAD_ADDR)
break;
}
if (offset == OF_BAD_ADDR) {
debug("OF: not found !\n");
return 1;
}
memcpy(addr, ranges + na, 4 * pna);
finish:
of_dump_addr("OF: parent translation for:", addr, pna);
debug("OF: with offset: "PRu64"\n", offset);
/* Translate it into parent bus space */
return pbus->translate(addr, offset, pna);
}
/*
* Translate an address from the device-tree into a CPU physical address,
* this walks up the tree and applies the various bus mappings on the
* way.
*
* Note: We consider that crossing any level with #size-cells == 0 to mean
* that translation is impossible (that is we are not dealing with a value
* that can be mapped to a cpu physical address). This is not really specified
* that way, but this is traditionally the way IBM at least do things
*/
u64 __of_translate_address(void *blob, int node_offset, const u32 *in_addr,
const char *rprop)
{
int parent;
struct of_bus *bus, *pbus;
u32 addr[OF_MAX_ADDR_CELLS];
int na, ns, pna, pns;
u64 result = OF_BAD_ADDR;
debug("OF: ** translation for device %s **\n",
fdt_get_name(blob, node_offset, NULL));
/* Get parent & match bus type */
parent = fdt_parent_offset(blob, node_offset);
if (parent < 0)
goto bail;
bus = &of_busses[0];
/* Cound address cells & copy address locally */
bus->count_cells(blob, parent, &na, &ns);
if (!OF_CHECK_COUNTS(na, ns)) {
printf("%s: Bad cell count for %s\n", __FUNCTION__,
fdt_get_name(blob, node_offset, NULL));
goto bail;
}
memcpy(addr, in_addr, na * 4);
debug("OF: bus is %s (na=%d, ns=%d) on %s\n",
bus->name, na, ns, fdt_get_name(blob, parent, NULL));
of_dump_addr("OF: translating address:", addr, na);
/* Translate */
for (;;) {
/* Switch to parent bus */
node_offset = parent;
parent = fdt_parent_offset(blob, node_offset);
/* If root, we have finished */
if (parent < 0) {
debug("OF: reached root node\n");
result = of_read_number(addr, na);
break;
}
/* Get new parent bus and counts */
pbus = &of_busses[0];
pbus->count_cells(blob, parent, &pna, &pns);
if (!OF_CHECK_COUNTS(pna, pns)) {
printf("%s: Bad cell count for %s\n", __FUNCTION__,
fdt_get_name(blob, node_offset, NULL));
break;
}
debug("OF: parent bus is %s (na=%d, ns=%d) on %s\n",
pbus->name, pna, pns, fdt_get_name(blob, parent, NULL));
/* Apply bus translation */
if (of_translate_one(blob, node_offset, bus, pbus,
addr, na, ns, pna, rprop))
break;
/* Complete the move up one level */
na = pna;
ns = pns;
bus = pbus;
of_dump_addr("OF: one level translation:", addr, na);
}
bail:
return result;
}
u64 fdt_translate_address(void *blob, int node_offset, const u32 *in_addr)
{
return __of_translate_address(blob, node_offset, in_addr, "ranges");
}
/**
* fdt_node_offset_by_compat_reg: Find a node that matches compatiable and
* who's reg property matches a physical cpu address
*
* @blob: ptr to device tree
* @compat: compatiable string to match
* @compat_off: property name
*
*/
int fdt_node_offset_by_compat_reg(void *blob, const char *compat,
phys_addr_t compat_off)
{
int len, off = fdt_node_offset_by_compatible(blob, -1, compat);
while (off != -FDT_ERR_NOTFOUND) {
u32 *reg = (u32 *)fdt_getprop(blob, off, "reg", &len);
if (reg) {
if (compat_off == fdt_translate_address(blob, off, reg))
return off;
}
off = fdt_node_offset_by_compatible(blob, off, compat);
}
return -FDT_ERR_NOTFOUND;
}
/**
* fdt_alloc_phandle: Return next free phandle value
*
* @blob: ptr to device tree
*/
int fdt_alloc_phandle(void *blob)
{
int offset, phandle = 0;
for (offset = fdt_next_node(blob, -1, NULL); offset >= 0;
offset = fdt_next_node(blob, offset, NULL)) {
phandle = max(phandle, fdt_get_phandle(blob, offset));
}
return phandle + 1;
}
/*
* fdt_set_phandle: Create a phandle property for the given node
*
* @fdt: ptr to device tree
* @nodeoffset: node to update
* @phandle: phandle value to set (must be unique)
*/
int fdt_set_phandle(void *fdt, int nodeoffset, uint32_t phandle)
{
int ret;
#ifdef DEBUG
int off = fdt_node_offset_by_phandle(fdt, phandle);
if ((off >= 0) && (off != nodeoffset)) {
char buf[64];
fdt_get_path(fdt, nodeoffset, buf, sizeof(buf));
printf("Trying to update node %s with phandle %u ",
buf, phandle);
fdt_get_path(fdt, off, buf, sizeof(buf));
printf("that already exists in node %s.\n", buf);
return -FDT_ERR_BADPHANDLE;
}
#endif
ret = fdt_setprop_cell(fdt, nodeoffset, "phandle", phandle);
if (ret < 0)
return ret;
/*
* For now, also set the deprecated "linux,phandle" property, so that we
* don't break older kernels.
*/
ret = fdt_setprop_cell(fdt, nodeoffset, "linux,phandle", phandle);
return ret;
}
/*
* fdt_create_phandle: Create a phandle property for the given node
*
* @fdt: ptr to device tree
* @nodeoffset: node to update
*/
unsigned int fdt_create_phandle(void *fdt, int nodeoffset)
{
/* see if there is a phandle already */
int phandle = fdt_get_phandle(fdt, nodeoffset);
/* if we got 0, means no phandle so create one */
if (phandle == 0) {
int ret;
phandle = fdt_alloc_phandle(fdt);
ret = fdt_set_phandle(fdt, nodeoffset, phandle);
if (ret < 0) {
printf("Can't set phandle %u: %s\n", phandle,
fdt_strerror(ret));
return 0;
}
}
return phandle;
}
/*
* fdt_set_node_status: Set status for the given node
*
* @fdt: ptr to device tree
* @nodeoffset: node to update
* @status: FDT_STATUS_OKAY, FDT_STATUS_DISABLED,
* FDT_STATUS_FAIL, FDT_STATUS_FAIL_ERROR_CODE
* @error_code: optional, only used if status is FDT_STATUS_FAIL_ERROR_CODE
*/
int fdt_set_node_status(void *fdt, int nodeoffset,
enum fdt_status status, unsigned int error_code)
{
char buf[16];
int ret = 0;
if (nodeoffset < 0)
return nodeoffset;
switch (status) {
case FDT_STATUS_OKAY:
ret = fdt_setprop_string(fdt, nodeoffset, "status", "okay");
break;
case FDT_STATUS_DISABLED:
ret = fdt_setprop_string(fdt, nodeoffset, "status", "disabled");
break;
case FDT_STATUS_FAIL:
ret = fdt_setprop_string(fdt, nodeoffset, "status", "fail");
break;
case FDT_STATUS_FAIL_ERROR_CODE:
sprintf(buf, "fail-%d", error_code);
ret = fdt_setprop_string(fdt, nodeoffset, "status", buf);
break;
default:
printf("Invalid fdt status: %x\n", status);
ret = -1;
break;
}
return ret;
}
/*
* fdt_set_status_by_alias: Set status for the given node given an alias
*
* @fdt: ptr to device tree
* @alias: alias of node to update
* @status: FDT_STATUS_OKAY, FDT_STATUS_DISABLED,
* FDT_STATUS_FAIL, FDT_STATUS_FAIL_ERROR_CODE
* @error_code: optional, only used if status is FDT_STATUS_FAIL_ERROR_CODE
*/
int fdt_set_status_by_alias(void *fdt, const char* alias,
enum fdt_status status, unsigned int error_code)
{
int offset = fdt_path_offset(fdt, alias);
return fdt_set_node_status(fdt, offset, status, error_code);
}
#if defined(CONFIG_VIDEO)
int fdt_add_edid(void *blob, const char *compat, unsigned char *edid_buf)
{
int noff;
int ret;
noff = fdt_node_offset_by_compatible(blob, -1, compat);
if (noff != -FDT_ERR_NOTFOUND) {
debug("%s: %s\n", fdt_get_name(blob, noff, 0), compat);
add_edid:
ret = fdt_setprop(blob, noff, "edid", edid_buf, 128);
if (ret == -FDT_ERR_NOSPACE) {
ret = fdt_increase_size(blob, 512);
if (!ret)
goto add_edid;
else
goto err_size;
} else if (ret < 0) {
printf("Can't add property: %s\n", fdt_strerror(ret));
return ret;
}
}
return 0;
err_size:
printf("Can't increase blob size: %s\n", fdt_strerror(ret));
return ret;
}
#endif
/*
* Verify the physical address of device tree node for a given alias
*
* This function locates the device tree node of a given alias, and then
* verifies that the physical address of that device matches the given
* parameter. It displays a message if there is a mismatch.
*
* Returns 1 on success, 0 on failure
*/
int fdt_verify_alias_address(void *fdt, int anode, const char *alias, u64 addr)
{
const char *path;
const u32 *reg;
int node, len;
u64 dt_addr;
path = fdt_getprop(fdt, anode, alias, NULL);
if (!path) {
/* If there's no such alias, then it's not a failure */
return 1;
}
node = fdt_path_offset(fdt, path);
if (node < 0) {
printf("Warning: device tree alias '%s' points to invalid "
"node %s.\n", alias, path);
return 0;
}
reg = fdt_getprop(fdt, node, "reg", &len);
if (!reg) {
printf("Warning: device tree node '%s' has no address.\n",
path);
return 0;
}
dt_addr = fdt_translate_address(fdt, node, reg);
if (addr != dt_addr) {
printf("Warning: U-Boot configured device %s at address %llx,\n"
" but the device tree has it address %llx.\n",
alias, addr, dt_addr);
return 0;
}
return 1;
}
/*
* Returns the base address of an SOC or PCI node
*/
u64 fdt_get_base_address(void *fdt, int node)
{
int size;
u32 naddr;
const u32 *prop;
prop = fdt_getprop(fdt, node, "#address-cells", &size);
if (prop && size == 4)
naddr = *prop;
else
naddr = 2;
prop = fdt_getprop(fdt, node, "ranges", &size);
return prop ? fdt_translate_address(fdt, node, prop + naddr) : 0;
}
|
1001-study-uboot
|
common/fdt_support.c
|
C
|
gpl3
| 34,794
|
/*
* U-boot - bootldr.c
*
* Copyright (c) 2005-2008 Analog Devices Inc.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* Licensed under the GPL-2 or later.
*/
#include <config.h>
#include <common.h>
#include <command.h>
#include <asm/blackfin.h>
#include <asm/mach-common/bits/bootrom.h>
/* Simple sanity check on the specified address to make sure it contains
* an LDR image of some sort.
*/
static bool ldr_valid_signature(uint8_t *data)
{
#if defined(__ADSPBF561__)
/* BF56x has a 4 byte global header */
if (data[3] == (GFLAG_56X_SIGN_MAGIC << (GFLAG_56X_SIGN_SHIFT - 24)))
return true;
#elif defined(__ADSPBF531__) || defined(__ADSPBF532__) || defined(__ADSPBF533__) || \
defined(__ADSPBF534__) || defined(__ADSPBF536__) || defined(__ADSPBF537__) || \
defined(__ADSPBF538__) || defined(__ADSPBF539__)
/* all the BF53x should start at this address mask */
uint32_t addr;
memmove(&addr, data, sizeof(addr));
if ((addr & 0xFF0FFF0F) == 0xFF000000)
return true;
#else
/* everything newer has a magic byte */
uint32_t count;
memmove(&count, data + 8, sizeof(count));
if (data[3] == 0xAD && count == 0)
return true;
#endif
return false;
}
/* If the Blackfin is new enough, the Blackfin on-chip ROM supports loading
* LDRs from random memory addresses. So whenever possible, use that. In
* the older cases (BF53x/BF561), parse the LDR format ourselves.
*/
static void ldr_load(uint8_t *base_addr)
{
#if defined(__ADSPBF531__) || defined(__ADSPBF532__) || defined(__ADSPBF533__) || \
/*defined(__ADSPBF534__) || defined(__ADSPBF536__) || defined(__ADSPBF537__) ||*/\
defined(__ADSPBF538__) || defined(__ADSPBF539__) || defined(__ADSPBF561__)
uint32_t addr;
uint32_t count;
uint16_t flags;
/* the bf56x has a 4 byte global header ... but it is useless to
* us when booting an LDR from a memory address, so skip it
*/
# ifdef __ADSPBF561__
base_addr += 4;
# endif
memmove(&flags, base_addr + 8, sizeof(flags));
bfin_write_EVT1(flags & BFLAG_53X_RESVECT ? 0xFFA00000 : 0xFFA08000);
do {
/* block header may not be aligned */
memmove(&addr, base_addr, sizeof(addr));
memmove(&count, base_addr+4, sizeof(count));
memmove(&flags, base_addr+8, sizeof(flags));
base_addr += sizeof(addr) + sizeof(count) + sizeof(flags);
printf("loading to 0x%08x (%#x bytes) flags: 0x%04x\n",
addr, count, flags);
if (!(flags & BFLAG_53X_IGNORE)) {
if (flags & BFLAG_53X_ZEROFILL)
memset((void *)addr, 0x00, count);
else
memcpy((void *)addr, base_addr, count);
if (flags & BFLAG_53X_INIT) {
void (*init)(void) = (void *)addr;
init();
}
}
if (!(flags & BFLAG_53X_ZEROFILL))
base_addr += count;
} while (!(flags & BFLAG_53X_FINAL));
#endif
}
/* For BF537, we use the _BOOTROM_BOOT_DXE_FLASH funky ROM function.
* For all other BF53x/BF56x, we just call the entry point.
* For everything else (newer), we use _BOOTROM_MEMBOOT ROM function.
*/
static void ldr_exec(void *addr)
{
#if defined(__ADSPBF534__) || defined(__ADSPBF536__) || defined(__ADSPBF537__)
/* restore EVT1 to reset value as this is what the bootrom uses as
* the default entry point when booting the final block of LDRs
*/
bfin_write_EVT1(L1_INST_SRAM);
__asm__("call (%0);" : : "a"(_BOOTROM_MEMBOOT), "q7"(addr) : "RETS", "memory");
#elif defined(__ADSPBF531__) || defined(__ADSPBF532__) || defined(__ADSPBF533__) || \
defined(__ADSPBF538__) || defined(__ADSPBF539__) || defined(__ADSPBF561__)
void (*ldr_entry)(void) = (void *)bfin_read_EVT1();
ldr_entry();
#else
int32_t (*BOOTROM_MEM)(void *, int32_t, int32_t, void *) = (void *)_BOOTROM_MEMBOOT;
BOOTROM_MEM(addr, 0, 0, NULL);
#endif
}
/*
* the bootldr command loads an address, checks to see if there
* is a Boot stream that the on-chip BOOTROM can understand,
* and loads it via the BOOTROM Callback. It is possible
* to also add booting from SPI, or TWI, but this function does
* not currently support that.
*/
int do_bootldr(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
void *addr;
/* Get the address */
if (argc < 2)
addr = (void *)load_addr;
else
addr = (void *)simple_strtoul(argv[1], NULL, 16);
/* Check if it is a LDR file */
if (ldr_valid_signature(addr)) {
printf("## Booting ldr image at 0x%p ...\n", addr);
ldr_load(addr);
icache_disable();
dcache_disable();
ldr_exec(addr);
} else
printf("## No ldr image at address 0x%p\n", addr);
return 0;
}
U_BOOT_CMD(
bootldr, 2, 0, do_bootldr,
"boot ldr image from memory",
"[addr]\n"
""
);
|
1001-study-uboot
|
common/cmd_bootldr.c
|
C
|
gpl3
| 4,592
|
/*
* Copyright 2006 Freescale Semiconductor
* York Sun (yorksun@freescale.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>
extern int do_mac(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
U_BOOT_CMD(
mac, 3, 1, do_mac,
"display and program the system ID and MAC addresses in EEPROM",
"[read|save|id|num|errata|date|ports|0|1|2|3|4|5|6|7]\n"
"mac read\n"
" - read EEPROM content into memory\n"
"mac save\n"
" - save to the EEPROM\n"
"mac id\n"
" - program system id\n"
"mac num\n"
" - program system serial number\n"
"mac errata\n"
" - program errata data\n"
"mac date\n"
" - program date\n"
"mac ports\n"
" - program the number of ports\n"
"mac X\n"
" - program the MAC address for port X [X=0...7]"
);
|
1001-study-uboot
|
common/cmd_mac.c
|
C
|
gpl3
| 1,561
|
/*
* (C) Copyright 2000-2011
* 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
*
*/
/*
* IDE support
*/
#include <common.h>
#include <config.h>
#include <watchdog.h>
#include <command.h>
#include <image.h>
#include <asm/byteorder.h>
#include <asm/io.h>
#if defined(CONFIG_IDE_8xx_DIRECT) || defined(CONFIG_IDE_PCMCIA)
# include <pcmcia.h>
#endif
#ifdef CONFIG_8xx
# include <mpc8xx.h>
#endif
#ifdef CONFIG_MPC5xxx
#include <mpc5xxx.h>
#endif
#include <ide.h>
#include <ata.h>
#ifdef CONFIG_STATUS_LED
# include <status_led.h>
#endif
#ifdef CONFIG_IDE_8xx_DIRECT
DECLARE_GLOBAL_DATA_PTR;
#endif
#ifdef __PPC__
# define EIEIO __asm__ volatile ("eieio")
# define SYNC __asm__ volatile ("sync")
#else
# define EIEIO /* nothing */
# define SYNC /* nothing */
#endif
#ifdef CONFIG_IDE_8xx_DIRECT
/* Timings for IDE Interface
*
* SETUP / LENGTH / HOLD - cycles valid for 50 MHz clk
* 70 165 30 PIO-Mode 0, [ns]
* 4 9 2 [Cycles]
* 50 125 20 PIO-Mode 1, [ns]
* 3 7 2 [Cycles]
* 30 100 15 PIO-Mode 2, [ns]
* 2 6 1 [Cycles]
* 30 80 10 PIO-Mode 3, [ns]
* 2 5 1 [Cycles]
* 25 70 10 PIO-Mode 4, [ns]
* 2 4 1 [Cycles]
*/
const static pio_config_t pio_config_ns [IDE_MAX_PIO_MODE+1] =
{
/* Setup Length Hold */
{ 70, 165, 30 }, /* PIO-Mode 0, [ns] */
{ 50, 125, 20 }, /* PIO-Mode 1, [ns] */
{ 30, 101, 15 }, /* PIO-Mode 2, [ns] */
{ 30, 80, 10 }, /* PIO-Mode 3, [ns] */
{ 25, 70, 10 }, /* PIO-Mode 4, [ns] */
};
static pio_config_t pio_config_clk [IDE_MAX_PIO_MODE+1];
#ifndef CONFIG_SYS_PIO_MODE
#define CONFIG_SYS_PIO_MODE 0 /* use a relaxed default */
#endif
static int pio_mode = CONFIG_SYS_PIO_MODE;
/* Make clock cycles and always round up */
#define PCMCIA_MK_CLKS( t, T ) (( (t) * (T) + 999U ) / 1000U )
#endif /* CONFIG_IDE_8xx_DIRECT */
/* ------------------------------------------------------------------------- */
/* Current I/O Device */
static int curr_device = -1;
/* Current offset for IDE0 / IDE1 bus access */
ulong ide_bus_offset[CONFIG_SYS_IDE_MAXBUS] = {
#if defined(CONFIG_SYS_ATA_IDE0_OFFSET)
CONFIG_SYS_ATA_IDE0_OFFSET,
#endif
#if defined(CONFIG_SYS_ATA_IDE1_OFFSET) && (CONFIG_SYS_IDE_MAXBUS > 1)
CONFIG_SYS_ATA_IDE1_OFFSET,
#endif
};
static int ide_bus_ok[CONFIG_SYS_IDE_MAXBUS];
block_dev_desc_t ide_dev_desc[CONFIG_SYS_IDE_MAXDEVICE];
/* ------------------------------------------------------------------------- */
#ifdef CONFIG_IDE_LED
# if !defined(CONFIG_BMS2003) && \
!defined(CONFIG_CPC45) && \
!defined(CONFIG_KUP4K) && \
!defined(CONFIG_KUP4X)
static void ide_led (uchar led, uchar status);
#else
extern void ide_led (uchar led, uchar status);
#endif
#else
#define ide_led(a,b) /* dummy */
#endif
#ifdef CONFIG_IDE_RESET
static void ide_reset (void);
#else
#define ide_reset() /* dummy */
#endif
static void ide_ident (block_dev_desc_t *dev_desc);
static uchar ide_wait (int dev, ulong t);
#define IDE_TIME_OUT 2000 /* 2 sec timeout */
#define ATAPI_TIME_OUT 7000 /* 7 sec timeout (5 sec seems to work...) */
#define IDE_SPIN_UP_TIME_OUT 5000 /* 5 sec spin-up timeout */
static void input_data(int dev, ulong *sect_buf, int words);
static void output_data(int dev, const ulong *sect_buf, int words);
static void ident_cpy (unsigned char *dest, unsigned char *src, unsigned int len);
#ifndef CONFIG_SYS_ATA_PORT_ADDR
#define CONFIG_SYS_ATA_PORT_ADDR(port) (port)
#endif
#ifdef CONFIG_ATAPI
static void atapi_inquiry(block_dev_desc_t *dev_desc);
ulong atapi_read (int device, lbaint_t blknr, ulong blkcnt, void *buffer);
#endif
#ifdef CONFIG_IDE_8xx_DIRECT
static void set_pcmcia_timing (int pmode);
#endif
/* ------------------------------------------------------------------------- */
int do_ide(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
{
int rcode = 0;
switch (argc) {
case 0:
case 1:
return cmd_usage(cmdtp);
case 2:
if (strncmp(argv[1], "res", 3) == 0) {
puts("\nReset IDE"
#ifdef CONFIG_IDE_8xx_DIRECT
" on PCMCIA " PCMCIA_SLOT_MSG
#endif
": ");
ide_init();
return 0;
} else if (strncmp(argv[1], "inf", 3) == 0) {
int i;
putc('\n');
for (i = 0; i < CONFIG_SYS_IDE_MAXDEVICE; ++i) {
if (ide_dev_desc[i].type == DEV_TYPE_UNKNOWN)
continue; /* list only known devices */
printf("IDE device %d: ", i);
dev_print(&ide_dev_desc[i]);
}
return 0;
} else if (strncmp(argv[1], "dev", 3) == 0) {
if ((curr_device < 0)
|| (curr_device >= CONFIG_SYS_IDE_MAXDEVICE)) {
puts("\nno IDE devices available\n");
return 1;
}
printf("\nIDE device %d: ", curr_device);
dev_print(&ide_dev_desc[curr_device]);
return 0;
} else if (strncmp(argv[1], "part", 4) == 0) {
int dev, ok;
for (ok = 0, dev = 0;
dev < CONFIG_SYS_IDE_MAXDEVICE;
++dev) {
if (ide_dev_desc[dev].part_type !=
PART_TYPE_UNKNOWN) {
++ok;
if (dev)
putc('\n');
print_part(&ide_dev_desc[dev]);
}
}
if (!ok) {
puts("\nno IDE devices available\n");
rcode++;
}
return rcode;
}
return cmd_usage(cmdtp);
case 3:
if (strncmp(argv[1], "dev", 3) == 0) {
int dev = (int) simple_strtoul(argv[2], NULL, 10);
printf("\nIDE device %d: ", dev);
if (dev >= CONFIG_SYS_IDE_MAXDEVICE) {
puts("unknown device\n");
return 1;
}
dev_print(&ide_dev_desc[dev]);
/*ide_print (dev); */
if (ide_dev_desc[dev].type == DEV_TYPE_UNKNOWN)
return 1;
curr_device = dev;
puts("... is now current device\n");
return 0;
} else if (strncmp(argv[1], "part", 4) == 0) {
int dev = (int) simple_strtoul(argv[2], NULL, 10);
if (ide_dev_desc[dev].part_type != PART_TYPE_UNKNOWN) {
print_part(&ide_dev_desc[dev]);
} else {
printf("\nIDE device %d not available\n",
dev);
rcode = 1;
}
return rcode;
}
return cmd_usage(cmdtp);
default:
/* at least 4 args */
if (strcmp(argv[1], "read") == 0) {
ulong addr = simple_strtoul(argv[2], NULL, 16);
ulong cnt = simple_strtoul(argv[4], NULL, 16);
ulong n;
#ifdef CONFIG_SYS_64BIT_LBA
lbaint_t blk = simple_strtoull(argv[3], NULL, 16);
printf("\nIDE read: device %d block # %lld, count %ld ... ",
curr_device, blk, cnt);
#else
lbaint_t blk = simple_strtoul(argv[3], NULL, 16);
printf("\nIDE read: device %d block # %ld, count %ld ... ",
curr_device, blk, cnt);
#endif
n = ide_dev_desc[curr_device].block_read(curr_device,
blk, cnt,
(ulong *)addr);
/* flush cache after read */
flush_cache(addr,
cnt * ide_dev_desc[curr_device].blksz);
printf("%ld blocks read: %s\n",
n, (n == cnt) ? "OK" : "ERROR");
if (n == cnt)
return 0;
else
return 1;
} else if (strcmp(argv[1], "write") == 0) {
ulong addr = simple_strtoul(argv[2], NULL, 16);
ulong cnt = simple_strtoul(argv[4], NULL, 16);
ulong n;
#ifdef CONFIG_SYS_64BIT_LBA
lbaint_t blk = simple_strtoull(argv[3], NULL, 16);
printf("\nIDE write: device %d block # %lld, count %ld ... ",
curr_device, blk, cnt);
#else
lbaint_t blk = simple_strtoul(argv[3], NULL, 16);
printf("\nIDE write: device %d block # %ld, count %ld ... ",
curr_device, blk, cnt);
#endif
n = ide_write(curr_device, blk, cnt, (ulong *) addr);
printf("%ld blocks written: %s\n",
n, (n == cnt) ? "OK" : "ERROR");
if (n == cnt)
return 0;
else
return 1;
} else {
return cmd_usage(cmdtp);
}
return rcode;
}
}
int do_diskboot(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
show_boot_progress(41);
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:
show_boot_progress(-42);
return cmd_usage(cmdtp);
}
show_boot_progress(42);
if (!boot_device) {
puts("\n** No boot device **\n");
show_boot_progress(-43);
return 1;
}
show_boot_progress(43);
dev = simple_strtoul(boot_device, &ep, 16);
if (ide_dev_desc[dev].type == DEV_TYPE_UNKNOWN) {
printf("\n** Device %d not available\n", dev);
show_boot_progress(-44);
return 1;
}
show_boot_progress(44);
if (*ep) {
if (*ep != ':') {
puts("\n** Invalid boot device, use `dev[:part]' **\n");
show_boot_progress(-45);
return 1;
}
part = simple_strtoul(++ep, NULL, 16);
}
show_boot_progress(45);
if (get_partition_info(&ide_dev_desc[dev], part, &info)) {
show_boot_progress(-46);
return 1;
}
show_boot_progress(46);
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);
show_boot_progress(-47);
return 1;
}
show_boot_progress(47);
printf("\nLoading from IDE 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 (ide_dev_desc[dev].
block_read(dev, info.start, 1, (ulong *) addr) != 1) {
printf("** Read error on %d:%d\n", dev, part);
show_boot_progress(-48);
return 1;
}
show_boot_progress(48);
switch (genimg_get_format((void *) addr)) {
case IMAGE_FORMAT_LEGACY:
hdr = (image_header_t *) addr;
show_boot_progress(49);
if (!image_check_hcrc(hdr)) {
puts("\n** Bad Header Checksum **\n");
show_boot_progress(-50);
return 1;
}
show_boot_progress(50);
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(-49);
puts("** Unknown image type\n");
return 1;
}
cnt += info.blksz - 1;
cnt /= info.blksz;
cnt -= 1;
if (ide_dev_desc[dev].block_read(dev, info.start + 1, cnt,
(ulong *)(addr + info.blksz)) != cnt) {
printf("** Read error on %d:%d\n", dev, part);
show_boot_progress(-51);
return 1;
}
show_boot_progress(51);
#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(-140);
puts("** Bad FIT image format\n");
return 1;
}
show_boot_progress(141);
fit_print_contents(fit_hdr);
}
#endif
/* Loading ok, update default load address */
load_addr = addr;
return bootm_maybe_autostart(cmdtp, argv[0]);
}
/* ------------------------------------------------------------------------- */
inline void __ide_outb(int dev, int port, unsigned char val)
{
debug("ide_outb (dev= %d, port= 0x%x, val= 0x%02x) : @ 0x%08lx\n",
dev, port, val,
(ATA_CURR_BASE(dev) + CONFIG_SYS_ATA_PORT_ADDR(port)));
#if defined(CONFIG_IDE_AHB)
if (port) {
/* write command */
ide_write_register(dev, port, val);
} else {
/* write data */
outb(val, (ATA_CURR_BASE(dev)));
}
#else
outb(val, (ATA_CURR_BASE(dev) + CONFIG_SYS_ATA_PORT_ADDR(port)));
#endif
}
void ide_outb(int dev, int port, unsigned char val)
__attribute__ ((weak, alias("__ide_outb")));
inline unsigned char __ide_inb(int dev, int port)
{
uchar val;
#if defined(CONFIG_IDE_AHB)
val = ide_read_register(dev, port);
#else
val = inb((ATA_CURR_BASE(dev) + CONFIG_SYS_ATA_PORT_ADDR(port)));
#endif
debug("ide_inb (dev= %d, port= 0x%x) : @ 0x%08lx -> 0x%02x\n",
dev, port,
(ATA_CURR_BASE(dev) + CONFIG_SYS_ATA_PORT_ADDR(port)), val);
return val;
}
unsigned char ide_inb(int dev, int port)
__attribute__ ((weak, alias("__ide_inb")));
#ifdef CONFIG_TUNE_PIO
inline int __ide_set_piomode(int pio_mode)
{
return 0;
}
inline int ide_set_piomode(int pio_mode)
__attribute__ ((weak, alias("__ide_set_piomode")));
#endif
void ide_init(void)
{
#ifdef CONFIG_IDE_8xx_DIRECT
volatile immap_t *immr = (immap_t *) CONFIG_SYS_IMMR;
volatile pcmconf8xx_t *pcmp = &(immr->im_pcmcia);
#endif
unsigned char c;
int i, bus;
#if defined(CONFIG_SC3)
unsigned int ata_reset_time = ATA_RESET_TIME;
#endif
#ifdef CONFIG_IDE_8xx_PCCARD
extern int pcmcia_on(void);
extern int ide_devices_found; /* Initialized in check_ide_device() */
#endif /* CONFIG_IDE_8xx_PCCARD */
#ifdef CONFIG_IDE_PREINIT
extern int ide_preinit(void);
WATCHDOG_RESET();
if (ide_preinit()) {
puts("ide_preinit failed\n");
return;
}
#endif /* CONFIG_IDE_PREINIT */
#ifdef CONFIG_IDE_8xx_PCCARD
extern int pcmcia_on(void);
extern int ide_devices_found; /* Initialized in check_ide_device() */
WATCHDOG_RESET();
ide_devices_found = 0;
/* initialize the PCMCIA IDE adapter card */
pcmcia_on();
if (!ide_devices_found)
return;
udelay(1000000); /* 1 s */
#endif /* CONFIG_IDE_8xx_PCCARD */
WATCHDOG_RESET();
#ifdef CONFIG_IDE_8xx_DIRECT
/* Initialize PIO timing tables */
for (i = 0; i <= IDE_MAX_PIO_MODE; ++i) {
pio_config_clk[i].t_setup =
PCMCIA_MK_CLKS(pio_config_ns[i].t_setup, gd->bus_clk);
pio_config_clk[i].t_length =
PCMCIA_MK_CLKS(pio_config_ns[i].t_length,
gd->bus_clk);
pio_config_clk[i].t_hold =
PCMCIA_MK_CLKS(pio_config_ns[i].t_hold, gd->bus_clk);
debug("PIO Mode %d: setup=%2d ns/%d clk" " len=%3d ns/%d clk"
" hold=%2d ns/%d clk\n", i, pio_config_ns[i].t_setup,
pio_config_clk[i].t_setup, pio_config_ns[i].t_length,
pio_config_clk[i].t_length, pio_config_ns[i].t_hold,
pio_config_clk[i].t_hold);
}
#endif /* CONFIG_IDE_8xx_DIRECT */
/*
* Reset the IDE just to be sure.
* Light LED's to show
*/
ide_led((LED_IDE1 | LED_IDE2), 1); /* LED's on */
/* ATAPI Drives seems to need a proper IDE Reset */
ide_reset();
#ifdef CONFIG_IDE_8xx_DIRECT
/* PCMCIA / IDE initialization for common mem space */
pcmp->pcmc_pgcrb = 0;
/* start in PIO mode 0 - most relaxed timings */
pio_mode = 0;
set_pcmcia_timing(pio_mode);
#endif /* CONFIG_IDE_8xx_DIRECT */
/*
* Wait for IDE to get ready.
* According to spec, this can take up to 31 seconds!
*/
for (bus = 0; bus < CONFIG_SYS_IDE_MAXBUS; ++bus) {
int dev =
bus * (CONFIG_SYS_IDE_MAXDEVICE /
CONFIG_SYS_IDE_MAXBUS);
#ifdef CONFIG_IDE_8xx_PCCARD
/* Skip non-ide devices from probing */
if ((ide_devices_found & (1 << bus)) == 0) {
ide_led((LED_IDE1 | LED_IDE2), 0); /* LED's off */
continue;
}
#endif
printf("Bus %d: ", bus);
ide_bus_ok[bus] = 0;
/* Select device
*/
udelay(100000); /* 100 ms */
ide_outb(dev, ATA_DEV_HD, ATA_LBA | ATA_DEVICE(dev));
udelay(100000); /* 100 ms */
i = 0;
do {
udelay(10000); /* 10 ms */
c = ide_inb(dev, ATA_STATUS);
i++;
#if defined(CONFIG_SC3)
if (i > (ata_reset_time * 100)) {
#else
if (i > (ATA_RESET_TIME * 100)) {
#endif
puts("** Timeout **\n");
/* LED's off */
ide_led((LED_IDE1 | LED_IDE2), 0);
return;
}
if ((i >= 100) && ((i % 100) == 0))
putc('.');
} while (c & ATA_STAT_BUSY);
if (c & (ATA_STAT_BUSY | ATA_STAT_FAULT)) {
puts("not available ");
debug("Status = 0x%02X ", c);
#ifndef CONFIG_ATAPI /* ATAPI Devices do not set DRDY */
} else if ((c & ATA_STAT_READY) == 0) {
puts("not available ");
debug("Status = 0x%02X ", c);
#endif
} else {
puts("OK ");
ide_bus_ok[bus] = 1;
}
WATCHDOG_RESET();
}
putc('\n');
ide_led((LED_IDE1 | LED_IDE2), 0); /* LED's off */
curr_device = -1;
for (i = 0; i < CONFIG_SYS_IDE_MAXDEVICE; ++i) {
#ifdef CONFIG_IDE_LED
int led = (IDE_BUS(i) == 0) ? LED_IDE1 : LED_IDE2;
#endif
ide_dev_desc[i].type = DEV_TYPE_UNKNOWN;
ide_dev_desc[i].if_type = IF_TYPE_IDE;
ide_dev_desc[i].dev = i;
ide_dev_desc[i].part_type = PART_TYPE_UNKNOWN;
ide_dev_desc[i].blksz = 0;
ide_dev_desc[i].lba = 0;
ide_dev_desc[i].block_read = ide_read;
ide_dev_desc[i].block_write = ide_write;
if (!ide_bus_ok[IDE_BUS(i)])
continue;
ide_led(led, 1); /* LED on */
ide_ident(&ide_dev_desc[i]);
ide_led(led, 0); /* LED off */
dev_print(&ide_dev_desc[i]);
if ((ide_dev_desc[i].lba > 0) && (ide_dev_desc[i].blksz > 0)) {
/* initialize partition type */
init_part(&ide_dev_desc[i]);
if (curr_device < 0)
curr_device = i;
}
}
WATCHDOG_RESET();
}
/* ------------------------------------------------------------------------- */
#ifdef CONFIG_PARTITIONS
block_dev_desc_t *ide_get_dev(int dev)
{
return (dev < CONFIG_SYS_IDE_MAXDEVICE) ? &ide_dev_desc[dev] : NULL;
}
#endif
#ifdef CONFIG_IDE_8xx_DIRECT
static void set_pcmcia_timing(int pmode)
{
volatile immap_t *immr = (immap_t *) CONFIG_SYS_IMMR;
volatile pcmconf8xx_t *pcmp = &(immr->im_pcmcia);
ulong timings;
debug("Set timing for PIO Mode %d\n", pmode);
timings = PCMCIA_SHT(pio_config_clk[pmode].t_hold)
| PCMCIA_SST(pio_config_clk[pmode].t_setup)
| PCMCIA_SL(pio_config_clk[pmode].t_length);
/*
* IDE 0
*/
pcmp->pcmc_pbr0 = CONFIG_SYS_PCMCIA_PBR0;
pcmp->pcmc_por0 = CONFIG_SYS_PCMCIA_POR0
#if (CONFIG_SYS_PCMCIA_POR0 != 0)
| timings
#endif
;
debug("PBR0: %08x POR0: %08x\n", pcmp->pcmc_pbr0, pcmp->pcmc_por0);
pcmp->pcmc_pbr1 = CONFIG_SYS_PCMCIA_PBR1;
pcmp->pcmc_por1 = CONFIG_SYS_PCMCIA_POR1
#if (CONFIG_SYS_PCMCIA_POR1 != 0)
| timings
#endif
;
debug("PBR1: %08x POR1: %08x\n", pcmp->pcmc_pbr1, pcmp->pcmc_por1);
pcmp->pcmc_pbr2 = CONFIG_SYS_PCMCIA_PBR2;
pcmp->pcmc_por2 = CONFIG_SYS_PCMCIA_POR2
#if (CONFIG_SYS_PCMCIA_POR2 != 0)
| timings
#endif
;
debug("PBR2: %08x POR2: %08x\n", pcmp->pcmc_pbr2, pcmp->pcmc_por2);
pcmp->pcmc_pbr3 = CONFIG_SYS_PCMCIA_PBR3;
pcmp->pcmc_por3 = CONFIG_SYS_PCMCIA_POR3
#if (CONFIG_SYS_PCMCIA_POR3 != 0)
| timings
#endif
;
debug("PBR3: %08x POR3: %08x\n", pcmp->pcmc_pbr3, pcmp->pcmc_por3);
/*
* IDE 1
*/
pcmp->pcmc_pbr4 = CONFIG_SYS_PCMCIA_PBR4;
pcmp->pcmc_por4 = CONFIG_SYS_PCMCIA_POR4
#if (CONFIG_SYS_PCMCIA_POR4 != 0)
| timings
#endif
;
debug("PBR4: %08x POR4: %08x\n", pcmp->pcmc_pbr4, pcmp->pcmc_por4);
pcmp->pcmc_pbr5 = CONFIG_SYS_PCMCIA_PBR5;
pcmp->pcmc_por5 = CONFIG_SYS_PCMCIA_POR5
#if (CONFIG_SYS_PCMCIA_POR5 != 0)
| timings
#endif
;
debug("PBR5: %08x POR5: %08x\n", pcmp->pcmc_pbr5, pcmp->pcmc_por5);
pcmp->pcmc_pbr6 = CONFIG_SYS_PCMCIA_PBR6;
pcmp->pcmc_por6 = CONFIG_SYS_PCMCIA_POR6
#if (CONFIG_SYS_PCMCIA_POR6 != 0)
| timings
#endif
;
debug("PBR6: %08x POR6: %08x\n", pcmp->pcmc_pbr6, pcmp->pcmc_por6);
pcmp->pcmc_pbr7 = CONFIG_SYS_PCMCIA_PBR7;
pcmp->pcmc_por7 = CONFIG_SYS_PCMCIA_POR7
#if (CONFIG_SYS_PCMCIA_POR7 != 0)
| timings
#endif
;
debug("PBR7: %08x POR7: %08x\n", pcmp->pcmc_pbr7, pcmp->pcmc_por7);
}
#endif /* CONFIG_IDE_8xx_DIRECT */
/* ------------------------------------------------------------------------- */
/* We only need to swap data if we are running on a big endian cpu. */
/* But Au1x00 cpu:s already swaps data in big endian mode! */
#if defined(__LITTLE_ENDIAN) || \
(defined(CONFIG_SOC_AU1X00) && !defined(CONFIG_GTH2))
#define input_swap_data(x,y,z) input_data(x,y,z)
#else
static void input_swap_data(int dev, ulong *sect_buf, int words)
{
#if defined(CONFIG_CPC45)
uchar i;
volatile uchar *pbuf_even =
(uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_EVEN);
volatile uchar *pbuf_odd =
(uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_ODD);
ushort *dbuf = (ushort *) sect_buf;
while (words--) {
for (i = 0; i < 2; i++) {
*(((uchar *) (dbuf)) + 1) = *pbuf_even;
*(uchar *) dbuf = *pbuf_odd;
dbuf += 1;
}
}
#else
volatile ushort *pbuf =
(ushort *) (ATA_CURR_BASE(dev) + ATA_DATA_REG);
ushort *dbuf = (ushort *) sect_buf;
debug("in input swap data base for read is %lx\n",
(unsigned long) pbuf);
while (words--) {
#ifdef __MIPS__
*dbuf++ = swab16p((u16 *) pbuf);
*dbuf++ = swab16p((u16 *) pbuf);
#elif defined(CONFIG_PCS440EP)
*dbuf++ = *pbuf;
*dbuf++ = *pbuf;
#else
*dbuf++ = ld_le16(pbuf);
*dbuf++ = ld_le16(pbuf);
#endif /* !MIPS */
}
#endif
}
#endif /* __LITTLE_ENDIAN || CONFIG_AU1X00 */
#if defined(CONFIG_IDE_SWAP_IO)
static void output_data(int dev, const ulong *sect_buf, int words)
{
#if defined(CONFIG_CPC45)
uchar *dbuf;
volatile uchar *pbuf_even;
volatile uchar *pbuf_odd;
pbuf_even = (uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_EVEN);
pbuf_odd = (uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_ODD);
dbuf = (uchar *) sect_buf;
while (words--) {
EIEIO;
*pbuf_even = *dbuf++;
EIEIO;
*pbuf_odd = *dbuf++;
EIEIO;
*pbuf_even = *dbuf++;
EIEIO;
*pbuf_odd = *dbuf++;
}
#else
ushort *dbuf;
volatile ushort *pbuf;
pbuf = (ushort *) (ATA_CURR_BASE(dev) + ATA_DATA_REG);
dbuf = (ushort *) sect_buf;
while (words--) {
#if defined(CONFIG_PCS440EP)
/* not tested, because CF was write protected */
EIEIO;
*pbuf = ld_le16(dbuf++);
EIEIO;
*pbuf = ld_le16(dbuf++);
#else
EIEIO;
*pbuf = *dbuf++;
EIEIO;
*pbuf = *dbuf++;
#endif
}
#endif
}
#else /* ! CONFIG_IDE_SWAP_IO */
static void output_data(int dev, const ulong *sect_buf, int words)
{
#if defined(CONFIG_IDE_AHB)
ide_write_data(dev, sect_buf, words);
#else
outsw(ATA_CURR_BASE(dev) + ATA_DATA_REG, sect_buf, words << 1);
#endif
}
#endif /* CONFIG_IDE_SWAP_IO */
#if defined(CONFIG_IDE_SWAP_IO)
static void input_data(int dev, ulong *sect_buf, int words)
{
#if defined(CONFIG_CPC45)
uchar *dbuf;
volatile uchar *pbuf_even;
volatile uchar *pbuf_odd;
pbuf_even = (uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_EVEN);
pbuf_odd = (uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_ODD);
dbuf = (uchar *) sect_buf;
while (words--) {
*dbuf++ = *pbuf_even;
EIEIO;
SYNC;
*dbuf++ = *pbuf_odd;
EIEIO;
SYNC;
*dbuf++ = *pbuf_even;
EIEIO;
SYNC;
*dbuf++ = *pbuf_odd;
EIEIO;
SYNC;
}
#else
ushort *dbuf;
volatile ushort *pbuf;
pbuf = (ushort *) (ATA_CURR_BASE(dev) + ATA_DATA_REG);
dbuf = (ushort *) sect_buf;
debug("in input data base for read is %lx\n", (unsigned long) pbuf);
while (words--) {
#if defined(CONFIG_PCS440EP)
EIEIO;
*dbuf++ = ld_le16(pbuf);
EIEIO;
*dbuf++ = ld_le16(pbuf);
#else
EIEIO;
*dbuf++ = *pbuf;
EIEIO;
*dbuf++ = *pbuf;
#endif
}
#endif
}
#else /* ! CONFIG_IDE_SWAP_IO */
static void input_data(int dev, ulong *sect_buf, int words)
{
#if defined(CONFIG_IDE_AHB)
ide_read_data(dev, sect_buf, words);
#else
insw(ATA_CURR_BASE(dev) + ATA_DATA_REG, sect_buf, words << 1);
#endif
}
#endif /* CONFIG_IDE_SWAP_IO */
/* -------------------------------------------------------------------------
*/
static void ide_ident(block_dev_desc_t *dev_desc)
{
unsigned char c;
hd_driveid_t iop;
#ifdef CONFIG_ATAPI
int retries = 0;
#endif
#ifdef CONFIG_TUNE_PIO
int pio_mode;
#endif
#if 0
int mode, cycle_time;
#endif
int device;
device = dev_desc->dev;
printf(" Device %d: ", device);
ide_led(DEVICE_LED(device), 1); /* LED on */
/* Select device
*/
ide_outb(device, ATA_DEV_HD, ATA_LBA | ATA_DEVICE(device));
dev_desc->if_type = IF_TYPE_IDE;
#ifdef CONFIG_ATAPI
retries = 0;
/* Warning: This will be tricky to read */
while (retries <= 1) {
/* check signature */
if ((ide_inb(device, ATA_SECT_CNT) == 0x01) &&
(ide_inb(device, ATA_SECT_NUM) == 0x01) &&
(ide_inb(device, ATA_CYL_LOW) == 0x14) &&
(ide_inb(device, ATA_CYL_HIGH) == 0xEB)) {
/* ATAPI Signature found */
dev_desc->if_type = IF_TYPE_ATAPI;
/*
* Start Ident Command
*/
ide_outb(device, ATA_COMMAND, ATAPI_CMD_IDENT);
/*
* Wait for completion - ATAPI devices need more time
* to become ready
*/
c = ide_wait(device, ATAPI_TIME_OUT);
} else
#endif
{
/*
* Start Ident Command
*/
ide_outb(device, ATA_COMMAND, ATA_CMD_IDENT);
/*
* Wait for completion
*/
c = ide_wait(device, IDE_TIME_OUT);
}
ide_led(DEVICE_LED(device), 0); /* LED off */
if (((c & ATA_STAT_DRQ) == 0) ||
((c & (ATA_STAT_FAULT | ATA_STAT_ERR)) != 0)) {
#ifdef CONFIG_ATAPI
{
/*
* Need to soft reset the device
* in case it's an ATAPI...
*/
debug("Retrying...\n");
ide_outb(device, ATA_DEV_HD,
ATA_LBA | ATA_DEVICE(device));
udelay(100000);
ide_outb(device, ATA_COMMAND, 0x08);
udelay(500000); /* 500 ms */
}
/*
* Select device
*/
ide_outb(device, ATA_DEV_HD,
ATA_LBA | ATA_DEVICE(device));
retries++;
#else
return;
#endif
}
#ifdef CONFIG_ATAPI
else
break;
} /* see above - ugly to read */
if (retries == 2) /* Not found */
return;
#endif
input_swap_data(device, (ulong *)&iop, ATA_SECTORWORDS);
ident_cpy((unsigned char *) dev_desc->revision, iop.fw_rev,
sizeof(dev_desc->revision));
ident_cpy((unsigned char *) dev_desc->vendor, iop.model,
sizeof(dev_desc->vendor));
ident_cpy((unsigned char *) dev_desc->product, iop.serial_no,
sizeof(dev_desc->product));
#ifdef __LITTLE_ENDIAN
/*
* firmware revision, model, and serial number have Big Endian Byte
* order in Word. Convert all three to little endian.
*
* See CF+ and CompactFlash Specification Revision 2.0:
* 6.2.1.6: Identify Drive, Table 39 for more details
*/
strswab(dev_desc->revision);
strswab(dev_desc->vendor);
strswab(dev_desc->product);
#endif /* __LITTLE_ENDIAN */
if ((iop.config & 0x0080) == 0x0080)
dev_desc->removable = 1;
else
dev_desc->removable = 0;
#ifdef CONFIG_TUNE_PIO
/* Mode 0 - 2 only, are directly determined by word 51. */
pio_mode = iop.tPIO;
if (pio_mode > 2) {
printf("WARNING: Invalid PIO (word 51 = %d).\n", pio_mode);
/* Force it to dead slow, and hope for the best... */
pio_mode = 0;
}
/* Any CompactFlash Storage Card that supports PIO mode 3 or above
* shall set bit 1 of word 53 to one and support the fields contained
* in words 64 through 70.
*/
if (iop.field_valid & 0x02) {
/*
* Mode 3 and above are possible. Check in order from slow
* to fast, so we wind up with the highest mode allowed.
*/
if (iop.eide_pio_modes & 0x01)
pio_mode = 3;
if (iop.eide_pio_modes & 0x02)
pio_mode = 4;
if (ata_id_is_cfa((u16 *)&iop)) {
if ((iop.cf_advanced_caps & 0x07) == 0x01)
pio_mode = 5;
if ((iop.cf_advanced_caps & 0x07) == 0x02)
pio_mode = 6;
}
}
/* System-specific, depends on bus speeds, etc. */
ide_set_piomode(pio_mode);
#endif /* CONFIG_TUNE_PIO */
#if 0
/*
* Drive PIO mode autoselection
*/
mode = iop.tPIO;
printf("tPIO = 0x%02x = %d\n", mode, mode);
if (mode > 2) { /* 2 is maximum allowed tPIO value */
mode = 2;
debug("Override tPIO -> 2\n");
}
if (iop.field_valid & 2) { /* drive implements ATA2? */
debug("Drive implements ATA2\n");
if (iop.capability & 8) { /* drive supports use_iordy? */
cycle_time = iop.eide_pio_iordy;
} else {
cycle_time = iop.eide_pio;
}
debug("cycle time = %d\n", cycle_time);
mode = 4;
if (cycle_time > 120)
mode = 3; /* 120 ns for PIO mode 4 */
if (cycle_time > 180)
mode = 2; /* 180 ns for PIO mode 3 */
if (cycle_time > 240)
mode = 1; /* 240 ns for PIO mode 4 */
if (cycle_time > 383)
mode = 0; /* 383 ns for PIO mode 4 */
}
printf("PIO mode to use: PIO %d\n", mode);
#endif /* 0 */
#ifdef CONFIG_ATAPI
if (dev_desc->if_type == IF_TYPE_ATAPI) {
atapi_inquiry(dev_desc);
return;
}
#endif /* CONFIG_ATAPI */
#ifdef __BIG_ENDIAN
/* swap shorts */
dev_desc->lba = (iop.lba_capacity << 16) | (iop.lba_capacity >> 16);
#else /* ! __BIG_ENDIAN */
/*
* do not swap shorts on little endian
*
* See CF+ and CompactFlash Specification Revision 2.0:
* 6.2.1.6: Identfy Drive, Table 39, Word Address 57-58 for details.
*/
dev_desc->lba = iop.lba_capacity;
#endif /* __BIG_ENDIAN */
#ifdef CONFIG_LBA48
if (iop.command_set_2 & 0x0400) { /* LBA 48 support */
dev_desc->lba48 = 1;
dev_desc->lba = (unsigned long long) iop.lba48_capacity[0] |
((unsigned long long) iop.lba48_capacity[1] << 16) |
((unsigned long long) iop.lba48_capacity[2] << 32) |
((unsigned long long) iop.lba48_capacity[3] << 48);
} else {
dev_desc->lba48 = 0;
}
#endif /* CONFIG_LBA48 */
/* assuming HD */
dev_desc->type = DEV_TYPE_HARDDISK;
dev_desc->blksz = ATA_BLOCKSIZE;
dev_desc->lun = 0; /* just to fill something in... */
#if 0 /* only used to test the powersaving mode,
* if enabled, the drive goes after 5 sec
* in standby mode */
ide_outb(device, ATA_DEV_HD, ATA_LBA | ATA_DEVICE(device));
c = ide_wait(device, IDE_TIME_OUT);
ide_outb(device, ATA_SECT_CNT, 1);
ide_outb(device, ATA_LBA_LOW, 0);
ide_outb(device, ATA_LBA_MID, 0);
ide_outb(device, ATA_LBA_HIGH, 0);
ide_outb(device, ATA_DEV_HD, ATA_LBA | ATA_DEVICE(device));
ide_outb(device, ATA_COMMAND, 0xe3);
udelay(50);
c = ide_wait(device, IDE_TIME_OUT); /* can't take over 500 ms */
#endif
}
/* ------------------------------------------------------------------------- */
ulong ide_read(int device, lbaint_t blknr, ulong blkcnt, void *buffer)
{
ulong n = 0;
unsigned char c;
unsigned char pwrsave = 0; /* power save */
#ifdef CONFIG_LBA48
unsigned char lba48 = 0;
if (blknr & 0x0000fffff0000000ULL) {
/* more than 28 bits used, use 48bit mode */
lba48 = 1;
}
#endif
debug("ide_read dev %d start %lX, blocks %lX buffer at %lX\n",
device, blknr, blkcnt, (ulong) buffer);
ide_led(DEVICE_LED(device), 1); /* LED on */
/* Select device
*/
ide_outb(device, ATA_DEV_HD, ATA_LBA | ATA_DEVICE(device));
c = ide_wait(device, IDE_TIME_OUT);
if (c & ATA_STAT_BUSY) {
printf("IDE read: device %d not ready\n", device);
goto IDE_READ_E;
}
/* first check if the drive is in Powersaving mode, if yes,
* increase the timeout value */
ide_outb(device, ATA_COMMAND, ATA_CMD_CHK_PWR);
udelay(50);
c = ide_wait(device, IDE_TIME_OUT); /* can't take over 500 ms */
if (c & ATA_STAT_BUSY) {
printf("IDE read: device %d not ready\n", device);
goto IDE_READ_E;
}
if ((c & ATA_STAT_ERR) == ATA_STAT_ERR) {
printf("No Powersaving mode %X\n", c);
} else {
c = ide_inb(device, ATA_SECT_CNT);
debug("Powersaving %02X\n", c);
if (c == 0)
pwrsave = 1;
}
while (blkcnt-- > 0) {
c = ide_wait(device, IDE_TIME_OUT);
if (c & ATA_STAT_BUSY) {
printf("IDE read: device %d not ready\n", device);
break;
}
#ifdef CONFIG_LBA48
if (lba48) {
/* write high bits */
ide_outb(device, ATA_SECT_CNT, 0);
ide_outb(device, ATA_LBA_LOW, (blknr >> 24) & 0xFF);
#ifdef CONFIG_SYS_64BIT_LBA
ide_outb(device, ATA_LBA_MID, (blknr >> 32) & 0xFF);
ide_outb(device, ATA_LBA_HIGH, (blknr >> 40) & 0xFF);
#else
ide_outb(device, ATA_LBA_MID, 0);
ide_outb(device, ATA_LBA_HIGH, 0);
#endif
}
#endif
ide_outb(device, ATA_SECT_CNT, 1);
ide_outb(device, ATA_LBA_LOW, (blknr >> 0) & 0xFF);
ide_outb(device, ATA_LBA_MID, (blknr >> 8) & 0xFF);
ide_outb(device, ATA_LBA_HIGH, (blknr >> 16) & 0xFF);
#ifdef CONFIG_LBA48
if (lba48) {
ide_outb(device, ATA_DEV_HD,
ATA_LBA | ATA_DEVICE(device));
ide_outb(device, ATA_COMMAND, ATA_CMD_READ_EXT);
} else
#endif
{
ide_outb(device, ATA_DEV_HD, ATA_LBA |
ATA_DEVICE(device) | ((blknr >> 24) & 0xF));
ide_outb(device, ATA_COMMAND, ATA_CMD_READ);
}
udelay(50);
if (pwrsave) {
/* may take up to 4 sec */
c = ide_wait(device, IDE_SPIN_UP_TIME_OUT);
pwrsave = 0;
} else {
/* can't take over 500 ms */
c = ide_wait(device, IDE_TIME_OUT);
}
if ((c & (ATA_STAT_DRQ | ATA_STAT_BUSY | ATA_STAT_ERR)) !=
ATA_STAT_DRQ) {
#if defined(CONFIG_SYS_64BIT_LBA)
printf("Error (no IRQ) dev %d blk %lld: status 0x%02x\n",
device, blknr, c);
#else
printf("Error (no IRQ) dev %d blk %ld: status 0x%02x\n",
device, (ulong) blknr, c);
#endif
break;
}
input_data(device, buffer, ATA_SECTORWORDS);
(void) ide_inb(device, ATA_STATUS); /* clear IRQ */
++n;
++blknr;
buffer += ATA_BLOCKSIZE;
}
IDE_READ_E:
ide_led(DEVICE_LED(device), 0); /* LED off */
return (n);
}
/* ------------------------------------------------------------------------- */
ulong ide_write(int device, lbaint_t blknr, ulong blkcnt, const void *buffer)
{
ulong n = 0;
unsigned char c;
#ifdef CONFIG_LBA48
unsigned char lba48 = 0;
if (blknr & 0x0000fffff0000000ULL) {
/* more than 28 bits used, use 48bit mode */
lba48 = 1;
}
#endif
ide_led(DEVICE_LED(device), 1); /* LED on */
/* Select device
*/
ide_outb(device, ATA_DEV_HD, ATA_LBA | ATA_DEVICE(device));
while (blkcnt-- > 0) {
c = ide_wait(device, IDE_TIME_OUT);
if (c & ATA_STAT_BUSY) {
printf("IDE read: device %d not ready\n", device);
goto WR_OUT;
}
#ifdef CONFIG_LBA48
if (lba48) {
/* write high bits */
ide_outb(device, ATA_SECT_CNT, 0);
ide_outb(device, ATA_LBA_LOW, (blknr >> 24) & 0xFF);
#ifdef CONFIG_SYS_64BIT_LBA
ide_outb(device, ATA_LBA_MID, (blknr >> 32) & 0xFF);
ide_outb(device, ATA_LBA_HIGH, (blknr >> 40) & 0xFF);
#else
ide_outb(device, ATA_LBA_MID, 0);
ide_outb(device, ATA_LBA_HIGH, 0);
#endif
}
#endif
ide_outb(device, ATA_SECT_CNT, 1);
ide_outb(device, ATA_LBA_LOW, (blknr >> 0) & 0xFF);
ide_outb(device, ATA_LBA_MID, (blknr >> 8) & 0xFF);
ide_outb(device, ATA_LBA_HIGH, (blknr >> 16) & 0xFF);
#ifdef CONFIG_LBA48
if (lba48) {
ide_outb(device, ATA_DEV_HD,
ATA_LBA | ATA_DEVICE(device));
ide_outb(device, ATA_COMMAND, ATA_CMD_WRITE_EXT);
} else
#endif
{
ide_outb(device, ATA_DEV_HD, ATA_LBA |
ATA_DEVICE(device) | ((blknr >> 24) & 0xF));
ide_outb(device, ATA_COMMAND, ATA_CMD_WRITE);
}
udelay(50);
/* can't take over 500 ms */
c = ide_wait(device, IDE_TIME_OUT);
if ((c & (ATA_STAT_DRQ | ATA_STAT_BUSY | ATA_STAT_ERR)) !=
ATA_STAT_DRQ) {
#if defined(CONFIG_SYS_64BIT_LBA)
printf("Error (no IRQ) dev %d blk %lld: status 0x%02x\n",
device, blknr, c);
#else
printf("Error (no IRQ) dev %d blk %ld: status 0x%02x\n",
device, (ulong) blknr, c);
#endif
goto WR_OUT;
}
output_data(device, buffer, ATA_SECTORWORDS);
c = ide_inb(device, ATA_STATUS); /* clear IRQ */
++n;
++blknr;
buffer += ATA_BLOCKSIZE;
}
WR_OUT:
ide_led(DEVICE_LED(device), 0); /* LED off */
return (n);
}
/* ------------------------------------------------------------------------- */
/*
* copy src to dest, skipping leading and trailing blanks and null
* terminate the string
* "len" is the size of available memory including the terminating '\0'
*/
static void ident_cpy(unsigned char *dst, unsigned char *src,
unsigned int len)
{
unsigned char *end, *last;
last = dst;
end = src + len - 1;
/* reserve space for '\0' */
if (len < 2)
goto OUT;
/* skip leading white space */
while ((*src) && (src < end) && (*src == ' '))
++src;
/* copy string, omitting trailing white space */
while ((*src) && (src < end)) {
*dst++ = *src;
if (*src++ != ' ')
last = dst;
}
OUT:
*last = '\0';
}
/* ------------------------------------------------------------------------- */
/*
* Wait until Busy bit is off, or timeout (in ms)
* Return last status
*/
static uchar ide_wait(int dev, ulong t)
{
ulong delay = 10 * t; /* poll every 100 us */
uchar c;
while ((c = ide_inb(dev, ATA_STATUS)) & ATA_STAT_BUSY) {
udelay(100);
if (delay-- == 0)
break;
}
return (c);
}
/* ------------------------------------------------------------------------- */
#ifdef CONFIG_IDE_RESET
extern void ide_set_reset(int idereset);
static void ide_reset(void)
{
#if defined(CONFIG_SYS_PB_12V_ENABLE) || defined(CONFIG_SYS_PB_IDE_MOTOR)
volatile immap_t *immr = (immap_t *) CONFIG_SYS_IMMR;
#endif
int i;
curr_device = -1;
for (i = 0; i < CONFIG_SYS_IDE_MAXBUS; ++i)
ide_bus_ok[i] = 0;
for (i = 0; i < CONFIG_SYS_IDE_MAXDEVICE; ++i)
ide_dev_desc[i].type = DEV_TYPE_UNKNOWN;
ide_set_reset(1); /* assert reset */
/* the reset signal shall be asserted for et least 25 us */
udelay(25);
WATCHDOG_RESET();
#ifdef CONFIG_SYS_PB_12V_ENABLE
/* 12V Enable output OFF */
immr->im_cpm.cp_pbdat &= ~(CONFIG_SYS_PB_12V_ENABLE);
immr->im_cpm.cp_pbpar &= ~(CONFIG_SYS_PB_12V_ENABLE);
immr->im_cpm.cp_pbodr &= ~(CONFIG_SYS_PB_12V_ENABLE);
immr->im_cpm.cp_pbdir |= CONFIG_SYS_PB_12V_ENABLE;
/* wait 500 ms for the voltage to stabilize */
for (i = 0; i < 500; ++i)
udelay(1000);
/* 12V Enable output ON */
immr->im_cpm.cp_pbdat |= CONFIG_SYS_PB_12V_ENABLE;
#endif /* CONFIG_SYS_PB_12V_ENABLE */
#ifdef CONFIG_SYS_PB_IDE_MOTOR
/* configure IDE Motor voltage monitor pin as input */
immr->im_cpm.cp_pbpar &= ~(CONFIG_SYS_PB_IDE_MOTOR);
immr->im_cpm.cp_pbodr &= ~(CONFIG_SYS_PB_IDE_MOTOR);
immr->im_cpm.cp_pbdir &= ~(CONFIG_SYS_PB_IDE_MOTOR);
/* wait up to 1 s for the motor voltage to stabilize */
for (i = 0; i < 1000; ++i) {
if ((immr->im_cpm.cp_pbdat & CONFIG_SYS_PB_IDE_MOTOR) != 0) {
break;
}
udelay(1000);
}
if (i == 1000) { /* Timeout */
printf("\nWarning: 5V for IDE Motor missing\n");
#ifdef CONFIG_STATUS_LED
#ifdef STATUS_LED_YELLOW
status_led_set(STATUS_LED_YELLOW, STATUS_LED_ON);
#endif
#ifdef STATUS_LED_GREEN
status_led_set(STATUS_LED_GREEN, STATUS_LED_OFF);
#endif
#endif /* CONFIG_STATUS_LED */
}
#endif /* CONFIG_SYS_PB_IDE_MOTOR */
WATCHDOG_RESET();
/* de-assert RESET signal */
ide_set_reset(0);
/* wait 250 ms */
for (i = 0; i < 250; ++i)
udelay(1000);
}
#endif /* CONFIG_IDE_RESET */
/* ------------------------------------------------------------------------- */
#if defined(CONFIG_IDE_LED) && \
!defined(CONFIG_CPC45) && \
!defined(CONFIG_KUP4K) && \
!defined(CONFIG_KUP4X)
static uchar led_buffer; /* Buffer for current LED status */
static void ide_led(uchar led, uchar status)
{
uchar *led_port = LED_PORT;
if (status) /* switch LED on */
led_buffer |= led;
else /* switch LED off */
led_buffer &= ~led;
*led_port = led_buffer;
}
#endif /* CONFIG_IDE_LED */
#if defined(CONFIG_OF_IDE_FIXUP)
int ide_device_present(int dev)
{
if (dev >= CONFIG_SYS_IDE_MAXBUS)
return 0;
return (ide_dev_desc[dev].type == DEV_TYPE_UNKNOWN ? 0 : 1);
}
#endif
/* ------------------------------------------------------------------------- */
#ifdef CONFIG_ATAPI
/****************************************************************************
* ATAPI Support
*/
#if defined(CONFIG_IDE_SWAP_IO)
/* since ATAPI may use commands with not 4 bytes alligned length
* we have our own transfer functions, 2 bytes alligned */
static void output_data_shorts(int dev, ushort *sect_buf, int shorts)
{
#if defined(CONFIG_CPC45)
uchar *dbuf;
volatile uchar *pbuf_even;
volatile uchar *pbuf_odd;
pbuf_even = (uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_EVEN);
pbuf_odd = (uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_ODD);
while (shorts--) {
EIEIO;
*pbuf_even = *dbuf++;
EIEIO;
*pbuf_odd = *dbuf++;
}
#else
ushort *dbuf;
volatile ushort *pbuf;
pbuf = (ushort *) (ATA_CURR_BASE(dev) + ATA_DATA_REG);
dbuf = (ushort *) sect_buf;
debug("in output data shorts base for read is %lx\n",
(unsigned long) pbuf);
while (shorts--) {
EIEIO;
*pbuf = *dbuf++;
}
#endif
}
static void input_data_shorts(int dev, ushort *sect_buf, int shorts)
{
#if defined(CONFIG_CPC45)
uchar *dbuf;
volatile uchar *pbuf_even;
volatile uchar *pbuf_odd;
pbuf_even = (uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_EVEN);
pbuf_odd = (uchar *) (ATA_CURR_BASE(dev) + ATA_DATA_ODD);
while (shorts--) {
EIEIO;
*dbuf++ = *pbuf_even;
EIEIO;
*dbuf++ = *pbuf_odd;
}
#else
ushort *dbuf;
volatile ushort *pbuf;
pbuf = (ushort *) (ATA_CURR_BASE(dev) + ATA_DATA_REG);
dbuf = (ushort *) sect_buf;
debug("in input data shorts base for read is %lx\n",
(unsigned long) pbuf);
while (shorts--) {
EIEIO;
*dbuf++ = *pbuf;
}
#endif
}
#else /* ! CONFIG_IDE_SWAP_IO */
static void output_data_shorts(int dev, ushort *sect_buf, int shorts)
{
outsw(ATA_CURR_BASE(dev) + ATA_DATA_REG, sect_buf, shorts);
}
static void input_data_shorts(int dev, ushort *sect_buf, int shorts)
{
insw(ATA_CURR_BASE(dev) + ATA_DATA_REG, sect_buf, shorts);
}
#endif /* CONFIG_IDE_SWAP_IO */
/*
* Wait until (Status & mask) == res, or timeout (in ms)
* Return last status
* This is used since some ATAPI CD ROMs clears their Busy Bit first
* and then they set their DRQ Bit
*/
static uchar atapi_wait_mask(int dev, ulong t, uchar mask, uchar res)
{
ulong delay = 10 * t; /* poll every 100 us */
uchar c;
/* prevents to read the status before valid */
c = ide_inb(dev, ATA_DEV_CTL);
while (((c = ide_inb(dev, ATA_STATUS)) & mask) != res) {
/* break if error occurs (doesn't make sense to wait more) */
if ((c & ATA_STAT_ERR) == ATA_STAT_ERR)
break;
udelay(100);
if (delay-- == 0)
break;
}
return (c);
}
/*
* issue an atapi command
*/
unsigned char atapi_issue(int device, unsigned char *ccb, int ccblen,
unsigned char *buffer, int buflen)
{
unsigned char c, err, mask, res;
int n;
ide_led(DEVICE_LED(device), 1); /* LED on */
/* Select device
*/
mask = ATA_STAT_BUSY | ATA_STAT_DRQ;
res = 0;
ide_outb(device, ATA_DEV_HD, ATA_LBA | ATA_DEVICE(device));
c = atapi_wait_mask(device, ATAPI_TIME_OUT, mask, res);
if ((c & mask) != res) {
printf("ATAPI_ISSUE: device %d not ready status %X\n", device,
c);
err = 0xFF;
goto AI_OUT;
}
/* write taskfile */
ide_outb(device, ATA_ERROR_REG, 0); /* no DMA, no overlaped */
ide_outb(device, ATA_SECT_CNT, 0);
ide_outb(device, ATA_SECT_NUM, 0);
ide_outb(device, ATA_CYL_LOW, (unsigned char) (buflen & 0xFF));
ide_outb(device, ATA_CYL_HIGH,
(unsigned char) ((buflen >> 8) & 0xFF));
ide_outb(device, ATA_DEV_HD, ATA_LBA | ATA_DEVICE(device));
ide_outb(device, ATA_COMMAND, ATAPI_CMD_PACKET);
udelay(50);
mask = ATA_STAT_DRQ | ATA_STAT_BUSY | ATA_STAT_ERR;
res = ATA_STAT_DRQ;
c = atapi_wait_mask(device, ATAPI_TIME_OUT, mask, res);
if ((c & mask) != res) { /* DRQ must be 1, BSY 0 */
printf("ATAPI_ISSUE: Error (no IRQ) before sending ccb dev %d status 0x%02x\n",
device, c);
err = 0xFF;
goto AI_OUT;
}
/* write command block */
output_data_shorts(device, (unsigned short *) ccb, ccblen / 2);
/* ATAPI Command written wait for completition */
udelay(5000); /* device must set bsy */
mask = ATA_STAT_DRQ | ATA_STAT_BUSY | ATA_STAT_ERR;
/*
* if no data wait for DRQ = 0 BSY = 0
* if data wait for DRQ = 1 BSY = 0
*/
res = 0;
if (buflen)
res = ATA_STAT_DRQ;
c = atapi_wait_mask(device, ATAPI_TIME_OUT, mask, res);
if ((c & mask) != res) {
if (c & ATA_STAT_ERR) {
err = (ide_inb(device, ATA_ERROR_REG)) >> 4;
debug("atapi_issue 1 returned sense key %X status %02X\n",
err, c);
} else {
printf("ATAPI_ISSUE: (no DRQ) after sending ccb (%x) status 0x%02x\n",
ccb[0], c);
err = 0xFF;
}
goto AI_OUT;
}
n = ide_inb(device, ATA_CYL_HIGH);
n <<= 8;
n += ide_inb(device, ATA_CYL_LOW);
if (n > buflen) {
printf("ERROR, transfer bytes %d requested only %d\n", n,
buflen);
err = 0xff;
goto AI_OUT;
}
if ((n == 0) && (buflen < 0)) {
printf("ERROR, transfer bytes %d requested %d\n", n, buflen);
err = 0xff;
goto AI_OUT;
}
if (n != buflen) {
debug("WARNING, transfer bytes %d not equal with requested %d\n",
n, buflen);
}
if (n != 0) { /* data transfer */
debug("ATAPI_ISSUE: %d Bytes to transfer\n", n);
/* we transfer shorts */
n >>= 1;
/* ok now decide if it is an in or output */
if ((ide_inb(device, ATA_SECT_CNT) & 0x02) == 0) {
debug("Write to device\n");
output_data_shorts(device, (unsigned short *) buffer,
n);
} else {
debug("Read from device @ %p shorts %d\n", buffer, n);
input_data_shorts(device, (unsigned short *) buffer,
n);
}
}
udelay(5000); /* seems that some CD ROMs need this... */
mask = ATA_STAT_BUSY | ATA_STAT_ERR;
res = 0;
c = atapi_wait_mask(device, ATAPI_TIME_OUT, mask, res);
if ((c & ATA_STAT_ERR) == ATA_STAT_ERR) {
err = (ide_inb(device, ATA_ERROR_REG) >> 4);
debug("atapi_issue 2 returned sense key %X status %X\n", err,
c);
} else {
err = 0;
}
AI_OUT:
ide_led(DEVICE_LED(device), 0); /* LED off */
return (err);
}
/*
* sending the command to atapi_issue. If an status other than good
* returns, an request_sense will be issued
*/
#define ATAPI_DRIVE_NOT_READY 100
#define ATAPI_UNIT_ATTN 10
unsigned char atapi_issue_autoreq(int device,
unsigned char *ccb,
int ccblen,
unsigned char *buffer, int buflen)
{
unsigned char sense_data[18], sense_ccb[12];
unsigned char res, key, asc, ascq;
int notready, unitattn;
unitattn = ATAPI_UNIT_ATTN;
notready = ATAPI_DRIVE_NOT_READY;
retry:
res = atapi_issue(device, ccb, ccblen, buffer, buflen);
if (res == 0)
return 0; /* Ok */
if (res == 0xFF)
return 0xFF; /* error */
debug("(auto_req)atapi_issue returned sense key %X\n", res);
memset(sense_ccb, 0, sizeof(sense_ccb));
memset(sense_data, 0, sizeof(sense_data));
sense_ccb[0] = ATAPI_CMD_REQ_SENSE;
sense_ccb[4] = 18; /* allocation Length */
res = atapi_issue(device, sense_ccb, 12, sense_data, 18);
key = (sense_data[2] & 0xF);
asc = (sense_data[12]);
ascq = (sense_data[13]);
debug("ATAPI_CMD_REQ_SENSE returned %x\n", res);
debug(" Sense page: %02X key %02X ASC %02X ASCQ %02X\n",
sense_data[0], key, asc, ascq);
if ((key == 0))
return 0; /* ok device ready */
if ((key == 6) || (asc == 0x29) || (asc == 0x28)) { /* Unit Attention */
if (unitattn-- > 0) {
udelay(200 * 1000);
goto retry;
}
printf("Unit Attention, tried %d\n", ATAPI_UNIT_ATTN);
goto error;
}
if ((asc == 0x4) && (ascq == 0x1)) {
/* not ready, but will be ready soon */
if (notready-- > 0) {
udelay(200 * 1000);
goto retry;
}
printf("Drive not ready, tried %d times\n",
ATAPI_DRIVE_NOT_READY);
goto error;
}
if (asc == 0x3a) {
debug("Media not present\n");
goto error;
}
printf("ERROR: Unknown Sense key %02X ASC %02X ASCQ %02X\n", key, asc,
ascq);
error:
debug("ERROR Sense key %02X ASC %02X ASCQ %02X\n", key, asc, ascq);
return (0xFF);
}
static void atapi_inquiry(block_dev_desc_t *dev_desc)
{
unsigned char ccb[12]; /* Command descriptor block */
unsigned char iobuf[64]; /* temp buf */
unsigned char c;
int device;
device = dev_desc->dev;
dev_desc->type = DEV_TYPE_UNKNOWN; /* not yet valid */
dev_desc->block_read = atapi_read;
memset(ccb, 0, sizeof(ccb));
memset(iobuf, 0, sizeof(iobuf));
ccb[0] = ATAPI_CMD_INQUIRY;
ccb[4] = 40; /* allocation Legnth */
c = atapi_issue_autoreq(device, ccb, 12, (unsigned char *) iobuf, 40);
debug("ATAPI_CMD_INQUIRY returned %x\n", c);
if (c != 0)
return;
/* copy device ident strings */
ident_cpy((unsigned char *) dev_desc->vendor, &iobuf[8], 8);
ident_cpy((unsigned char *) dev_desc->product, &iobuf[16], 16);
ident_cpy((unsigned char *) dev_desc->revision, &iobuf[32], 5);
dev_desc->lun = 0;
dev_desc->lba = 0;
dev_desc->blksz = 0;
dev_desc->type = iobuf[0] & 0x1f;
if ((iobuf[1] & 0x80) == 0x80)
dev_desc->removable = 1;
else
dev_desc->removable = 0;
memset(ccb, 0, sizeof(ccb));
memset(iobuf, 0, sizeof(iobuf));
ccb[0] = ATAPI_CMD_START_STOP;
ccb[4] = 0x03; /* start */
c = atapi_issue_autoreq(device, ccb, 12, (unsigned char *) iobuf, 0);
debug("ATAPI_CMD_START_STOP returned %x\n", c);
if (c != 0)
return;
memset(ccb, 0, sizeof(ccb));
memset(iobuf, 0, sizeof(iobuf));
c = atapi_issue_autoreq(device, ccb, 12, (unsigned char *) iobuf, 0);
debug("ATAPI_CMD_UNIT_TEST_READY returned %x\n", c);
if (c != 0)
return;
memset(ccb, 0, sizeof(ccb));
memset(iobuf, 0, sizeof(iobuf));
ccb[0] = ATAPI_CMD_READ_CAP;
c = atapi_issue_autoreq(device, ccb, 12, (unsigned char *) iobuf, 8);
debug("ATAPI_CMD_READ_CAP returned %x\n", c);
if (c != 0)
return;
debug("Read Cap: LBA %02X%02X%02X%02X blksize %02X%02X%02X%02X\n",
iobuf[0], iobuf[1], iobuf[2], iobuf[3],
iobuf[4], iobuf[5], iobuf[6], iobuf[7]);
dev_desc->lba = ((unsigned long) iobuf[0] << 24) +
((unsigned long) iobuf[1] << 16) +
((unsigned long) iobuf[2] << 8) + ((unsigned long) iobuf[3]);
dev_desc->blksz = ((unsigned long) iobuf[4] << 24) +
((unsigned long) iobuf[5] << 16) +
((unsigned long) iobuf[6] << 8) + ((unsigned long) iobuf[7]);
#ifdef CONFIG_LBA48
/* ATAPI devices cannot use 48bit addressing (ATA/ATAPI v7) */
dev_desc->lba48 = 0;
#endif
return;
}
/*
* atapi_read:
* we transfer only one block per command, since the multiple DRQ per
* command is not yet implemented
*/
#define ATAPI_READ_MAX_BYTES 2048 /* we read max 2kbytes */
#define ATAPI_READ_BLOCK_SIZE 2048 /* assuming CD part */
#define ATAPI_READ_MAX_BLOCK (ATAPI_READ_MAX_BYTES/ATAPI_READ_BLOCK_SIZE)
ulong atapi_read(int device, lbaint_t blknr, ulong blkcnt, void *buffer)
{
ulong n = 0;
unsigned char ccb[12]; /* Command descriptor block */
ulong cnt;
debug("atapi_read dev %d start %lX, blocks %lX buffer at %lX\n",
device, blknr, blkcnt, (ulong) buffer);
do {
if (blkcnt > ATAPI_READ_MAX_BLOCK)
cnt = ATAPI_READ_MAX_BLOCK;
else
cnt = blkcnt;
ccb[0] = ATAPI_CMD_READ_12;
ccb[1] = 0; /* reserved */
ccb[2] = (unsigned char) (blknr >> 24) & 0xFF; /* MSB Block */
ccb[3] = (unsigned char) (blknr >> 16) & 0xFF; /* */
ccb[4] = (unsigned char) (blknr >> 8) & 0xFF;
ccb[5] = (unsigned char) blknr & 0xFF; /* LSB Block */
ccb[6] = (unsigned char) (cnt >> 24) & 0xFF; /* MSB Block cnt */
ccb[7] = (unsigned char) (cnt >> 16) & 0xFF;
ccb[8] = (unsigned char) (cnt >> 8) & 0xFF;
ccb[9] = (unsigned char) cnt & 0xFF; /* LSB Block */
ccb[10] = 0; /* reserved */
ccb[11] = 0; /* reserved */
if (atapi_issue_autoreq(device, ccb, 12,
(unsigned char *) buffer,
cnt * ATAPI_READ_BLOCK_SIZE)
== 0xFF) {
return (n);
}
n += cnt;
blkcnt -= cnt;
blknr += cnt;
buffer += (cnt * ATAPI_READ_BLOCK_SIZE);
} while (blkcnt > 0);
return (n);
}
/* ------------------------------------------------------------------------- */
#endif /* CONFIG_ATAPI */
U_BOOT_CMD(ide, 5, 1, do_ide,
"IDE sub-system",
"reset - reset IDE controller\n"
"ide info - show available IDE devices\n"
"ide device [dev] - show or set current device\n"
"ide part [dev] - print partition table of one or all IDE devices\n"
"ide read addr blk# cnt\n"
"ide write addr blk# cnt - read/write `cnt'"
" blocks starting at block `blk#'\n"
" to/from memory address `addr'");
U_BOOT_CMD(diskboot, 3, 1, do_diskboot,
"boot from IDE device", "loadAddr dev:part");
|
1001-study-uboot
|
common/cmd_ide.c
|
C
|
gpl3
| 51,578
|
/*
* 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_echo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
int putnl = 1;
for (i = 1; i < argc; i++) {
char *p = argv[i], c;
if (i > 1)
putc(' ');
while ((c = *p++) != '\0') {
if (c == '\\' && *p == 'c') {
putnl = 0;
p++;
} else {
putc(c);
}
}
}
if (putnl)
putc('\n');
return 0;
}
U_BOOT_CMD(
echo, CONFIG_SYS_MAXARGS, 1, do_echo,
"echo args to console",
"[args..]\n"
" - echo args to console; \\c suppresses newline"
);
|
1001-study-uboot
|
common/cmd_echo.c
|
C
|
gpl3
| 1,419
|
/*
* (C) Copyright 2003
* 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 <linux/compiler.h>
DECLARE_GLOBAL_DATA_PTR;
__maybe_unused
static void print_num(const char *name, ulong value)
{
printf("%-12s= 0x%08lX\n", name, value);
}
__maybe_unused
static void print_eth(int idx)
{
char name[10], *val;
if (idx)
sprintf(name, "eth%iaddr", idx);
else
strcpy(name, "ethaddr");
val = getenv(name);
if (!val)
val = "(not set)";
printf("%-12s= %s\n", name, val);
}
__maybe_unused
static void print_lnum(const char *name, u64 value)
{
printf("%-12s= 0x%.8llX\n", name, value);
}
__maybe_unused
static void print_mhz(const char *name, unsigned long hz)
{
char buf[32];
printf("%-12s= %6s MHz\n", name, strmhz(buf, hz));
}
#if defined(CONFIG_PPC)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
#ifdef DEBUG
print_num("bd address", (ulong)bd);
#endif
print_num("memstart", bd->bi_memstart);
print_lnum("memsize", bd->bi_memsize);
print_num("flashstart", bd->bi_flashstart);
print_num("flashsize", bd->bi_flashsize);
print_num("flashoffset", bd->bi_flashoffset);
print_num("sramstart", bd->bi_sramstart);
print_num("sramsize", bd->bi_sramsize);
#if defined(CONFIG_5xx) || defined(CONFIG_8xx) || \
defined(CONFIG_8260) || defined(CONFIG_E500)
print_num("immr_base", bd->bi_immr_base);
#endif
print_num("bootflags", bd->bi_bootflags);
#if defined(CONFIG_405CR) || defined(CONFIG_405EP) || \
defined(CONFIG_405GP) || \
defined(CONFIG_440EP) || defined(CONFIG_440EPX) || \
defined(CONFIG_440GR) || defined(CONFIG_440GRX) || \
defined(CONFIG_440SP) || defined(CONFIG_440SPE) || \
defined(CONFIG_XILINX_405)
print_mhz("procfreq", bd->bi_procfreq);
print_mhz("plb_busfreq", bd->bi_plb_busfreq);
#if defined(CONFIG_405EP) || defined(CONFIG_405GP) || \
defined(CONFIG_440EP) || defined(CONFIG_440EPX) || \
defined(CONFIG_440GR) || defined(CONFIG_440GRX) || \
defined(CONFIG_440SPE) || defined(CONFIG_XILINX_405)
print_mhz("pci_busfreq", bd->bi_pci_busfreq);
#endif
#else /* ! CONFIG_405GP, CONFIG_405CR, CONFIG_405EP, CONFIG_XILINX_405, CONFIG_440EP CONFIG_440GR */
#if defined(CONFIG_CPM2)
print_mhz("vco", bd->bi_vco);
print_mhz("sccfreq", bd->bi_sccfreq);
print_mhz("brgfreq", bd->bi_brgfreq);
#endif
print_mhz("intfreq", bd->bi_intfreq);
#if defined(CONFIG_CPM2)
print_mhz("cpmfreq", bd->bi_cpmfreq);
#endif
print_mhz("busfreq", bd->bi_busfreq);
#endif /* CONFIG_405GP, CONFIG_405CR, CONFIG_405EP, CONFIG_XILINX_405, CONFIG_440EP CONFIG_440GR */
#if defined(CONFIG_MPC8220)
print_mhz("inpfreq", bd->bi_inpfreq);
print_mhz("flbfreq", bd->bi_flbfreq);
print_mhz("pcifreq", bd->bi_pcifreq);
print_mhz("vcofreq", bd->bi_vcofreq);
print_mhz("pevfreq", bd->bi_pevfreq);
#endif
print_eth(0);
#if defined(CONFIG_HAS_ETH1)
print_eth(1);
#endif
#if defined(CONFIG_HAS_ETH2)
print_eth(2);
#endif
#if defined(CONFIG_HAS_ETH3)
print_eth(3);
#endif
#if defined(CONFIG_HAS_ETH4)
print_eth(4);
#endif
#if defined(CONFIG_HAS_ETH5)
print_eth(5);
#endif
#ifdef CONFIG_HERMES
print_mhz("ethspeed", bd->bi_ethspeed);
#endif
printf("IP addr = %pI4\n", &bd->bi_ip_addr);
printf("baudrate = %6ld bps\n", bd->bi_baudrate);
print_num("relocaddr", gd->relocaddr);
return 0;
}
#elif defined(CONFIG_NIOS2)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
print_num("mem start", (ulong)bd->bi_memstart);
print_lnum("mem size", (u64)bd->bi_memsize);
print_num("flash start", (ulong)bd->bi_flashstart);
print_num("flash size", (ulong)bd->bi_flashsize);
print_num("flash offset", (ulong)bd->bi_flashoffset);
#if defined(CONFIG_SYS_SRAM_BASE)
print_num ("sram start", (ulong)bd->bi_sramstart);
print_num ("sram size", (ulong)bd->bi_sramsize);
#endif
#if defined(CONFIG_CMD_NET)
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
#endif
printf("baudrate = %ld bps\n", bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_MICROBLAZE)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
print_num("mem start ", (ulong)bd->bi_memstart);
print_lnum("mem size ", (u64)bd->bi_memsize);
print_num("flash start ", (ulong)bd->bi_flashstart);
print_num("flash size ", (ulong)bd->bi_flashsize);
print_num("flash offset ", (ulong)bd->bi_flashoffset);
#if defined(CONFIG_SYS_SRAM_BASE)
print_num("sram start ", (ulong)bd->bi_sramstart);
print_num("sram size ", (ulong)bd->bi_sramsize);
#endif
#if defined(CONFIG_CMD_NET)
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
#endif
printf("baudrate = %ld bps\n", (ulong)bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_SPARC)
int do_bdinfo(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
#ifdef DEBUG
print_num("bd address ", (ulong) bd);
#endif
print_num("memstart ", bd->bi_memstart);
print_lnum("memsize ", bd->bi_memsize);
print_num("flashstart ", bd->bi_flashstart);
print_num("CONFIG_SYS_MONITOR_BASE ", CONFIG_SYS_MONITOR_BASE);
print_num("CONFIG_ENV_ADDR ", CONFIG_ENV_ADDR);
printf("CONFIG_SYS_RELOC_MONITOR_BASE = 0x%lx (%d)\n", CONFIG_SYS_RELOC_MONITOR_BASE,
CONFIG_SYS_MONITOR_LEN);
printf("CONFIG_SYS_MALLOC_BASE = 0x%lx (%d)\n", CONFIG_SYS_MALLOC_BASE,
CONFIG_SYS_MALLOC_LEN);
printf("CONFIG_SYS_INIT_SP_OFFSET = 0x%lx (%d)\n", CONFIG_SYS_INIT_SP_OFFSET,
CONFIG_SYS_STACK_SIZE);
printf("CONFIG_SYS_PROM_OFFSET = 0x%lx (%d)\n", CONFIG_SYS_PROM_OFFSET,
CONFIG_SYS_PROM_SIZE);
printf("CONFIG_SYS_GBL_DATA_OFFSET = 0x%lx (%d)\n", CONFIG_SYS_GBL_DATA_OFFSET,
GENERATED_GBL_DATA_SIZE);
#if defined(CONFIG_CMD_NET)
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
#endif
printf("baudrate = %6ld bps\n", bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_M68K)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
print_num("memstart", (ulong)bd->bi_memstart);
print_lnum("memsize", (u64)bd->bi_memsize);
print_num("flashstart", (ulong)bd->bi_flashstart);
print_num("flashsize", (ulong)bd->bi_flashsize);
print_num("flashoffset", (ulong)bd->bi_flashoffset);
#if defined(CONFIG_SYS_INIT_RAM_ADDR)
print_num("sramstart", (ulong)bd->bi_sramstart);
print_num("sramsize", (ulong)bd->bi_sramsize);
#endif
#if defined(CONFIG_SYS_MBAR)
print_num("mbar", bd->bi_mbar_base);
#endif
print_mhz("cpufreq", bd->bi_intfreq);
print_mhz("busfreq", bd->bi_busfreq);
#ifdef CONFIG_PCI
print_mhz("pcifreq", bd->bi_pcifreq);
#endif
#ifdef CONFIG_EXTRA_CLOCK
print_mhz("flbfreq", bd->bi_flbfreq);
print_mhz("inpfreq", bd->bi_inpfreq);
print_mhz("vcofreq", bd->bi_vcofreq);
#endif
#if defined(CONFIG_CMD_NET)
print_eth(0);
#if defined(CONFIG_HAS_ETH1)
print_eth(1);
#endif
#if defined(CONFIG_HAS_ETH2)
print_eth(2);
#endif
#if defined(CONFIG_HAS_ETH3)
print_eth(3);
#endif
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
#endif
printf("baudrate = %ld bps\n", bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_BLACKFIN)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
printf("U-Boot = %s\n", bd->bi_r_version);
printf("CPU = %s\n", bd->bi_cpu);
printf("Board = %s\n", bd->bi_board_name);
print_mhz("VCO", bd->bi_vco);
print_mhz("CCLK", bd->bi_cclk);
print_mhz("SCLK", bd->bi_sclk);
print_num("boot_params", (ulong)bd->bi_boot_params);
print_num("memstart", (ulong)bd->bi_memstart);
print_lnum("memsize", (u64)bd->bi_memsize);
print_num("flashstart", (ulong)bd->bi_flashstart);
print_num("flashsize", (ulong)bd->bi_flashsize);
print_num("flashoffset", (ulong)bd->bi_flashoffset);
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
printf("baudrate = %d bps\n", bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_MIPS)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
print_num("boot_params", (ulong)bd->bi_boot_params);
print_num("memstart", (ulong)bd->bi_memstart);
print_lnum("memsize", (u64)bd->bi_memsize);
print_num("flashstart", (ulong)bd->bi_flashstart);
print_num("flashsize", (ulong)bd->bi_flashsize);
print_num("flashoffset", (ulong)bd->bi_flashoffset);
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
printf("baudrate = %d bps\n", bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_AVR32)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
print_num("boot_params", (ulong)bd->bi_boot_params);
print_num("memstart", (ulong)bd->bi_memstart);
print_lnum("memsize", (u64)bd->bi_memsize);
print_num("flashstart", (ulong)bd->bi_flashstart);
print_num("flashsize", (ulong)bd->bi_flashsize);
print_num("flashoffset", (ulong)bd->bi_flashoffset);
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
printf("baudrate = %lu bps\n", bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_ARM)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
bd_t *bd = gd->bd;
print_num("arch_number", bd->bi_arch_number);
print_num("boot_params", (ulong)bd->bi_boot_params);
for (i = 0; i < CONFIG_NR_DRAM_BANKS; ++i) {
print_num("DRAM bank", i);
print_num("-> start", bd->bi_dram[i].start);
print_num("-> size", bd->bi_dram[i].size);
}
#if defined(CONFIG_CMD_NET)
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
#endif
printf("baudrate = %d bps\n", bd->bi_baudrate);
#if !(defined(CONFIG_SYS_ICACHE_OFF) && defined(CONFIG_SYS_DCACHE_OFF))
print_num("TLB addr", gd->tlb_addr);
#endif
print_num("relocaddr", gd->relocaddr);
print_num("reloc off", gd->reloc_off);
print_num("irq_sp", gd->irq_sp); /* irq stack pointer */
print_num("sp start ", gd->start_addr_sp);
print_num("FB base ", gd->fb_base);
#ifdef CONFIG_NAND_BOOT
printf("Wangxi:NandBoot_Start: %x\n", CONFIG_SYS_TEXT_BASE);
#endif
return 0;
}
#elif defined(CONFIG_SH)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
print_num("mem start ", (ulong)bd->bi_memstart);
print_lnum("mem size ", (u64)bd->bi_memsize);
print_num("flash start ", (ulong)bd->bi_flashstart);
print_num("flash size ", (ulong)bd->bi_flashsize);
print_num("flash offset ", (ulong)bd->bi_flashoffset);
#if defined(CONFIG_CMD_NET)
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
#endif
printf("baudrate = %ld bps\n", (ulong)bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_X86)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
bd_t *bd = gd->bd;
print_num("boot_params", (ulong)bd->bi_boot_params);
print_num("bi_memstart", bd->bi_memstart);
print_num("bi_memsize", bd->bi_memsize);
print_num("bi_flashstart", bd->bi_flashstart);
print_num("bi_flashsize", bd->bi_flashsize);
print_num("bi_flashoffset", bd->bi_flashoffset);
print_num("bi_sramstart", bd->bi_sramstart);
print_num("bi_sramsize", bd->bi_sramsize);
print_num("bi_bootflags", bd->bi_bootflags);
print_mhz("cpufreq", bd->bi_intfreq);
print_mhz("busfreq", bd->bi_busfreq);
for (i = 0; i < CONFIG_NR_DRAM_BANKS; ++i) {
print_num("DRAM bank", i);
print_num("-> start", bd->bi_dram[i].start);
print_num("-> size", bd->bi_dram[i].size);
}
#if defined(CONFIG_CMD_NET)
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
print_mhz("ethspeed", bd->bi_ethspeed);
#endif
printf("baudrate = %d bps\n", bd->bi_baudrate);
return 0;
}
#elif defined(CONFIG_SANDBOX)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
bd_t *bd = gd->bd;
print_num("boot_params", (ulong)bd->bi_boot_params);
for (i = 0; i < CONFIG_NR_DRAM_BANKS; ++i) {
print_num("DRAM bank", i);
print_num("-> start", bd->bi_dram[i].start);
print_num("-> size", bd->bi_dram[i].size);
}
#if defined(CONFIG_CMD_NET)
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
#endif
print_num("FB base ", gd->fb_base);
return 0;
}
#elif defined(CONFIG_NDS32)
int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
bd_t *bd = gd->bd;
print_num("arch_number", bd->bi_arch_number);
print_num("boot_params", (ulong)bd->bi_boot_params);
for (i = 0; i < CONFIG_NR_DRAM_BANKS; ++i) {
print_num("DRAM bank", i);
print_num("-> start", bd->bi_dram[i].start);
print_num("-> size", bd->bi_dram[i].size);
}
#if defined(CONFIG_CMD_NET)
print_eth(0);
printf("ip_addr = %pI4\n", &bd->bi_ip_addr);
#endif
printf("baudrate = %d bps\n", bd->bi_baudrate);
return 0;
}
#else
#error "a case for this architecture does not exist!"
#endif
/* -------------------------------------------------------------------- */
U_BOOT_CMD(
bdinfo, 1, 1, do_bdinfo,
"print Board Info structure",
""
);
|
1001-study-uboot
|
common/cmd_bdinfo.c
|
C
|
gpl3
| 13,899
|
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* based on: cmd_jffs2.c
*
* Add support for a CRAMFS located in RAM
*/
/*
* CRAMFS support
*/
#include <common.h>
#include <command.h>
#include <malloc.h>
#include <linux/list.h>
#include <linux/ctype.h>
#include <jffs2/jffs2.h>
#include <jffs2/load_kernel.h>
#include <cramfs/cramfs_fs.h>
/* enable/disable debugging messages */
#define DEBUG_CRAMFS
#undef DEBUG_CRAMFS
#ifdef DEBUG_CRAMFS
# define DEBUGF(fmt, args...) printf(fmt ,##args)
#else
# define DEBUGF(fmt, args...)
#endif
#ifdef CONFIG_CRAMFS_CMDLINE
#include <flash.h>
#ifdef CONFIG_SYS_NO_FLASH
# define OFFSET_ADJUSTMENT 0
#else
# define OFFSET_ADJUSTMENT (flash_info[id.num].start[0])
#endif
#ifndef CONFIG_CMD_JFFS2
#include <linux/stat.h>
char *mkmodestr(unsigned long mode, char *str)
{
static const char *l = "xwr";
int mask = 1, i;
char c;
switch (mode & S_IFMT) {
case S_IFDIR: str[0] = 'd'; break;
case S_IFBLK: str[0] = 'b'; break;
case S_IFCHR: str[0] = 'c'; break;
case S_IFIFO: str[0] = 'f'; break;
case S_IFLNK: str[0] = 'l'; break;
case S_IFSOCK: str[0] = 's'; break;
case S_IFREG: str[0] = '-'; break;
default: str[0] = '?';
}
for(i = 0; i < 9; i++) {
c = l[i%3];
str[9-i] = (mode & mask)?c:'-';
mask = mask<<1;
}
if(mode & S_ISUID) str[3] = (mode & S_IXUSR)?'s':'S';
if(mode & S_ISGID) str[6] = (mode & S_IXGRP)?'s':'S';
if(mode & S_ISVTX) str[9] = (mode & S_IXOTH)?'t':'T';
str[10] = '\0';
return str;
}
#endif /* CONFIG_CMD_JFFS2 */
extern int cramfs_check (struct part_info *info);
extern int cramfs_load (char *loadoffset, struct part_info *info, char *filename);
extern int cramfs_ls (struct part_info *info, char *filename);
extern int cramfs_info (struct part_info *info);
/***************************************************/
/* U-boot commands */
/***************************************************/
/**
* Routine implementing fsload u-boot command. This routine tries to load
* a requested file from cramfs filesystem at location 'cramfsaddr'.
* cramfsaddr is an evironment variable.
*
* @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_cramfs_load(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename;
int size;
ulong offset = load_addr;
struct part_info part;
struct mtd_device dev;
struct mtdids id;
ulong addr;
addr = simple_strtoul(getenv("cramfsaddr"), NULL, 16);
/* hack! */
/* cramfs_* only supports NOR flash chips */
/* fake the device type */
id.type = MTD_DEV_TYPE_NOR;
id.num = 0;
dev.id = &id;
part.dev = &dev;
/* fake the address offset */
part.offset = addr - OFFSET_ADJUSTMENT;
/* pre-set Boot file name */
if ((filename = getenv("bootfile")) == NULL) {
filename = "uImage";
}
if (argc == 2) {
filename = argv[1];
}
if (argc == 3) {
offset = simple_strtoul(argv[1], NULL, 0);
load_addr = offset;
filename = argv[2];
}
size = 0;
if (cramfs_check(&part))
size = cramfs_load ((char *) offset, &part, filename);
if (size > 0) {
char buf[10];
printf("### CRAMFS load complete: %d bytes loaded to 0x%lx\n",
size, offset);
sprintf(buf, "%x", size);
setenv("filesize", buf);
} else {
printf("### CRAMFS LOAD ERROR<%x> for %s!\n", size, filename);
}
return !(size > 0);
}
/**
* Routine implementing u-boot ls command which lists content of a given
* directory at location 'cramfsaddr'.
* cramfsaddr is an evironment variable.
*
* @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_cramfs_ls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = "/";
int ret;
struct part_info part;
struct mtd_device dev;
struct mtdids id;
ulong addr;
addr = simple_strtoul(getenv("cramfsaddr"), NULL, 16);
/* hack! */
/* cramfs_* only supports NOR flash chips */
/* fake the device type */
id.type = MTD_DEV_TYPE_NOR;
id.num = 0;
dev.id = &id;
part.dev = &dev;
/* fake the address offset */
part.offset = addr - OFFSET_ADJUSTMENT;
if (argc == 2)
filename = argv[1];
ret = 0;
if (cramfs_check(&part))
ret = cramfs_ls (&part, filename);
return ret ? 0 : 1;
}
/* command line only */
/***************************************************/
U_BOOT_CMD(
cramfsload, 3, 0, do_cramfs_load,
"load binary file from a filesystem image",
"[ off ] [ filename ]\n"
" - load binary file from address 'cramfsaddr'\n"
" with offset 'off'\n"
);
U_BOOT_CMD(
cramfsls, 2, 1, do_cramfs_ls,
"list files in a directory (default /)",
"[ directory ]\n"
" - list files in a directory.\n"
);
#endif /* #ifdef CONFIG_CRAMFS_CMDLINE */
/***************************************************/
|
1001-study-uboot
|
common/cmd_cramfs.c
|
C
|
gpl3
| 5,627
|
/*
* (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
*
********************************************************************
*
* Lots of code copied from:
*
* m8xx_pcmcia.c - Linux PCMCIA socket driver for the mpc8xx series.
* (C) 1999-2000 Magnus Damm <damm@bitsmart.com>
*
* "The ExCA standard specifies that socket controllers should provide
* two IO and five memory windows per socket, which can be independently
* configured and positioned in the host address space and mapped to
* arbitrary segments of card address space. " - David A Hinds. 1999
*
* This controller does _not_ meet the ExCA standard.
*
* m8xx pcmcia controller brief info:
* + 8 windows (attrib, mem, i/o)
* + up to two slots (SLOT_A and SLOT_B)
* + inputpins, outputpins, event and mask registers.
* - no offset register. sigh.
*
* Because of the lacking offset register we must map the whole card.
* We assign each memory window PCMCIA_MEM_WIN_SIZE address space.
* Make sure there is (PCMCIA_MEM_WIN_SIZE * PCMCIA_MEM_WIN_NO
* * PCMCIA_SOCKETS_NO) bytes at PCMCIA_MEM_WIN_BASE.
* The i/o windows are dynamically allocated at PCMCIA_IO_WIN_BASE.
* They are maximum 64KByte each...
*/
/* #define DEBUG 1 */
/*
* PCMCIA support
*/
#include <common.h>
#include <command.h>
#include <config.h>
#include <pcmcia.h>
#include <asm/io.h>
/* -------------------------------------------------------------------- */
#if defined(CONFIG_CMD_PCMCIA)
extern int pcmcia_on (void);
extern int pcmcia_off (void);
int do_pinit (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int rcode = 0;
if (argc != 2) {
printf ("Usage: pinit {on | off}\n");
return 1;
}
if (strcmp(argv[1],"on") == 0) {
rcode = pcmcia_on ();
} else if (strcmp(argv[1],"off") == 0) {
rcode = pcmcia_off ();
} else {
printf ("Usage: pinit {on | off}\n");
return 1;
}
return rcode;
}
U_BOOT_CMD(
pinit, 2, 0, do_pinit,
"PCMCIA sub-system",
"on - power on PCMCIA socket\n"
"pinit off - power off PCMCIA socket"
);
#endif
/* -------------------------------------------------------------------- */
#undef CHECK_IDE_DEVICE
#if defined(CONFIG_CMD_IDE) && defined(CONFIG_IDE_8xx_PCCARD)
#define CHECK_IDE_DEVICE
#endif
#if defined(CONFIG_PXA_PCMCIA)
#define CHECK_IDE_DEVICE
#endif
#ifdef CHECK_IDE_DEVICE
int ide_devices_found;
static uchar *known_cards[] = {
(uchar *)"ARGOSY PnPIDE D5",
NULL
};
#define MAX_TUPEL_SZ 512
#define MAX_FEATURES 4
#define MAX_IDENT_CHARS 64
#define MAX_IDENT_FIELDS 4
#define indent "\t "
static void print_funcid (int func)
{
puts (indent);
switch (func) {
case CISTPL_FUNCID_MULTI:
puts (" Multi-Function");
break;
case CISTPL_FUNCID_MEMORY:
puts (" Memory");
break;
case CISTPL_FUNCID_SERIAL:
puts (" Serial Port");
break;
case CISTPL_FUNCID_PARALLEL:
puts (" Parallel Port");
break;
case CISTPL_FUNCID_FIXED:
puts (" Fixed Disk");
break;
case CISTPL_FUNCID_VIDEO:
puts (" Video Adapter");
break;
case CISTPL_FUNCID_NETWORK:
puts (" Network Adapter");
break;
case CISTPL_FUNCID_AIMS:
puts (" AIMS Card");
break;
case CISTPL_FUNCID_SCSI:
puts (" SCSI Adapter");
break;
default:
puts (" Unknown");
break;
}
puts (" Card\n");
}
static void print_fixed (volatile uchar *p)
{
if (p == NULL)
return;
puts(indent);
switch (*p) {
case CISTPL_FUNCE_IDE_IFACE:
{ uchar iface = *(p+2);
puts ((iface == CISTPL_IDE_INTERFACE) ? " IDE" : " unknown");
puts (" interface ");
break;
}
case CISTPL_FUNCE_IDE_MASTER:
case CISTPL_FUNCE_IDE_SLAVE:
{ uchar f1 = *(p+2);
uchar f2 = *(p+4);
puts ((f1 & CISTPL_IDE_SILICON) ? " [silicon]" : " [rotating]");
if (f1 & CISTPL_IDE_UNIQUE)
puts (" [unique]");
puts ((f1 & CISTPL_IDE_DUAL) ? " [dual]" : " [single]");
if (f2 & CISTPL_IDE_HAS_SLEEP)
puts (" [sleep]");
if (f2 & CISTPL_IDE_HAS_STANDBY)
puts (" [standby]");
if (f2 & CISTPL_IDE_HAS_IDLE)
puts (" [idle]");
if (f2 & CISTPL_IDE_LOW_POWER)
puts (" [low power]");
if (f2 & CISTPL_IDE_REG_INHIBIT)
puts (" [reg inhibit]");
if (f2 & CISTPL_IDE_HAS_INDEX)
puts (" [index]");
if (f2 & CISTPL_IDE_IOIS16)
puts (" [IOis16]");
break;
}
}
putc ('\n');
}
static int identify (volatile uchar *p)
{
uchar id_str[MAX_IDENT_CHARS];
uchar data;
uchar *t;
uchar **card;
int i, done;
if (p == NULL)
return (0); /* Don't know */
t = id_str;
done =0;
for (i=0; i<=4 && !done; ++i, p+=2) {
while ((data = *p) != '\0') {
if (data == 0xFF) {
done = 1;
break;
}
*t++ = data;
if (t == &id_str[MAX_IDENT_CHARS-1]) {
done = 1;
break;
}
p += 2;
}
if (!done)
*t++ = ' ';
}
*t = '\0';
while (--t > id_str) {
if (*t == ' ')
*t = '\0';
else
break;
}
puts ((char *)id_str);
putc ('\n');
for (card=known_cards; *card; ++card) {
debug ("## Compare against \"%s\"\n", *card);
if (strcmp((char *)*card, (char *)id_str) == 0) { /* found! */
debug ("## CARD FOUND ##\n");
return (1);
}
}
return (0); /* don't know */
}
int check_ide_device (int slot)
{
volatile uchar *ident = NULL;
volatile uchar *feature_p[MAX_FEATURES];
volatile uchar *p, *start, *addr;
int n_features = 0;
uchar func_id = ~0;
uchar code, len;
ushort config_base = 0;
int found = 0;
int i;
addr = (volatile uchar *)(CONFIG_SYS_PCMCIA_MEM_ADDR +
CONFIG_SYS_PCMCIA_MEM_SIZE * (slot * 4));
debug ("PCMCIA MEM: %08lX\n", (ulong)addr);
start = p = (volatile uchar *) addr;
while ((p - start) < MAX_TUPEL_SZ) {
code = *p; p += 2;
if (code == 0xFF) { /* End of chain */
break;
}
len = *p; p += 2;
#if defined(DEBUG) && (DEBUG > 1)
{ volatile uchar *q = p;
printf ("\nTuple code %02x length %d\n\tData:",
code, len);
for (i = 0; i < len; ++i) {
printf (" %02x", *q);
q+= 2;
}
}
#endif /* DEBUG */
switch (code) {
case CISTPL_VERS_1:
ident = p + 4;
break;
case CISTPL_FUNCID:
/* Fix for broken SanDisk which may have 0x80 bit set */
func_id = *p & 0x7F;
break;
case CISTPL_FUNCE:
if (n_features < MAX_FEATURES)
feature_p[n_features++] = p;
break;
case CISTPL_CONFIG:
config_base = (*(p+6) << 8) + (*(p+4));
debug ("\n## Config_base = %04x ###\n", config_base);
default:
break;
}
p += 2 * len;
}
found = identify (ident);
if (func_id != ((uchar)~0)) {
print_funcid (func_id);
if (func_id == CISTPL_FUNCID_FIXED)
found = 1;
else
return (1); /* no disk drive */
}
for (i=0; i<n_features; ++i) {
print_fixed (feature_p[i]);
}
if (!found) {
printf ("unknown card type\n");
return (1);
}
ide_devices_found |= (1 << slot);
#if CONFIG_CPC45
#else
/* set I/O area in config reg -> only valid for ARGOSY D5!!! */
*((uchar *)(addr + config_base)) = 1;
#endif
#if 0
printf("\n## Config_base = %04x ###\n", config_base);
printf("Configuration Option Register: %02x @ %x\n", readb(addr + config_base), addr + config_base);
printf("Card Configuration and Status Register: %02x\n", readb(addr + config_base + 2));
printf("Pin Replacement Register Register: %02x\n", readb(addr + config_base + 4));
printf("Socket and Copy Register: %02x\n", readb(addr + config_base + 6));
#endif
return (0);
}
#endif /* CHECK_IDE_DEVICE */
|
1001-study-uboot
|
common/cmd_pcmcia.c
|
C
|
gpl3
| 8,115
|
/*
* (C) Copyright 2000-2003
* 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
*/
/*
* Misc boot support
*/
#include <common.h>
#include <command.h>
#include <net.h>
#ifdef CONFIG_CMD_GO
/* Allow ports to override the default behavior */
__attribute__((weak))
unsigned long do_go_exec (ulong (*entry)(int, char * const []), int argc, char * const argv[])
{
return entry (argc, argv);
}
int do_go (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr, rc;
int rcode = 0;
if (argc < 2)
return cmd_usage(cmdtp);
addr = simple_strtoul(argv[1], NULL, 16);
printf ("## Starting application at 0x%08lX ...\n", addr);
/*
* pass address parameter as argv[0] (aka command name),
* and all remaining args
*/
rc = do_go_exec ((void *)addr, argc - 1, argv + 1);
if (rc != 0) rcode = 1;
printf ("## Application terminated, rc = 0x%lX\n", rc);
return rcode;
}
/* -------------------------------------------------------------------- */
U_BOOT_CMD(
go, CONFIG_SYS_MAXARGS, 1, do_go,
"start application at address 'addr'",
"addr [arg ...]\n - start application at address 'addr'\n"
" passing 'arg' as arguments"
);
#endif
U_BOOT_CMD(
reset, 1, 0, do_reset,
"Perform RESET of the CPU",
""
);
|
1001-study-uboot
|
common/cmd_boot.c
|
C
|
gpl3
| 2,049
|
/*
* (C) Copyright 2009 Reinhard Arlt, reinhard.arlt@esd-electronics.com
*
* base on universe.h by
*
* (C) Copyright 2003 Stefan Roese, stefan.roese@esd-electronics.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 <malloc.h>
#include <asm/io.h>
#include <pci.h>
#include <tsi148.h>
#define PCI_VENDOR PCI_VENDOR_ID_TUNDRA
#define PCI_DEVICE PCI_DEVICE_ID_TUNDRA_TSI148
typedef struct _TSI148_DEV TSI148_DEV;
struct _TSI148_DEV {
int bus;
pci_dev_t busdevfn;
TSI148 *uregs;
unsigned int pci_bs;
};
static TSI148_DEV *dev;
/*
* Most of the TSI148 register are BIGENDIAN
* This is the reason for the __raw_writel(htonl(x), x) usage!
*/
int tsi148_init(void)
{
int j, result;
pci_dev_t busdevfn;
unsigned int val;
busdevfn = pci_find_device(PCI_VENDOR, PCI_DEVICE, 0);
if (busdevfn == -1) {
puts("Tsi148: No Tundra Tsi148 found!\n");
return -1;
}
/* Lets turn Latency off */
pci_write_config_dword(busdevfn, 0x0c, 0);
dev = malloc(sizeof(*dev));
if (NULL == dev) {
puts("Tsi148: No memory!\n");
return -1;
}
memset(dev, 0, sizeof(*dev));
dev->busdevfn = busdevfn;
pci_read_config_dword(busdevfn, PCI_BASE_ADDRESS_0, &val);
val &= ~0xf;
dev->uregs = (TSI148 *)val;
debug("Tsi148: Base : %p\n", dev->uregs);
/* check mapping */
debug("Tsi148: Read via mapping, PCI_ID = %08X\n",
readl(&dev->uregs->pci_id));
if (((PCI_DEVICE << 16) | PCI_VENDOR) != readl(&dev->uregs->pci_id)) {
printf("Tsi148: Cannot read PCI-ID via Mapping: %08x\n",
readl(&dev->uregs->pci_id));
result = -1;
goto break_30;
}
debug("Tsi148: PCI_BS = %08X\n", readl(&dev->uregs->pci_mbarl));
dev->pci_bs = readl(&dev->uregs->pci_mbarl);
/* turn off windows */
for (j = 0; j < 8; j++) {
__raw_writel(htonl(0x00000000), &dev->uregs->outbound[j].otat);
__raw_writel(htonl(0x00000000), &dev->uregs->inbound[j].itat);
}
/* Tsi148 VME timeout etc */
__raw_writel(htonl(0x00000084), &dev->uregs->vctrl);
#ifdef DEBUG
if ((__raw_readl(&dev->uregs->vstat) & 0x00000100) != 0)
printf("Tsi148: System Controller!\n");
else
printf("Tsi148: Not System Controller!\n");
#endif
/*
* Lets turn off interrupts
*/
/* Disable interrupts in Tsi148 first */
__raw_writel(htonl(0x00000000), &dev->uregs->inten);
/* Disable interrupt out */
__raw_writel(htonl(0x00000000), &dev->uregs->inteo);
eieio();
/* Reset all IRQ's */
__raw_writel(htonl(0x03ff3f00), &dev->uregs->intc);
/* Map all ints to 0 */
__raw_writel(htonl(0x00000000), &dev->uregs->intm1);
__raw_writel(htonl(0x00000000), &dev->uregs->intm2);
eieio();
val = __raw_readl(&dev->uregs->vstat);
val &= ~(0x00004000);
__raw_writel(val, &dev->uregs->vstat);
eieio();
debug("Tsi148: register struct size %08x\n", sizeof(TSI148));
return 0;
break_30:
free(dev);
dev = NULL;
return result;
}
/*
* Create pci slave window (access: pci -> vme)
*/
int tsi148_pci_slave_window(unsigned int pciAddr, unsigned int vmeAddr,
int size, int vam, int vdw)
{
int result, i;
unsigned int ctl = 0;
if (NULL == dev) {
result = -1;
goto exit_10;
}
for (i = 0; i < 8; i++) {
if (0x00000000 == readl(&dev->uregs->outbound[i].otat))
break;
}
if (i > 7) {
printf("Tsi148: No Image available\n");
result = -1;
goto exit_10;
}
debug("Tsi148: Using image %d\n", i);
printf("Tsi148: Pci addr %08x\n", pciAddr);
__raw_writel(htonl(pciAddr), &dev->uregs->outbound[i].otsal);
__raw_writel(0x00000000, &dev->uregs->outbound[i].otsau);
__raw_writel(htonl(pciAddr + size), &dev->uregs->outbound[i].oteal);
__raw_writel(0x00000000, &dev->uregs->outbound[i].oteau);
__raw_writel(htonl(vmeAddr - pciAddr), &dev->uregs->outbound[i].otofl);
__raw_writel(0x00000000, &dev->uregs->outbound[i].otofu);
switch (vam & VME_AM_Axx) {
case VME_AM_A16:
ctl = 0x00000000;
break;
case VME_AM_A24:
ctl = 0x00000001;
break;
case VME_AM_A32:
ctl = 0x00000002;
break;
}
switch (vam & VME_AM_Mxx) {
case VME_AM_DATA:
ctl |= 0x00000000;
break;
case VME_AM_PROG:
ctl |= 0x00000010;
break;
}
if (vam & VME_AM_SUP)
ctl |= 0x00000020;
switch (vdw & VME_FLAG_Dxx) {
case VME_FLAG_D16:
ctl |= 0x00000000;
break;
case VME_FLAG_D32:
ctl |= 0x00000040;
break;
}
ctl |= 0x80040000; /* enable, no prefetch */
__raw_writel(htonl(ctl), &dev->uregs->outbound[i].otat);
debug("Tsi148: window-addr =%p\n",
&dev->uregs->outbound[i].otsau);
debug("Tsi148: pci slave window[%d] attr =%08x\n",
i, ntohl(__raw_readl(&dev->uregs->outbound[i].otat)));
debug("Tsi148: pci slave window[%d] start =%08x\n",
i, ntohl(__raw_readl(&dev->uregs->outbound[i].otsal)));
debug("Tsi148: pci slave window[%d] end =%08x\n",
i, ntohl(__raw_readl(&dev->uregs->outbound[i].oteal)));
debug("Tsi148: pci slave window[%d] offset=%08x\n",
i, ntohl(__raw_readl(&dev->uregs->outbound[i].otofl)));
return 0;
exit_10:
return -result;
}
unsigned int tsi148_eval_vam(int vam)
{
unsigned int ctl = 0;
switch (vam & VME_AM_Axx) {
case VME_AM_A16:
ctl = 0x00000000;
break;
case VME_AM_A24:
ctl = 0x00000010;
break;
case VME_AM_A32:
ctl = 0x00000020;
break;
}
switch (vam & VME_AM_Mxx) {
case VME_AM_DATA:
ctl |= 0x00000001;
break;
case VME_AM_PROG:
ctl |= 0x00000002;
break;
case (VME_AM_PROG | VME_AM_DATA):
ctl |= 0x00000003;
break;
}
if (vam & VME_AM_SUP)
ctl |= 0x00000008;
if (vam & VME_AM_USR)
ctl |= 0x00000004;
return ctl;
}
/*
* Create vme slave window (access: vme -> pci)
*/
int tsi148_vme_slave_window(unsigned int vmeAddr, unsigned int pciAddr,
int size, int vam)
{
int result, i;
unsigned int ctl = 0;
if (NULL == dev) {
result = -1;
goto exit_10;
}
for (i = 0; i < 8; i++) {
if (0x00000000 == readl(&dev->uregs->inbound[i].itat))
break;
}
if (i > 7) {
printf("Tsi148: No Image available\n");
result = -1;
goto exit_10;
}
debug("Tsi148: Using image %d\n", i);
__raw_writel(htonl(vmeAddr), &dev->uregs->inbound[i].itsal);
__raw_writel(0x00000000, &dev->uregs->inbound[i].itsau);
__raw_writel(htonl(vmeAddr + size), &dev->uregs->inbound[i].iteal);
__raw_writel(0x00000000, &dev->uregs->inbound[i].iteau);
__raw_writel(htonl(pciAddr - vmeAddr), &dev->uregs->inbound[i].itofl);
if (vmeAddr > pciAddr)
__raw_writel(0xffffffff, &dev->uregs->inbound[i].itofu);
else
__raw_writel(0x00000000, &dev->uregs->inbound[i].itofu);
ctl = tsi148_eval_vam(vam);
ctl |= 0x80000000; /* enable */
__raw_writel(htonl(ctl), &dev->uregs->inbound[i].itat);
debug("Tsi148: window-addr =%p\n",
&dev->uregs->inbound[i].itsau);
debug("Tsi148: vme slave window[%d] attr =%08x\n",
i, ntohl(__raw_readl(&dev->uregs->inbound[i].itat)));
debug("Tsi148: vme slave window[%d] start =%08x\n",
i, ntohl(__raw_readl(&dev->uregs->inbound[i].itsal)));
debug("Tsi148: vme slave window[%d] end =%08x\n",
i, ntohl(__raw_readl(&dev->uregs->inbound[i].iteal)));
debug("Tsi148: vme slave window[%d] offset=%08x\n",
i, ntohl(__raw_readl(&dev->uregs->inbound[i].itofl)));
return 0;
exit_10:
return -result;
}
/*
* Create vme slave window (access: vme -> gcsr)
*/
int tsi148_vme_gcsr_window(unsigned int vmeAddr, int vam)
{
int result;
unsigned int ctl;
result = 0;
if (NULL == dev) {
result = 1;
} else {
__raw_writel(htonl(vmeAddr), &dev->uregs->gbal);
__raw_writel(0x00000000, &dev->uregs->gbau);
ctl = tsi148_eval_vam(vam);
ctl |= 0x00000080; /* enable */
__raw_writel(htonl(ctl), &dev->uregs->gcsrat);
}
return result;
}
/*
* Create vme slave window (access: vme -> crcsr)
*/
int tsi148_vme_crcsr_window(unsigned int vmeAddr)
{
int result;
unsigned int ctl;
result = 0;
if (NULL == dev) {
result = 1;
} else {
__raw_writel(htonl(vmeAddr), &dev->uregs->crol);
__raw_writel(0x00000000, &dev->uregs->crou);
ctl = 0x00000080; /* enable */
__raw_writel(htonl(ctl), &dev->uregs->crat);
}
return result;
}
/*
* Create vme slave window (access: vme -> crg)
*/
int tsi148_vme_crg_window(unsigned int vmeAddr, int vam)
{
int result;
unsigned int ctl;
result = 0;
if (NULL == dev) {
result = 1;
} else {
__raw_writel(htonl(vmeAddr), &dev->uregs->cbal);
__raw_writel(0x00000000, &dev->uregs->cbau);
ctl = tsi148_eval_vam(vam);
ctl |= 0x00000080; /* enable */
__raw_writel(htonl(ctl), &dev->uregs->crgat);
}
return result;
}
/*
* Tundra Tsi148 configuration
*/
int do_tsi148(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr1 = 0, addr2 = 0, size = 0, vam = 0, vdw = 0;
char cmd = 'x';
/* get parameter */
if (argc > 1)
cmd = argv[1][0];
if (argc > 2)
addr1 = simple_strtoul(argv[2], NULL, 16);
if (argc > 3)
addr2 = simple_strtoul(argv[3], NULL, 16);
if (argc > 4)
size = simple_strtoul(argv[4], NULL, 16);
if (argc > 5)
vam = simple_strtoul(argv[5], NULL, 16);
if (argc > 6)
vdw = simple_strtoul(argv[6], NULL, 16);
switch (cmd) {
case 'c':
if (strcmp(argv[1], "crg") == 0) {
vam = addr2;
printf("Tsi148: Configuring VME CRG Window "
"(VME->CRG):\n");
printf(" vme=%08lx vam=%02lx\n", addr1, vam);
tsi148_vme_crg_window(addr1, vam);
} else {
printf("Tsi148: Configuring VME CR/CSR Window "
"(VME->CR/CSR):\n");
printf(" pci=%08lx\n", addr1);
tsi148_vme_crcsr_window(addr1);
}
break;
case 'i': /* init */
tsi148_init();
break;
case 'g':
vam = addr2;
printf("Tsi148: Configuring VME GCSR Window (VME->GCSR):\n");
printf(" vme=%08lx vam=%02lx\n", addr1, vam);
tsi148_vme_gcsr_window(addr1, vam);
break;
case 'v': /* vme */
printf("Tsi148: Configuring VME Slave Window (VME->PCI):\n");
printf(" vme=%08lx pci=%08lx size=%08lx vam=%02lx\n",
addr1, addr2, size, vam);
tsi148_vme_slave_window(addr1, addr2, size, vam);
break;
case 'p': /* pci */
printf("Tsi148: Configuring PCI Slave Window (PCI->VME):\n");
printf(" pci=%08lx vme=%08lx size=%08lx vam=%02lx vdw=%02lx\n",
addr1, addr2, size, vam, vdw);
tsi148_pci_slave_window(addr1, addr2, size, vam, vdw);
break;
default:
printf("Tsi148: Command %s not supported!\n", argv[1]);
}
return 0;
}
U_BOOT_CMD(
tsi148, 7, 1, do_tsi148,
"initialize and configure Turndra Tsi148\n",
"init\n"
" - initialize tsi148\n"
"tsi148 vme [vme_addr] [pci_addr] [size] [vam]\n"
" - create vme slave window (access: vme->pci)\n"
"tsi148 pci [pci_addr] [vme_addr] [size] [vam] [vdw]\n"
" - create pci slave window (access: pci->vme)\n"
"tsi148 crg [vme_addr] [vam]\n"
" - create vme slave window: (access vme->CRG\n"
"tsi148 crcsr [pci_addr]\n"
" - create vme slave window: (access vme->CR/CSR\n"
"tsi148 gcsr [vme_addr] [vam]\n"
" - create vme slave window: (access vme->GCSR\n"
" [vam] = VMEbus Address-Modifier: 01 -> A16 Address Space\n"
" 02 -> A24 Address Space\n"
" 03 -> A32 Address Space\n"
" 04 -> Usr AM Code\n"
" 08 -> Supervisor AM Code\n"
" 10 -> Data AM Code\n"
" 20 -> Program AM Code\n"
" [vdw] = VMEbus Maximum Datawidth: 02 -> D16 Data Width\n"
" 03 -> D32 Data Width\n"
);
|
1001-study-uboot
|
common/cmd_tsi148.c
|
C
|
gpl3
| 12,213
|
/*
* 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_help(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
return _do_help(&__u_boot_cmd_start,
&__u_boot_cmd_end - &__u_boot_cmd_start,
cmdtp, flag, argc, argv);
}
U_BOOT_CMD(
help, CONFIG_SYS_MAXARGS, 1, do_help,
"print command description/usage",
"\n"
" - print brief description of all commands\n"
"help command ...\n"
" - print detailed usage of 'command'"
);
/* This does not use the U_BOOT_CMD macro as ? can't be used in symbol names */
cmd_tbl_t __u_boot_cmd_question_mark Struct_Section = {
"?", CONFIG_SYS_MAXARGS, 1, do_help,
"alias for 'help'",
#ifdef CONFIG_SYS_LONGHELP
""
#endif /* CONFIG_SYS_LONGHELP */
};
|
1001-study-uboot
|
common/cmd_help.c
|
C
|
gpl3
| 1,583
|
/*
* cmd_cplbinfo.c - dump the instruction/data cplb tables
*
* Copyright (c) 2007-2008 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <common.h>
#include <command.h>
#include <asm/blackfin.h>
#include <asm/cplb.h>
#include <asm/mach-common/bits/mpu.h>
/*
* Translate the PAGE_SIZE bits into a human string
*/
static const char *cplb_page_size(uint32_t data)
{
static const char page_size_string_table[][4] = { "1K", "4K", "1M", "4M" };
return page_size_string_table[(data & PAGE_SIZE_MASK) >> PAGE_SIZE_SHIFT];
}
/*
* show a hardware cplb table
*/
static void show_cplb_table(uint32_t *addr, uint32_t *data)
{
int i;
printf(" Address Data Size Valid Locked\n");
for (i = 1; i <= 16; ++i) {
printf(" %2i 0x%p 0x%05X %s %c %c\n",
i, (void *)*addr, *data,
cplb_page_size(*data),
(*data & CPLB_VALID ? 'Y' : 'N'),
(*data & CPLB_LOCK ? 'Y' : 'N'));
++addr;
++data;
}
}
/*
* display current instruction and data cplb tables
*/
int do_cplbinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
printf("%s CPLB table [%08x]:\n", "Instruction", *(uint32_t *)DMEM_CONTROL);
show_cplb_table((uint32_t *)ICPLB_ADDR0, (uint32_t *)ICPLB_DATA0);
printf("%s CPLB table [%08x]:\n", "Data", *(uint32_t *)IMEM_CONTROL);
show_cplb_table((uint32_t *)DCPLB_ADDR0, (uint32_t *)DCPLB_DATA0);
return 0;
}
U_BOOT_CMD(
cplbinfo, 1, 0, do_cplbinfo,
"display current CPLB tables",
""
);
|
1001-study-uboot
|
common/cmd_cplbinfo.c
|
C
|
gpl3
| 1,470
|
/*
* (C) Copyright 2007 Michal Simek
*
* Michal SIMEK <monstr@monstr.eu>
*
* 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
*/
/*
* Microblaze FSL support
*/
#include <common.h>
#include <config.h>
#include <command.h>
#include <asm/asm.h>
int do_frd (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned int fslnum;
unsigned int num;
unsigned int blocking;
if (argc < 2)
return cmd_usage(cmdtp);
fslnum = (unsigned int)simple_strtoul (argv[1], NULL, 16);
blocking = (unsigned int)simple_strtoul (argv[2], NULL, 16);
if (fslnum < 0 || fslnum >= XILINX_FSL_NUMBER) {
puts ("Bad number of FSL\n");
return cmd_usage(cmdtp);
}
switch (fslnum) {
#if (XILINX_FSL_NUMBER > 0)
case 0:
switch (blocking) {
case 0: NGET (num, 0);
break;
case 1: NCGET (num, 0);
break;
case 2: GET (num, 0);
break;
case 3: CGET (num, 0);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 1)
case 1:
switch (blocking) {
case 0: NGET (num, 1);
break;
case 1: NCGET (num, 1);
break;
case 2: GET (num, 1);
break;
case 3: CGET (num, 1);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 2)
case 2:
switch (blocking) {
case 0: NGET (num, 2);
break;
case 1: NCGET (num, 2);
break;
case 2: GET (num, 2);
break;
case 3: CGET (num, 2);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 3)
case 3:
switch (blocking) {
case 0: NGET (num, 3);
break;
case 1: NCGET (num, 3);
break;
case 2: GET (num, 3);
break;
case 3: CGET (num, 3);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 4)
case 4:
switch (blocking) {
case 0: NGET (num, 4);
break;
case 1: NCGET (num, 4);
break;
case 2: GET (num, 4);
break;
case 3: CGET (num, 4);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 5)
case 5:
switch (blocking) {
case 0: NGET (num, 5);
break;
case 1: NCGET (num, 5);
break;
case 2: GET (num, 5);
break;
case 3: CGET (num, 5);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 6)
case 6:
switch (blocking) {
case 0: NGET (num, 6);
break;
case 1: NCGET (num, 6);
break;
case 2: GET (num, 6);
break;
case 3: CGET (num, 6);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 7)
case 7:
switch (blocking) {
case 0: NGET (num, 7);
break;
case 1: NCGET (num, 7);
break;
case 2: GET (num, 7);
break;
case 3: CGET (num, 7);
break;
default:
return 2;
}
break;
#endif
default:
return 1;
}
printf ("%01x: 0x%08x - %s %s read\n", fslnum, num,
blocking < 2 ? "non blocking" : "blocking",
((blocking == 1) || (blocking == 3)) ? "control" : "data" );
return 0;
}
int do_fwr (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned int fslnum;
unsigned int num;
unsigned int blocking;
if (argc < 3)
return cmd_usage(cmdtp);
fslnum = (unsigned int)simple_strtoul (argv[1], NULL, 16);
num = (unsigned int)simple_strtoul (argv[2], NULL, 16);
blocking = (unsigned int)simple_strtoul (argv[3], NULL, 16);
if (fslnum < 0 || fslnum >= XILINX_FSL_NUMBER)
return cmd_usage(cmdtp);
switch (fslnum) {
#if (XILINX_FSL_NUMBER > 0)
case 0:
switch (blocking) {
case 0: NPUT (num, 0);
break;
case 1: NCPUT (num, 0);
break;
case 2: PUT (num, 0);
break;
case 3: CPUT (num, 0);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 1)
case 1:
switch (blocking) {
case 0: NPUT (num, 1);
break;
case 1: NCPUT (num, 1);
break;
case 2: PUT (num, 1);
break;
case 3: CPUT (num, 1);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 2)
case 2:
switch (blocking) {
case 0: NPUT (num, 2);
break;
case 1: NCPUT (num, 2);
break;
case 2: PUT (num, 2);
break;
case 3: CPUT (num, 2);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 3)
case 3:
switch (blocking) {
case 0: NPUT (num, 3);
break;
case 1: NCPUT (num, 3);
break;
case 2: PUT (num, 3);
break;
case 3: CPUT (num, 3);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 4)
case 4:
switch (blocking) {
case 0: NPUT (num, 4);
break;
case 1: NCPUT (num, 4);
break;
case 2: PUT (num, 4);
break;
case 3: CPUT (num, 4);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 5)
case 5:
switch (blocking) {
case 0: NPUT (num, 5);
break;
case 1: NCPUT (num, 5);
break;
case 2: PUT (num, 5);
break;
case 3: CPUT (num, 5);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 6)
case 6:
switch (blocking) {
case 0: NPUT (num, 6);
break;
case 1: NCPUT (num, 6);
break;
case 2: PUT (num, 6);
break;
case 3: CPUT (num, 6);
break;
default:
return 2;
}
break;
#endif
#if (XILINX_FSL_NUMBER > 7)
case 7:
switch (blocking) {
case 0: NPUT (num, 7);
break;
case 1: NCPUT (num, 7);
break;
case 2: PUT (num, 7);
break;
case 3: CPUT (num, 7);
break;
default:
return 2;
}
break;
#endif
default:
return 1;
}
printf ("%01x: 0x%08x - %s %s write\n", fslnum, num,
blocking < 2 ? "non blocking" : "blocking",
((blocking == 1) || (blocking == 3)) ? "control" : "data" );
return 0;
}
int do_rspr (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
unsigned int reg = 0;
unsigned int val = 0;
if (argc < 2)
return cmd_usage(cmdtp);
reg = (unsigned int)simple_strtoul (argv[1], NULL, 16);
val = (unsigned int)simple_strtoul (argv[2], NULL, 16);
switch (reg) {
case 0x1:
if (argc > 2) {
MTS (val, rmsr);
NOP;
MFS (val, rmsr);
} else {
MFS (val, rmsr);
}
puts ("MSR");
break;
case 0x3:
MFS (val, rear);
puts ("EAR");
break;
case 0x5:
MFS (val, resr);
puts ("ESR");
break;
default:
puts ("Unsupported register\n");
return 1;
}
printf (": 0x%08x\n", val);
return 0;
}
/***************************************************/
U_BOOT_CMD (frd, 3, 1, do_frd,
"read data from FSL",
"- [fslnum [0|1|2|3]]\n"
" 0 - non blocking data read\n"
" 1 - non blocking control read\n"
" 2 - blocking data read\n"
" 3 - blocking control read");
U_BOOT_CMD (fwr, 4, 1, do_fwr,
"write data to FSL",
"- [fslnum [0|1|2|3]]\n"
" 0 - non blocking data write\n"
" 1 - non blocking control write\n"
" 2 - blocking data write\n"
" 3 - blocking control write");
U_BOOT_CMD (rspr, 3, 1, do_rspr,
"read/write special purpose register",
"- reg_num [write value] read/write special purpose register\n"
" 1 - MSR - Machine status register\n"
" 3 - EAR - Exception address register\n"
" 5 - ESR - Exception status register");
|
1001-study-uboot
|
common/cmd_mfsl.c
|
C
|
gpl3
| 7,588
|
/*
* U-boot - stub functions for common kgdb code,
* can be overridden in board specific files
*
* Copyright 2009 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <common.h>
#include <kgdb.h>
int (*debugger_exception_handler)(struct pt_regs *);
__attribute__((weak))
void kgdb_serial_init(void)
{
puts("[on serial] ");
}
__attribute__((weak))
void putDebugChar(int c)
{
serial_putc(c);
}
__attribute__((weak))
void putDebugStr(const char *str)
{
#ifdef DEBUG
serial_puts(str);
#endif
}
__attribute__((weak))
int getDebugChar(void)
{
return serial_getc();
}
__attribute__((weak))
void kgdb_interruptible(int yes)
{
return;
}
__attribute__((weak))
void kgdb_flush_cache_range(void *from, void *to)
{
flush_cache((unsigned long)from, (unsigned long)(to - from));
}
__attribute__((weak))
void kgdb_flush_cache_all(void)
{
if (dcache_status()) {
dcache_disable();
dcache_enable();
}
if (icache_status()) {
icache_disable();
icache_enable();
}
}
|
1001-study-uboot
|
common/kgdb_stubs.c
|
C
|
gpl3
| 1,005
|
/*
* (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>
*
* Copyright 2011 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
*/
/*
* Support for persistent environment data
*
* The "environment" is stored on external storage as a list of '\0'
* terminated "name=value" strings. The end of the list is marked by
* a double '\0'. The environment is preceeded by a 32 bit CRC over
* the data part and, in case of redundant environment, a byte of
* flags.
*
* This linearized representation will also be used before
* relocation, i. e. as long as we don't have a full C runtime
* environment. After that, we use a hash table.
*/
#include <common.h>
#include <command.h>
#include <environment.h>
#include <search.h>
#include <errno.h>
#include <malloc.h>
#include <watchdog.h>
#include <serial.h>
#include <linux/stddef.h>
#include <asm/byteorder.h>
#if defined(CONFIG_CMD_NET)
#include <net.h>
#endif
DECLARE_GLOBAL_DATA_PTR;
#if !defined(CONFIG_ENV_IS_IN_EEPROM) && \
!defined(CONFIG_ENV_IS_IN_FLASH) && \
!defined(CONFIG_ENV_IS_IN_DATAFLASH) && \
!defined(CONFIG_ENV_IS_IN_MG_DISK) && \
!defined(CONFIG_ENV_IS_IN_MMC) && \
!defined(CONFIG_ENV_IS_IN_NAND) && \
!defined(CONFIG_ENV_IS_IN_NVRAM) && \
!defined(CONFIG_ENV_IS_IN_ONENAND) && \
!defined(CONFIG_ENV_IS_IN_SPI_FLASH) && \
!defined(CONFIG_ENV_IS_NOWHERE)
# error Define one of CONFIG_ENV_IS_IN_{EEPROM|FLASH|DATAFLASH|ONENAND|\
SPI_FLASH|MG_DISK|NVRAM|MMC} or CONFIG_ENV_IS_NOWHERE
#endif
#define XMK_STR(x) #x
#define MK_STR(x) XMK_STR(x)
/*
* Maximum expected input data size for import command
*/
#define MAX_ENV_SIZE (1 << 20) /* 1 MiB */
ulong load_addr = CONFIG_SYS_LOAD_ADDR; /* Default Load Address */
ulong save_addr; /* Default Save Address */
ulong save_size; /* Default Save Size (in bytes) */
/*
* Table with supported baudrates (defined in config_xyz.h)
*/
static const unsigned long baudrate_table[] = CONFIG_SYS_BAUDRATE_TABLE;
#define N_BAUDRATES (sizeof(baudrate_table) / sizeof(baudrate_table[0]))
/*
* This variable is incremented on each do_env_set(), so it can
* be used via get_env_id() as an indication, if the environment
* has changed or not. So it is possible to reread an environment
* variable only if the environment was changed ... done so for
* example in NetInitLoop()
*/
static int env_id = 1;
int get_env_id(void)
{
return env_id;
}
/*
* Command interface: print one or all environment variables
*
* Returns 0 in case of error, or length of printed string
*/
static int env_print(char *name)
{
char *res = NULL;
size_t len;
if (name) { /* print a single name */
ENTRY e, *ep;
e.key = name;
e.data = NULL;
hsearch_r(e, FIND, &ep, &env_htab);
if (ep == NULL)
return 0;
len = printf("%s=%s\n", ep->key, ep->data);
return len;
}
/* print whole list */
len = hexport_r(&env_htab, '\n', &res, 0, 0, NULL);
if (len > 0) {
puts(res);
free(res);
return len;
}
/* should never happen */
return 0;
}
int do_env_print (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i;
int rcode = 0;
if (argc == 1) {
/* print all env vars */
rcode = env_print(NULL);
if (!rcode)
return 1;
printf("\nEnvironment size: %d/%ld bytes\n",
rcode, (ulong)ENV_SIZE);
return 0;
}
/* print selected env vars */
for (i = 1; i < argc; ++i) {
int rc = env_print(argv[i]);
if (!rc) {
printf("## Error: \"%s\" not defined\n", argv[i]);
++rcode;
}
}
return rcode;
}
#ifdef CONFIG_CMD_GREPENV
static int do_env_grep(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
ENTRY *match;
unsigned char matched[env_htab.size / 8];
int rcode = 1, arg = 1, idx;
if (argc < 2)
return cmd_usage(cmdtp);
memset(matched, 0, env_htab.size / 8);
while (arg <= argc) {
idx = 0;
while ((idx = hstrstr_r(argv[arg], idx, &match, &env_htab))) {
if (!(matched[idx / 8] & (1 << (idx & 7)))) {
puts(match->key);
puts("=");
puts(match->data);
puts("\n");
}
matched[idx / 8] |= 1 << (idx & 7);
rcode = 0;
}
arg++;
}
return rcode;
}
#endif
/*
* Set a new environment variable,
* or replace or delete an existing one.
*/
int _do_env_set(int flag, int argc, char * const argv[])
{
bd_t *bd = gd->bd;
int i, len;
int console = -1;
char *name, *value, *s;
ENTRY e, *ep;
name = argv[1];
if (strchr(name, '=')) {
printf("## Error: illegal character '=' in variable name"
"\"%s\"\n", name);
return 1;
}
env_id++;
/*
* search if variable with this name already exists
*/
e.key = name;
e.data = NULL;
hsearch_r(e, FIND, &ep, &env_htab);
/* Check for console redirection */
if (strcmp(name, "stdin") == 0)
console = stdin;
else if (strcmp(name, "stdout") == 0)
console = stdout;
else if (strcmp(name, "stderr") == 0)
console = stderr;
if (console != -1) {
if (argc < 3) { /* Cannot delete it! */
printf("Can't delete \"%s\"\n", name);
return 1;
}
#ifdef CONFIG_CONSOLE_MUX
i = iomux_doenv(console, argv[2]);
if (i)
return i;
#else
/* Try assigning specified device */
if (console_assign(console, argv[2]) < 0)
return 1;
#ifdef CONFIG_SERIAL_MULTI
if (serial_assign(argv[2]) < 0)
return 1;
#endif
#endif /* CONFIG_CONSOLE_MUX */
}
/*
* Some variables like "ethaddr" and "serial#" can be set only
* once and cannot be deleted; also, "ver" is readonly.
*/
if (ep) { /* variable exists */
#ifndef CONFIG_ENV_OVERWRITE
if (strcmp(name, "serial#") == 0 ||
(strcmp(name, "ethaddr") == 0
#if defined(CONFIG_OVERWRITE_ETHADDR_ONCE) && defined(CONFIG_ETHADDR)
&& strcmp(ep->data, MK_STR(CONFIG_ETHADDR)) != 0
#endif /* CONFIG_OVERWRITE_ETHADDR_ONCE && CONFIG_ETHADDR */
)) {
printf("Can't overwrite \"%s\"\n", name);
return 1;
}
#endif
/*
* Switch to new baudrate if new baudrate is supported
*/
if (strcmp(name, "baudrate") == 0) {
int baudrate = simple_strtoul(argv[2], NULL, 10);
int i;
for (i = 0; i < N_BAUDRATES; ++i) {
if (baudrate == baudrate_table[i])
break;
}
if (i == N_BAUDRATES) {
printf("## Baudrate %d bps not supported\n",
baudrate);
return 1;
}
printf("## Switch baudrate to %d bps and"
"press ENTER ...\n", baudrate);
udelay(50000);
gd->baudrate = baudrate;
#if defined(CONFIG_PPC) || defined(CONFIG_MCF52x2)
gd->bd->bi_baudrate = baudrate;
#endif
serial_setbrg();
udelay(50000);
while (getc() != '\r')
;
}
}
/* Delete only ? */
if (argc < 3 || argv[2] == NULL) {
int rc = hdelete_r(name, &env_htab);
return !rc;
}
/*
* Insert / replace new value
*/
for (i = 2, len = 0; i < argc; ++i)
len += strlen(argv[i]) + 1;
value = malloc(len);
if (value == NULL) {
printf("## Can't malloc %d bytes\n", len);
return 1;
}
for (i = 2, s = value; i < argc; ++i) {
char *v = argv[i];
while ((*s++ = *v++) != '\0')
;
*(s - 1) = ' ';
}
if (s != value)
*--s = '\0';
e.key = name;
e.data = value;
hsearch_r(e, ENTER, &ep, &env_htab);
free(value);
if (!ep) {
printf("## Error inserting \"%s\" variable, errno=%d\n",
name, errno);
return 1;
}
/*
* Some variables should be updated when the corresponding
* entry in the environment is changed
*/
if (strcmp(name, "ipaddr") == 0) {
char *s = argv[2]; /* always use only one arg */
char *e;
unsigned long addr;
bd->bi_ip_addr = 0;
for (addr = 0, i = 0; i < 4; ++i) {
ulong val = s ? simple_strtoul(s, &e, 10) : 0;
addr <<= 8;
addr |= val & 0xFF;
if (s)
s = *e ? e + 1 : e;
}
bd->bi_ip_addr = htonl(addr);
return 0;
} else if (strcmp(argv[1], "loadaddr") == 0) {
load_addr = simple_strtoul(argv[2], NULL, 16);
return 0;
}
#if defined(CONFIG_CMD_NET)
else if (strcmp(argv[1], "bootfile") == 0) {
copy_filename(BootFile, argv[2], sizeof(BootFile));
return 0;
}
#endif
return 0;
}
int setenv(const char *varname, const char *varvalue)
{
const char * const argv[4] = { "setenv", varname, varvalue, NULL };
if (varvalue == NULL || varvalue[0] == '\0')
return _do_env_set(0, 2, (char * const *)argv);
else
return _do_env_set(0, 3, (char * const *)argv);
}
/**
* Set an environment variable to an integer value
*
* @param varname Environmet variable to set
* @param value Value to set it to
* @return 0 if ok, 1 on error
*/
int setenv_ulong(const char *varname, ulong value)
{
/* TODO: this should be unsigned */
char *str = simple_itoa(value);
return setenv(varname, str);
}
/**
* Set an environment variable to an address in hex
*
* @param varname Environmet variable to set
* @param addr Value to set it to
* @return 0 if ok, 1 on error
*/
int setenv_addr(const char *varname, const void *addr)
{
char str[17];
sprintf(str, "%lx", (uintptr_t)addr);
return setenv(varname, str);
}
int do_env_set(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc < 2)
return cmd_usage(cmdtp);
return _do_env_set(flag, argc, argv);
}
/*
* Prompt for environment variable
*/
#if defined(CONFIG_CMD_ASKENV)
int do_env_ask(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char message[CONFIG_SYS_CBSIZE];
int size = CONFIG_SYS_CBSIZE - 1;
int i, len, pos;
char *local_args[4];
local_args[0] = argv[0];
local_args[1] = argv[1];
local_args[2] = NULL;
local_args[3] = NULL;
/* Check the syntax */
switch (argc) {
case 1:
return cmd_usage(cmdtp);
case 2: /* env_ask envname */
sprintf(message, "Please enter '%s':", argv[1]);
break;
case 3: /* env_ask envname size */
sprintf(message, "Please enter '%s':", argv[1]);
size = simple_strtoul(argv[2], NULL, 10);
break;
default: /* env_ask envname message1 ... messagen size */
for (i = 2, pos = 0; i < argc - 1; i++) {
if (pos)
message[pos++] = ' ';
strcpy(message + pos, argv[i]);
pos += strlen(argv[i]);
}
message[pos] = '\0';
size = simple_strtoul(argv[argc - 1], NULL, 10);
break;
}
if (size >= CONFIG_SYS_CBSIZE)
size = CONFIG_SYS_CBSIZE - 1;
if (size <= 0)
return 1;
/* prompt for input */
len = readline(message);
if (size < len)
console_buffer[size] = '\0';
len = 2;
if (console_buffer[0] != '\0') {
local_args[2] = console_buffer;
len = 3;
}
/* Continue calling setenv code */
return _do_env_set(flag, len, local_args);
}
#endif
/*
* Interactively edit an environment variable
*/
#if defined(CONFIG_CMD_EDITENV)
int do_env_edit(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char buffer[CONFIG_SYS_CBSIZE];
char *init_val;
if (argc < 2)
return cmd_usage(cmdtp);
/* Set read buffer to initial value or empty sting */
init_val = getenv(argv[1]);
if (init_val)
sprintf(buffer, "%s", init_val);
else
buffer[0] = '\0';
readline_into_buffer("edit: ", buffer);
return setenv(argv[1], buffer);
}
#endif /* CONFIG_CMD_EDITENV */
/*
* Look up variable from environment,
* return address of storage for that variable,
* or NULL if not found
*/
char *getenv(const char *name)
{
if (gd->flags & GD_FLG_ENV_READY) { /* after import into hashtable */
ENTRY e, *ep;
WATCHDOG_RESET();
e.key = name;
e.data = NULL;
hsearch_r(e, FIND, &ep, &env_htab);
return ep ? ep->data : NULL;
}
/* restricted capabilities before import */
if (getenv_f(name, (char *)(gd->env_buf), sizeof(gd->env_buf)) > 0)
return (char *)(gd->env_buf);
return NULL;
}
/*
* Look up variable from environment for restricted C runtime env.
*/
int getenv_f(const char *name, char *buf, unsigned len)
{
int i, nxt;
for (i = 0; env_get_char(i) != '\0'; i = nxt + 1) {
int val, n;
for (nxt = i; env_get_char(nxt) != '\0'; ++nxt) {
if (nxt >= CONFIG_ENV_SIZE)
return -1;
}
val = envmatch((uchar *)name, i);
if (val < 0)
continue;
/* found; copy out */
for (n = 0; n < len; ++n, ++buf) {
*buf = env_get_char(val++);
if (*buf == '\0')
return n;
}
if (n)
*--buf = '\0';
printf("env_buf [%d bytes] too small for value of \"%s\"\n",
len, name);
return n;
}
return -1;
}
/**
* Decode the integer value of an environment variable and return it.
*
* @param name Name of environemnt variable
* @param base Number base to use (normally 10, or 16 for hex)
* @param default_val Default value to return if the variable is not
* found
* @return the decoded value, or default_val if not found
*/
ulong getenv_ulong(const char *name, int base, ulong default_val)
{
/*
* We can use getenv() here, even before relocation, since the
* environment variable value is an integer and thus short.
*/
const char *str = getenv(name);
return str ? simple_strtoul(str, NULL, base) : default_val;
}
#if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
int do_env_save(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
printf("Saving Environment to %s...\n", env_name_spec);
return saveenv() ? 1 : 0;
}
U_BOOT_CMD(
saveenv, 1, 0, do_env_save,
"save environment variables to persistent storage",
""
);
#endif
/*
* Match a name / name=value pair
*
* s1 is either a simple 'name', or a 'name=value' pair.
* i2 is the environment index for a 'name2=value2' pair.
* If the names match, return the index for the value2, else -1.
*/
int envmatch(uchar *s1, int i2)
{
while (*s1 == env_get_char(i2++))
if (*s1++ == '=')
return i2;
if (*s1 == '\0' && env_get_char(i2-1) == '=')
return i2;
return -1;
}
static int do_env_default(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
if (argc != 2 || strcmp(argv[1], "-f") != 0)
return cmd_usage(cmdtp);
set_default_env("## Resetting to default environment\n");
return 0;
}
static int do_env_delete(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
printf("Not implemented yet\n");
return 0;
}
#ifdef CONFIG_CMD_EXPORTENV
/*
* env export [-t | -b | -c] [-s size] addr [var ...]
* -t: export as text format; if size is given, data will be
* padded with '\0' bytes; if not, one terminating '\0'
* will be added (which is included in the "filesize"
* setting so you can for exmple copy this to flash and
* keep the termination).
* -b: export as binary format (name=value pairs separated by
* '\0', list end marked by double "\0\0")
* -c: export as checksum protected environment format as
* used for example by "saveenv" command
* -s size:
* size of output buffer
* addr: memory address where environment gets stored
* var... List of variable names that get included into the
* export. Without arguments, the whole environment gets
* exported.
*
* With "-c" and size is NOT given, then the export command will
* format the data as currently used for the persistent storage,
* i. e. it will use CONFIG_ENV_SECT_SIZE as output block size and
* prepend a valid CRC32 checksum and, in case of resundant
* environment, a "current" redundancy flag. If size is given, this
* value will be used instead of CONFIG_ENV_SECT_SIZE; again, CRC32
* checksum and redundancy flag will be inserted.
*
* With "-b" and "-t", always only the real data (including a
* terminating '\0' byte) will be written; here the optional size
* argument will be used to make sure not to overflow the user
* provided buffer; the command will abort if the size is not
* sufficient. Any remainign space will be '\0' padded.
*
* On successful return, the variable "filesize" will be set.
* Note that filesize includes the trailing/terminating '\0' byte(s).
*
* Usage szenario: create a text snapshot/backup of the current settings:
*
* => env export -t 100000
* => era ${backup_addr} +${filesize}
* => cp.b 100000 ${backup_addr} ${filesize}
*
* Re-import this snapshot, deleting all other settings:
*
* => env import -d -t ${backup_addr}
*/
static int do_env_export(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
char buf[32];
char *addr, *cmd, *res;
size_t size = 0;
ssize_t len;
env_t *envp;
char sep = '\n';
int chk = 0;
int fmt = 0;
cmd = *argv;
while (--argc > 0 && **++argv == '-') {
char *arg = *argv;
while (*++arg) {
switch (*arg) {
case 'b': /* raw binary format */
if (fmt++)
goto sep_err;
sep = '\0';
break;
case 'c': /* external checksum format */
if (fmt++)
goto sep_err;
sep = '\0';
chk = 1;
break;
case 's': /* size given */
if (--argc <= 0)
return cmd_usage(cmdtp);
size = simple_strtoul(*++argv, NULL, 16);
goto NXTARG;
case 't': /* text format */
if (fmt++)
goto sep_err;
sep = '\n';
break;
default:
return cmd_usage(cmdtp);
}
}
NXTARG: ;
}
if (argc < 1)
return cmd_usage(cmdtp);
addr = (char *)simple_strtoul(argv[0], NULL, 16);
if (size)
memset(addr, '\0', size);
argc--;
argv++;
if (sep) { /* export as text file */
len = hexport_r(&env_htab, sep, &addr, size, argc, argv);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
return 1;
}
sprintf(buf, "%zX", (size_t)len);
setenv("filesize", buf);
return 0;
}
envp = (env_t *)addr;
if (chk) /* export as checksum protected block */
res = (char *)envp->data;
else /* export as raw binary data */
res = addr;
len = hexport_r(&env_htab, '\0', &res, ENV_SIZE, argc, argv);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
return 1;
}
if (chk) {
envp->crc = crc32(0, envp->data, ENV_SIZE);
#ifdef CONFIG_ENV_ADDR_REDUND
envp->flags = ACTIVE_FLAG;
#endif
}
sprintf(buf, "%zX", (size_t)(len + offsetof(env_t, data)));
setenv("filesize", buf);
return 0;
sep_err:
printf("## %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n", cmd);
return 1;
}
#endif
#ifdef CONFIG_CMD_IMPORTENV
/*
* env import [-d] [-t | -b | -c] addr [size]
* -d: delete existing environment before importing;
* otherwise overwrite / append to existion definitions
* -t: assume text format; either "size" must be given or the
* text data must be '\0' terminated
* -b: assume binary format ('\0' separated, "\0\0" terminated)
* -c: assume checksum protected environment format
* addr: memory address to read from
* size: length of input data; if missing, proper '\0'
* termination is mandatory
*/
static int do_env_import(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
char *cmd, *addr;
char sep = '\n';
int chk = 0;
int fmt = 0;
int del = 0;
size_t size;
cmd = *argv;
while (--argc > 0 && **++argv == '-') {
char *arg = *argv;
while (*++arg) {
switch (*arg) {
case 'b': /* raw binary format */
if (fmt++)
goto sep_err;
sep = '\0';
break;
case 'c': /* external checksum format */
if (fmt++)
goto sep_err;
sep = '\0';
chk = 1;
break;
case 't': /* text format */
if (fmt++)
goto sep_err;
sep = '\n';
break;
case 'd':
del = 1;
break;
default:
return cmd_usage(cmdtp);
}
}
}
if (argc < 1)
return cmd_usage(cmdtp);
if (!fmt)
printf("## Warning: defaulting to text format\n");
addr = (char *)simple_strtoul(argv[0], NULL, 16);
if (argc == 2) {
size = simple_strtoul(argv[1], NULL, 16);
} else {
char *s = addr;
size = 0;
while (size < MAX_ENV_SIZE) {
if ((*s == sep) && (*(s+1) == '\0'))
break;
++s;
++size;
}
if (size == MAX_ENV_SIZE) {
printf("## Warning: Input data exceeds %d bytes"
" - truncated\n", MAX_ENV_SIZE);
}
size += 2;
printf("## Info: input data size = %zu = 0x%zX\n", size, size);
}
if (chk) {
uint32_t crc;
env_t *ep = (env_t *)addr;
size -= offsetof(env_t, data);
memcpy(&crc, &ep->crc, sizeof(crc));
if (crc32(0, ep->data, size) != crc) {
puts("## Error: bad CRC, import failed\n");
return 1;
}
addr = (char *)ep->data;
}
if (himport_r(&env_htab, addr, size, sep, del ? 0 : H_NOCLEAR) == 0) {
error("Environment import failed: errno = %d\n", errno);
return 1;
}
gd->flags |= GD_FLG_ENV_READY;
return 0;
sep_err:
printf("## %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n",
cmd);
return 1;
}
#endif
/*
* New command line interface: "env" command with subcommands
*/
static cmd_tbl_t cmd_env_sub[] = {
#if defined(CONFIG_CMD_ASKENV)
U_BOOT_CMD_MKENT(ask, CONFIG_SYS_MAXARGS, 1, do_env_ask, "", ""),
#endif
U_BOOT_CMD_MKENT(default, 1, 0, do_env_default, "", ""),
U_BOOT_CMD_MKENT(delete, 2, 0, do_env_delete, "", ""),
#if defined(CONFIG_CMD_EDITENV)
U_BOOT_CMD_MKENT(edit, 2, 0, do_env_edit, "", ""),
#endif
#if defined(CONFIG_CMD_EXPORTENV)
U_BOOT_CMD_MKENT(export, 4, 0, do_env_export, "", ""),
#endif
#if defined(CONFIG_CMD_GREPENV)
U_BOOT_CMD_MKENT(grep, CONFIG_SYS_MAXARGS, 1, do_env_grep, "", ""),
#endif
#if defined(CONFIG_CMD_IMPORTENV)
U_BOOT_CMD_MKENT(import, 5, 0, do_env_import, "", ""),
#endif
U_BOOT_CMD_MKENT(print, CONFIG_SYS_MAXARGS, 1, do_env_print, "", ""),
#if defined(CONFIG_CMD_RUN)
U_BOOT_CMD_MKENT(run, CONFIG_SYS_MAXARGS, 1, do_run, "", ""),
#endif
#if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
U_BOOT_CMD_MKENT(save, 1, 0, do_env_save, "", ""),
#endif
U_BOOT_CMD_MKENT(set, CONFIG_SYS_MAXARGS, 0, do_env_set, "", ""),
};
#if defined(CONFIG_NEEDS_MANUAL_RELOC)
void env_reloc(void)
{
fixup_cmdtable(cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
}
#endif
static int do_env(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
cmd_tbl_t *cp;
if (argc < 2)
return cmd_usage(cmdtp);
/* drop initial "env" arg */
argc--;
argv++;
cp = find_cmd_tbl(argv[0], cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
if (cp)
return cp->cmd(cmdtp, flag, argc, argv);
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
env, CONFIG_SYS_MAXARGS, 1, do_env,
"environment handling commands",
#if defined(CONFIG_CMD_ASKENV)
"ask name [message] [size] - ask for environment variable\nenv "
#endif
"default -f - reset default environment\n"
#if defined(CONFIG_CMD_EDITENV)
"env edit name - edit environment variable\n"
#endif
"env export [-t | -b | -c] [-s size] addr [var ...] - export environment\n"
#if defined(CONFIG_CMD_GREPENV)
"env grep string [...] - search environment\n"
#endif
"env import [-d] [-t | -b | -c] addr [size] - import environment\n"
"env print [name ...] - print environment\n"
#if defined(CONFIG_CMD_RUN)
"env run var [...] - run commands in an environment variable\n"
#endif
#if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
"env save - save environment\n"
#endif
"env set [-f] name [arg ...]\n"
);
/*
* Old command line interface, kept for compatibility
*/
#if defined(CONFIG_CMD_EDITENV)
U_BOOT_CMD_COMPLETE(
editenv, 2, 0, do_env_edit,
"edit environment variable",
"name\n"
" - edit environment variable 'name'",
var_complete
);
#endif
U_BOOT_CMD_COMPLETE(
printenv, CONFIG_SYS_MAXARGS, 1, do_env_print,
"print environment variables",
"\n - print values of all environment variables\n"
"printenv name ...\n"
" - print value of environment variable 'name'",
var_complete
);
#ifdef CONFIG_CMD_GREPENV
U_BOOT_CMD_COMPLETE(
grepenv, CONFIG_SYS_MAXARGS, 0, do_env_grep,
"search environment variables",
"string ...\n"
" - list environment name=value pairs matching 'string'",
var_complete
);
#endif
U_BOOT_CMD_COMPLETE(
setenv, CONFIG_SYS_MAXARGS, 0, do_env_set,
"set environment variables",
"name value ...\n"
" - set environment variable 'name' to 'value ...'\n"
"setenv name\n"
" - delete environment variable 'name'",
var_complete
);
#if defined(CONFIG_CMD_ASKENV)
U_BOOT_CMD(
askenv, CONFIG_SYS_MAXARGS, 1, do_env_ask,
"get environment variables from stdin",
"name [message] [size]\n"
" - get environment variable 'name' from stdin (max 'size' chars)\n"
"askenv name\n"
" - get environment variable 'name' from stdin\n"
"askenv name size\n"
" - get environment variable 'name' from stdin (max 'size' chars)\n"
"askenv name [message] size\n"
" - display 'message' string and get environment variable 'name'"
"from stdin (max 'size' chars)"
);
#endif
#if defined(CONFIG_CMD_RUN)
U_BOOT_CMD_COMPLETE(
run, CONFIG_SYS_MAXARGS, 1, do_run,
"run commands in an environment variable",
"var [...]\n"
" - run the commands in the environment variable(s) 'var'",
var_complete
);
#endif
|
1001-study-uboot
|
common/cmd_nvedit.c
|
C
|
gpl3
| 25,080
|
/*
* (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 <config.h>
#ifdef __PPC__
/*
* At least on G2 PowerPC cores, sequential accesses to non-existent
* memory must be synchronized.
*/
# include <asm/io.h> /* for sync() */
#else
# define sync() /* nothing */
#endif
/*
* Check memory range for valid RAM. A simple memory test determines
* the actually available RAM size between addresses `base' and
* `base + maxsize'.
*/
long get_ram_size(long *base, long maxsize)
{
volatile long *addr;
long save[32];
long cnt;
long val;
long size;
int i = 0;
for (cnt = (maxsize / sizeof (long)) >> 1; cnt > 0; cnt >>= 1) {
addr = base + cnt; /* pointer arith! */
sync ();
save[i++] = *addr;
sync ();
*addr = ~cnt;
}
addr = base;
sync ();
save[i] = *addr;
sync ();
*addr = 0;
sync ();
if ((val = *addr) != 0) {
/* Restore the original data before leaving the function.
*/
sync ();
*addr = save[i];
for (cnt = 1; cnt < maxsize / sizeof(long); cnt <<= 1) {
addr = base + cnt;
sync ();
*addr = save[--i];
}
return (0);
}
for (cnt = 1; cnt < maxsize / sizeof (long); cnt <<= 1) {
addr = base + cnt; /* pointer arith! */
val = *addr;
*addr = save[--i];
if (val != ~cnt) {
size = cnt * sizeof (long);
/* Restore the original data before leaving the function.
*/
for (cnt <<= 1; cnt < maxsize / sizeof (long); cnt <<= 1) {
addr = base + cnt;
*addr = save[--i];
}
return (size);
}
}
return (maxsize);
}
|
1001-study-uboot
|
common/memsize.c
|
C
|
gpl3
| 2,377
|
/*
* (C) Copyright 2003
* Tait Electronics Limited, Christchurch, New Zealand
*
* 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 provides a shell like 'test' function to return
* true/false from an integer or string compare of two memory
* locations or a location and a scalar/literal.
* A few parts were lifted from bash 'test' command
*/
#include <common.h>
#include <config.h>
#include <command.h>
#define EQ 0
#define NE 1
#define LT 2
#define GT 3
#define LE 4
#define GE 5
struct op_tbl_s {
char *op; /* operator string */
int opcode; /* internal representation of opcode */
};
typedef struct op_tbl_s op_tbl_t;
static const op_tbl_t op_table [] = {
{ "-lt", LT },
{ "<" , LT },
{ "-gt", GT },
{ ">" , GT },
{ "-eq", EQ },
{ "==" , EQ },
{ "-ne", NE },
{ "!=" , NE },
{ "<>" , NE },
{ "-ge", GE },
{ ">=" , GE },
{ "-le", LE },
{ "<=" , LE },
};
static long evalexp(char *s, int w)
{
long l = 0;
long *p;
/* if the parameter starts with a * then assume is a pointer to the value we want */
if (s[0] == '*') {
p = (long *)simple_strtoul(&s[1], NULL, 16);
switch (w) {
case 1: return((long)(*(unsigned char *)p));
case 2: return((long)(*(unsigned short *)p));
case 4: return(*p);
}
} else {
l = simple_strtoul(s, NULL, 16);
}
return (l & ((1 << (w * 8)) - 1));
}
static char * evalstr(char *s)
{
/* if the parameter starts with a * then assume a string pointer else its a literal */
if (s[0] == '*') {
return (char *)simple_strtoul(&s[1], NULL, 16);
} else {
return s;
}
}
static int stringcomp(char *s, char *t, int op)
{
int p;
char *l, *r;
l = evalstr(s);
r = evalstr(t);
p = strcmp(l, r);
switch (op) {
case EQ: return (p == 0);
case NE: return (p != 0);
case LT: return (p < 0);
case GT: return (p > 0);
case LE: return (p <= 0);
case GE: return (p >= 0);
}
return (0);
}
static int arithcomp (char *s, char *t, int op, int w)
{
long l, r;
l = evalexp (s, w);
r = evalexp (t, w);
switch (op) {
case EQ: return (l == r);
case NE: return (l != r);
case LT: return (l < r);
case GT: return (l > r);
case LE: return (l <= r);
case GE: return (l >= r);
}
return (0);
}
int binary_test (char *op, char *arg1, char *arg2, int w)
{
int len, i;
const op_tbl_t *optp;
len = strlen(op);
for (optp = (op_tbl_t *)&op_table, i = 0;
i < ARRAY_SIZE(op_table);
optp++, i++) {
if ((strncmp (op, optp->op, len) == 0) && (len == strlen (optp->op))) {
if (w == 0) {
return (stringcomp(arg1, arg2, optp->opcode));
} else {
return (arithcomp (arg1, arg2, optp->opcode, w));
}
}
}
printf("Unknown operator '%s'\n", op);
return 0; /* op code not found */
}
/* command line interface to the shell test */
int do_itest ( cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[] )
{
int value, w;
/* Validate arguments */
if ((argc != 4))
return cmd_usage(cmdtp);
/* Check for a data width specification.
* Defaults to long (4) if no specification.
* Uses -2 as 'width' for .s (string) so as not to upset existing code
*/
switch (w = cmd_get_data_size(argv[0], 4)) {
case 1:
case 2:
case 4:
value = binary_test (argv[2], argv[1], argv[3], w);
break;
case -2:
value = binary_test (argv[2], argv[1], argv[3], 0);
break;
case -1:
default:
puts("Invalid data width specifier\n");
value = 0;
break;
}
return !value;
}
U_BOOT_CMD(
itest, 4, 0, do_itest,
"return true/false on integer compare",
"[.b, .w, .l, .s] [*]value1 <op> [*]value2"
);
|
1001-study-uboot
|
common/cmd_itest.c
|
C
|
gpl3
| 4,265
|
/*
* Command for accessing SPI flash.
*
* Copyright (C) 2008 Atmel Corporation
* Licensed under the GPL-2 or later.
*/
#include <common.h>
#include <malloc.h>
#include <spi_flash.h>
#include <asm/io.h>
#ifndef CONFIG_SF_DEFAULT_SPEED
# define CONFIG_SF_DEFAULT_SPEED 1000000
#endif
#ifndef CONFIG_SF_DEFAULT_MODE
# define CONFIG_SF_DEFAULT_MODE SPI_MODE_3
#endif
static struct spi_flash *flash;
/*
* This function computes the length argument for the erase command.
* The length on which the command is to operate can be given in two forms:
* 1. <cmd> offset len - operate on <'offset', 'len')
* 2. <cmd> offset +len - operate on <'offset', 'round_up(len)')
* If the second form is used and the length doesn't fall on the
* sector boundary, than it will be adjusted to the next sector boundary.
* If it isn't in the flash, the function will fail (return -1).
* Input:
* arg: length specification (i.e. both command arguments)
* Output:
* len: computed length for operation
* Return:
* 1: success
* -1: failure (bad format, bad address).
*/
static int sf_parse_len_arg(char *arg, ulong *len)
{
char *ep;
char round_up_len; /* indicates if the "+length" form used */
ulong len_arg;
round_up_len = 0;
if (*arg == '+') {
round_up_len = 1;
++arg;
}
len_arg = simple_strtoul(arg, &ep, 16);
if (ep == arg || *ep != '\0')
return -1;
if (round_up_len && flash->sector_size > 0)
*len = ROUND(len_arg, flash->sector_size);
else
*len = len_arg;
return 1;
}
static int do_spi_flash_probe(int argc, char * const argv[])
{
unsigned int bus = 0;
unsigned int cs;
unsigned int speed = CONFIG_SF_DEFAULT_SPEED;
unsigned int mode = CONFIG_SF_DEFAULT_MODE;
char *endp;
struct spi_flash *new;
if (argc < 2)
return -1;
cs = simple_strtoul(argv[1], &endp, 0);
if (*argv[1] == 0 || (*endp != 0 && *endp != ':'))
return -1;
if (*endp == ':') {
if (endp[1] == 0)
return -1;
bus = cs;
cs = simple_strtoul(endp + 1, &endp, 0);
if (*endp != 0)
return -1;
}
if (argc >= 3) {
speed = simple_strtoul(argv[2], &endp, 0);
if (*argv[2] == 0 || *endp != 0)
return -1;
}
if (argc >= 4) {
mode = simple_strtoul(argv[3], &endp, 16);
if (*argv[3] == 0 || *endp != 0)
return -1;
}
new = spi_flash_probe(bus, cs, speed, mode);
if (!new) {
printf("Failed to initialize SPI flash at %u:%u\n", bus, cs);
return 1;
}
if (flash)
spi_flash_free(flash);
flash = new;
return 0;
}
/**
* Write a block of data to SPI flash, first checking if it is different from
* what is already there.
*
* If the data being written is the same, then *skipped is incremented by len.
*
* @param flash flash context pointer
* @param offset flash offset to write
* @param len number of bytes to write
* @param buf buffer to write from
* @param cmp_buf read buffer to use to compare data
* @param skipped Count of skipped data (incremented by this function)
* @return NULL if OK, else a string containing the stage which failed
*/
static const char *spi_flash_update_block(struct spi_flash *flash, u32 offset,
size_t len, const char *buf, char *cmp_buf, size_t *skipped)
{
debug("offset=%#x, sector_size=%#x, len=%#x\n",
offset, flash->sector_size, len);
if (spi_flash_read(flash, offset, len, cmp_buf))
return "read";
if (memcmp(cmp_buf, buf, len) == 0) {
debug("Skip region %x size %x: no change\n",
offset, len);
*skipped += len;
return NULL;
}
if (spi_flash_erase(flash, offset, len))
return "erase";
if (spi_flash_write(flash, offset, len, buf))
return "write";
return NULL;
}
/**
* Update an area of SPI flash by erasing and writing any blocks which need
* to change. Existing blocks with the correct data are left unchanged.
*
* @param flash flash context pointer
* @param offset flash offset to write
* @param len number of bytes to write
* @param buf buffer to write from
* @return 0 if ok, 1 on error
*/
static int spi_flash_update(struct spi_flash *flash, u32 offset,
size_t len, const char *buf)
{
const char *err_oper = NULL;
char *cmp_buf;
const char *end = buf + len;
size_t todo; /* number of bytes to do in this pass */
size_t skipped = 0; /* statistics */
cmp_buf = malloc(flash->sector_size);
if (cmp_buf) {
for (; buf < end && !err_oper; buf += todo, offset += todo) {
todo = min(end - buf, flash->sector_size);
err_oper = spi_flash_update_block(flash, offset, todo,
buf, cmp_buf, &skipped);
}
} else {
err_oper = "malloc";
}
free(cmp_buf);
if (err_oper) {
printf("SPI flash failed in %s step\n", err_oper);
return 1;
}
printf("%zu bytes written, %zu bytes skipped\n", len - skipped,
skipped);
return 0;
}
static int do_spi_flash_read_write(int argc, char * const argv[])
{
unsigned long addr;
unsigned long offset;
unsigned long len;
void *buf;
char *endp;
int ret;
if (argc < 4)
return -1;
addr = simple_strtoul(argv[1], &endp, 16);
if (*argv[1] == 0 || *endp != 0)
return -1;
offset = simple_strtoul(argv[2], &endp, 16);
if (*argv[2] == 0 || *endp != 0)
return -1;
len = simple_strtoul(argv[3], &endp, 16);
if (*argv[3] == 0 || *endp != 0)
return -1;
buf = map_physmem(addr, len, MAP_WRBACK);
if (!buf) {
puts("Failed to map physical memory\n");
return 1;
}
if (strcmp(argv[0], "update") == 0)
ret = spi_flash_update(flash, offset, len, buf);
else if (strcmp(argv[0], "read") == 0)
ret = spi_flash_read(flash, offset, len, buf);
else
ret = spi_flash_write(flash, offset, len, buf);
unmap_physmem(buf, len);
if (ret) {
printf("SPI flash %s failed\n", argv[0]);
return 1;
}
return 0;
}
static int do_spi_flash_erase(int argc, char * const argv[])
{
unsigned long offset;
unsigned long len;
char *endp;
int ret;
if (argc < 3)
return -1;
offset = simple_strtoul(argv[1], &endp, 16);
if (*argv[1] == 0 || *endp != 0)
return -1;
ret = sf_parse_len_arg(argv[2], &len);
if (ret != 1)
return -1;
ret = spi_flash_erase(flash, offset, len);
if (ret) {
printf("SPI flash %s failed\n", argv[0]);
return 1;
}
return 0;
}
static int do_spi_flash(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
const char *cmd;
int ret;
/* need at least two arguments */
if (argc < 2)
goto usage;
cmd = argv[1];
--argc;
++argv;
if (strcmp(cmd, "probe") == 0) {
ret = do_spi_flash_probe(argc, argv);
goto done;
}
/* The remaining commands require a selected device */
if (!flash) {
puts("No SPI flash selected. Please run `sf probe'\n");
return 1;
}
if (strcmp(cmd, "read") == 0 || strcmp(cmd, "write") == 0 ||
strcmp(cmd, "update") == 0)
ret = do_spi_flash_read_write(argc, argv);
else if (strcmp(cmd, "erase") == 0)
ret = do_spi_flash_erase(argc, argv);
else
ret = -1;
done:
if (ret != -1)
return ret;
usage:
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
sf, 5, 1, do_spi_flash,
"SPI flash sub-system",
"probe [bus:]cs [hz] [mode] - init flash device on given SPI bus\n"
" and chip select\n"
"sf read addr offset len - read `len' bytes starting at\n"
" `offset' to memory at `addr'\n"
"sf write addr offset len - write `len' bytes from memory\n"
" at `addr' to flash at `offset'\n"
"sf erase offset [+]len - erase `len' bytes from `offset'\n"
" `+len' round up `len' to block size\n"
"sf update addr offset len - erase and write `len' bytes from memory\n"
" at `addr' to flash at `offset'"
);
|
1001-study-uboot
|
common/cmd_sf.c
|
C
|
gpl3
| 7,427
|
/*
* (C) Copyright 2002
* Detlev Zundel, DENX Software Engineering, dzu@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* BMP handling routines
*/
#include <common.h>
#include <lcd.h>
#include <bmp_layout.h>
#include <command.h>
#include <asm/byteorder.h>
#include <malloc.h>
static int bmp_info (ulong addr);
static int bmp_display (ulong addr, int x, int y);
/*
* Allocate and decompress a BMP image using gunzip().
*
* Returns a pointer to the decompressed image data. Must be freed by
* the caller after use.
*
* Returns NULL if decompression failed, or if the decompressed data
* didn't contain a valid BMP signature.
*/
#ifdef CONFIG_VIDEO_BMP_GZIP
bmp_image_t *gunzip_bmp(unsigned long addr, unsigned long *lenp)
{
void *dst;
unsigned long len;
bmp_image_t *bmp;
/*
* Decompress bmp image
*/
len = CONFIG_SYS_VIDEO_LOGO_MAX_SIZE;
dst = malloc(CONFIG_SYS_VIDEO_LOGO_MAX_SIZE);
if (dst == NULL) {
puts("Error: malloc in gunzip failed!\n");
return NULL;
}
if (gunzip(dst, CONFIG_SYS_VIDEO_LOGO_MAX_SIZE, (uchar *)addr, &len) != 0) {
free(dst);
return NULL;
}
if (len == CONFIG_SYS_VIDEO_LOGO_MAX_SIZE)
puts("Image could be truncated"
" (increase CONFIG_SYS_VIDEO_LOGO_MAX_SIZE)!\n");
bmp = dst;
/*
* Check for bmp mark 'BM'
*/
if (!((bmp->header.signature[0] == 'B') &&
(bmp->header.signature[1] == 'M'))) {
free(dst);
return NULL;
}
debug("Gzipped BMP image detected!\n");
return bmp;
}
#else
bmp_image_t *gunzip_bmp(unsigned long addr, unsigned long *lenp)
{
return NULL;
}
#endif
static int do_bmp_info(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong addr;
switch (argc) {
case 1: /* use load_addr as default address */
addr = load_addr;
break;
case 2: /* use argument */
addr = simple_strtoul(argv[1], NULL, 16);
break;
default:
return cmd_usage(cmdtp);
}
return (bmp_info(addr));
}
static int do_bmp_display(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
ulong addr;
int x = 0, y = 0;
switch (argc) {
case 1: /* use load_addr as default address */
addr = load_addr;
break;
case 2: /* use argument */
addr = simple_strtoul(argv[1], NULL, 16);
break;
case 4:
addr = simple_strtoul(argv[1], NULL, 16);
x = simple_strtoul(argv[2], NULL, 10);
y = simple_strtoul(argv[3], NULL, 10);
break;
default:
return cmd_usage(cmdtp);
}
return (bmp_display(addr, x, y));
}
static cmd_tbl_t cmd_bmp_sub[] = {
U_BOOT_CMD_MKENT(info, 3, 0, do_bmp_info, "", ""),
U_BOOT_CMD_MKENT(display, 5, 0, do_bmp_display, "", ""),
};
#ifdef CONFIG_NEEDS_MANUAL_RELOC
void bmp_reloc(void) {
fixup_cmdtable(cmd_bmp_sub, ARRAY_SIZE(cmd_bmp_sub));
}
#endif
/*
* Subroutine: do_bmp
*
* Description: Handler for 'bmp' command..
*
* Inputs: argv[1] contains the subcommand
*
* Return: None
*
*/
static int do_bmp(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
cmd_tbl_t *c;
/* Strip off leading 'bmp' command argument */
argc--;
argv++;
c = find_cmd_tbl(argv[0], &cmd_bmp_sub[0], ARRAY_SIZE(cmd_bmp_sub));
if (c)
return c->cmd(cmdtp, flag, argc, argv);
else
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
bmp, 5, 1, do_bmp,
"manipulate BMP image data",
"info <imageAddr> - display image info\n"
"bmp display <imageAddr> [x y] - display image at x,y"
);
/*
* Subroutine: bmp_info
*
* Description: Show information about bmp file in memory
*
* Inputs: addr address of the bmp file
*
* Return: None
*
*/
static int bmp_info(ulong addr)
{
bmp_image_t *bmp=(bmp_image_t *)addr;
unsigned long len;
if (!((bmp->header.signature[0]=='B') &&
(bmp->header.signature[1]=='M')))
bmp = gunzip_bmp(addr, &len);
if (bmp == NULL) {
printf("There is no valid bmp file at the given address\n");
return 1;
}
printf("Image size : %d x %d\n", le32_to_cpu(bmp->header.width),
le32_to_cpu(bmp->header.height));
printf("Bits per pixel: %d\n", le16_to_cpu(bmp->header.bit_count));
printf("Compression : %d\n", le32_to_cpu(bmp->header.compression));
if ((unsigned long)bmp != addr)
free(bmp);
return(0);
}
/*
* Subroutine: bmp_display
*
* Description: Display bmp file located in memory
*
* Inputs: addr address of the bmp file
*
* Return: None
*
*/
static int bmp_display(ulong addr, int x, int y)
{
int ret;
bmp_image_t *bmp = (bmp_image_t *)addr;
unsigned long len;
if (!((bmp->header.signature[0]=='B') &&
(bmp->header.signature[1]=='M')))
bmp = gunzip_bmp(addr, &len);
if (!bmp) {
printf("There is no valid bmp file at the given address\n");
return 1;
}
#if defined(CONFIG_LCD)
ret = lcd_display_bitmap((ulong)bmp, x, y);
#elif defined(CONFIG_VIDEO)
extern int video_display_bitmap (ulong, int, int);
ret = video_display_bitmap ((unsigned long)bmp, x, y);
#else
# error bmp_display() requires CONFIG_LCD or CONFIG_VIDEO
#endif
if ((unsigned long)bmp != addr)
free(bmp);
return ret;
}
|
1001-study-uboot
|
common/cmd_bmp.c
|
C
|
gpl3
| 5,744
|
/*
* (C) Copyright 2004
* esd gmbh <www.esd-electronics.com>
* Reinhard Arlt <reinhard.arlt@esd-electronics.com>
*
* made from cmd_reiserfs by
*
* (C) Copyright 2003 - 2004
* Sysgo Real-Time Solutions, AG <www.elinos.com>
* Pavel Bartusek <pba@sysgo.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
*
*/
/*
* Ext2fs support
*/
#include <common.h>
#include <part.h>
#include <config.h>
#include <command.h>
#include <image.h>
#include <linux/ctype.h>
#include <asm/byteorder.h>
#include <ext2fs.h>
#if defined(CONFIG_CMD_USB) && defined(CONFIG_USB_STORAGE)
#include <usb.h>
#endif
#if !defined(CONFIG_DOS_PARTITION) && !defined(CONFIG_EFI_PARTITION)
#error DOS or EFI partition support must be selected
#endif
/* #define EXT2_DEBUG */
#ifdef EXT2_DEBUG
#define PRINTF(fmt,args...) printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif
int do_ext2ls (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = "/";
int dev=0;
int part=1;
char *ep;
block_dev_desc_t *dev_desc=NULL;
int part_length;
if (argc < 3)
return cmd_usage(cmdtp);
dev = (int)simple_strtoul (argv[2], &ep, 16);
dev_desc = get_dev(argv[1],dev);
if (dev_desc == NULL) {
printf ("\n** Block device %s %d not supported\n", argv[1], dev);
return 1;
}
if (*ep) {
if (*ep != ':') {
puts ("\n** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = (int)simple_strtoul(++ep, NULL, 16);
}
if (argc == 4)
filename = argv[3];
PRINTF("Using device %s %d:%d, directory: %s\n", argv[1], dev, part, filename);
if ((part_length = ext2fs_set_blk_dev(dev_desc, part)) == 0) {
printf ("** Bad partition - %s %d:%d **\n", argv[1], dev, part);
ext2fs_close();
return 1;
}
if (!ext2fs_mount(part_length)) {
printf ("** Bad ext2 partition or disk - %s %d:%d **\n", argv[1], dev, part);
ext2fs_close();
return 1;
}
if (ext2fs_ls (filename)) {
printf ("** Error ext2fs_ls() **\n");
ext2fs_close();
return 1;
};
ext2fs_close();
return 0;
}
U_BOOT_CMD(
ext2ls, 4, 1, do_ext2ls,
"list files in a directory (default /)",
"<interface> <dev[:part]> [directory]\n"
" - list files from 'dev' on 'interface' in a 'directory'"
);
/******************************************************************************
* Ext2fs boot command intepreter. Derived from diskboot
*/
int do_ext2load (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = NULL;
char *ep;
int dev, part = 1;
ulong addr = 0, part_length;
int filelen;
disk_partition_t info;
block_dev_desc_t *dev_desc = NULL;
char buf [12];
unsigned long count;
char *addr_str;
switch (argc) {
case 3:
addr_str = getenv("loadaddr");
if (addr_str != NULL)
addr = simple_strtoul (addr_str, NULL, 16);
else
addr = CONFIG_SYS_LOAD_ADDR;
filename = getenv ("bootfile");
count = 0;
break;
case 4:
addr = simple_strtoul (argv[3], NULL, 16);
filename = getenv ("bootfile");
count = 0;
break;
case 5:
addr = simple_strtoul (argv[3], NULL, 16);
filename = argv[4];
count = 0;
break;
case 6:
addr = simple_strtoul (argv[3], NULL, 16);
filename = argv[4];
count = simple_strtoul (argv[5], NULL, 16);
break;
default:
return cmd_usage(cmdtp);
}
if (!filename) {
puts ("** No boot file defined **\n");
return 1;
}
dev = (int)simple_strtoul (argv[2], &ep, 16);
dev_desc = get_dev(argv[1],dev);
if (dev_desc==NULL) {
printf ("** Block device %s %d not supported\n", argv[1], dev);
return 1;
}
if (*ep) {
if (*ep != ':') {
puts ("** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = (int)simple_strtoul(++ep, NULL, 16);
}
PRINTF("Using device %s%d, partition %d\n", argv[1], dev, part);
if (part != 0) {
if (get_partition_info (dev_desc, part, &info)) {
printf ("** Bad partition %d **\n", part);
return 1;
}
if (strncmp((char *)info.type, BOOT_PART_TYPE, sizeof(info.type)) != 0) {
printf ("** Invalid partition type \"%.32s\""
" (expect \"" BOOT_PART_TYPE "\")\n",
info.type);
return 1;
}
printf ("Loading file \"%s\" "
"from %s device %d:%d (%.32s)\n",
filename,
argv[1], dev, part, info.name);
} else {
printf ("Loading file \"%s\" from %s device %d\n",
filename, argv[1], dev);
}
if ((part_length = ext2fs_set_blk_dev(dev_desc, part)) == 0) {
printf ("** Bad partition - %s %d:%d **\n", argv[1], dev, part);
ext2fs_close();
return 1;
}
if (!ext2fs_mount(part_length)) {
printf ("** Bad ext2 partition or disk - %s %d:%d **\n",
argv[1], dev, part);
ext2fs_close();
return 1;
}
filelen = ext2fs_open(filename);
if (filelen < 0) {
printf("** File not found %s\n", filename);
ext2fs_close();
return 1;
}
if ((count < filelen) && (count != 0)) {
filelen = count;
}
if (ext2fs_read((char *)addr, filelen) != filelen) {
printf("** Unable to read \"%s\" from %s %d:%d **\n",
filename, argv[1], dev, part);
ext2fs_close();
return 1;
}
ext2fs_close();
/* Loading ok, update default load address */
load_addr = addr;
printf ("%d bytes read\n", filelen);
sprintf(buf, "%X", filelen);
setenv("filesize", buf);
return 0;
}
U_BOOT_CMD(
ext2load, 6, 0, do_ext2load,
"load binary file from a Ext2 filesystem",
"<interface> <dev[:part]> [addr] [filename] [bytes]\n"
" - load binary file 'filename' from 'dev' on 'interface'\n"
" to address 'addr' from ext2 filesystem"
);
|
1001-study-uboot
|
common/cmd_ext2.c
|
C
|
gpl3
| 6,178
|
/*
* (C) Copyright 2002
* Richard Jones, rjones@nexus-tech.net
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* Boot support
*/
#include <common.h>
#include <command.h>
#include <s_record.h>
#include <net.h>
#include <ata.h>
#include <part.h>
#include <fat.h>
int do_fat_fsload (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
long size;
unsigned long offset;
unsigned long count;
char buf [12];
block_dev_desc_t *dev_desc=NULL;
int dev=0;
int part=1;
char *ep;
if (argc < 5) {
printf( "usage: fatload <interface> <dev[:part]> "
"<addr> <filename> [bytes]\n");
return 1;
}
dev = (int)simple_strtoul(argv[2], &ep, 16);
dev_desc = get_dev(argv[1],dev);
if (dev_desc == NULL) {
puts("\n** Invalid boot device **\n");
return 1;
}
if (*ep) {
if (*ep != ':') {
puts("\n** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = (int)simple_strtoul(++ep, NULL, 16);
}
if (fat_register_device(dev_desc,part)!=0) {
printf("\n** Unable to use %s %d:%d for fatload **\n",
argv[1], dev, part);
return 1;
}
offset = simple_strtoul(argv[3], NULL, 16);
if (argc == 6)
count = simple_strtoul(argv[5], NULL, 16);
else
count = 0;
size = file_fat_read(argv[4], (unsigned char *)offset, count);
if(size==-1) {
printf("\n** Unable to read \"%s\" from %s %d:%d **\n",
argv[4], argv[1], dev, part);
return 1;
}
printf("\n%ld bytes read\n", size);
sprintf(buf, "%lX", size);
setenv("filesize", buf);
return 0;
}
U_BOOT_CMD(
fatload, 6, 0, do_fat_fsload,
"load binary file from a dos filesystem",
"<interface> <dev[:part]> <addr> <filename> [bytes]\n"
" - load binary file 'filename' from 'dev' on 'interface'\n"
" to address 'addr' from dos filesystem"
);
int do_fat_ls (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = "/";
int ret;
int dev=0;
int part=1;
char *ep;
block_dev_desc_t *dev_desc=NULL;
if (argc < 3) {
printf("usage: fatls <interface> <dev[:part]> [directory]\n");
return 0;
}
dev = (int)simple_strtoul(argv[2], &ep, 16);
dev_desc = get_dev(argv[1],dev);
if (dev_desc == NULL) {
puts("\n** Invalid boot device **\n");
return 1;
}
if (*ep) {
if (*ep != ':') {
puts("\n** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = (int)simple_strtoul(++ep, NULL, 16);
}
if (fat_register_device(dev_desc,part)!=0) {
printf("\n** Unable to use %s %d:%d for fatls **\n",
argv[1], dev, part);
return 1;
}
if (argc == 4)
ret = file_fat_ls(argv[3]);
else
ret = file_fat_ls(filename);
if(ret!=0)
printf("No Fat FS detected\n");
return ret;
}
U_BOOT_CMD(
fatls, 4, 1, do_fat_ls,
"list files in a directory (default /)",
"<interface> <dev[:part]> [directory]\n"
" - list files from 'dev' on 'interface' in a 'directory'"
);
int do_fat_fsinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int dev=0;
int part=1;
char *ep;
block_dev_desc_t *dev_desc=NULL;
if (argc < 2) {
printf("usage: fatinfo <interface> <dev[:part]>\n");
return 0;
}
dev = (int)simple_strtoul(argv[2], &ep, 16);
dev_desc = get_dev(argv[1],dev);
if (dev_desc == NULL) {
puts("\n** Invalid boot device **\n");
return 1;
}
if (*ep) {
if (*ep != ':') {
puts("\n** Invalid boot device, use `dev[:part]' **\n");
return 1;
}
part = (int)simple_strtoul(++ep, NULL, 16);
}
if (fat_register_device(dev_desc,part)!=0) {
printf("\n** Unable to use %s %d:%d for fatinfo **\n",
argv[1], dev, part);
return 1;
}
return file_fat_detectfs();
}
U_BOOT_CMD(
fatinfo, 3, 1, do_fat_fsinfo,
"print information about filesystem",
"<interface> <dev[:part]>\n"
" - print information about filesystem from 'dev' on 'interface'"
);
|
1001-study-uboot
|
common/cmd_fat.c
|
C
|
gpl3
| 4,494
|
/*
* cmd_strings.c - just like `strings` command
*
* Copyright (c) 2008 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <config.h>
#include <common.h>
#include <command.h>
static char *start_addr, *last_addr;
int do_strings(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc == 1)
return cmd_usage(cmdtp);
if ((flag & CMD_FLAG_REPEAT) == 0) {
start_addr = (char *)simple_strtoul(argv[1], NULL, 16);
if (argc > 2)
last_addr = (char *)simple_strtoul(argv[2], NULL, 16);
else
last_addr = (char *)-1;
}
char *addr = start_addr;
do {
puts(addr);
puts("\n");
addr += strlen(addr) + 1;
} while (addr[0] && addr < last_addr);
last_addr = addr + (last_addr - start_addr);
start_addr = addr;
return 0;
}
U_BOOT_CMD(
strings, 3, 1, do_strings,
"display strings",
"<addr> [byte count]\n"
" - display strings at <addr> for at least [byte count] or first double NUL"
);
|
1001-study-uboot
|
common/cmd_strings.c
|
C
|
gpl3
| 948
|
/* taken from arch/powerpc/kernel/ppc-stub.c */
/****************************************************************************
THIS SOFTWARE IS NOT COPYRIGHTED
HP offers the following for use in the public domain. HP makes no
warranty with regard to the software or its performance and the
user accepts the software "AS IS" with all faults.
HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD
TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
****************************************************************************/
/****************************************************************************
* Header: remcom.c,v 1.34 91/03/09 12:29:49 glenne Exp $
*
* Module name: remcom.c $
* Revision: 1.34 $
* Date: 91/03/09 12:29:49 $
* Contributor: Lake Stevens Instrument Division$
*
* Description: low level support for gdb debugger. $
*
* Considerations: only works on target hardware $
*
* Written by: Glenn Engel $
* ModuleState: Experimental $
*
* NOTES: See Below $
*
* Modified for SPARC by Stu Grossman, Cygnus Support.
*
* This code has been extensively tested on the Fujitsu SPARClite demo board.
*
* To enable debugger support, two things need to happen. One, a
* call to set_debug_traps() is necessary in order to allow any breakpoints
* or error conditions to be properly intercepted and reported to gdb.
* Two, a breakpoint needs to be generated to begin communication. This
* is most easily accomplished by a call to breakpoint(). Breakpoint()
* simulates a breakpoint by executing a trap #1.
*
*************
*
* The following gdb commands are supported:
*
* command function Return value
*
* g return the value of the CPU registers hex data or ENN
* G set the value of the CPU registers OK or ENN
* qOffsets Get section offsets. Reply is Text=xxx;Data=yyy;Bss=zzz
*
* mAA..AA,LLLL Read LLLL bytes at address AA..AA hex data or ENN
* MAA..AA,LLLL: Write LLLL bytes at address AA.AA OK or ENN
*
* c Resume at current address SNN ( signal NN)
* cAA..AA Continue at address AA..AA SNN
*
* s Step one instruction SNN
* sAA..AA Step one instruction from AA..AA SNN
*
* k kill
*
* ? What was the last sigval ? SNN (signal NN)
*
* bBB..BB Set baud rate to BB..BB OK or BNN, then sets
* baud rate
*
* All commands and responses are sent with a packet which includes a
* checksum. A packet consists of
*
* $<packet info>#<checksum>.
*
* where
* <packet info> :: <characters representing the command or response>
* <checksum> :: <two hex digits computed as modulo 256 sum of <packetinfo>>
*
* When a packet is received, it is first acknowledged with either '+' or '-'.
* '+' indicates a successful transfer. '-' indicates a failed transfer.
*
* Example:
*
* Host: Reply:
* $m0,10#2a +$00010203040506070809101112131415#42
*
****************************************************************************/
#include <common.h>
#include <kgdb.h>
#include <command.h>
#undef KGDB_DEBUG
/*
* BUFMAX defines the maximum number of characters in inbound/outbound buffers
*/
#define BUFMAX 1024
static char remcomInBuffer[BUFMAX];
static char remcomOutBuffer[BUFMAX];
static char remcomRegBuffer[BUFMAX];
static int initialized = 0;
static int kgdb_active = 0, first_entry = 1;
static struct pt_regs entry_regs;
static long error_jmp_buf[BUFMAX/2];
static int longjmp_on_fault = 0;
#ifdef KGDB_DEBUG
static int kdebug = 1;
#endif
static const char hexchars[]="0123456789abcdef";
/* Convert ch from a hex digit to an int */
static int
hex(unsigned char ch)
{
if (ch >= 'a' && ch <= 'f')
return ch-'a'+10;
if (ch >= '0' && ch <= '9')
return ch-'0';
if (ch >= 'A' && ch <= 'F')
return ch-'A'+10;
return -1;
}
/* Convert the memory pointed to by mem into hex, placing result in buf.
* Return a pointer to the last char put in buf (null).
*/
static unsigned char *
mem2hex(char *mem, char *buf, int count)
{
char *tmp;
unsigned char ch;
/*
* We use the upper half of buf as an intermediate buffer for the
* raw memory copy. Hex conversion will work against this one.
*/
tmp = buf + count;
longjmp_on_fault = 1;
memcpy(tmp, mem, count);
while (count-- > 0) {
ch = *tmp++;
*buf++ = hexchars[ch >> 4];
*buf++ = hexchars[ch & 0xf];
}
*buf = 0;
longjmp_on_fault = 0;
return (unsigned char *)buf;
}
/* convert the hex array pointed to by buf into binary to be placed in mem
* return a pointer to the character AFTER the last byte fetched from buf.
*/
static char *
hex2mem(char *buf, char *mem, int count)
{
int hexValue;
char *tmp_raw, *tmp_hex;
/*
* We use the upper half of buf as an intermediate buffer for the
* raw memory that is converted from hex.
*/
tmp_raw = buf + count * 2;
tmp_hex = tmp_raw - 1;
longjmp_on_fault = 1;
while (tmp_hex >= buf) {
tmp_raw--;
hexValue = hex(*tmp_hex--);
if (hexValue < 0)
kgdb_error(KGDBERR_NOTHEXDIG);
*tmp_raw = hexValue;
hexValue = hex(*tmp_hex--);
if (hexValue < 0)
kgdb_error(KGDBERR_NOTHEXDIG);
*tmp_raw |= hexValue << 4;
}
memcpy(mem, tmp_raw, count);
kgdb_flush_cache_range((void *)mem, (void *)(mem+count));
longjmp_on_fault = 0;
return buf;
}
/*
* While we find nice hex chars, build an int.
* Return number of chars processed.
*/
static int
hexToInt(char **ptr, int *intValue)
{
int numChars = 0;
int hexValue;
*intValue = 0;
longjmp_on_fault = 1;
while (**ptr) {
hexValue = hex(**ptr);
if (hexValue < 0)
break;
*intValue = (*intValue << 4) | hexValue;
numChars ++;
(*ptr)++;
}
longjmp_on_fault = 0;
return (numChars);
}
/* scan for the sequence $<data>#<checksum> */
static void
getpacket(char *buffer)
{
unsigned char checksum;
unsigned char xmitcsum;
int i;
int count;
unsigned char ch;
do {
/* wait around for the start character, ignore all other
* characters */
while ((ch = (getDebugChar() & 0x7f)) != '$') {
#ifdef KGDB_DEBUG
if (kdebug)
putc(ch);
#endif
;
}
checksum = 0;
xmitcsum = -1;
count = 0;
/* now, read until a # or end of buffer is found */
while (count < BUFMAX) {
ch = getDebugChar() & 0x7f;
if (ch == '#')
break;
checksum = checksum + ch;
buffer[count] = ch;
count = count + 1;
}
if (count >= BUFMAX)
continue;
buffer[count] = 0;
if (ch == '#') {
xmitcsum = hex(getDebugChar() & 0x7f) << 4;
xmitcsum |= hex(getDebugChar() & 0x7f);
if (checksum != xmitcsum)
putDebugChar('-'); /* failed checksum */
else {
putDebugChar('+'); /* successful transfer */
/* if a sequence char is present, reply the ID */
if (buffer[2] == ':') {
putDebugChar(buffer[0]);
putDebugChar(buffer[1]);
/* remove sequence chars from buffer */
count = strlen(buffer);
for (i=3; i <= count; i++)
buffer[i-3] = buffer[i];
}
}
}
} while (checksum != xmitcsum);
}
/* send the packet in buffer. */
static void
putpacket(unsigned char *buffer)
{
unsigned char checksum;
int count;
unsigned char ch, recv;
/* $<packet info>#<checksum>. */
do {
putDebugChar('$');
checksum = 0;
count = 0;
while ((ch = buffer[count])) {
putDebugChar(ch);
checksum += ch;
count += 1;
}
putDebugChar('#');
putDebugChar(hexchars[checksum >> 4]);
putDebugChar(hexchars[checksum & 0xf]);
recv = getDebugChar();
} while ((recv & 0x7f) != '+');
}
/*
* This function does all command processing for interfacing to gdb.
*/
static int
handle_exception (struct pt_regs *regs)
{
int addr;
int length;
char *ptr;
kgdb_data kd;
int i;
if (!initialized) {
printf("kgdb: exception before kgdb is initialized! huh?\n");
return (0);
}
/* probably should check which exception occured as well */
if (longjmp_on_fault) {
longjmp_on_fault = 0;
kgdb_longjmp(error_jmp_buf, KGDBERR_MEMFAULT);
panic("kgdb longjump failed!\n");
}
if (kgdb_active) {
printf("kgdb: unexpected exception from within kgdb\n");
return (0);
}
kgdb_active = 1;
kgdb_interruptible(0);
printf("kgdb: handle_exception; trap [0x%x]\n", kgdb_trap(regs));
if (kgdb_setjmp(error_jmp_buf) != 0)
panic("kgdb: error or fault in entry init!\n");
kgdb_enter(regs, &kd);
if (first_entry) {
/*
* the first time we enter kgdb, we save the processor
* state so that we can return to the monitor if the
* remote end quits gdb (or at least, tells us to quit
* with the 'k' packet)
*/
entry_regs = *regs;
first_entry = 0;
}
ptr = remcomOutBuffer;
*ptr++ = 'T';
*ptr++ = hexchars[kd.sigval >> 4];
*ptr++ = hexchars[kd.sigval & 0xf];
for (i = 0; i < kd.nregs; i++) {
kgdb_reg *rp = &kd.regs[i];
*ptr++ = hexchars[rp->num >> 4];
*ptr++ = hexchars[rp->num & 0xf];
*ptr++ = ':';
ptr = (char *)mem2hex((char *)&rp->val, ptr, 4);
*ptr++ = ';';
}
*ptr = 0;
#ifdef KGDB_DEBUG
if (kdebug)
printf("kgdb: remcomOutBuffer: %s\n", remcomOutBuffer);
#endif
putpacket((unsigned char *)&remcomOutBuffer);
while (1) {
volatile int errnum;
remcomOutBuffer[0] = 0;
getpacket(remcomInBuffer);
ptr = &remcomInBuffer[1];
#ifdef KGDB_DEBUG
if (kdebug)
printf("kgdb: remcomInBuffer: %s\n", remcomInBuffer);
#endif
errnum = kgdb_setjmp(error_jmp_buf);
if (errnum == 0) switch (remcomInBuffer[0]) {
case '?': /* report most recent signal */
remcomOutBuffer[0] = 'S';
remcomOutBuffer[1] = hexchars[kd.sigval >> 4];
remcomOutBuffer[2] = hexchars[kd.sigval & 0xf];
remcomOutBuffer[3] = 0;
break;
#ifdef KGDB_DEBUG
case 'd':
/* toggle debug flag */
kdebug ^= 1;
break;
#endif
case 'g': /* return the value of the CPU registers. */
length = kgdb_getregs(regs, remcomRegBuffer, BUFMAX);
mem2hex(remcomRegBuffer, remcomOutBuffer, length);
break;
case 'G': /* set the value of the CPU registers */
length = strlen(ptr);
if ((length & 1) != 0) kgdb_error(KGDBERR_BADPARAMS);
hex2mem(ptr, remcomRegBuffer, length/2);
kgdb_putregs(regs, remcomRegBuffer, length/2);
strcpy(remcomOutBuffer,"OK");
break;
case 'm': /* mAA..AA,LLLL Read LLLL bytes at address AA..AA */
/* Try to read %x,%x. */
if (hexToInt(&ptr, &addr)
&& *ptr++ == ','
&& hexToInt(&ptr, &length)) {
mem2hex((char *)addr, remcomOutBuffer, length);
} else {
kgdb_error(KGDBERR_BADPARAMS);
}
break;
case 'M': /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
/* Try to read '%x,%x:'. */
if (hexToInt(&ptr, &addr)
&& *ptr++ == ','
&& hexToInt(&ptr, &length)
&& *ptr++ == ':') {
hex2mem(ptr, (char *)addr, length);
strcpy(remcomOutBuffer, "OK");
} else {
kgdb_error(KGDBERR_BADPARAMS);
}
break;
case 'k': /* kill the program, actually return to monitor */
kd.extype = KGDBEXIT_KILL;
*regs = entry_regs;
first_entry = 1;
goto doexit;
case 'C': /* CSS continue with signal SS */
*ptr = '\0'; /* ignore the signal number for now */
/* fall through */
case 'c': /* cAA..AA Continue; address AA..AA optional */
/* try to read optional parameter, pc unchanged if no parm */
kd.extype = KGDBEXIT_CONTINUE;
if (hexToInt(&ptr, &addr)) {
kd.exaddr = addr;
kd.extype |= KGDBEXIT_WITHADDR;
}
goto doexit;
case 'S': /* SSS single step with signal SS */
*ptr = '\0'; /* ignore the signal number for now */
/* fall through */
case 's':
kd.extype = KGDBEXIT_SINGLE;
if (hexToInt(&ptr, &addr)) {
kd.exaddr = addr;
kd.extype |= KGDBEXIT_WITHADDR;
}
doexit:
/* Need to flush the instruction cache here, as we may have deposited a
* breakpoint, and the icache probably has no way of knowing that a data ref to
* some location may have changed something that is in the instruction cache.
*/
kgdb_flush_cache_all();
kgdb_exit(regs, &kd);
kgdb_active = 0;
kgdb_interruptible(1);
return (1);
case 'r': /* Reset (if user process..exit ???)*/
panic("kgdb reset.");
break;
case 'P': /* Pr=v set reg r to value v (r and v are hex) */
if (hexToInt(&ptr, &addr)
&& *ptr++ == '='
&& ((length = strlen(ptr)) & 1) == 0) {
hex2mem(ptr, remcomRegBuffer, length/2);
kgdb_putreg(regs, addr,
remcomRegBuffer, length/2);
strcpy(remcomOutBuffer,"OK");
} else {
kgdb_error(KGDBERR_BADPARAMS);
}
break;
} /* switch */
if (errnum != 0)
sprintf(remcomOutBuffer, "E%02d", errnum);
#ifdef KGDB_DEBUG
if (kdebug)
printf("kgdb: remcomOutBuffer: %s\n", remcomOutBuffer);
#endif
/* reply to the request */
putpacket((unsigned char *)&remcomOutBuffer);
} /* while(1) */
}
/*
* kgdb_init must be called *after* the
* monitor is relocated into ram
*/
void
kgdb_init(void)
{
kgdb_serial_init();
debugger_exception_handler = handle_exception;
initialized = 1;
putDebugStr("kgdb ready\n");
puts("ready\n");
}
void
kgdb_error(int errnum)
{
longjmp_on_fault = 0;
kgdb_longjmp(error_jmp_buf, errnum);
panic("kgdb_error: longjmp failed!\n");
}
/* Output string in GDB O-packet format if GDB has connected. If nothing
output, returns 0 (caller must then handle output). */
int
kgdb_output_string (const char* s, unsigned int count)
{
char buffer[512];
count = (count <= (sizeof(buffer) / 2 - 2))
? count : (sizeof(buffer) / 2 - 2);
buffer[0] = 'O';
mem2hex ((char *)s, &buffer[1], count);
putpacket((unsigned char *)&buffer);
return 1;
}
void
breakpoint(void)
{
if (!initialized) {
printf("breakpoint() called b4 kgdb init\n");
return;
}
kgdb_breakpoint(0, 0);
}
int
do_kgdb(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
printf("Entering KGDB mode via exception handler...\n\n");
kgdb_breakpoint(argc - 1, argv + 1);
printf("\nReturned from KGDB mode\n");
return 0;
}
U_BOOT_CMD(
kgdb, CONFIG_SYS_MAXARGS, 1, do_kgdb,
"enter gdb remote debug mode",
"[arg0 arg1 .. argN]\n"
" - executes a breakpoint so that kgdb mode is\n"
" entered via the exception handler. To return\n"
" to the monitor, the remote gdb debugger must\n"
" execute a \"continue\" or \"quit\" command.\n"
"\n"
" if a program is loaded by the remote gdb, any args\n"
" passed to the kgdb command are given to the loaded\n"
" program if it is executed (see the \"hello_world\"\n"
" example program in the U-Boot examples directory)."
);
|
1001-study-uboot
|
common/kgdb.c
|
C
|
gpl3
| 14,767
|
/*
* (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
*/
/*
* Misc functions
*/
#include <common.h>
#include <command.h>
int do_sleep (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong start = get_timer(0);
ulong delay;
if (argc != 2)
return cmd_usage(cmdtp);
delay = simple_strtoul(argv[1], NULL, 10) * CONFIG_SYS_HZ;
while (get_timer(start) < delay) {
if (ctrlc ())
return (-1);
udelay (100);
}
return 0;
}
U_BOOT_CMD(
sleep , 2, 1, do_sleep,
"delay execution for some time",
"N\n"
" - delay execution for N seconds (N is _decimal_ !!!)"
);
|
1001-study-uboot
|
common/cmd_misc.c
|
C
|
gpl3
| 1,427
|
/*
* U-boot - spibootldr.c
*
* Copyright (c) 2005-2008 Analog Devices Inc.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* Licensed under the GPL-2 or later.
*/
#include <common.h>
#include <command.h>
#include <asm/blackfin.h>
#include <asm/mach-common/bits/bootrom.h>
int do_spibootldr(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
s32 addr;
/* Get the address */
if (argc < 2)
addr = 0;
else
addr = simple_strtoul(argv[1], NULL, 16);
printf("## Booting ldr image at SPI offset 0x%x ...\n", addr);
return bfrom_SpiBoot(addr, BFLAG_PERIPHERAL | 4, 0, NULL);
}
U_BOOT_CMD(
spibootldr, 2, 0, do_spibootldr,
"boot ldr image from spi",
"[offset]\n"
" - boot ldr image stored at offset into spi\n");
|
1001-study-uboot
|
common/cmd_spibootldr.c
|
C
|
gpl3
| 775
|
/*
*
* Most of this source has been derived from the Linux USB
* project:
* (C) Copyright Linus Torvalds 1999
* (C) Copyright Johannes Erdfelt 1999-2001
* (C) Copyright Andreas Gal 1999
* (C) Copyright Gregory P. Smith 1999
* (C) Copyright Deti Fliegl 1999 (new USB architecture)
* (C) Copyright Randy Dunlap 2000
* (C) Copyright David Brownell 2000 (kernel hotplug, usb_device_id)
* (C) Copyright Yggdrasil Computing, Inc. 2000
* (usb_device_id matching changes by Adam J. Richter)
*
* Adapted for U-Boot:
* (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
*
*/
/*
* How it works:
*
* Since this is a bootloader, the devices will not be automatic
* (re)configured on hotplug, but after a restart of the USB the
* device should work.
*
* For each transfer (except "Interrupt") we wait for completion.
*/
#include <common.h>
#include <command.h>
#include <asm/processor.h>
#include <linux/ctype.h>
#include <asm/byteorder.h>
#include <asm/unaligned.h>
#include <usb.h>
#ifdef CONFIG_4xx
#include <asm/4xx_pci.h>
#endif
#ifdef DEBUG
#define USB_DEBUG 1
#define USB_HUB_DEBUG 1
#else
#define USB_DEBUG 0
#define USB_HUB_DEBUG 0
#endif
#define USB_PRINTF(fmt, args...) debug_cond(USB_DEBUG, fmt, ##args)
#define USB_HUB_PRINTF(fmt, args...) debug_cond(USB_HUB_DEBUG, fmt, ##args)
#define USB_BUFSIZ 512
static struct usb_device usb_dev[USB_MAX_DEVICE];
static int dev_index;
static int running;
static int asynch_allowed;
static struct devrequest setup_packet;
char usb_started; /* flag for the started/stopped USB status */
/**********************************************************************
* some forward declerations...
*/
void usb_scan_devices(void);
int usb_hub_probe(struct usb_device *dev, int ifnum);
void usb_hub_reset(void);
static int hub_port_reset(struct usb_device *dev, int port,
unsigned short *portstat);
/***********************************************************************
* wait_ms
*/
inline void wait_ms(unsigned long ms)
{
while (ms-- > 0)
udelay(1000);
}
/***************************************************************************
* Init USB Device
*/
int usb_init(void)
{
int result;
running = 0;
dev_index = 0;
asynch_allowed = 1;
usb_hub_reset();
/* init low_level USB */
printf("USB: ");
result = usb_lowlevel_init();
/* if lowlevel init is OK, scan the bus for devices
* i.e. search HUBs and configure them */
if (result == 0) {
printf("scanning bus for devices... ");
running = 1;
usb_scan_devices();
usb_started = 1;
return 0;
} else {
printf("Error, couldn't init Lowlevel part\n");
usb_started = 0;
return -1;
}
}
/******************************************************************************
* Stop USB this stops the LowLevel Part and deregisters USB devices.
*/
int usb_stop(void)
{
int res = 0;
if (usb_started) {
asynch_allowed = 1;
usb_started = 0;
usb_hub_reset();
res = usb_lowlevel_stop();
}
return res;
}
/*
* disables the asynch behaviour of the control message. This is used for data
* transfers that uses the exclusiv access to the control and bulk messages.
* Returns the old value so it can be restored later.
*/
int usb_disable_asynch(int disable)
{
int old_value = asynch_allowed;
asynch_allowed = !disable;
return old_value;
}
/*-------------------------------------------------------------------
* Message wrappers.
*
*/
/*
* submits an Interrupt Message
*/
int usb_submit_int_msg(struct usb_device *dev, unsigned long pipe,
void *buffer, int transfer_len, int interval)
{
return submit_int_msg(dev, pipe, buffer, transfer_len, interval);
}
/*
* submits a control message and waits for comletion (at least timeout * 1ms)
* If timeout is 0, we don't wait for completion (used as example to set and
* clear keyboards LEDs). For data transfers, (storage transfers) we don't
* allow control messages with 0 timeout, by previousely resetting the flag
* asynch_allowed (usb_disable_asynch(1)).
* returns the transfered length if OK or -1 if error. The transfered length
* and the current status are stored in the dev->act_len and dev->status.
*/
int usb_control_msg(struct usb_device *dev, unsigned int pipe,
unsigned char request, unsigned char requesttype,
unsigned short value, unsigned short index,
void *data, unsigned short size, int timeout)
{
if ((timeout == 0) && (!asynch_allowed)) {
/* request for a asynch control pipe is not allowed */
return -1;
}
/* set setup command */
setup_packet.requesttype = requesttype;
setup_packet.request = request;
setup_packet.value = cpu_to_le16(value);
setup_packet.index = cpu_to_le16(index);
setup_packet.length = cpu_to_le16(size);
USB_PRINTF("usb_control_msg: request: 0x%X, requesttype: 0x%X, " \
"value 0x%X index 0x%X length 0x%X\n",
request, requesttype, value, index, size);
dev->status = USB_ST_NOT_PROC; /*not yet processed */
submit_control_msg(dev, pipe, data, size, &setup_packet);
if (timeout == 0)
return (int)size;
/*
* Wait for status to update until timeout expires, USB driver
* interrupt handler may set the status when the USB operation has
* been completed.
*/
while (timeout--) {
if (!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
break;
wait_ms(1);
}
if (dev->status)
return -1;
return dev->act_len;
}
/*-------------------------------------------------------------------
* submits bulk message, and waits for completion. returns 0 if Ok or
* -1 if Error.
* synchronous behavior
*/
int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout)
{
if (len < 0)
return -1;
dev->status = USB_ST_NOT_PROC; /*not yet processed */
submit_bulk_msg(dev, pipe, data, len);
while (timeout--) {
if (!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
break;
wait_ms(1);
}
*actual_length = dev->act_len;
if (dev->status == 0)
return 0;
else
return -1;
}
/*-------------------------------------------------------------------
* Max Packet stuff
*/
/*
* returns the max packet size, depending on the pipe direction and
* the configurations values
*/
int usb_maxpacket(struct usb_device *dev, unsigned long pipe)
{
/* direction is out -> use emaxpacket out */
if ((pipe & USB_DIR_IN) == 0)
return dev->epmaxpacketout[((pipe>>15) & 0xf)];
else
return dev->epmaxpacketin[((pipe>>15) & 0xf)];
}
/*
* The routine usb_set_maxpacket_ep() is extracted from the loop of routine
* usb_set_maxpacket(), because the optimizer of GCC 4.x chokes on this routine
* when it is inlined in 1 single routine. What happens is that the register r3
* is used as loop-count 'i', but gets overwritten later on.
* This is clearly a compiler bug, but it is easier to workaround it here than
* to update the compiler (Occurs with at least several GCC 4.{1,2},x
* CodeSourcery compilers like e.g. 2007q3, 2008q1, 2008q3 lite editions on ARM)
*
* NOTE: Similar behaviour was observed with GCC4.6 on ARMv5.
*/
static void __attribute__((noinline))
usb_set_maxpacket_ep(struct usb_device *dev, int if_idx, int ep_idx)
{
int b;
struct usb_endpoint_descriptor *ep;
u16 ep_wMaxPacketSize;
ep = &dev->config.if_desc[if_idx].ep_desc[ep_idx];
b = ep->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
ep_wMaxPacketSize = get_unaligned(&ep->wMaxPacketSize);
if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_CONTROL) {
/* Control => bidirectional */
dev->epmaxpacketout[b] = ep_wMaxPacketSize;
dev->epmaxpacketin[b] = ep_wMaxPacketSize;
USB_PRINTF("##Control EP epmaxpacketout/in[%d] = %d\n",
b, dev->epmaxpacketin[b]);
} else {
if ((ep->bEndpointAddress & 0x80) == 0) {
/* OUT Endpoint */
if (ep_wMaxPacketSize > dev->epmaxpacketout[b]) {
dev->epmaxpacketout[b] = ep_wMaxPacketSize;
USB_PRINTF("##EP epmaxpacketout[%d] = %d\n",
b, dev->epmaxpacketout[b]);
}
} else {
/* IN Endpoint */
if (ep_wMaxPacketSize > dev->epmaxpacketin[b]) {
dev->epmaxpacketin[b] = ep_wMaxPacketSize;
USB_PRINTF("##EP epmaxpacketin[%d] = %d\n",
b, dev->epmaxpacketin[b]);
}
} /* if out */
} /* if control */
}
/*
* set the max packed value of all endpoints in the given configuration
*/
int usb_set_maxpacket(struct usb_device *dev)
{
int i, ii;
for (i = 0; i < dev->config.desc.bNumInterfaces; i++)
for (ii = 0; ii < dev->config.if_desc[i].desc.bNumEndpoints; ii++)
usb_set_maxpacket_ep(dev, i, ii);
return 0;
}
/*******************************************************************************
* Parse the config, located in buffer, and fills the dev->config structure.
* Note that all little/big endian swapping are done automatically.
*/
int usb_parse_config(struct usb_device *dev, unsigned char *buffer, int cfgno)
{
struct usb_descriptor_header *head;
int index, ifno, epno, curr_if_num;
int i;
u16 ep_wMaxPacketSize;
ifno = -1;
epno = -1;
curr_if_num = -1;
dev->configno = cfgno;
head = (struct usb_descriptor_header *) &buffer[0];
if (head->bDescriptorType != USB_DT_CONFIG) {
printf(" ERROR: NOT USB_CONFIG_DESC %x\n",
head->bDescriptorType);
return -1;
}
memcpy(&dev->config, buffer, buffer[0]);
le16_to_cpus(&(dev->config.desc.wTotalLength));
dev->config.no_of_if = 0;
index = dev->config.desc.bLength;
/* Ok the first entry must be a configuration entry,
* now process the others */
head = (struct usb_descriptor_header *) &buffer[index];
while (index + 1 < dev->config.desc.wTotalLength) {
switch (head->bDescriptorType) {
case USB_DT_INTERFACE:
if (((struct usb_interface_descriptor *) \
&buffer[index])->bInterfaceNumber != curr_if_num) {
/* this is a new interface, copy new desc */
ifno = dev->config.no_of_if;
dev->config.no_of_if++;
memcpy(&dev->config.if_desc[ifno],
&buffer[index], buffer[index]);
dev->config.if_desc[ifno].no_of_ep = 0;
dev->config.if_desc[ifno].num_altsetting = 1;
curr_if_num =
dev->config.if_desc[ifno].desc.bInterfaceNumber;
} else {
/* found alternate setting for the interface */
dev->config.if_desc[ifno].num_altsetting++;
}
break;
case USB_DT_ENDPOINT:
epno = dev->config.if_desc[ifno].no_of_ep;
/* found an endpoint */
dev->config.if_desc[ifno].no_of_ep++;
memcpy(&dev->config.if_desc[ifno].ep_desc[epno],
&buffer[index], buffer[index]);
ep_wMaxPacketSize = get_unaligned(&dev->config.\
if_desc[ifno].\
ep_desc[epno].\
wMaxPacketSize);
put_unaligned(le16_to_cpu(ep_wMaxPacketSize),
&dev->config.\
if_desc[ifno].\
ep_desc[epno].\
wMaxPacketSize);
USB_PRINTF("if %d, ep %d\n", ifno, epno);
break;
default:
if (head->bLength == 0)
return 1;
USB_PRINTF("unknown Description Type : %x\n",
head->bDescriptorType);
{
#ifdef USB_DEBUG
unsigned char *ch = (unsigned char *)head;
#endif
for (i = 0; i < head->bLength; i++)
USB_PRINTF("%02X ", *ch++);
USB_PRINTF("\n\n\n");
}
break;
}
index += head->bLength;
head = (struct usb_descriptor_header *)&buffer[index];
}
return 1;
}
/***********************************************************************
* Clears an endpoint
* endp: endpoint number in bits 0-3;
* direction flag in bit 7 (1 = IN, 0 = OUT)
*/
int usb_clear_halt(struct usb_device *dev, int pipe)
{
int result;
int endp = usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0,
endp, NULL, 0, USB_CNTL_TIMEOUT * 3);
/* don't clear if failed */
if (result < 0)
return result;
/*
* NOTE: we do not get status and verify reset was successful
* as some devices are reported to lock up upon this check..
*/
usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
/* toggle is reset on clear */
usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
return 0;
}
/**********************************************************************
* get_descriptor type
*/
int usb_get_descriptor(struct usb_device *dev, unsigned char type,
unsigned char index, void *buf, int size)
{
int res;
res = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(type << 8) + index, 0,
buf, size, USB_CNTL_TIMEOUT);
return res;
}
/**********************************************************************
* gets configuration cfgno and store it in the buffer
*/
int usb_get_configuration_no(struct usb_device *dev,
unsigned char *buffer, int cfgno)
{
int result;
unsigned int tmp;
struct usb_configuration_descriptor *config;
config = (struct usb_configuration_descriptor *)&buffer[0];
result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 9);
if (result < 9) {
if (result < 0)
printf("unable to get descriptor, error %lX\n",
dev->status);
else
printf("config descriptor too short " \
"(expected %i, got %i)\n", 9, result);
return -1;
}
tmp = le16_to_cpu(config->wTotalLength);
if (tmp > USB_BUFSIZ) {
USB_PRINTF("usb_get_configuration_no: failed to get " \
"descriptor - too long: %d\n", tmp);
return -1;
}
result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, tmp);
USB_PRINTF("get_conf_no %d Result %d, wLength %d\n",
cfgno, result, tmp);
return result;
}
/********************************************************************
* set address of a device to the value in dev->devnum.
* This can only be done by addressing the device via the default address (0)
*/
int usb_set_address(struct usb_device *dev)
{
int res;
USB_PRINTF("set address %d\n", dev->devnum);
res = usb_control_msg(dev, usb_snddefctrl(dev),
USB_REQ_SET_ADDRESS, 0,
(dev->devnum), 0,
NULL, 0, USB_CNTL_TIMEOUT);
return res;
}
/********************************************************************
* set interface number to interface
*/
int usb_set_interface(struct usb_device *dev, int interface, int alternate)
{
struct usb_interface *if_face = NULL;
int ret, i;
for (i = 0; i < dev->config.desc.bNumInterfaces; i++) {
if (dev->config.if_desc[i].desc.bInterfaceNumber == interface) {
if_face = &dev->config.if_desc[i];
break;
}
}
if (!if_face) {
printf("selecting invalid interface %d", interface);
return -1;
}
/*
* We should return now for devices with only one alternate setting.
* According to 9.4.10 of the Universal Serial Bus Specification
* Revision 2.0 such devices can return with a STALL. This results in
* some USB sticks timeouting during initialization and then being
* unusable in U-Boot.
*/
if (if_face->num_altsetting == 1)
return 0;
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
alternate, interface, NULL, 0,
USB_CNTL_TIMEOUT * 5);
if (ret < 0)
return ret;
return 0;
}
/********************************************************************
* set configuration number to configuration
*/
int usb_set_configuration(struct usb_device *dev, int configuration)
{
int res;
USB_PRINTF("set configuration %d\n", configuration);
/* set setup command */
res = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_CONFIGURATION, 0,
configuration, 0,
NULL, 0, USB_CNTL_TIMEOUT);
if (res == 0) {
dev->toggle[0] = 0;
dev->toggle[1] = 0;
return 0;
} else
return -1;
}
/********************************************************************
* set protocol to protocol
*/
int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
{
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
protocol, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
}
/********************************************************************
* set idle
*/
int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
{
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
(duration << 8) | report_id, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
}
/********************************************************************
* get report
*/
int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type,
unsigned char id, void *buf, int size)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_REPORT,
USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
(type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
}
/********************************************************************
* get class descriptor
*/
int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
unsigned char type, unsigned char id, void *buf, int size)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
(type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
}
/********************************************************************
* get string index in buffer
*/
int usb_get_string(struct usb_device *dev, unsigned short langid,
unsigned char index, void *buf, int size)
{
int i;
int result;
for (i = 0; i < 3; ++i) {
/* some devices are flaky */
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(USB_DT_STRING << 8) + index, langid, buf, size,
USB_CNTL_TIMEOUT);
if (result > 0)
break;
}
return result;
}
static void usb_try_string_workarounds(unsigned char *buf, int *length)
{
int newlength, oldlength = *length;
for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
if (!isprint(buf[newlength]) || buf[newlength + 1])
break;
if (newlength > 2) {
buf[0] = newlength;
*length = newlength;
}
}
static int usb_string_sub(struct usb_device *dev, unsigned int langid,
unsigned int index, unsigned char *buf)
{
int rc;
/* Try to read the string descriptor by asking for the maximum
* possible number of bytes */
rc = usb_get_string(dev, langid, index, buf, 255);
/* If that failed try to read the descriptor length, then
* ask for just that many bytes */
if (rc < 2) {
rc = usb_get_string(dev, langid, index, buf, 2);
if (rc == 2)
rc = usb_get_string(dev, langid, index, buf, buf[0]);
}
if (rc >= 2) {
if (!buf[0] && !buf[1])
usb_try_string_workarounds(buf, &rc);
/* There might be extra junk at the end of the descriptor */
if (buf[0] < rc)
rc = buf[0];
rc = rc - (rc & 1); /* force a multiple of two */
}
if (rc < 2)
rc = -1;
return rc;
}
/********************************************************************
* usb_string:
* Get string index and translate it to ascii.
* returns string length (> 0) or error (< 0)
*/
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
{
unsigned char mybuf[USB_BUFSIZ];
unsigned char *tbuf;
int err;
unsigned int u, idx;
if (size <= 0 || !buf || !index)
return -1;
buf[0] = 0;
tbuf = &mybuf[0];
/* get langid for strings if it's not yet known */
if (!dev->have_langid) {
err = usb_string_sub(dev, 0, 0, tbuf);
if (err < 0) {
USB_PRINTF("error getting string descriptor 0 " \
"(error=%lx)\n", dev->status);
return -1;
} else if (tbuf[0] < 4) {
USB_PRINTF("string descriptor 0 too short\n");
return -1;
} else {
dev->have_langid = -1;
dev->string_langid = tbuf[2] | (tbuf[3] << 8);
/* always use the first langid listed */
USB_PRINTF("USB device number %d default " \
"language ID 0x%x\n",
dev->devnum, dev->string_langid);
}
}
err = usb_string_sub(dev, dev->string_langid, index, tbuf);
if (err < 0)
return err;
size--; /* leave room for trailing NULL char in output buffer */
for (idx = 0, u = 2; u < err; u += 2) {
if (idx >= size)
break;
if (tbuf[u+1]) /* high byte */
buf[idx++] = '?'; /* non-ASCII character */
else
buf[idx++] = tbuf[u];
}
buf[idx] = 0;
err = idx;
return err;
}
/********************************************************************
* USB device handling:
* the USB device are static allocated [USB_MAX_DEVICE].
*/
/* returns a pointer to the device with the index [index].
* if the device is not assigned (dev->devnum==-1) returns NULL
*/
struct usb_device *usb_get_dev_index(int index)
{
if (usb_dev[index].devnum == -1)
return NULL;
else
return &usb_dev[index];
}
/* returns a pointer of a new device structure or NULL, if
* no device struct is available
*/
struct usb_device *usb_alloc_new_device(void)
{
int i;
USB_PRINTF("New Device %d\n", dev_index);
if (dev_index == USB_MAX_DEVICE) {
printf("ERROR, too many USB Devices, max=%d\n", USB_MAX_DEVICE);
return NULL;
}
/* default Address is 0, real addresses start with 1 */
usb_dev[dev_index].devnum = dev_index + 1;
usb_dev[dev_index].maxchild = 0;
for (i = 0; i < USB_MAXCHILDREN; i++)
usb_dev[dev_index].children[i] = NULL;
usb_dev[dev_index].parent = NULL;
dev_index++;
return &usb_dev[dev_index - 1];
}
/*
* By the time we get here, the device has gotten a new device ID
* and is in the default state. We need to identify the thing and
* get the ball rolling..
*
* Returns 0 for success, != 0 for error.
*/
int usb_new_device(struct usb_device *dev)
{
int addr, err;
int tmp;
unsigned char tmpbuf[USB_BUFSIZ];
/* We still haven't set the Address yet */
addr = dev->devnum;
dev->devnum = 0;
#ifdef CONFIG_LEGACY_USB_INIT_SEQ
/* this is the old and known way of initializing devices, it is
* different than what Windows and Linux are doing. Windows and Linux
* both retrieve 64 bytes while reading the device descriptor
* Several USB stick devices report ERR: CTL_TIMEOUT, caused by an
* invalid header while reading 8 bytes as device descriptor. */
dev->descriptor.bMaxPacketSize0 = 8; /* Start off at 8 bytes */
dev->maxpacketsize = PACKET_SIZE_8;
dev->epmaxpacketin[0] = 8;
dev->epmaxpacketout[0] = 8;
err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, 8);
if (err < 8) {
printf("\n USB device not responding, " \
"giving up (status=%lX)\n", dev->status);
return 1;
}
#else
/* This is a Windows scheme of initialization sequence, with double
* reset of the device (Linux uses the same sequence)
* Some equipment is said to work only with such init sequence; this
* patch is based on the work by Alan Stern:
* http://sourceforge.net/mailarchive/forum.php?
* thread_id=5729457&forum_id=5398
*/
struct usb_device_descriptor *desc;
int port = -1;
struct usb_device *parent = dev->parent;
unsigned short portstatus;
/* send 64-byte GET-DEVICE-DESCRIPTOR request. Since the descriptor is
* only 18 bytes long, this will terminate with a short packet. But if
* the maxpacket size is 8 or 16 the device may be waiting to transmit
* some more, or keeps on retransmitting the 8 byte header. */
desc = (struct usb_device_descriptor *)tmpbuf;
dev->descriptor.bMaxPacketSize0 = 64; /* Start off at 64 bytes */
/* Default to 64 byte max packet size */
dev->maxpacketsize = PACKET_SIZE_64;
dev->epmaxpacketin[0] = 64;
dev->epmaxpacketout[0] = 64;
err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, 64);
if (err < 0) {
USB_PRINTF("usb_new_device: usb_get_descriptor() failed\n");
return 1;
}
dev->descriptor.bMaxPacketSize0 = desc->bMaxPacketSize0;
/* find the port number we're at */
if (parent) {
int j;
for (j = 0; j < parent->maxchild; j++) {
if (parent->children[j] == dev) {
port = j;
break;
}
}
if (port < 0) {
printf("usb_new_device:cannot locate device's port.\n");
return 1;
}
/* reset the port for the second time */
err = hub_port_reset(dev->parent, port, &portstatus);
if (err < 0) {
printf("\n Couldn't reset port %i\n", port);
return 1;
}
}
#endif
dev->epmaxpacketin[0] = dev->descriptor.bMaxPacketSize0;
dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
switch (dev->descriptor.bMaxPacketSize0) {
case 8:
dev->maxpacketsize = PACKET_SIZE_8;
break;
case 16:
dev->maxpacketsize = PACKET_SIZE_16;
break;
case 32:
dev->maxpacketsize = PACKET_SIZE_32;
break;
case 64:
dev->maxpacketsize = PACKET_SIZE_64;
break;
}
dev->devnum = addr;
err = usb_set_address(dev); /* set address */
if (err < 0) {
printf("\n USB device not accepting new address " \
"(error=%lX)\n", dev->status);
return 1;
}
wait_ms(10); /* Let the SET_ADDRESS settle */
tmp = sizeof(dev->descriptor);
err = usb_get_descriptor(dev, USB_DT_DEVICE, 0,
&dev->descriptor, sizeof(dev->descriptor));
if (err < tmp) {
if (err < 0)
printf("unable to get device descriptor (error=%d)\n",
err);
else
printf("USB device descriptor short read " \
"(expected %i, got %i)\n", tmp, err);
return 1;
}
/* correct le values */
le16_to_cpus(&dev->descriptor.bcdUSB);
le16_to_cpus(&dev->descriptor.idVendor);
le16_to_cpus(&dev->descriptor.idProduct);
le16_to_cpus(&dev->descriptor.bcdDevice);
/* only support for one config for now */
usb_get_configuration_no(dev, &tmpbuf[0], 0);
usb_parse_config(dev, &tmpbuf[0], 0);
usb_set_maxpacket(dev);
/* we set the default configuration here */
if (usb_set_configuration(dev, dev->config.desc.bConfigurationValue)) {
printf("failed to set default configuration " \
"len %d, status %lX\n", dev->act_len, dev->status);
return -1;
}
USB_PRINTF("new device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
dev->descriptor.iManufacturer, dev->descriptor.iProduct,
dev->descriptor.iSerialNumber);
memset(dev->mf, 0, sizeof(dev->mf));
memset(dev->prod, 0, sizeof(dev->prod));
memset(dev->serial, 0, sizeof(dev->serial));
if (dev->descriptor.iManufacturer)
usb_string(dev, dev->descriptor.iManufacturer,
dev->mf, sizeof(dev->mf));
if (dev->descriptor.iProduct)
usb_string(dev, dev->descriptor.iProduct,
dev->prod, sizeof(dev->prod));
if (dev->descriptor.iSerialNumber)
usb_string(dev, dev->descriptor.iSerialNumber,
dev->serial, sizeof(dev->serial));
USB_PRINTF("Manufacturer %s\n", dev->mf);
USB_PRINTF("Product %s\n", dev->prod);
USB_PRINTF("SerialNumber %s\n", dev->serial);
/* now prode if the device is a hub */
usb_hub_probe(dev, 0);
return 0;
}
/* build device Tree */
void usb_scan_devices(void)
{
int i;
struct usb_device *dev;
/* first make all devices unknown */
for (i = 0; i < USB_MAX_DEVICE; i++) {
memset(&usb_dev[i], 0, sizeof(struct usb_device));
usb_dev[i].devnum = -1;
}
dev_index = 0;
/* device 0 is always present (root hub, so let it analyze) */
dev = usb_alloc_new_device();
if (usb_new_device(dev))
printf("No USB Device found\n");
else
printf("%d USB Device(s) found\n", dev_index);
/* insert "driver" if possible */
#ifdef CONFIG_USB_KEYBOARD
drv_usb_kbd_init();
#endif
USB_PRINTF("scan end\n");
}
/****************************************************************************
* HUB "Driver"
* Probes device for being a hub and configurate it
*/
static struct usb_hub_device hub_dev[USB_MAX_HUB];
static int usb_hub_index;
int usb_get_hub_descriptor(struct usb_device *dev, void *data, int size)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
USB_DT_HUB << 8, 0, data, size, USB_CNTL_TIMEOUT);
}
int usb_clear_hub_feature(struct usb_device *dev, int feature)
{
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature,
0, NULL, 0, USB_CNTL_TIMEOUT);
}
int usb_clear_port_feature(struct usb_device *dev, int port, int feature)
{
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature,
port, NULL, 0, USB_CNTL_TIMEOUT);
}
int usb_set_port_feature(struct usb_device *dev, int port, int feature)
{
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_FEATURE, USB_RT_PORT, feature,
port, NULL, 0, USB_CNTL_TIMEOUT);
}
int usb_get_hub_status(struct usb_device *dev, void *data)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
data, sizeof(struct usb_hub_status), USB_CNTL_TIMEOUT);
}
int usb_get_port_status(struct usb_device *dev, int port, void *data)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port,
data, sizeof(struct usb_hub_status), USB_CNTL_TIMEOUT);
}
static void usb_hub_power_on(struct usb_hub_device *hub)
{
int i;
struct usb_device *dev;
dev = hub->pusb_dev;
/* Enable power to the ports */
USB_HUB_PRINTF("enabling power on all ports\n");
for (i = 0; i < dev->maxchild; i++) {
usb_set_port_feature(dev, i + 1, USB_PORT_FEAT_POWER);
USB_HUB_PRINTF("port %d returns %lX\n", i + 1, dev->status);
wait_ms(hub->desc.bPwrOn2PwrGood * 2);
}
}
void usb_hub_reset(void)
{
usb_hub_index = 0;
}
struct usb_hub_device *usb_hub_allocate(void)
{
if (usb_hub_index < USB_MAX_HUB)
return &hub_dev[usb_hub_index++];
printf("ERROR: USB_MAX_HUB (%d) reached\n", USB_MAX_HUB);
return NULL;
}
#define MAX_TRIES 5
static inline char *portspeed(int portstatus)
{
if (portstatus & (1 << USB_PORT_FEAT_HIGHSPEED))
return "480 Mb/s";
else if (portstatus & (1 << USB_PORT_FEAT_LOWSPEED))
return "1.5 Mb/s";
else
return "12 Mb/s";
}
static int hub_port_reset(struct usb_device *dev, int port,
unsigned short *portstat)
{
int tries;
struct usb_port_status portsts;
unsigned short portstatus, portchange;
USB_HUB_PRINTF("hub_port_reset: resetting port %d...\n", port);
for (tries = 0; tries < MAX_TRIES; tries++) {
usb_set_port_feature(dev, port + 1, USB_PORT_FEAT_RESET);
wait_ms(200);
if (usb_get_port_status(dev, port + 1, &portsts) < 0) {
USB_HUB_PRINTF("get_port_status failed status %lX\n",
dev->status);
return -1;
}
portstatus = le16_to_cpu(portsts.wPortStatus);
portchange = le16_to_cpu(portsts.wPortChange);
USB_HUB_PRINTF("portstatus %x, change %x, %s\n",
portstatus, portchange,
portspeed(portstatus));
USB_HUB_PRINTF("STAT_C_CONNECTION = %d STAT_CONNECTION = %d" \
" USB_PORT_STAT_ENABLE %d\n",
(portchange & USB_PORT_STAT_C_CONNECTION) ? 1 : 0,
(portstatus & USB_PORT_STAT_CONNECTION) ? 1 : 0,
(portstatus & USB_PORT_STAT_ENABLE) ? 1 : 0);
if ((portchange & USB_PORT_STAT_C_CONNECTION) ||
!(portstatus & USB_PORT_STAT_CONNECTION))
return -1;
if (portstatus & USB_PORT_STAT_ENABLE)
break;
wait_ms(200);
}
if (tries == MAX_TRIES) {
USB_HUB_PRINTF("Cannot enable port %i after %i retries, " \
"disabling port.\n", port + 1, MAX_TRIES);
USB_HUB_PRINTF("Maybe the USB cable is bad?\n");
return -1;
}
usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_RESET);
*portstat = portstatus;
return 0;
}
void usb_hub_port_connect_change(struct usb_device *dev, int port)
{
struct usb_device *usb;
struct usb_port_status portsts;
unsigned short portstatus;
/* Check status */
if (usb_get_port_status(dev, port + 1, &portsts) < 0) {
USB_HUB_PRINTF("get_port_status failed\n");
return;
}
portstatus = le16_to_cpu(portsts.wPortStatus);
USB_HUB_PRINTF("portstatus %x, change %x, %s\n",
portstatus,
le16_to_cpu(portsts.wPortChange),
portspeed(portstatus));
/* Clear the connection change status */
usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_CONNECTION);
/* Disconnect any existing devices under this port */
if (((!(portstatus & USB_PORT_STAT_CONNECTION)) &&
(!(portstatus & USB_PORT_STAT_ENABLE))) || (dev->children[port])) {
USB_HUB_PRINTF("usb_disconnect(&hub->children[port]);\n");
/* Return now if nothing is connected */
if (!(portstatus & USB_PORT_STAT_CONNECTION))
return;
}
wait_ms(200);
/* Reset the port */
if (hub_port_reset(dev, port, &portstatus) < 0) {
printf("cannot reset port %i!?\n", port + 1);
return;
}
wait_ms(200);
/* Allocate a new device struct for it */
usb = usb_alloc_new_device();
if (portstatus & USB_PORT_STAT_HIGH_SPEED)
usb->speed = USB_SPEED_HIGH;
else if (portstatus & USB_PORT_STAT_LOW_SPEED)
usb->speed = USB_SPEED_LOW;
else
usb->speed = USB_SPEED_FULL;
dev->children[port] = usb;
usb->parent = dev;
usb->portnr = port + 1;
/* Run it through the hoops (find a driver, etc) */
if (usb_new_device(usb)) {
/* Woops, disable the port */
USB_HUB_PRINTF("hub: disabling port %d\n", port + 1);
usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_ENABLE);
}
}
int usb_hub_configure(struct usb_device *dev)
{
int i;
unsigned char buffer[USB_BUFSIZ], *bitmap;
struct usb_hub_descriptor *descriptor;
struct usb_hub_device *hub;
#ifdef USB_HUB_DEBUG
struct usb_hub_status *hubsts;
#endif
/* "allocate" Hub device */
hub = usb_hub_allocate();
if (hub == NULL)
return -1;
hub->pusb_dev = dev;
/* Get the the hub descriptor */
if (usb_get_hub_descriptor(dev, buffer, 4) < 0) {
USB_HUB_PRINTF("usb_hub_configure: failed to get hub " \
"descriptor, giving up %lX\n", dev->status);
return -1;
}
descriptor = (struct usb_hub_descriptor *)buffer;
/* silence compiler warning if USB_BUFSIZ is > 256 [= sizeof(char)] */
i = descriptor->bLength;
if (i > USB_BUFSIZ) {
USB_HUB_PRINTF("usb_hub_configure: failed to get hub " \
"descriptor - too long: %d\n",
descriptor->bLength);
return -1;
}
if (usb_get_hub_descriptor(dev, buffer, descriptor->bLength) < 0) {
USB_HUB_PRINTF("usb_hub_configure: failed to get hub " \
"descriptor 2nd giving up %lX\n", dev->status);
return -1;
}
memcpy((unsigned char *)&hub->desc, buffer, descriptor->bLength);
/* adjust 16bit values */
hub->desc.wHubCharacteristics =
le16_to_cpu(descriptor->wHubCharacteristics);
/* set the bitmap */
bitmap = (unsigned char *)&hub->desc.DeviceRemovable[0];
/* devices not removable by default */
memset(bitmap, 0xff, (USB_MAXCHILDREN+1+7)/8);
bitmap = (unsigned char *)&hub->desc.PortPowerCtrlMask[0];
memset(bitmap, 0xff, (USB_MAXCHILDREN+1+7)/8); /* PowerMask = 1B */
for (i = 0; i < ((hub->desc.bNbrPorts + 1 + 7)/8); i++)
hub->desc.DeviceRemovable[i] = descriptor->DeviceRemovable[i];
for (i = 0; i < ((hub->desc.bNbrPorts + 1 + 7)/8); i++)
hub->desc.PortPowerCtrlMask[i] = descriptor->PortPowerCtrlMask[i];
dev->maxchild = descriptor->bNbrPorts;
USB_HUB_PRINTF("%d ports detected\n", dev->maxchild);
switch (hub->desc.wHubCharacteristics & HUB_CHAR_LPSM) {
case 0x00:
USB_HUB_PRINTF("ganged power switching\n");
break;
case 0x01:
USB_HUB_PRINTF("individual port power switching\n");
break;
case 0x02:
case 0x03:
USB_HUB_PRINTF("unknown reserved power switching mode\n");
break;
}
if (hub->desc.wHubCharacteristics & HUB_CHAR_COMPOUND)
USB_HUB_PRINTF("part of a compound device\n");
else
USB_HUB_PRINTF("standalone hub\n");
switch (hub->desc.wHubCharacteristics & HUB_CHAR_OCPM) {
case 0x00:
USB_HUB_PRINTF("global over-current protection\n");
break;
case 0x08:
USB_HUB_PRINTF("individual port over-current protection\n");
break;
case 0x10:
case 0x18:
USB_HUB_PRINTF("no over-current protection\n");
break;
}
USB_HUB_PRINTF("power on to power good time: %dms\n",
descriptor->bPwrOn2PwrGood * 2);
USB_HUB_PRINTF("hub controller current requirement: %dmA\n",
descriptor->bHubContrCurrent);
for (i = 0; i < dev->maxchild; i++)
USB_HUB_PRINTF("port %d is%s removable\n", i + 1,
hub->desc.DeviceRemovable[(i + 1) / 8] & \
(1 << ((i + 1) % 8)) ? " not" : "");
if (sizeof(struct usb_hub_status) > USB_BUFSIZ) {
USB_HUB_PRINTF("usb_hub_configure: failed to get Status - " \
"too long: %d\n", descriptor->bLength);
return -1;
}
if (usb_get_hub_status(dev, buffer) < 0) {
USB_HUB_PRINTF("usb_hub_configure: failed to get Status %lX\n",
dev->status);
return -1;
}
#ifdef USB_HUB_DEBUG
hubsts = (struct usb_hub_status *)buffer;
#endif
USB_HUB_PRINTF("get_hub_status returned status %X, change %X\n",
le16_to_cpu(hubsts->wHubStatus),
le16_to_cpu(hubsts->wHubChange));
USB_HUB_PRINTF("local power source is %s\n",
(le16_to_cpu(hubsts->wHubStatus) & HUB_STATUS_LOCAL_POWER) ? \
"lost (inactive)" : "good");
USB_HUB_PRINTF("%sover-current condition exists\n",
(le16_to_cpu(hubsts->wHubStatus) & HUB_STATUS_OVERCURRENT) ? \
"" : "no ");
usb_hub_power_on(hub);
for (i = 0; i < dev->maxchild; i++) {
struct usb_port_status portsts;
unsigned short portstatus, portchange;
if (usb_get_port_status(dev, i + 1, &portsts) < 0) {
USB_HUB_PRINTF("get_port_status failed\n");
continue;
}
portstatus = le16_to_cpu(portsts.wPortStatus);
portchange = le16_to_cpu(portsts.wPortChange);
USB_HUB_PRINTF("Port %d Status %X Change %X\n",
i + 1, portstatus, portchange);
if (portchange & USB_PORT_STAT_C_CONNECTION) {
USB_HUB_PRINTF("port %d connection change\n", i + 1);
usb_hub_port_connect_change(dev, i);
}
if (portchange & USB_PORT_STAT_C_ENABLE) {
USB_HUB_PRINTF("port %d enable change, status %x\n",
i + 1, portstatus);
usb_clear_port_feature(dev, i + 1,
USB_PORT_FEAT_C_ENABLE);
/* EM interference sometimes causes bad shielded USB
* devices to be shutdown by the hub, this hack enables
* them again. Works at least with mouse driver */
if (!(portstatus & USB_PORT_STAT_ENABLE) &&
(portstatus & USB_PORT_STAT_CONNECTION) &&
((dev->children[i]))) {
USB_HUB_PRINTF("already running port %i " \
"disabled by hub (EMI?), " \
"re-enabling...\n", i + 1);
usb_hub_port_connect_change(dev, i);
}
}
if (portstatus & USB_PORT_STAT_SUSPEND) {
USB_HUB_PRINTF("port %d suspend change\n", i + 1);
usb_clear_port_feature(dev, i + 1,
USB_PORT_FEAT_SUSPEND);
}
if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
USB_HUB_PRINTF("port %d over-current change\n", i + 1);
usb_clear_port_feature(dev, i + 1,
USB_PORT_FEAT_C_OVER_CURRENT);
usb_hub_power_on(hub);
}
if (portchange & USB_PORT_STAT_C_RESET) {
USB_HUB_PRINTF("port %d reset change\n", i + 1);
usb_clear_port_feature(dev, i + 1,
USB_PORT_FEAT_C_RESET);
}
} /* end for i all ports */
return 0;
}
int usb_hub_probe(struct usb_device *dev, int ifnum)
{
struct usb_interface *iface;
struct usb_endpoint_descriptor *ep;
int ret;
iface = &dev->config.if_desc[ifnum];
/* Is it a hub? */
if (iface->desc.bInterfaceClass != USB_CLASS_HUB)
return 0;
/* Some hubs have a subclass of 1, which AFAICT according to the */
/* specs is not defined, but it works */
if ((iface->desc.bInterfaceSubClass != 0) &&
(iface->desc.bInterfaceSubClass != 1))
return 0;
/* Multiple endpoints? What kind of mutant ninja-hub is this? */
if (iface->desc.bNumEndpoints != 1)
return 0;
ep = &iface->ep_desc[0];
/* Output endpoint? Curiousier and curiousier.. */
if (!(ep->bEndpointAddress & USB_DIR_IN))
return 0;
/* If it's not an interrupt endpoint, we'd better punt! */
if ((ep->bmAttributes & 3) != 3)
return 0;
/* We found a hub */
USB_HUB_PRINTF("USB hub found\n");
ret = usb_hub_configure(dev);
return ret;
}
/* EOF */
|
1001-study-uboot
|
common/usb.c
|
C
|
gpl3
| 39,874
|
/*
* (C) Copyright 2010
* Jason Kridner <jkridner@beagleboard.org>
*
* Based on cmd_led.c patch from:
* http://www.mail-archive.com/u-boot@lists.denx.de/msg06873.html
* (C) Copyright 2008
* Ulf Samuelsson <ulf.samuelsson@atmel.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 <status_led.h>
struct led_tbl_s {
char *string; /* String for use in the command */
led_id_t mask; /* Mask used for calling __led_set() */
void (*off)(void); /* Optional function for turning LED off */
void (*on)(void); /* Optional function for turning LED on */
void (*toggle)(void);/* Optional function for toggling LED */
};
typedef struct led_tbl_s led_tbl_t;
static const led_tbl_t led_commands[] = {
#ifdef CONFIG_BOARD_SPECIFIC_LED
#ifdef STATUS_LED_BIT
{ "0", STATUS_LED_BIT, NULL, NULL, NULL },
#endif
#ifdef STATUS_LED_BIT1
{ "1", STATUS_LED_BIT1, NULL, NULL, NULL },
#endif
#ifdef STATUS_LED_BIT2
{ "2", STATUS_LED_BIT2, NULL, NULL, NULL },
#endif
#ifdef STATUS_LED_BIT3
{ "3", STATUS_LED_BIT3, NULL, NULL, NULL },
#endif
#endif
#ifdef STATUS_LED_GREEN
{ "green", STATUS_LED_GREEN, green_led_off, green_led_on, NULL },
#endif
#ifdef STATUS_LED_YELLOW
{ "yellow", STATUS_LED_YELLOW, yellow_led_off, yellow_led_on, NULL },
#endif
#ifdef STATUS_LED_RED
{ "red", STATUS_LED_RED, red_led_off, red_led_on, NULL },
#endif
#ifdef STATUS_LED_BLUE
{ "blue", STATUS_LED_BLUE, blue_led_off, blue_led_on, NULL },
#endif
{ NULL, 0, NULL, NULL, NULL }
};
enum led_cmd { LED_ON, LED_OFF, LED_TOGGLE };
enum led_cmd get_led_cmd(char *var)
{
if (strcmp(var, "off") == 0) {
return LED_OFF;
}
if (strcmp(var, "on") == 0) {
return LED_ON;
}
if (strcmp(var, "toggle") == 0)
return LED_TOGGLE;
return -1;
}
int do_led (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i, match = 0;
enum led_cmd cmd;
/* Validate arguments */
if ((argc != 3)) {
return cmd_usage(cmdtp);
}
cmd = get_led_cmd(argv[2]);
if (cmd < 0) {
return cmd_usage(cmdtp);
}
for (i = 0; led_commands[i].string; i++) {
if ((strcmp("all", argv[1]) == 0) ||
(strcmp(led_commands[i].string, argv[1]) == 0)) {
match = 1;
switch (cmd) {
case LED_ON:
if (led_commands[i].on)
led_commands[i].on();
else
__led_set(led_commands[i].mask, 1);
break;
case LED_OFF:
if (led_commands[i].off)
led_commands[i].off();
else
__led_set(led_commands[i].mask, 0);
break;
case LED_TOGGLE:
if (led_commands[i].toggle)
led_commands[i].toggle();
else
__led_toggle(led_commands[i].mask);
}
/* Need to set only 1 led if led_name wasn't 'all' */
if (strcmp("all", argv[1]) != 0)
break;
}
}
/* If we ran out of matches, print Usage */
if (!match) {
return cmd_usage(cmdtp);
}
return 0;
}
U_BOOT_CMD(
led, 3, 1, do_led,
"led\t- ["
#ifdef CONFIG_BOARD_SPECIFIC_LED
#ifdef STATUS_LED_BIT
"0|"
#endif
#ifdef STATUS_LED_BIT1
"1|"
#endif
#ifdef STATUS_LED_BIT2
"2|"
#endif
#ifdef STATUS_LED_BIT3
"3|"
#endif
#endif
#ifdef STATUS_LED_GREEN
"green|"
#endif
#ifdef STATUS_LED_YELLOW
"yellow|"
#endif
#ifdef STATUS_LED_RED
"red|"
#endif
#ifdef STATUS_LED_BLUE
"blue|"
#endif
"all] [on|off|toggle]\n",
"led [led_name] [on|off|toggle] sets or clears led(s)\n"
);
|
1001-study-uboot
|
common/cmd_led.c
|
C
|
gpl3
| 4,074
|
/*
* sh.c -- a prototype Bourne shell grammar parser
* Intended to follow the original Thompson and Ritchie
* "small and simple is beautiful" philosophy, which
* incidentally is a good match to today's BusyBox.
*
* Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
*
* Credits:
* The parser routines proper are all original material, first
* written Dec 2000 and Jan 2001 by Larry Doolittle.
* The execution engine, the builtins, and much of the underlying
* support has been adapted from busybox-0.49pre's lash,
* which is Copyright (C) 2000 by Lineo, Inc., and
* written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>.
* That, in turn, is based in part on ladsh.c, by Michael K. Johnson and
* Erik W. Troan, which they placed in the public domain. I don't know
* how much of the Johnson/Troan code has survived the repeated rewrites.
* Other credits:
* b_addchr() derived from similar w_addchar function in glibc-2.2
* setup_redirect(), redirect_opt_num(), and big chunks of main()
* and many builtins derived from contributions by Erik Andersen
* miscellaneous bugfixes from Matt Kraai
*
* There are two big (and related) architecture differences between
* this parser and the lash parser. One is that this version is
* actually designed from the ground up to understand nearly all
* of the Bourne grammar. The second, consequential change is that
* the parser and input reader have been turned inside out. Now,
* the parser is in control, and asks for input as needed. The old
* way had the input reader in control, and it asked for parsing to
* take place as needed. The new way makes it much easier to properly
* handle the recursion implicit in the various substitutions, especially
* across continuation lines.
*
* Bash grammar not implemented: (how many of these were in original sh?)
* $@ (those sure look like weird quoting rules)
* $_
* ! negation operator for pipes
* &> and >& redirection of stdout+stderr
* Brace Expansion
* Tilde Expansion
* fancy forms of Parameter Expansion
* aliases
* Arithmetic Expansion
* <(list) and >(list) Process Substitution
* reserved words: case, esac, select, function
* Here Documents ( << word )
* Functions
* Major bugs:
* job handling woefully incomplete and buggy
* reserved word execution woefully incomplete and buggy
* to-do:
* port selected bugfixes from post-0.49 busybox lash - done?
* finish implementing reserved words: for, while, until, do, done
* change { and } from special chars to reserved words
* builtins: break, continue, eval, return, set, trap, ulimit
* test magic exec
* handle children going into background
* clean up recognition of null pipes
* check setting of global_argc and global_argv
* control-C handling, probably with longjmp
* follow IFS rules more precisely, including update semantics
* figure out what to do with backslash-newline
* explain why we use signal instead of sigaction
* propagate syntax errors, die on resource errors?
* continuation lines, both explicit and implicit - done?
* memory leak finding and plugging - done?
* more testing, especially quoting rules and redirection
* document how quoting rules not precisely followed for variable assignments
* maybe change map[] to use 2-bit entries
* (eventually) remove all the printf's
*
* 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 __U_BOOT__
#ifdef __U_BOOT__
#include <malloc.h> /* malloc, free, realloc*/
#include <linux/ctype.h> /* isalpha, isdigit */
#include <common.h> /* readline */
#include <hush.h>
#include <command.h> /* find_cmd */
#endif
#ifndef __U_BOOT__
#include <ctype.h> /* isalpha, isdigit */
#include <unistd.h> /* getpid */
#include <stdlib.h> /* getenv, atoi */
#include <string.h> /* strchr */
#include <stdio.h> /* popen etc. */
#include <glob.h> /* glob, of course */
#include <stdarg.h> /* va_list */
#include <errno.h>
#include <fcntl.h>
#include <getopt.h> /* should be pretty obvious */
#include <sys/stat.h> /* ulimit */
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
/* #include <dmalloc.h> */
#if 1
#include "busybox.h"
#include "cmdedit.h"
#else
#define applet_name "hush"
#include "standalone.h"
#define hush_main main
#undef CONFIG_FEATURE_SH_FANCY_PROMPT
#define BB_BANNER
#endif
#endif
#define SPECIAL_VAR_SYMBOL 03
#ifndef __U_BOOT__
#define FLAG_EXIT_FROM_LOOP 1
#define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
#define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
#endif
#ifdef __U_BOOT__
DECLARE_GLOBAL_DATA_PTR;
#define EXIT_SUCCESS 0
#define EOF -1
#define syntax() syntax_err()
#define xstrdup strdup
#define error_msg printf
#else
typedef enum {
REDIRECT_INPUT = 1,
REDIRECT_OVERWRITE = 2,
REDIRECT_APPEND = 3,
REDIRECT_HEREIS = 4,
REDIRECT_IO = 5
} redir_type;
/* The descrip member of this structure is only used to make debugging
* output pretty */
struct {int mode; int default_fd; char *descrip;} redir_table[] = {
{ 0, 0, "()" },
{ O_RDONLY, 0, "<" },
{ O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
{ O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
{ O_RDONLY, -1, "<<" },
{ O_RDWR, 1, "<>" }
};
#endif
typedef enum {
PIPE_SEQ = 1,
PIPE_AND = 2,
PIPE_OR = 3,
PIPE_BG = 4,
} pipe_style;
/* might eventually control execution */
typedef enum {
RES_NONE = 0,
RES_IF = 1,
RES_THEN = 2,
RES_ELIF = 3,
RES_ELSE = 4,
RES_FI = 5,
RES_FOR = 6,
RES_WHILE = 7,
RES_UNTIL = 8,
RES_DO = 9,
RES_DONE = 10,
RES_XXXX = 11,
RES_IN = 12,
RES_SNTX = 13
} reserved_style;
#define FLAG_END (1<<RES_NONE)
#define FLAG_IF (1<<RES_IF)
#define FLAG_THEN (1<<RES_THEN)
#define FLAG_ELIF (1<<RES_ELIF)
#define FLAG_ELSE (1<<RES_ELSE)
#define FLAG_FI (1<<RES_FI)
#define FLAG_FOR (1<<RES_FOR)
#define FLAG_WHILE (1<<RES_WHILE)
#define FLAG_UNTIL (1<<RES_UNTIL)
#define FLAG_DO (1<<RES_DO)
#define FLAG_DONE (1<<RES_DONE)
#define FLAG_IN (1<<RES_IN)
#define FLAG_START (1<<RES_XXXX)
/* This holds pointers to the various results of parsing */
struct p_context {
struct child_prog *child;
struct pipe *list_head;
struct pipe *pipe;
#ifndef __U_BOOT__
struct redir_struct *pending_redirect;
#endif
reserved_style w;
int old_flag; /* for figuring out valid reserved words */
struct p_context *stack;
int type; /* define type of parser : ";$" common or special symbol */
/* How about quoting status? */
};
#ifndef __U_BOOT__
struct redir_struct {
redir_type type; /* type of redirection */
int fd; /* file descriptor being redirected */
int dup; /* -1, or file descriptor being duplicated */
struct redir_struct *next; /* pointer to the next redirect in the list */
glob_t word; /* *word.gl_pathv is the filename */
};
#endif
struct child_prog {
#ifndef __U_BOOT__
pid_t pid; /* 0 if exited */
#endif
char **argv; /* program name and arguments */
#ifdef __U_BOOT__
int argc; /* number of program arguments */
#endif
struct pipe *group; /* if non-NULL, first in group or subshell */
#ifndef __U_BOOT__
int subshell; /* flag, non-zero if group must be forked */
struct redir_struct *redirects; /* I/O redirections */
glob_t glob_result; /* result of parameter globbing */
int is_stopped; /* is the program currently running? */
struct pipe *family; /* pointer back to the child's parent pipe */
#endif
int sp; /* number of SPECIAL_VAR_SYMBOL */
int type;
};
struct pipe {
#ifndef __U_BOOT__
int jobid; /* job number */
#endif
int num_progs; /* total number of programs in job */
#ifndef __U_BOOT__
int running_progs; /* number of programs running */
char *text; /* name of job */
char *cmdbuf; /* buffer various argv's point into */
pid_t pgrp; /* process group ID for the job */
#endif
struct child_prog *progs; /* array of commands in pipe */
struct pipe *next; /* to track background commands */
#ifndef __U_BOOT__
int stopped_progs; /* number of programs alive, but stopped */
int job_context; /* bitmask defining current context */
#endif
pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
reserved_style r_mode; /* supports if, for, while, until */
};
#ifndef __U_BOOT__
struct close_me {
int fd;
struct close_me *next;
};
#endif
struct variables {
char *name;
char *value;
int flg_export;
int flg_read_only;
struct variables *next;
};
/* globals, connect us to the outside world
* the first three support $?, $#, and $1 */
#ifndef __U_BOOT__
char **global_argv;
unsigned int global_argc;
#endif
unsigned int last_return_code;
int nesting_level;
#ifndef __U_BOOT__
extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
#endif
/* "globals" within this file */
static uchar *ifs;
static char map[256];
#ifndef __U_BOOT__
static int fake_mode;
static int interactive;
static struct close_me *close_me_head;
static const char *cwd;
static struct pipe *job_list;
static unsigned int last_bg_pid;
static unsigned int last_jobid;
static unsigned int shell_terminal;
static char *PS1;
static char *PS2;
struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 };
struct variables *top_vars = &shell_ver;
#else
static int flag_repeat = 0;
static int do_repeat = 0;
static struct variables *top_vars = NULL ;
#endif /*__U_BOOT__ */
#define B_CHUNK (100)
#define B_NOSPAC 1
typedef struct {
char *data;
int length;
int maxlen;
int quote;
int nonnull;
} o_string;
#define NULL_O_STRING {NULL,0,0,0,0}
/* used for initialization:
o_string foo = NULL_O_STRING; */
/* I can almost use ordinary FILE *. Is open_memstream() universally
* available? Where is it documented? */
struct in_str {
const char *p;
#ifndef __U_BOOT__
char peek_buf[2];
#endif
int __promptme;
int promptmode;
#ifndef __U_BOOT__
FILE *file;
#endif
int (*get) (struct in_str *);
int (*peek) (struct in_str *);
};
#define b_getch(input) ((input)->get(input))
#define b_peek(input) ((input)->peek(input))
#ifndef __U_BOOT__
#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
struct built_in_command {
char *cmd; /* name */
char *descr; /* description */
int (*function) (struct child_prog *); /* function ptr */
};
#endif
/* define DEBUG_SHELL for debugging output (obviously ;-)) */
#if 0
#define DEBUG_SHELL
#endif
/* This should be in utility.c */
#ifdef DEBUG_SHELL
#ifndef __U_BOOT__
static void debug_printf(const char *format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
}
#else
#define debug_printf(fmt,args...) printf (fmt ,##args)
#endif
#else
static inline void debug_printf(const char *format, ...) { }
#endif
#define final_printf debug_printf
#ifdef __U_BOOT__
static void syntax_err(void) {
printf("syntax error\n");
}
#else
static void __syntax(char *file, int line) {
error_msg("syntax error %s:%d", file, line);
}
#define syntax() __syntax(__FILE__, __LINE__)
#endif
#ifdef __U_BOOT__
static void *xmalloc(size_t size);
static void *xrealloc(void *ptr, size_t size);
#else
/* Index of subroutines: */
/* function prototypes for builtins */
static int builtin_cd(struct child_prog *child);
static int builtin_env(struct child_prog *child);
static int builtin_eval(struct child_prog *child);
static int builtin_exec(struct child_prog *child);
static int builtin_exit(struct child_prog *child);
static int builtin_export(struct child_prog *child);
static int builtin_fg_bg(struct child_prog *child);
static int builtin_help(struct child_prog *child);
static int builtin_jobs(struct child_prog *child);
static int builtin_pwd(struct child_prog *child);
static int builtin_read(struct child_prog *child);
static int builtin_set(struct child_prog *child);
static int builtin_shift(struct child_prog *child);
static int builtin_source(struct child_prog *child);
static int builtin_umask(struct child_prog *child);
static int builtin_unset(struct child_prog *child);
static int builtin_not_written(struct child_prog *child);
#endif
/* o_string manipulation: */
static int b_check_space(o_string *o, int len);
static int b_addchr(o_string *o, int ch);
static void b_reset(o_string *o);
static int b_addqchr(o_string *o, int ch, int quote);
#ifndef __U_BOOT__
static int b_adduint(o_string *o, unsigned int i);
#endif
/* in_str manipulations: */
static int static_get(struct in_str *i);
static int static_peek(struct in_str *i);
static int file_get(struct in_str *i);
static int file_peek(struct in_str *i);
#ifndef __U_BOOT__
static void setup_file_in_str(struct in_str *i, FILE *f);
#else
static void setup_file_in_str(struct in_str *i);
#endif
static void setup_string_in_str(struct in_str *i, const char *s);
#ifndef __U_BOOT__
/* close_me manipulations: */
static void mark_open(int fd);
static void mark_closed(int fd);
static void close_all(void);
#endif
/* "run" the final data structures: */
static char *indenter(int i);
static int free_pipe_list(struct pipe *head, int indent);
static int free_pipe(struct pipe *pi, int indent);
/* really run the final data structures: */
#ifndef __U_BOOT__
static int setup_redirects(struct child_prog *prog, int squirrel[]);
#endif
static int run_list_real(struct pipe *pi);
#ifndef __U_BOOT__
static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn));
#endif
static int run_pipe_real(struct pipe *pi);
/* extended glob support: */
#ifndef __U_BOOT__
static int globhack(const char *src, int flags, glob_t *pglob);
static int glob_needed(const char *s);
static int xglob(o_string *dest, int flags, glob_t *pglob);
#endif
/* variable assignment: */
static int is_assignment(const char *s);
/* data structure manipulation: */
#ifndef __U_BOOT__
static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
#endif
static void initialize_context(struct p_context *ctx);
static int done_word(o_string *dest, struct p_context *ctx);
static int done_command(struct p_context *ctx);
static int done_pipe(struct p_context *ctx, pipe_style type);
/* primary string parsing: */
#ifndef __U_BOOT__
static int redirect_dup_num(struct in_str *input);
static int redirect_opt_num(o_string *o);
static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
#endif
static char *lookup_param(char *src);
static char *make_string(char **inp);
static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
#ifndef __U_BOOT__
static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
#endif
static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
/* setup: */
static int parse_stream_outer(struct in_str *inp, int flag);
#ifndef __U_BOOT__
static int parse_string_outer(const char *s, int flag);
static int parse_file_outer(FILE *f);
#endif
#ifndef __U_BOOT__
/* job management: */
static int checkjobs(struct pipe* fg_pipe);
static void insert_bg_job(struct pipe *pi);
static void remove_bg_job(struct pipe *pi);
#endif
/* local variable support */
static char **make_list_in(char **inp, char *name);
static char *insert_var_value(char *inp);
#ifndef __U_BOOT__
/* Table of built-in functions. They can be forked or not, depending on
* context: within pipes, they fork. As simple commands, they do not.
* When used in non-forking context, they can change global variables
* in the parent shell process. If forked, of course they can not.
* For example, 'unset foo | whatever' will parse and run, but foo will
* still be set at the end. */
static struct built_in_command bltins[] = {
{"bg", "Resume a job in the background", builtin_fg_bg},
{"break", "Exit for, while or until loop", builtin_not_written},
{"cd", "Change working directory", builtin_cd},
{"continue", "Continue for, while or until loop", builtin_not_written},
{"env", "Print all environment variables", builtin_env},
{"eval", "Construct and run shell command", builtin_eval},
{"exec", "Exec command, replacing this shell with the exec'd process",
builtin_exec},
{"exit", "Exit from shell()", builtin_exit},
{"export", "Set environment variable", builtin_export},
{"fg", "Bring job into the foreground", builtin_fg_bg},
{"jobs", "Lists the active jobs", builtin_jobs},
{"pwd", "Print current directory", builtin_pwd},
{"read", "Input environment variable", builtin_read},
{"return", "Return from a function", builtin_not_written},
{"set", "Set/unset shell local variables", builtin_set},
{"shift", "Shift positional parameters", builtin_shift},
{"trap", "Trap signals", builtin_not_written},
{"ulimit","Controls resource limits", builtin_not_written},
{"umask","Sets file creation mask", builtin_umask},
{"unset", "Unset environment variable", builtin_unset},
{".", "Source-in and run commands in a file", builtin_source},
{"help", "List shell built-in commands", builtin_help},
{NULL, NULL, NULL}
};
static const char *set_cwd(void)
{
if(cwd==unknown)
cwd = NULL; /* xgetcwd(arg) called free(arg) */
cwd = xgetcwd((char *)cwd);
if (!cwd)
cwd = unknown;
return cwd;
}
/* built-in 'eval' handler */
static int builtin_eval(struct child_prog *child)
{
char *str = NULL;
int rcode = EXIT_SUCCESS;
if (child->argv[1]) {
str = make_string(child->argv + 1);
parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
FLAG_PARSE_SEMICOLON);
free(str);
rcode = last_return_code;
}
return rcode;
}
/* built-in 'cd <path>' handler */
static int builtin_cd(struct child_prog *child)
{
char *newdir;
if (child->argv[1] == NULL)
newdir = getenv("HOME");
else
newdir = child->argv[1];
if (chdir(newdir)) {
printf("cd: %s: %s\n", newdir, strerror(errno));
return EXIT_FAILURE;
}
set_cwd();
return EXIT_SUCCESS;
}
/* built-in 'env' handler */
static int builtin_env(struct child_prog *dummy)
{
char **e = environ;
if (e == NULL) return EXIT_FAILURE;
for (; *e; e++) {
puts(*e);
}
return EXIT_SUCCESS;
}
/* built-in 'exec' handler */
static int builtin_exec(struct child_prog *child)
{
if (child->argv[1] == NULL)
return EXIT_SUCCESS; /* Really? */
child->argv++;
pseudo_exec(child);
/* never returns */
}
/* built-in 'exit' handler */
static int builtin_exit(struct child_prog *child)
{
if (child->argv[1] == NULL)
exit(last_return_code);
exit (atoi(child->argv[1]));
}
/* built-in 'export VAR=value' handler */
static int builtin_export(struct child_prog *child)
{
int res = 0;
char *name = child->argv[1];
if (name == NULL) {
return (builtin_env(child));
}
name = strdup(name);
if(name) {
char *value = strchr(name, '=');
if (!value) {
char *tmp;
/* They are exporting something without an =VALUE */
value = get_local_var(name);
if (value) {
size_t ln = strlen(name);
tmp = realloc(name, ln+strlen(value)+2);
if(tmp==NULL)
res = -1;
else {
sprintf(tmp+ln, "=%s", value);
name = tmp;
}
} else {
/* bash does not return an error when trying to export
* an undefined variable. Do likewise. */
res = 1;
}
}
}
if (res<0)
perror_msg("export");
else if(res==0)
res = set_local_var(name, 1);
else
res = 0;
free(name);
return res;
}
/* built-in 'fg' and 'bg' handler */
static int builtin_fg_bg(struct child_prog *child)
{
int i, jobnum;
struct pipe *pi=NULL;
if (!interactive)
return EXIT_FAILURE;
/* If they gave us no args, assume they want the last backgrounded task */
if (!child->argv[1]) {
for (pi = job_list; pi; pi = pi->next) {
if (pi->jobid == last_jobid) {
break;
}
}
if (!pi) {
error_msg("%s: no current job", child->argv[0]);
return EXIT_FAILURE;
}
} else {
if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
return EXIT_FAILURE;
}
for (pi = job_list; pi; pi = pi->next) {
if (pi->jobid == jobnum) {
break;
}
}
if (!pi) {
error_msg("%s: %d: no such job", child->argv[0], jobnum);
return EXIT_FAILURE;
}
}
if (*child->argv[0] == 'f') {
/* Put the job into the foreground. */
tcsetpgrp(shell_terminal, pi->pgrp);
}
/* Restart the processes in the job */
for (i = 0; i < pi->num_progs; i++)
pi->progs[i].is_stopped = 0;
if ( (i=kill(- pi->pgrp, SIGCONT)) < 0) {
if (i == ESRCH) {
remove_bg_job(pi);
} else {
perror_msg("kill (SIGCONT)");
}
}
pi->stopped_progs = 0;
return EXIT_SUCCESS;
}
/* built-in 'help' handler */
static int builtin_help(struct child_prog *dummy)
{
struct built_in_command *x;
printf("\nBuilt-in commands:\n");
printf("-------------------\n");
for (x = bltins; x->cmd; x++) {
if (x->descr==NULL)
continue;
printf("%s\t%s\n", x->cmd, x->descr);
}
printf("\n\n");
return EXIT_SUCCESS;
}
/* built-in 'jobs' handler */
static int builtin_jobs(struct child_prog *child)
{
struct pipe *job;
char *status_string;
for (job = job_list; job; job = job->next) {
if (job->running_progs == job->stopped_progs)
status_string = "Stopped";
else
status_string = "Running";
printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
}
return EXIT_SUCCESS;
}
/* built-in 'pwd' handler */
static int builtin_pwd(struct child_prog *dummy)
{
puts(set_cwd());
return EXIT_SUCCESS;
}
/* built-in 'read VAR' handler */
static int builtin_read(struct child_prog *child)
{
int res;
if (child->argv[1]) {
char string[BUFSIZ];
char *var = 0;
string[0] = 0; /* In case stdin has only EOF */
/* read string */
fgets(string, sizeof(string), stdin);
chomp(string);
var = malloc(strlen(child->argv[1])+strlen(string)+2);
if(var) {
sprintf(var, "%s=%s", child->argv[1], string);
res = set_local_var(var, 0);
} else
res = -1;
if (res)
fprintf(stderr, "read: %m\n");
free(var); /* So not move up to avoid breaking errno */
return res;
} else {
do res=getchar(); while(res!='\n' && res!=EOF);
return 0;
}
}
/* built-in 'set VAR=value' handler */
static int builtin_set(struct child_prog *child)
{
char *temp = child->argv[1];
struct variables *e;
if (temp == NULL)
for(e = top_vars; e; e=e->next)
printf("%s=%s\n", e->name, e->value);
else
set_local_var(temp, 0);
return EXIT_SUCCESS;
}
/* Built-in 'shift' handler */
static int builtin_shift(struct child_prog *child)
{
int n=1;
if (child->argv[1]) {
n=atoi(child->argv[1]);
}
if (n>=0 && n<global_argc) {
/* XXX This probably breaks $0 */
global_argc -= n;
global_argv += n;
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
}
/* Built-in '.' handler (read-in and execute commands from file) */
static int builtin_source(struct child_prog *child)
{
FILE *input;
int status;
if (child->argv[1] == NULL)
return EXIT_FAILURE;
/* XXX search through $PATH is missing */
input = fopen(child->argv[1], "r");
if (!input) {
error_msg("Couldn't open file '%s'", child->argv[1]);
return EXIT_FAILURE;
}
/* Now run the file */
/* XXX argv and argc are broken; need to save old global_argv
* (pointer only is OK!) on this stack frame,
* set global_argv=child->argv+1, recurse, and restore. */
mark_open(fileno(input));
status = parse_file_outer(input);
mark_closed(fileno(input));
fclose(input);
return (status);
}
static int builtin_umask(struct child_prog *child)
{
mode_t new_umask;
const char *arg = child->argv[1];
char *end;
if (arg) {
new_umask=strtoul(arg, &end, 8);
if (*end!='\0' || end == arg) {
return EXIT_FAILURE;
}
} else {
printf("%.3o\n", (unsigned int) (new_umask=umask(0)));
}
umask(new_umask);
return EXIT_SUCCESS;
}
/* built-in 'unset VAR' handler */
static int builtin_unset(struct child_prog *child)
{
/* bash returned already true */
unset_local_var(child->argv[1]);
return EXIT_SUCCESS;
}
static int builtin_not_written(struct child_prog *child)
{
printf("builtin_%s not written\n",child->argv[0]);
return EXIT_FAILURE;
}
#endif
static int b_check_space(o_string *o, int len)
{
/* It would be easy to drop a more restrictive policy
* in here, such as setting a maximum string length */
if (o->length + len > o->maxlen) {
char *old_data = o->data;
/* assert (data == NULL || o->maxlen != 0); */
o->maxlen += max(2*len, B_CHUNK);
o->data = realloc(o->data, 1 + o->maxlen);
if (o->data == NULL) {
free(old_data);
}
}
return o->data == NULL;
}
static int b_addchr(o_string *o, int ch)
{
debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
if (b_check_space(o, 1)) return B_NOSPAC;
o->data[o->length] = ch;
o->length++;
o->data[o->length] = '\0';
return 0;
}
static void b_reset(o_string *o)
{
o->length = 0;
o->nonnull = 0;
if (o->data != NULL) *o->data = '\0';
}
static void b_free(o_string *o)
{
b_reset(o);
free(o->data);
o->data = NULL;
o->maxlen = 0;
}
/* My analysis of quoting semantics tells me that state information
* is associated with a destination, not a source.
*/
static int b_addqchr(o_string *o, int ch, int quote)
{
if (quote && strchr("*?[\\",ch)) {
int rc;
rc = b_addchr(o, '\\');
if (rc) return rc;
}
return b_addchr(o, ch);
}
#ifndef __U_BOOT__
static int b_adduint(o_string *o, unsigned int i)
{
int r;
char *p = simple_itoa(i);
/* no escape checking necessary */
do r=b_addchr(o, *p++); while (r==0 && *p);
return r;
}
#endif
static int static_get(struct in_str *i)
{
int ch = *i->p++;
if (ch=='\0') return EOF;
return ch;
}
static int static_peek(struct in_str *i)
{
return *i->p;
}
#ifndef __U_BOOT__
static inline void cmdedit_set_initial_prompt(void)
{
#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
PS1 = NULL;
#else
PS1 = getenv("PS1");
if(PS1==0)
PS1 = "\\w \\$ ";
#endif
}
static inline void setup_prompt_string(int promptmode, char **prompt_str)
{
debug_printf("setup_prompt_string %d ",promptmode);
#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
/* Set up the prompt */
if (promptmode == 1) {
free(PS1);
PS1=xmalloc(strlen(cwd)+4);
sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# ");
*prompt_str = PS1;
} else {
*prompt_str = PS2;
}
#else
*prompt_str = (promptmode==1)? PS1 : PS2;
#endif
debug_printf("result %s\n",*prompt_str);
}
#endif
static void get_user_input(struct in_str *i)
{
#ifndef __U_BOOT__
char *prompt_str;
static char the_command[BUFSIZ];
setup_prompt_string(i->promptmode, &prompt_str);
#ifdef CONFIG_FEATURE_COMMAND_EDITING
/*
** enable command line editing only while a command line
** is actually being read; otherwise, we'll end up bequeathing
** atexit() handlers and other unwanted stuff to our
** child processes (rob@sysgo.de)
*/
cmdedit_read_input(prompt_str, the_command);
#else
fputs(prompt_str, stdout);
fflush(stdout);
the_command[0]=fgetc(i->file);
the_command[1]='\0';
#endif
fflush(stdout);
i->p = the_command;
#else
int n;
static char the_command[CONFIG_SYS_CBSIZE];
#ifdef CONFIG_BOOT_RETRY_TIME
# ifndef CONFIG_RESET_TO_RETRY
# error "This currently only works with CONFIG_RESET_TO_RETRY enabled"
# endif
reset_cmd_timeout();
#endif
i->__promptme = 1;
if (i->promptmode == 1) {
n = readline(CONFIG_SYS_PROMPT);
} else {
n = readline(CONFIG_SYS_PROMPT_HUSH_PS2);
}
#ifdef CONFIG_BOOT_RETRY_TIME
if (n == -2) {
puts("\nTimeout waiting for command\n");
# ifdef CONFIG_RESET_TO_RETRY
do_reset(NULL, 0, 0, NULL);
# else
# error "This currently only works with CONFIG_RESET_TO_RETRY enabled"
# endif
}
#endif
if (n == -1 ) {
flag_repeat = 0;
i->__promptme = 0;
}
n = strlen(console_buffer);
console_buffer[n] = '\n';
console_buffer[n+1]= '\0';
if (had_ctrlc()) flag_repeat = 0;
clear_ctrlc();
do_repeat = 0;
if (i->promptmode == 1) {
if (console_buffer[0] == '\n'&& flag_repeat == 0) {
strcpy(the_command,console_buffer);
}
else {
if (console_buffer[0] != '\n') {
strcpy(the_command,console_buffer);
flag_repeat = 1;
}
else {
do_repeat = 1;
}
}
i->p = the_command;
}
else {
if (console_buffer[0] != '\n') {
if (strlen(the_command) + strlen(console_buffer)
< CONFIG_SYS_CBSIZE) {
n = strlen(the_command);
the_command[n-1] = ' ';
strcpy(&the_command[n],console_buffer);
}
else {
the_command[0] = '\n';
the_command[1] = '\0';
flag_repeat = 0;
}
}
if (i->__promptme == 0) {
the_command[0] = '\n';
the_command[1] = '\0';
}
i->p = console_buffer;
}
#endif
}
/* This is the magic location that prints prompts
* and gets data back from the user */
static int file_get(struct in_str *i)
{
int ch;
ch = 0;
/* If there is data waiting, eat it up */
if (i->p && *i->p) {
ch = *i->p++;
} else {
/* need to double check i->file because we might be doing something
* more complicated by now, like sourcing or substituting. */
#ifndef __U_BOOT__
if (i->__promptme && interactive && i->file == stdin) {
while(! i->p || (interactive && strlen(i->p)==0) ) {
#else
while(! i->p || strlen(i->p)==0 ) {
#endif
get_user_input(i);
}
i->promptmode=2;
#ifndef __U_BOOT__
i->__promptme = 0;
#endif
if (i->p && *i->p) {
ch = *i->p++;
}
#ifndef __U_BOOT__
} else {
ch = fgetc(i->file);
}
#endif
debug_printf("b_getch: got a %d\n", ch);
}
#ifndef __U_BOOT__
if (ch == '\n') i->__promptme=1;
#endif
return ch;
}
/* All the callers guarantee this routine will never be
* used right after a newline, so prompting is not needed.
*/
static int file_peek(struct in_str *i)
{
#ifndef __U_BOOT__
if (i->p && *i->p) {
#endif
return *i->p;
#ifndef __U_BOOT__
} else {
i->peek_buf[0] = fgetc(i->file);
i->peek_buf[1] = '\0';
i->p = i->peek_buf;
debug_printf("b_peek: got a %d\n", *i->p);
return *i->p;
}
#endif
}
#ifndef __U_BOOT__
static void setup_file_in_str(struct in_str *i, FILE *f)
#else
static void setup_file_in_str(struct in_str *i)
#endif
{
i->peek = file_peek;
i->get = file_get;
i->__promptme=1;
i->promptmode=1;
#ifndef __U_BOOT__
i->file = f;
#endif
i->p = NULL;
}
static void setup_string_in_str(struct in_str *i, const char *s)
{
i->peek = static_peek;
i->get = static_get;
i->__promptme=1;
i->promptmode=1;
i->p = s;
}
#ifndef __U_BOOT__
static void mark_open(int fd)
{
struct close_me *new = xmalloc(sizeof(struct close_me));
new->fd = fd;
new->next = close_me_head;
close_me_head = new;
}
static void mark_closed(int fd)
{
struct close_me *tmp;
if (close_me_head == NULL || close_me_head->fd != fd)
error_msg_and_die("corrupt close_me");
tmp = close_me_head;
close_me_head = close_me_head->next;
free(tmp);
}
static void close_all(void)
{
struct close_me *c;
for (c=close_me_head; c; c=c->next) {
close(c->fd);
}
close_me_head = NULL;
}
/* squirrel != NULL means we squirrel away copies of stdin, stdout,
* and stderr if they are redirected. */
static int setup_redirects(struct child_prog *prog, int squirrel[])
{
int openfd, mode;
struct redir_struct *redir;
for (redir=prog->redirects; redir; redir=redir->next) {
if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
/* something went wrong in the parse. Pretend it didn't happen */
continue;
}
if (redir->dup == -1) {
mode=redir_table[redir->type].mode;
openfd = open(redir->word.gl_pathv[0], mode, 0666);
if (openfd < 0) {
/* this could get lost if stderr has been redirected, but
bash and ash both lose it as well (though zsh doesn't!) */
perror_msg("error opening %s", redir->word.gl_pathv[0]);
return 1;
}
} else {
openfd = redir->dup;
}
if (openfd != redir->fd) {
if (squirrel && redir->fd < 3) {
squirrel[redir->fd] = dup(redir->fd);
}
if (openfd == -3) {
close(openfd);
} else {
dup2(openfd, redir->fd);
if (redir->dup == -1)
close (openfd);
}
}
}
return 0;
}
static void restore_redirects(int squirrel[])
{
int i, fd;
for (i=0; i<3; i++) {
fd = squirrel[i];
if (fd != -1) {
/* No error checking. I sure wouldn't know what
* to do with an error if I found one! */
dup2(fd, i);
close(fd);
}
}
}
/* never returns */
/* XXX no exit() here. If you don't exec, use _exit instead.
* The at_exit handlers apparently confuse the calling process,
* in particular stdin handling. Not sure why? */
static void pseudo_exec(struct child_prog *child)
{
int i, rcode;
char *p;
struct built_in_command *x;
if (child->argv) {
for (i=0; is_assignment(child->argv[i]); i++) {
debug_printf("pid %d environment modification: %s\n",getpid(),child->argv[i]);
p = insert_var_value(child->argv[i]);
putenv(strdup(p));
if (p != child->argv[i]) free(p);
}
child->argv+=i; /* XXX this hack isn't so horrible, since we are about
to exit, and therefore don't need to keep data
structures consistent for free() use. */
/* If a variable is assigned in a forest, and nobody listens,
* was it ever really set?
*/
if (child->argv[0] == NULL) {
_exit(EXIT_SUCCESS);
}
/*
* Check if the command matches any of the builtins.
* Depending on context, this might be redundant. But it's
* easier to waste a few CPU cycles than it is to figure out
* if this is one of those cases.
*/
for (x = bltins; x->cmd; x++) {
if (strcmp(child->argv[0], x->cmd) == 0 ) {
debug_printf("builtin exec %s\n", child->argv[0]);
rcode = x->function(child);
fflush(stdout);
_exit(rcode);
}
}
/* Check if the command matches any busybox internal commands
* ("applets") here.
* FIXME: This feature is not 100% safe, since
* BusyBox is not fully reentrant, so we have no guarantee the things
* from the .bss are still zeroed, or that things from .data are still
* at their defaults. We could exec ourself from /proc/self/exe, but I
* really dislike relying on /proc for things. We could exec ourself
* from global_argv[0], but if we are in a chroot, we may not be able
* to find ourself... */
#ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
{
int argc_l;
char** argv_l=child->argv;
char *name = child->argv[0];
#ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
/* Following discussions from November 2000 on the busybox mailing
* list, the default configuration, (without
* get_last_path_component()) lets the user force use of an
* external command by specifying the full (with slashes) filename.
* If you enable CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN then applets
* _aways_ override external commands, so if you want to run
* /bin/cat, it will use BusyBox cat even if /bin/cat exists on the
* filesystem and is _not_ busybox. Some systems may want this,
* most do not. */
name = get_last_path_component(name);
#endif
/* Count argc for use in a second... */
for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++);
optind = 1;
debug_printf("running applet %s\n", name);
run_applet_by_name(name, argc_l, child->argv);
}
#endif
debug_printf("exec of %s\n",child->argv[0]);
execvp(child->argv[0],child->argv);
perror_msg("couldn't exec: %s",child->argv[0]);
_exit(1);
} else if (child->group) {
debug_printf("runtime nesting to group\n");
interactive=0; /* crucial!!!! */
rcode = run_list_real(child->group);
/* OK to leak memory by not calling free_pipe_list,
* since this process is about to exit */
_exit(rcode);
} else {
/* Can happen. See what bash does with ">foo" by itself. */
debug_printf("trying to pseudo_exec null command\n");
_exit(EXIT_SUCCESS);
}
}
static void insert_bg_job(struct pipe *pi)
{
struct pipe *thejob;
/* Linear search for the ID of the job to use */
pi->jobid = 1;
for (thejob = job_list; thejob; thejob = thejob->next)
if (thejob->jobid >= pi->jobid)
pi->jobid = thejob->jobid + 1;
/* add thejob to the list of running jobs */
if (!job_list) {
thejob = job_list = xmalloc(sizeof(*thejob));
} else {
for (thejob = job_list; thejob->next; thejob = thejob->next) /* nothing */;
thejob->next = xmalloc(sizeof(*thejob));
thejob = thejob->next;
}
/* physically copy the struct job */
memcpy(thejob, pi, sizeof(struct pipe));
thejob->next = NULL;
thejob->running_progs = thejob->num_progs;
thejob->stopped_progs = 0;
thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
/*if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0]) */
{
char *bar=thejob->text;
char **foo=pi->progs[0].argv;
while(foo && *foo) {
bar += sprintf(bar, "%s ", *foo++);
}
}
/* we don't wait for background thejobs to return -- append it
to the list of backgrounded thejobs and leave it alone */
printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
last_bg_pid = thejob->progs[0].pid;
last_jobid = thejob->jobid;
}
/* remove a backgrounded job */
static void remove_bg_job(struct pipe *pi)
{
struct pipe *prev_pipe;
if (pi == job_list) {
job_list = pi->next;
} else {
prev_pipe = job_list;
while (prev_pipe->next != pi)
prev_pipe = prev_pipe->next;
prev_pipe->next = pi->next;
}
if (job_list)
last_jobid = job_list->jobid;
else
last_jobid = 0;
pi->stopped_progs = 0;
free_pipe(pi, 0);
free(pi);
}
/* Checks to see if any processes have exited -- if they
have, figure out why and see if a job has completed */
static int checkjobs(struct pipe* fg_pipe)
{
int attributes;
int status;
int prognum = 0;
struct pipe *pi;
pid_t childpid;
attributes = WUNTRACED;
if (fg_pipe==NULL) {
attributes |= WNOHANG;
}
while ((childpid = waitpid(-1, &status, attributes)) > 0) {
if (fg_pipe) {
int i, rcode = 0;
for (i=0; i < fg_pipe->num_progs; i++) {
if (fg_pipe->progs[i].pid == childpid) {
if (i==fg_pipe->num_progs-1)
rcode=WEXITSTATUS(status);
(fg_pipe->num_progs)--;
return(rcode);
}
}
}
for (pi = job_list; pi; pi = pi->next) {
prognum = 0;
while (prognum < pi->num_progs && pi->progs[prognum].pid != childpid) {
prognum++;
}
if (prognum < pi->num_progs)
break;
}
if(pi==NULL) {
debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
continue;
}
if (WIFEXITED(status) || WIFSIGNALED(status)) {
/* child exited */
pi->running_progs--;
pi->progs[prognum].pid = 0;
if (!pi->running_progs) {
printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text);
remove_bg_job(pi);
}
} else {
/* child stopped */
pi->stopped_progs++;
pi->progs[prognum].is_stopped = 1;
#if 0
/* Printing this stuff is a pain, since it tends to
* overwrite the prompt an inconveinient moments. So
* don't do that. */
if (pi->stopped_progs == pi->num_progs) {
printf("\n"JOB_STATUS_FORMAT, pi->jobid, "Stopped", pi->text);
}
#endif
}
}
if (childpid == -1 && errno != ECHILD)
perror_msg("waitpid");
/* move the shell to the foreground */
/*if (interactive && tcsetpgrp(shell_terminal, getpgid(0))) */
/* perror_msg("tcsetpgrp-2"); */
return -1;
}
/* Figure out our controlling tty, checking in order stderr,
* stdin, and stdout. If check_pgrp is set, also check that
* we belong to the foreground process group associated with
* that tty. The value of shell_terminal is needed in order to call
* tcsetpgrp(shell_terminal, ...); */
void controlling_tty(int check_pgrp)
{
pid_t curpgrp;
if ((curpgrp = tcgetpgrp(shell_terminal = 2)) < 0
&& (curpgrp = tcgetpgrp(shell_terminal = 0)) < 0
&& (curpgrp = tcgetpgrp(shell_terminal = 1)) < 0)
goto shell_terminal_error;
if (check_pgrp && curpgrp != getpgid(0))
goto shell_terminal_error;
return;
shell_terminal_error:
shell_terminal = -1;
return;
}
#endif
/* run_pipe_real() starts all the jobs, but doesn't wait for anything
* to finish. See checkjobs().
*
* return code is normally -1, when the caller has to wait for children
* to finish to determine the exit status of the pipe. If the pipe
* is a simple builtin command, however, the action is done by the
* time run_pipe_real returns, and the exit code is provided as the
* return value.
*
* The input of the pipe is always stdin, the output is always
* stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
* because it tries to avoid running the command substitution in
* subshell, when that is in fact necessary. The subshell process
* now has its stdout directed to the input of the appropriate pipe,
* so this routine is noticeably simpler.
*/
static int run_pipe_real(struct pipe *pi)
{
int i;
#ifndef __U_BOOT__
int nextin, nextout;
int pipefds[2]; /* pipefds[0] is for reading */
struct child_prog *child;
struct built_in_command *x;
char *p;
# if __GNUC__
/* Avoid longjmp clobbering */
(void) &i;
(void) &nextin;
(void) &nextout;
(void) &child;
# endif
#else
int nextin;
int flag = do_repeat ? CMD_FLAG_REPEAT : 0;
struct child_prog *child;
cmd_tbl_t *cmdtp;
char *p;
# if __GNUC__
/* Avoid longjmp clobbering */
(void) &i;
(void) &nextin;
(void) &child;
# endif
#endif /* __U_BOOT__ */
nextin = 0;
#ifndef __U_BOOT__
pi->pgrp = -1;
#endif
/* Check if this is a simple builtin (not part of a pipe).
* Builtins within pipes have to fork anyway, and are handled in
* pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
*/
if (pi->num_progs == 1) child = & (pi->progs[0]);
#ifndef __U_BOOT__
if (pi->num_progs == 1 && child->group && child->subshell == 0) {
int squirrel[] = {-1, -1, -1};
int rcode;
debug_printf("non-subshell grouping\n");
setup_redirects(child, squirrel);
/* XXX could we merge code with following builtin case,
* by creating a pseudo builtin that calls run_list_real? */
rcode = run_list_real(child->group);
restore_redirects(squirrel);
#else
if (pi->num_progs == 1 && child->group) {
int rcode;
debug_printf("non-subshell grouping\n");
rcode = run_list_real(child->group);
#endif
return rcode;
} else if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
for (i=0; is_assignment(child->argv[i]); i++) { /* nothing */ }
if (i!=0 && child->argv[i]==NULL) {
/* assignments, but no command: set the local environment */
for (i=0; child->argv[i]!=NULL; i++) {
/* Ok, this case is tricky. We have to decide if this is a
* local variable, or an already exported variable. If it is
* already exported, we have to export the new value. If it is
* not exported, we need only set this as a local variable.
* This junk is all to decide whether or not to export this
* variable. */
int export_me=0;
char *name, *value;
name = xstrdup(child->argv[i]);
debug_printf("Local environment set: %s\n", name);
value = strchr(name, '=');
if (value)
*value=0;
#ifndef __U_BOOT__
if ( get_local_var(name)) {
export_me=1;
}
#endif
free(name);
p = insert_var_value(child->argv[i]);
set_local_var(p, export_me);
if (p != child->argv[i]) free(p);
}
return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
}
for (i = 0; is_assignment(child->argv[i]); i++) {
p = insert_var_value(child->argv[i]);
#ifndef __U_BOOT__
putenv(strdup(p));
#else
set_local_var(p, 0);
#endif
if (p != child->argv[i]) {
child->sp--;
free(p);
}
}
if (child->sp) {
char * str = NULL;
str = make_string((child->argv + i));
parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
free(str);
return last_return_code;
}
#ifndef __U_BOOT__
for (x = bltins; x->cmd; x++) {
if (strcmp(child->argv[i], x->cmd) == 0 ) {
int squirrel[] = {-1, -1, -1};
int rcode;
if (x->function == builtin_exec && child->argv[i+1]==NULL) {
debug_printf("magic exec\n");
setup_redirects(child,NULL);
return EXIT_SUCCESS;
}
debug_printf("builtin inline %s\n", child->argv[0]);
/* XXX setup_redirects acts on file descriptors, not FILEs.
* This is perfect for work that comes after exec().
* Is it really safe for inline use? Experimentally,
* things seem to work with glibc. */
setup_redirects(child, squirrel);
#else
/* check ";", because ,example , argv consist from
* "help;flinfo" must not execute
*/
if (strchr(child->argv[i], ';')) {
printf ("Unknown command '%s' - try 'help' or use 'run' command\n",
child->argv[i]);
return -1;
}
/* Look up command in command table */
if ((cmdtp = find_cmd(child->argv[i])) == NULL) {
printf ("Unknown command '%s' - try 'help'\n", child->argv[i]);
return -1; /* give up after bad command */
} else {
int rcode;
#if defined(CONFIG_CMD_BOOTD)
/* avoid "bootd" recursion */
if (cmdtp->cmd == do_bootd) {
if (flag & CMD_FLAG_BOOTD) {
printf ("'bootd' recursion detected\n");
return -1;
}
else
flag |= CMD_FLAG_BOOTD;
}
#endif
/* found - check max args */
if ((child->argc - i) > cmdtp->maxargs)
return cmd_usage(cmdtp);
#endif
child->argv+=i; /* XXX horrible hack */
#ifndef __U_BOOT__
rcode = x->function(child);
#else
/* OK - call function to do the command */
rcode = (cmdtp->cmd)
(cmdtp, flag,child->argc-i,&child->argv[i]);
if ( !cmdtp->repeatable )
flag_repeat = 0;
#endif
child->argv-=i; /* XXX restore hack so free() can work right */
#ifndef __U_BOOT__
restore_redirects(squirrel);
#endif
return rcode;
}
}
#ifndef __U_BOOT__
}
for (i = 0; i < pi->num_progs; i++) {
child = & (pi->progs[i]);
/* pipes are inserted between pairs of commands */
if ((i + 1) < pi->num_progs) {
if (pipe(pipefds)<0) perror_msg_and_die("pipe");
nextout = pipefds[1];
} else {
nextout=1;
pipefds[0] = -1;
}
/* XXX test for failed fork()? */
if (!(child->pid = fork())) {
/* Set the handling for job control signals back to the default. */
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
signal(SIGTTOU, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
close_all();
if (nextin != 0) {
dup2(nextin, 0);
close(nextin);
}
if (nextout != 1) {
dup2(nextout, 1);
close(nextout);
}
if (pipefds[0]!=-1) {
close(pipefds[0]); /* opposite end of our output pipe */
}
/* Like bash, explicit redirects override pipes,
* and the pipe fd is available for dup'ing. */
setup_redirects(child,NULL);
if (interactive && pi->followup!=PIPE_BG) {
/* If we (the child) win the race, put ourselves in the process
* group whose leader is the first process in this pipe. */
if (pi->pgrp < 0) {
pi->pgrp = getpid();
}
if (setpgid(0, pi->pgrp) == 0) {
tcsetpgrp(2, pi->pgrp);
}
}
pseudo_exec(child);
}
/* put our child in the process group whose leader is the
first process in this pipe */
if (pi->pgrp < 0) {
pi->pgrp = child->pid;
}
/* Don't check for errors. The child may be dead already,
* in which case setpgid returns error code EACCES. */
setpgid(child->pid, pi->pgrp);
if (nextin != 0)
close(nextin);
if (nextout != 1)
close(nextout);
/* If there isn't another process, nextin is garbage
but it doesn't matter */
nextin = pipefds[0];
}
#endif
return -1;
}
static int run_list_real(struct pipe *pi)
{
char *save_name = NULL;
char **list = NULL;
char **save_list = NULL;
struct pipe *rpipe;
int flag_rep = 0;
#ifndef __U_BOOT__
int save_num_progs;
#endif
int rcode=0, flag_skip=1;
int flag_restore = 0;
int if_code=0, next_if_code=0; /* need double-buffer to handle elif */
reserved_style rmode, skip_more_in_this_rmode=RES_XXXX;
/* check syntax for "for" */
for (rpipe = pi; rpipe; rpipe = rpipe->next) {
if ((rpipe->r_mode == RES_IN ||
rpipe->r_mode == RES_FOR) &&
(rpipe->next == NULL)) {
syntax();
#ifdef __U_BOOT__
flag_repeat = 0;
#endif
return 1;
}
if ((rpipe->r_mode == RES_IN &&
(rpipe->next->r_mode == RES_IN &&
rpipe->next->progs->argv != NULL))||
(rpipe->r_mode == RES_FOR &&
rpipe->next->r_mode != RES_IN)) {
syntax();
#ifdef __U_BOOT__
flag_repeat = 0;
#endif
return 1;
}
}
for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL ||
pi->r_mode == RES_FOR) {
#ifdef __U_BOOT__
/* check Ctrl-C */
ctrlc();
if ((had_ctrlc())) {
return 1;
}
#endif
flag_restore = 0;
if (!rpipe) {
flag_rep = 0;
rpipe = pi;
}
}
rmode = pi->r_mode;
debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n", rmode, if_code, next_if_code, skip_more_in_this_rmode);
if (rmode == skip_more_in_this_rmode && flag_skip) {
if (pi->followup == PIPE_SEQ) flag_skip=0;
continue;
}
flag_skip = 1;
skip_more_in_this_rmode = RES_XXXX;
if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
if (rmode == RES_THEN && if_code) continue;
if (rmode == RES_ELSE && !if_code) continue;
if (rmode == RES_ELIF && !if_code) break;
if (rmode == RES_FOR && pi->num_progs) {
if (!list) {
/* if no variable values after "in" we skip "for" */
if (!pi->next->progs->argv) continue;
/* create list of variable values */
list = make_list_in(pi->next->progs->argv,
pi->progs->argv[0]);
save_list = list;
save_name = pi->progs->argv[0];
pi->progs->argv[0] = NULL;
flag_rep = 1;
}
if (!(*list)) {
free(pi->progs->argv[0]);
free(save_list);
list = NULL;
flag_rep = 0;
pi->progs->argv[0] = save_name;
#ifndef __U_BOOT__
pi->progs->glob_result.gl_pathv[0] =
pi->progs->argv[0];
#endif
continue;
} else {
/* insert new value from list for variable */
if (pi->progs->argv[0])
free(pi->progs->argv[0]);
pi->progs->argv[0] = *list++;
#ifndef __U_BOOT__
pi->progs->glob_result.gl_pathv[0] =
pi->progs->argv[0];
#endif
}
}
if (rmode == RES_IN) continue;
if (rmode == RES_DO) {
if (!flag_rep) continue;
}
if ((rmode == RES_DONE)) {
if (flag_rep) {
flag_restore = 1;
} else {
rpipe = NULL;
}
}
if (pi->num_progs == 0) continue;
#ifndef __U_BOOT__
save_num_progs = pi->num_progs; /* save number of programs */
#endif
rcode = run_pipe_real(pi);
debug_printf("run_pipe_real returned %d\n",rcode);
#ifndef __U_BOOT__
if (rcode!=-1) {
/* We only ran a builtin: rcode was set by the return value
* of run_pipe_real(), and we don't need to wait for anything. */
} else if (pi->followup==PIPE_BG) {
/* XXX check bash's behavior with nontrivial pipes */
/* XXX compute jobid */
/* XXX what does bash do with attempts to background builtins? */
insert_bg_job(pi);
rcode = EXIT_SUCCESS;
} else {
if (interactive) {
/* move the new process group into the foreground */
if (tcsetpgrp(shell_terminal, pi->pgrp) && errno != ENOTTY)
perror_msg("tcsetpgrp-3");
rcode = checkjobs(pi);
/* move the shell to the foreground */
if (tcsetpgrp(shell_terminal, getpgid(0)) && errno != ENOTTY)
perror_msg("tcsetpgrp-4");
} else {
rcode = checkjobs(pi);
}
debug_printf("checkjobs returned %d\n",rcode);
}
last_return_code=rcode;
#else
if (rcode < -1) {
last_return_code = -rcode - 2;
return -2; /* exit */
}
last_return_code=(rcode == 0) ? 0 : 1;
#endif
#ifndef __U_BOOT__
pi->num_progs = save_num_progs; /* restore number of programs */
#endif
if ( rmode == RES_IF || rmode == RES_ELIF )
next_if_code=rcode; /* can be overwritten a number of times */
if (rmode == RES_WHILE)
flag_rep = !last_return_code;
if (rmode == RES_UNTIL)
flag_rep = last_return_code;
if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
(rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
skip_more_in_this_rmode=rmode;
#ifndef __U_BOOT__
checkjobs(NULL);
#endif
}
return rcode;
}
/* broken, of course, but OK for testing */
static char *indenter(int i)
{
static char blanks[]=" ";
return &blanks[sizeof(blanks)-i-1];
}
/* return code is the exit status of the pipe */
static int free_pipe(struct pipe *pi, int indent)
{
char **p;
struct child_prog *child;
#ifndef __U_BOOT__
struct redir_struct *r, *rnext;
#endif
int a, i, ret_code=0;
char *ind = indenter(indent);
#ifndef __U_BOOT__
if (pi->stopped_progs > 0)
return ret_code;
final_printf("%s run pipe: (pid %d)\n",ind,getpid());
#endif
for (i=0; i<pi->num_progs; i++) {
child = &pi->progs[i];
final_printf("%s command %d:\n",ind,i);
if (child->argv) {
for (a=0,p=child->argv; *p; a++,p++) {
final_printf("%s argv[%d] = %s\n",ind,a,*p);
}
#ifndef __U_BOOT__
globfree(&child->glob_result);
#else
for (a = 0; a < child->argc; a++) {
free(child->argv[a]);
}
free(child->argv);
child->argc = 0;
#endif
child->argv=NULL;
} else if (child->group) {
#ifndef __U_BOOT__
final_printf("%s begin group (subshell:%d)\n",ind, child->subshell);
#endif
ret_code = free_pipe_list(child->group,indent+3);
final_printf("%s end group\n",ind);
} else {
final_printf("%s (nil)\n",ind);
}
#ifndef __U_BOOT__
for (r=child->redirects; r; r=rnext) {
final_printf("%s redirect %d%s", ind, r->fd, redir_table[r->type].descrip);
if (r->dup == -1) {
/* guard against the case >$FOO, where foo is unset or blank */
if (r->word.gl_pathv) {
final_printf(" %s\n", *r->word.gl_pathv);
globfree(&r->word);
}
} else {
final_printf("&%d\n", r->dup);
}
rnext=r->next;
free(r);
}
child->redirects=NULL;
#endif
}
free(pi->progs); /* children are an array, they get freed all at once */
pi->progs=NULL;
return ret_code;
}
static int free_pipe_list(struct pipe *head, int indent)
{
int rcode=0; /* if list has no members */
struct pipe *pi, *next;
char *ind = indenter(indent);
for (pi=head; pi; pi=next) {
final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode);
rcode = free_pipe(pi, indent);
final_printf("%s pipe followup code %d\n", ind, pi->followup);
next=pi->next;
pi->next=NULL;
free(pi);
}
return rcode;
}
/* Select which version we will use */
static int run_list(struct pipe *pi)
{
int rcode=0;
#ifndef __U_BOOT__
if (fake_mode==0) {
#endif
rcode = run_list_real(pi);
#ifndef __U_BOOT__
}
#endif
/* free_pipe_list has the side effect of clearing memory
* In the long run that function can be merged with run_list_real,
* but doing that now would hobble the debugging effort. */
free_pipe_list(pi,0);
return rcode;
}
/* The API for glob is arguably broken. This routine pushes a non-matching
* string into the output structure, removing non-backslashed backslashes.
* If someone can prove me wrong, by performing this function within the
* original glob(3) api, feel free to rewrite this routine into oblivion.
* Return code (0 vs. GLOB_NOSPACE) matches glob(3).
* XXX broken if the last character is '\\', check that before calling.
*/
#ifndef __U_BOOT__
static int globhack(const char *src, int flags, glob_t *pglob)
{
int cnt=0, pathc;
const char *s;
char *dest;
for (cnt=1, s=src; s && *s; s++) {
if (*s == '\\') s++;
cnt++;
}
dest = malloc(cnt);
if (!dest) return GLOB_NOSPACE;
if (!(flags & GLOB_APPEND)) {
pglob->gl_pathv=NULL;
pglob->gl_pathc=0;
pglob->gl_offs=0;
pglob->gl_offs=0;
}
pathc = ++pglob->gl_pathc;
pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
pglob->gl_pathv[pathc-1]=dest;
pglob->gl_pathv[pathc]=NULL;
for (s=src; s && *s; s++, dest++) {
if (*s == '\\') s++;
*dest = *s;
}
*dest='\0';
return 0;
}
/* XXX broken if the last character is '\\', check that before calling */
static int glob_needed(const char *s)
{
for (; *s; s++) {
if (*s == '\\') s++;
if (strchr("*[?",*s)) return 1;
}
return 0;
}
#if 0
static void globprint(glob_t *pglob)
{
int i;
debug_printf("glob_t at %p:\n", pglob);
debug_printf(" gl_pathc=%d gl_pathv=%p gl_offs=%d gl_flags=%d\n",
pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags);
for (i=0; i<pglob->gl_pathc; i++)
debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i,
pglob->gl_pathv[i], pglob->gl_pathv[i]);
}
#endif
static int xglob(o_string *dest, int flags, glob_t *pglob)
{
int gr;
/* short-circuit for null word */
/* we can code this better when the debug_printf's are gone */
if (dest->length == 0) {
if (dest->nonnull) {
/* bash man page calls this an "explicit" null */
gr = globhack(dest->data, flags, pglob);
debug_printf("globhack returned %d\n",gr);
} else {
return 0;
}
} else if (glob_needed(dest->data)) {
gr = glob(dest->data, flags, NULL, pglob);
debug_printf("glob returned %d\n",gr);
if (gr == GLOB_NOMATCH) {
/* quote removal, or more accurately, backslash removal */
gr = globhack(dest->data, flags, pglob);
debug_printf("globhack returned %d\n",gr);
}
} else {
gr = globhack(dest->data, flags, pglob);
debug_printf("globhack returned %d\n",gr);
}
if (gr == GLOB_NOSPACE)
error_msg_and_die("out of memory during glob");
if (gr != 0) { /* GLOB_ABORTED ? */
error_msg("glob(3) error %d",gr);
}
/* globprint(glob_target); */
return gr;
}
#endif
#ifdef __U_BOOT__
static char *get_dollar_var(char ch);
#endif
/* This is used to get/check local shell variables */
char *get_local_var(const char *s)
{
struct variables *cur;
if (!s)
return NULL;
#ifdef __U_BOOT__
if (*s == '$')
return get_dollar_var(s[1]);
#endif
for (cur = top_vars; cur; cur=cur->next)
if(strcmp(cur->name, s)==0)
return cur->value;
return NULL;
}
/* This is used to set local shell variables
flg_export==0 if only local (not exporting) variable
flg_export==1 if "new" exporting environ
flg_export>1 if current startup environ (not call putenv()) */
int set_local_var(const char *s, int flg_export)
{
char *name, *value;
int result=0;
struct variables *cur;
#ifdef __U_BOOT__
/* might be possible! */
if (!isalpha(*s))
return -1;
#endif
name=strdup(s);
#ifdef __U_BOOT__
if (getenv(name) != NULL) {
printf ("ERROR: "
"There is a global environment variable with the same name.\n");
free(name);
return -1;
}
#endif
/* Assume when we enter this function that we are already in
* NAME=VALUE format. So the first order of business is to
* split 's' on the '=' into 'name' and 'value' */
value = strchr(name, '=');
if (value==0 && ++value==0) {
free(name);
return -1;
}
*value++ = 0;
for(cur = top_vars; cur; cur = cur->next) {
if(strcmp(cur->name, name)==0)
break;
}
if(cur) {
if(strcmp(cur->value, value)==0) {
if(flg_export>0 && cur->flg_export==0)
cur->flg_export=flg_export;
else
result++;
} else {
if(cur->flg_read_only) {
error_msg("%s: readonly variable", name);
result = -1;
} else {
if(flg_export>0 || cur->flg_export>1)
cur->flg_export=1;
free(cur->value);
cur->value = strdup(value);
}
}
} else {
cur = malloc(sizeof(struct variables));
if(!cur) {
result = -1;
} else {
cur->name = strdup(name);
if(cur->name == 0) {
free(cur);
result = -1;
} else {
struct variables *bottom = top_vars;
cur->value = strdup(value);
cur->next = 0;
cur->flg_export = flg_export;
cur->flg_read_only = 0;
while(bottom->next) bottom=bottom->next;
bottom->next = cur;
}
}
}
#ifndef __U_BOOT__
if(result==0 && cur->flg_export==1) {
*(value-1) = '=';
result = putenv(name);
} else {
#endif
free(name);
#ifndef __U_BOOT__
if(result>0) /* equivalent to previous set */
result = 0;
}
#endif
return result;
}
void unset_local_var(const char *name)
{
struct variables *cur;
if (name) {
for (cur = top_vars; cur; cur=cur->next) {
if(strcmp(cur->name, name)==0)
break;
}
if(cur!=0) {
struct variables *next = top_vars;
if(cur->flg_read_only) {
error_msg("%s: readonly variable", name);
return;
} else {
#ifndef __U_BOOT__
if(cur->flg_export)
unsetenv(cur->name);
#endif
free(cur->name);
free(cur->value);
while (next->next != cur)
next = next->next;
next->next = cur->next;
}
free(cur);
}
}
}
static int is_assignment(const char *s)
{
if (s == NULL)
return 0;
if (!isalpha(*s)) return 0;
++s;
while(isalnum(*s) || *s=='_') ++s;
return *s=='=';
}
#ifndef __U_BOOT__
/* the src parameter allows us to peek forward to a possible &n syntax
* for file descriptor duplication, e.g., "2>&1".
* Return code is 0 normally, 1 if a syntax error is detected in src.
* Resource errors (in xmalloc) cause the process to exit */
static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
struct in_str *input)
{
struct child_prog *child=ctx->child;
struct redir_struct *redir = child->redirects;
struct redir_struct *last_redir=NULL;
/* Create a new redir_struct and drop it onto the end of the linked list */
while(redir) {
last_redir=redir;
redir=redir->next;
}
redir = xmalloc(sizeof(struct redir_struct));
redir->next=NULL;
redir->word.gl_pathv=NULL;
if (last_redir) {
last_redir->next=redir;
} else {
child->redirects=redir;
}
redir->type=style;
redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
/* Check for a '2>&1' type redirect */
redir->dup = redirect_dup_num(input);
if (redir->dup == -2) return 1; /* syntax error */
if (redir->dup != -1) {
/* Erik had a check here that the file descriptor in question
* is legit; I postpone that to "run time"
* A "-" representation of "close me" shows up as a -3 here */
debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
} else {
/* We do _not_ try to open the file that src points to,
* since we need to return and let src be expanded first.
* Set ctx->pending_redirect, so we know what to do at the
* end of the next parsed word.
*/
ctx->pending_redirect = redir;
}
return 0;
}
#endif
struct pipe *new_pipe(void) {
struct pipe *pi;
pi = xmalloc(sizeof(struct pipe));
pi->num_progs = 0;
pi->progs = NULL;
pi->next = NULL;
pi->followup = 0; /* invalid */
pi->r_mode = RES_NONE;
return pi;
}
static void initialize_context(struct p_context *ctx)
{
ctx->pipe=NULL;
#ifndef __U_BOOT__
ctx->pending_redirect=NULL;
#endif
ctx->child=NULL;
ctx->list_head=new_pipe();
ctx->pipe=ctx->list_head;
ctx->w=RES_NONE;
ctx->stack=NULL;
#ifdef __U_BOOT__
ctx->old_flag=0;
#endif
done_command(ctx); /* creates the memory for working child */
}
/* normal return is 0
* if a reserved word is found, and processed, return 1
* should handle if, then, elif, else, fi, for, while, until, do, done.
* case, function, and select are obnoxious, save those for later.
*/
struct reserved_combo {
char *literal;
int code;
long flag;
};
/* Mostly a list of accepted follow-up reserved words.
* FLAG_END means we are done with the sequence, and are ready
* to turn the compound list into a command.
* FLAG_START means the word must start a new compound list.
*/
static struct reserved_combo reserved_list[] = {
{ "if", RES_IF, FLAG_THEN | FLAG_START },
{ "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
{ "elif", RES_ELIF, FLAG_THEN },
{ "else", RES_ELSE, FLAG_FI },
{ "fi", RES_FI, FLAG_END },
{ "for", RES_FOR, FLAG_IN | FLAG_START },
{ "while", RES_WHILE, FLAG_DO | FLAG_START },
{ "until", RES_UNTIL, FLAG_DO | FLAG_START },
{ "in", RES_IN, FLAG_DO },
{ "do", RES_DO, FLAG_DONE },
{ "done", RES_DONE, FLAG_END }
};
#define NRES (sizeof(reserved_list)/sizeof(struct reserved_combo))
int reserved_word(o_string *dest, struct p_context *ctx)
{
struct reserved_combo *r;
for (r=reserved_list;
r<reserved_list+NRES; r++) {
if (strcmp(dest->data, r->literal) == 0) {
debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
if (r->flag & FLAG_START) {
struct p_context *new = xmalloc(sizeof(struct p_context));
debug_printf("push stack\n");
if (ctx->w == RES_IN || ctx->w == RES_FOR) {
syntax();
free(new);
ctx->w = RES_SNTX;
b_reset(dest);
return 1;
}
*new = *ctx; /* physical copy */
initialize_context(ctx);
ctx->stack=new;
} else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
syntax();
ctx->w = RES_SNTX;
b_reset(dest);
return 1;
}
ctx->w=r->code;
ctx->old_flag = r->flag;
if (ctx->old_flag & FLAG_END) {
struct p_context *old;
debug_printf("pop stack\n");
done_pipe(ctx,PIPE_SEQ);
old = ctx->stack;
old->child->group = ctx->list_head;
#ifndef __U_BOOT__
old->child->subshell = 0;
#endif
*ctx = *old; /* physical copy */
free(old);
}
b_reset (dest);
return 1;
}
}
return 0;
}
/* normal return is 0.
* Syntax or xglob errors return 1. */
static int done_word(o_string *dest, struct p_context *ctx)
{
struct child_prog *child=ctx->child;
#ifndef __U_BOOT__
glob_t *glob_target;
int gr, flags = 0;
#else
char *str, *s;
int argc, cnt;
#endif
debug_printf("done_word: %s %p\n", dest->data, child);
if (dest->length == 0 && !dest->nonnull) {
debug_printf(" true null, ignored\n");
return 0;
}
#ifndef __U_BOOT__
if (ctx->pending_redirect) {
glob_target = &ctx->pending_redirect->word;
} else {
#endif
if (child->group) {
syntax();
return 1; /* syntax error, groups and arglists don't mix */
}
if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
debug_printf("checking %s for reserved-ness\n",dest->data);
if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
}
#ifndef __U_BOOT__
glob_target = &child->glob_result;
if (child->argv) flags |= GLOB_APPEND;
#else
for (cnt = 1, s = dest->data; s && *s; s++) {
if (*s == '\\') s++;
cnt++;
}
str = malloc(cnt);
if (!str) return 1;
if ( child->argv == NULL) {
child->argc=0;
}
argc = ++child->argc;
child->argv = realloc(child->argv, (argc+1)*sizeof(*child->argv));
if (child->argv == NULL) return 1;
child->argv[argc-1]=str;
child->argv[argc]=NULL;
for (s = dest->data; s && *s; s++,str++) {
if (*s == '\\') s++;
*str = *s;
}
*str = '\0';
#endif
#ifndef __U_BOOT__
}
gr = xglob(dest, flags, glob_target);
if (gr != 0) return 1;
#endif
b_reset(dest);
#ifndef __U_BOOT__
if (ctx->pending_redirect) {
ctx->pending_redirect=NULL;
if (glob_target->gl_pathc != 1) {
error_msg("ambiguous redirect");
return 1;
}
} else {
child->argv = glob_target->gl_pathv;
}
#endif
if (ctx->w == RES_FOR) {
done_word(dest,ctx);
done_pipe(ctx,PIPE_SEQ);
}
return 0;
}
/* The only possible error here is out of memory, in which case
* xmalloc exits. */
static int done_command(struct p_context *ctx)
{
/* The child is really already in the pipe structure, so
* advance the pipe counter and make a new, null child.
* Only real trickiness here is that the uncommitted
* child structure, to which ctx->child points, is not
* counted in pi->num_progs. */
struct pipe *pi=ctx->pipe;
struct child_prog *prog=ctx->child;
if (prog && prog->group == NULL
&& prog->argv == NULL
#ifndef __U_BOOT__
&& prog->redirects == NULL) {
#else
) {
#endif
debug_printf("done_command: skipping null command\n");
return 0;
} else if (prog) {
pi->num_progs++;
debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
} else {
debug_printf("done_command: initializing\n");
}
pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
prog = pi->progs + pi->num_progs;
#ifndef __U_BOOT__
prog->redirects = NULL;
#endif
prog->argv = NULL;
#ifndef __U_BOOT__
prog->is_stopped = 0;
#endif
prog->group = NULL;
#ifndef __U_BOOT__
prog->glob_result.gl_pathv = NULL;
prog->family = pi;
#endif
prog->sp = 0;
ctx->child = prog;
prog->type = ctx->type;
/* but ctx->pipe and ctx->list_head remain unchanged */
return 0;
}
static int done_pipe(struct p_context *ctx, pipe_style type)
{
struct pipe *new_p;
done_command(ctx); /* implicit closure of previous command */
debug_printf("done_pipe, type %d\n", type);
ctx->pipe->followup = type;
ctx->pipe->r_mode = ctx->w;
new_p=new_pipe();
ctx->pipe->next = new_p;
ctx->pipe = new_p;
ctx->child = NULL;
done_command(ctx); /* set up new pipe to accept commands */
return 0;
}
#ifndef __U_BOOT__
/* peek ahead in the in_str to find out if we have a "&n" construct,
* as in "2>&1", that represents duplicating a file descriptor.
* returns either -2 (syntax error), -1 (no &), or the number found.
*/
static int redirect_dup_num(struct in_str *input)
{
int ch, d=0, ok=0;
ch = b_peek(input);
if (ch != '&') return -1;
b_getch(input); /* get the & */
ch=b_peek(input);
if (ch == '-') {
b_getch(input);
return -3; /* "-" represents "close me" */
}
while (isdigit(ch)) {
d = d*10+(ch-'0');
ok=1;
b_getch(input);
ch = b_peek(input);
}
if (ok) return d;
error_msg("ambiguous redirect");
return -2;
}
/* If a redirect is immediately preceded by a number, that number is
* supposed to tell which file descriptor to redirect. This routine
* looks for such preceding numbers. In an ideal world this routine
* needs to handle all the following classes of redirects...
* echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
* echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
* echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
* echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
* A -1 output from this program means no valid number was found, so the
* caller should use the appropriate default for this redirection.
*/
static int redirect_opt_num(o_string *o)
{
int num;
if (o->length==0) return -1;
for(num=0; num<o->length; num++) {
if (!isdigit(*(o->data+num))) {
return -1;
}
}
/* reuse num (and save an int) */
num=atoi(o->data);
b_reset(o);
return num;
}
FILE *generate_stream_from_list(struct pipe *head)
{
FILE *pf;
#if 1
int pid, channel[2];
if (pipe(channel)<0) perror_msg_and_die("pipe");
pid=fork();
if (pid<0) {
perror_msg_and_die("fork");
} else if (pid==0) {
close(channel[0]);
if (channel[1] != 1) {
dup2(channel[1],1);
close(channel[1]);
}
#if 0
#define SURROGATE "surrogate response"
write(1,SURROGATE,sizeof(SURROGATE));
_exit(run_list(head));
#else
_exit(run_list_real(head)); /* leaks memory */
#endif
}
debug_printf("forked child %d\n",pid);
close(channel[1]);
pf = fdopen(channel[0],"r");
debug_printf("pipe on FILE *%p\n",pf);
#else
free_pipe_list(head,0);
pf=popen("echo surrogate response","r");
debug_printf("started fake pipe on FILE *%p\n",pf);
#endif
return pf;
}
/* this version hacked for testing purposes */
/* return code is exit status of the process that is run. */
static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
{
int retcode;
o_string result=NULL_O_STRING;
struct p_context inner;
FILE *p;
struct in_str pipe_str;
initialize_context(&inner);
/* recursion to generate command */
retcode = parse_stream(&result, &inner, input, subst_end);
if (retcode != 0) return retcode; /* syntax error or EOF */
done_word(&result, &inner);
done_pipe(&inner, PIPE_SEQ);
b_free(&result);
p=generate_stream_from_list(inner.list_head);
if (p==NULL) return 1;
mark_open(fileno(p));
setup_file_in_str(&pipe_str, p);
/* now send results of command back into original context */
retcode = parse_stream(dest, ctx, &pipe_str, '\0');
/* XXX In case of a syntax error, should we try to kill the child?
* That would be tough to do right, so just read until EOF. */
if (retcode == 1) {
while (b_getch(&pipe_str)!=EOF) { /* discard */ };
}
debug_printf("done reading from pipe, pclose()ing\n");
/* This is the step that wait()s for the child. Should be pretty
* safe, since we just read an EOF from its stdout. We could try
* to better, by using wait(), and keeping track of background jobs
* at the same time. That would be a lot of work, and contrary
* to the KISS philosophy of this program. */
mark_closed(fileno(p));
retcode=pclose(p);
free_pipe_list(inner.list_head,0);
debug_printf("pclosed, retcode=%d\n",retcode);
/* XXX this process fails to trim a single trailing newline */
return retcode;
}
static int parse_group(o_string *dest, struct p_context *ctx,
struct in_str *input, int ch)
{
int rcode, endch=0;
struct p_context sub;
struct child_prog *child = ctx->child;
if (child->argv) {
syntax();
return 1; /* syntax error, groups and arglists don't mix */
}
initialize_context(&sub);
switch(ch) {
case '(': endch=')'; child->subshell=1; break;
case '{': endch='}'; break;
default: syntax(); /* really logic error */
}
rcode=parse_stream(dest,&sub,input,endch);
done_word(dest,&sub); /* finish off the final word in the subcontext */
done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
child->group = sub.list_head;
return rcode;
/* child remains "open", available for possible redirects */
}
#endif
/* basically useful version until someone wants to get fancier,
* see the bash man page under "Parameter Expansion" */
static char *lookup_param(char *src)
{
char *p;
if (!src)
return NULL;
p = getenv(src);
if (!p)
p = get_local_var(src);
return p;
}
#ifdef __U_BOOT__
static char *get_dollar_var(char ch)
{
static char buf[40];
buf[0] = '\0';
switch (ch) {
case '?':
sprintf(buf, "%u", (unsigned int)last_return_code);
break;
default:
return NULL;
}
return buf;
}
#endif
/* return code: 0 for OK, 1 for syntax error */
static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
{
#ifndef __U_BOOT__
int i, advance=0;
#else
int advance=0;
#endif
#ifndef __U_BOOT__
char sep[]=" ";
#endif
int ch = input->peek(input); /* first character after the $ */
debug_printf("handle_dollar: ch=%c\n",ch);
if (isalpha(ch)) {
b_addchr(dest, SPECIAL_VAR_SYMBOL);
ctx->child->sp++;
while(ch=b_peek(input),isalnum(ch) || ch=='_') {
b_getch(input);
b_addchr(dest,ch);
}
b_addchr(dest, SPECIAL_VAR_SYMBOL);
#ifndef __U_BOOT__
} else if (isdigit(ch)) {
i = ch-'0'; /* XXX is $0 special? */
if (i<global_argc) {
parse_string(dest, ctx, global_argv[i]); /* recursion */
}
advance = 1;
#endif
} else switch (ch) {
#ifndef __U_BOOT__
case '$':
b_adduint(dest,getpid());
advance = 1;
break;
case '!':
if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
advance = 1;
break;
#endif
case '?':
#ifndef __U_BOOT__
b_adduint(dest,last_return_code);
#else
ctx->child->sp++;
b_addchr(dest, SPECIAL_VAR_SYMBOL);
b_addchr(dest, '$');
b_addchr(dest, '?');
b_addchr(dest, SPECIAL_VAR_SYMBOL);
#endif
advance = 1;
break;
#ifndef __U_BOOT__
case '#':
b_adduint(dest,global_argc ? global_argc-1 : 0);
advance = 1;
break;
#endif
case '{':
b_addchr(dest, SPECIAL_VAR_SYMBOL);
ctx->child->sp++;
b_getch(input);
/* XXX maybe someone will try to escape the '}' */
while(ch=b_getch(input),ch!=EOF && ch!='}') {
b_addchr(dest,ch);
}
if (ch != '}') {
syntax();
return 1;
}
b_addchr(dest, SPECIAL_VAR_SYMBOL);
break;
#ifndef __U_BOOT__
case '(':
b_getch(input);
process_command_subs(dest, ctx, input, ')');
break;
case '*':
sep[0]=ifs[0];
for (i=1; i<global_argc; i++) {
parse_string(dest, ctx, global_argv[i]);
if (i+1 < global_argc) parse_string(dest, ctx, sep);
}
break;
case '@':
case '-':
case '_':
/* still unhandled, but should be eventually */
error_msg("unhandled syntax: $%c",ch);
return 1;
break;
#endif
default:
b_addqchr(dest,'$',dest->quote);
}
/* Eat the character if the flag was set. If the compiler
* is smart enough, we could substitute "b_getch(input);"
* for all the "advance = 1;" above, and also end up with
* a nice size-optimized program. Hah! That'll be the day.
*/
if (advance) b_getch(input);
return 0;
}
#ifndef __U_BOOT__
int parse_string(o_string *dest, struct p_context *ctx, const char *src)
{
struct in_str foo;
setup_string_in_str(&foo, src);
return parse_stream(dest, ctx, &foo, '\0');
}
#endif
/* return code is 0 for normal exit, 1 for syntax error */
int parse_stream(o_string *dest, struct p_context *ctx,
struct in_str *input, int end_trigger)
{
unsigned int ch, m;
#ifndef __U_BOOT__
int redir_fd;
redir_type redir_style;
#endif
int next;
/* Only double-quote state is handled in the state variable dest->quote.
* A single-quote triggers a bypass of the main loop until its mate is
* found. When recursing, quote state is passed in via dest->quote. */
debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
while ((ch=b_getch(input))!=EOF) {
m = map[ch];
#ifdef __U_BOOT__
if (input->__promptme == 0) return 1;
#endif
next = (ch == '\n') ? 0 : b_peek(input);
debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d - %c\n",
ch >= ' ' ? ch : '.', ch, m,
dest->quote, ctx->stack == NULL ? '*' : '.');
if (m==0 || ((m==1 || m==2) && dest->quote)) {
b_addqchr(dest, ch, dest->quote);
} else {
if (m==2) { /* unquoted IFS */
if (done_word(dest, ctx)) {
return 1;
}
/* If we aren't performing a substitution, treat a newline as a
* command separator. */
if (end_trigger != '\0' && ch=='\n')
done_pipe(ctx,PIPE_SEQ);
}
if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
debug_printf("leaving parse_stream (triggered)\n");
return 0;
}
#if 0
if (ch=='\n') {
/* Yahoo! Time to run with it! */
done_pipe(ctx,PIPE_SEQ);
run_list(ctx->list_head);
initialize_context(ctx);
}
#endif
if (m!=2) switch (ch) {
case '#':
if (dest->length == 0 && !dest->quote) {
while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
} else {
b_addqchr(dest, ch, dest->quote);
}
break;
case '\\':
if (next == EOF) {
syntax();
return 1;
}
b_addqchr(dest, '\\', dest->quote);
b_addqchr(dest, b_getch(input), dest->quote);
break;
case '$':
if (handle_dollar(dest, ctx, input)!=0) return 1;
break;
case '\'':
dest->nonnull = 1;
while(ch=b_getch(input),ch!=EOF && ch!='\'') {
#ifdef __U_BOOT__
if(input->__promptme == 0) return 1;
#endif
b_addchr(dest,ch);
}
if (ch==EOF) {
syntax();
return 1;
}
break;
case '"':
dest->nonnull = 1;
dest->quote = !dest->quote;
break;
#ifndef __U_BOOT__
case '`':
process_command_subs(dest, ctx, input, '`');
break;
case '>':
redir_fd = redirect_opt_num(dest);
done_word(dest, ctx);
redir_style=REDIRECT_OVERWRITE;
if (next == '>') {
redir_style=REDIRECT_APPEND;
b_getch(input);
} else if (next == '(') {
syntax(); /* until we support >(list) Process Substitution */
return 1;
}
setup_redirect(ctx, redir_fd, redir_style, input);
break;
case '<':
redir_fd = redirect_opt_num(dest);
done_word(dest, ctx);
redir_style=REDIRECT_INPUT;
if (next == '<') {
redir_style=REDIRECT_HEREIS;
b_getch(input);
} else if (next == '>') {
redir_style=REDIRECT_IO;
b_getch(input);
} else if (next == '(') {
syntax(); /* until we support <(list) Process Substitution */
return 1;
}
setup_redirect(ctx, redir_fd, redir_style, input);
break;
#endif
case ';':
done_word(dest, ctx);
done_pipe(ctx,PIPE_SEQ);
break;
case '&':
done_word(dest, ctx);
if (next=='&') {
b_getch(input);
done_pipe(ctx,PIPE_AND);
} else {
#ifndef __U_BOOT__
done_pipe(ctx,PIPE_BG);
#else
syntax_err();
return 1;
#endif
}
break;
case '|':
done_word(dest, ctx);
if (next=='|') {
b_getch(input);
done_pipe(ctx,PIPE_OR);
} else {
/* we could pick up a file descriptor choice here
* with redirect_opt_num(), but bash doesn't do it.
* "echo foo 2| cat" yields "foo 2". */
#ifndef __U_BOOT__
done_command(ctx);
#else
syntax_err();
return 1;
#endif
}
break;
#ifndef __U_BOOT__
case '(':
case '{':
if (parse_group(dest, ctx, input, ch)!=0) return 1;
break;
case ')':
case '}':
syntax(); /* Proper use of this character caught by end_trigger */
return 1;
break;
#endif
default:
syntax(); /* this is really an internal logic error */
return 1;
}
}
}
/* complain if quote? No, maybe we just finished a command substitution
* that was quoted. Example:
* $ echo "`cat foo` plus more"
* and we just got the EOF generated by the subshell that ran "cat foo"
* The only real complaint is if we got an EOF when end_trigger != '\0',
* that is, we were really supposed to get end_trigger, and never got
* one before the EOF. Can't use the standard "syntax error" return code,
* so that parse_stream_outer can distinguish the EOF and exit smoothly. */
debug_printf("leaving parse_stream (EOF)\n");
if (end_trigger != '\0') return -1;
return 0;
}
void mapset(const unsigned char *set, int code)
{
const unsigned char *s;
for (s=set; *s; s++) map[*s] = code;
}
void update_ifs_map(void)
{
/* char *ifs and char map[256] are both globals. */
ifs = (uchar *)getenv("IFS");
if (ifs == NULL) ifs=(uchar *)" \t\n";
/* Precompute a list of 'flow through' behavior so it can be treated
* quickly up front. Computation is necessary because of IFS.
* Special case handling of IFS == " \t\n" is not implemented.
* The map[] array only really needs two bits each, and on most machines
* that would be faster because of the reduced L1 cache footprint.
*/
memset(map,0,sizeof(map)); /* most characters flow through always */
#ifndef __U_BOOT__
mapset((uchar *)"\\$'\"`", 3); /* never flow through */
mapset((uchar *)"<>;&|(){}#", 1); /* flow through if quoted */
#else
mapset((uchar *)"\\$'\"", 3); /* never flow through */
mapset((uchar *)";&|#", 1); /* flow through if quoted */
#endif
mapset(ifs, 2); /* also flow through if quoted */
}
/* most recursion does not come through here, the exeception is
* from builtin_source() */
int parse_stream_outer(struct in_str *inp, int flag)
{
struct p_context ctx;
o_string temp=NULL_O_STRING;
int rcode;
#ifdef __U_BOOT__
int code = 0;
#endif
do {
ctx.type = flag;
initialize_context(&ctx);
update_ifs_map();
if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING)) mapset((uchar *)";$&|", 0);
inp->promptmode=1;
rcode = parse_stream(&temp, &ctx, inp, '\n');
#ifdef __U_BOOT__
if (rcode == 1) flag_repeat = 0;
#endif
if (rcode != 1 && ctx.old_flag != 0) {
syntax();
#ifdef __U_BOOT__
flag_repeat = 0;
#endif
}
if (rcode != 1 && ctx.old_flag == 0) {
done_word(&temp, &ctx);
done_pipe(&ctx,PIPE_SEQ);
#ifndef __U_BOOT__
run_list(ctx.list_head);
#else
code = run_list(ctx.list_head);
if (code == -2) { /* exit */
b_free(&temp);
code = 0;
/* XXX hackish way to not allow exit from main loop */
if (inp->peek == file_peek) {
printf("exit not allowed from main input shell.\n");
continue;
}
break;
}
if (code == -1)
flag_repeat = 0;
#endif
} else {
if (ctx.old_flag != 0) {
free(ctx.stack);
b_reset(&temp);
}
#ifdef __U_BOOT__
if (inp->__promptme == 0) printf("<INTERRUPT>\n");
inp->__promptme = 1;
#endif
temp.nonnull = 0;
temp.quote = 0;
inp->p = NULL;
free_pipe_list(ctx.list_head,0);
}
b_free(&temp);
} while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
#ifndef __U_BOOT__
return 0;
#else
return (code != 0) ? 1 : 0;
#endif /* __U_BOOT__ */
}
#ifndef __U_BOOT__
static int parse_string_outer(const char *s, int flag)
#else
int parse_string_outer(const char *s, int flag)
#endif /* __U_BOOT__ */
{
struct in_str input;
#ifdef __U_BOOT__
char *p = NULL;
int rcode;
if ( !s || !*s)
return 1;
if (!(p = strchr(s, '\n')) || *++p) {
p = xmalloc(strlen(s) + 2);
strcpy(p, s);
strcat(p, "\n");
setup_string_in_str(&input, p);
rcode = parse_stream_outer(&input, flag);
free(p);
return rcode;
} else {
#endif
setup_string_in_str(&input, s);
return parse_stream_outer(&input, flag);
#ifdef __U_BOOT__
}
#endif
}
#ifndef __U_BOOT__
static int parse_file_outer(FILE *f)
#else
int parse_file_outer(void)
#endif
{
int rcode;
struct in_str input;
#ifndef __U_BOOT__
setup_file_in_str(&input, f);
#else
setup_file_in_str(&input);
#endif
rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
return rcode;
}
#ifdef __U_BOOT__
#ifdef CONFIG_NEEDS_MANUAL_RELOC
static void u_boot_hush_reloc(void)
{
unsigned long addr;
struct reserved_combo *r;
for (r=reserved_list; r<reserved_list+NRES; r++) {
addr = (ulong) (r->literal) + gd->reloc_off;
r->literal = (char *)addr;
}
}
#endif
int u_boot_hush_start(void)
{
if (top_vars == NULL) {
top_vars = malloc(sizeof(struct variables));
top_vars->name = "HUSH_VERSION";
top_vars->value = "0.01";
top_vars->next = 0;
top_vars->flg_export = 0;
top_vars->flg_read_only = 1;
#ifdef CONFIG_NEEDS_MANUAL_RELOC
u_boot_hush_reloc();
#endif
}
return 0;
}
static void *xmalloc(size_t size)
{
void *p = NULL;
if (!(p = malloc(size))) {
printf("ERROR : memory not allocated\n");
for(;;);
}
return p;
}
static void *xrealloc(void *ptr, size_t size)
{
void *p = NULL;
if (!(p = realloc(ptr, size))) {
printf("ERROR : memory not allocated\n");
for(;;);
}
return p;
}
#endif /* __U_BOOT__ */
#ifndef __U_BOOT__
/* Make sure we have a controlling tty. If we get started under a job
* aware app (like bash for example), make sure we are now in charge so
* we don't fight over who gets the foreground */
static void setup_job_control(void)
{
static pid_t shell_pgrp;
/* Loop until we are in the foreground. */
while (tcgetpgrp (shell_terminal) != (shell_pgrp = getpgrp ()))
kill (- shell_pgrp, SIGTTIN);
/* Ignore interactive and job-control signals. */
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTERM, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
/* Put ourselves in our own process group. */
setsid();
shell_pgrp = getpid ();
setpgid (shell_pgrp, shell_pgrp);
/* Grab control of the terminal. */
tcsetpgrp(shell_terminal, shell_pgrp);
}
int hush_main(int argc, char * const *argv)
{
int opt;
FILE *input;
char **e = environ;
/* XXX what should these be while sourcing /etc/profile? */
global_argc = argc;
global_argv = argv;
/* (re?) initialize globals. Sometimes hush_main() ends up calling
* hush_main(), therefore we cannot rely on the BSS to zero out this
* stuff. Reset these to 0 every time. */
ifs = NULL;
/* map[] is taken care of with call to update_ifs_map() */
fake_mode = 0;
interactive = 0;
close_me_head = NULL;
last_bg_pid = 0;
job_list = NULL;
last_jobid = 0;
/* Initialize some more globals to non-zero values */
set_cwd();
#ifdef CONFIG_FEATURE_COMMAND_EDITING
cmdedit_set_initial_prompt();
#else
PS1 = NULL;
#endif
PS2 = "> ";
/* initialize our shell local variables with the values
* currently living in the environment */
if (e) {
for (; *e; e++)
set_local_var(*e, 2); /* without call putenv() */
}
last_return_code=EXIT_SUCCESS;
if (argv[0] && argv[0][0] == '-') {
debug_printf("\nsourcing /etc/profile\n");
if ((input = fopen("/etc/profile", "r")) != NULL) {
mark_open(fileno(input));
parse_file_outer(input);
mark_closed(fileno(input));
fclose(input);
}
}
input=stdin;
while ((opt = getopt(argc, argv, "c:xif")) > 0) {
switch (opt) {
case 'c':
{
global_argv = argv+optind;
global_argc = argc-optind;
opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
goto final_return;
}
break;
case 'i':
interactive++;
break;
case 'f':
fake_mode++;
break;
default:
#ifndef BB_VER
fprintf(stderr, "Usage: sh [FILE]...\n"
" or: sh -c command [args]...\n\n");
exit(EXIT_FAILURE);
#else
show_usage();
#endif
}
}
/* A shell is interactive if the `-i' flag was given, or if all of
* the following conditions are met:
* no -c command
* no arguments remaining or the -s flag given
* standard input is a terminal
* standard output is a terminal
* Refer to Posix.2, the description of the `sh' utility. */
if (argv[optind]==NULL && input==stdin &&
isatty(fileno(stdin)) && isatty(fileno(stdout))) {
interactive++;
}
debug_printf("\ninteractive=%d\n", interactive);
if (interactive) {
/* Looks like they want an interactive shell */
#ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
printf( "\n\n" BB_BANNER " hush - the humble shell v0.01 (testing)\n");
printf( "Enter 'help' for a list of built-in commands.\n\n");
#endif
setup_job_control();
}
if (argv[optind]==NULL) {
opt=parse_file_outer(stdin);
goto final_return;
}
debug_printf("\nrunning script '%s'\n", argv[optind]);
global_argv = argv+optind;
global_argc = argc-optind;
input = xfopen(argv[optind], "r");
opt = parse_file_outer(input);
#ifdef CONFIG_FEATURE_CLEAN_UP
fclose(input);
if (cwd && cwd != unknown)
free((char*)cwd);
{
struct variables *cur, *tmp;
for(cur = top_vars; cur; cur = tmp) {
tmp = cur->next;
if (!cur->flg_read_only) {
free(cur->name);
free(cur->value);
free(cur);
}
}
}
#endif
final_return:
return(opt?opt:last_return_code);
}
#endif
static char *insert_var_value(char *inp)
{
int res_str_len = 0;
int len;
int done = 0;
char *p, *p1, *res_str = NULL;
while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
if (p != inp) {
len = p - inp;
res_str = xrealloc(res_str, (res_str_len + len));
strncpy((res_str + res_str_len), inp, len);
res_str_len += len;
}
inp = ++p;
p = strchr(inp, SPECIAL_VAR_SYMBOL);
*p = '\0';
if ((p1 = lookup_param(inp))) {
len = res_str_len + strlen(p1);
res_str = xrealloc(res_str, (1 + len));
strcpy((res_str + res_str_len), p1);
res_str_len = len;
}
*p = SPECIAL_VAR_SYMBOL;
inp = ++p;
done = 1;
}
if (done) {
res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
strcpy((res_str + res_str_len), inp);
while ((p = strchr(res_str, '\n'))) {
*p = ' ';
}
}
return (res_str == NULL) ? inp : res_str;
}
static char **make_list_in(char **inp, char *name)
{
int len, i;
int name_len = strlen(name);
int n = 0;
char **list;
char *p1, *p2, *p3;
/* create list of variable values */
list = xmalloc(sizeof(*list));
for (i = 0; inp[i]; i++) {
p3 = insert_var_value(inp[i]);
p1 = p3;
while (*p1) {
if ((*p1 == ' ')) {
p1++;
continue;
}
if ((p2 = strchr(p1, ' '))) {
len = p2 - p1;
} else {
len = strlen(p1);
p2 = p1 + len;
}
/* we use n + 2 in realloc for list,because we add
* new element and then we will add NULL element */
list = xrealloc(list, sizeof(*list) * (n + 2));
list[n] = xmalloc(2 + name_len + len);
strcpy(list[n], name);
strcat(list[n], "=");
strncat(list[n], p1, len);
list[n++][name_len + len + 1] = '\0';
p1 = p2;
}
if (p3 != inp[i]) free(p3);
}
list[n] = NULL;
return list;
}
/* Make new string for parser */
static char * make_string(char ** inp)
{
char *p;
char *str = NULL;
int n;
int len = 2;
for (n = 0; inp[n]; n++) {
p = insert_var_value(inp[n]);
str = xrealloc(str, (len + strlen(p)));
if (n) {
strcat(str, " ");
} else {
*str = '\0';
}
strcat(str, p);
len = strlen(str) + 3;
if (p != inp[n]) free(p);
}
len = strlen(str);
*(str + len) = '\n';
*(str + len + 1) = '\0';
return str;
}
#ifdef __U_BOOT__
int do_showvar (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int i, k;
int rcode = 0;
struct variables *cur;
if (argc == 1) { /* Print all env variables */
for (cur = top_vars; cur; cur = cur->next) {
printf ("%s=%s\n", cur->name, cur->value);
if (ctrlc ()) {
puts ("\n ** Abort\n");
return 1;
}
}
return 0;
}
for (i = 1; i < argc; ++i) { /* print single env variables */
char *name = argv[i];
k = -1;
for (cur = top_vars; cur; cur = cur->next) {
if(strcmp (cur->name, name) == 0) {
k = 0;
printf ("%s=%s\n", cur->name, cur->value);
}
if (ctrlc ()) {
puts ("\n ** Abort\n");
return 1;
}
}
if (k < 0) {
printf ("## Error: \"%s\" not defined\n", name);
rcode ++;
}
}
return rcode;
}
U_BOOT_CMD(
showvar, CONFIG_SYS_MAXARGS, 1, do_showvar,
"print local hushshell variables",
"\n - print values of all hushshell variables\n"
"showvar name ...\n"
" - print value of hushshell variable 'name'"
);
#endif
/****************************************************************************/
|
1001-study-uboot
|
common/hush.c
|
C
|
gpl3
| 93,902
|
/*
* 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_test(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char * const *ap;
int left, adv, expr, last_expr, neg, last_cmp;
/* args? */
if (argc < 3)
return 1;
#if 0
{
printf("test:");
left = 1;
while (argv[left])
printf(" %s", argv[left++]);
}
#endif
last_expr = 0;
left = argc - 1; ap = argv + 1;
if (left > 0 && strcmp(ap[0], "!") == 0) {
neg = 1;
ap++;
left--;
} else
neg = 0;
expr = -1;
last_cmp = -1;
last_expr = -1;
while (left > 0) {
if (strcmp(ap[0], "-o") == 0 || strcmp(ap[0], "-a") == 0)
adv = 1;
else if (strcmp(ap[0], "-z") == 0 || strcmp(ap[0], "-n") == 0)
adv = 2;
else
adv = 3;
if (left < adv) {
expr = 1;
break;
}
if (adv == 1) {
if (strcmp(ap[0], "-o") == 0) {
last_expr = expr;
last_cmp = 0;
} else if (strcmp(ap[0], "-a") == 0) {
last_expr = expr;
last_cmp = 1;
} else {
expr = 1;
break;
}
}
if (adv == 2) {
if (strcmp(ap[0], "-z") == 0)
expr = strlen(ap[1]) == 0 ? 1 : 0;
else if (strcmp(ap[0], "-n") == 0)
expr = strlen(ap[1]) == 0 ? 0 : 1;
else {
expr = 1;
break;
}
if (last_cmp == 0)
expr = last_expr || expr;
else if (last_cmp == 1)
expr = last_expr && expr;
last_cmp = -1;
}
if (adv == 3) {
if (strcmp(ap[1], "=") == 0)
expr = strcmp(ap[0], ap[2]) == 0;
else if (strcmp(ap[1], "!=") == 0)
expr = strcmp(ap[0], ap[2]) != 0;
else if (strcmp(ap[1], ">") == 0)
expr = strcmp(ap[0], ap[2]) > 0;
else if (strcmp(ap[1], "<") == 0)
expr = strcmp(ap[0], ap[2]) < 0;
else if (strcmp(ap[1], "-eq") == 0)
expr = simple_strtol(ap[0], NULL, 10) == simple_strtol(ap[2], NULL, 10);
else if (strcmp(ap[1], "-ne") == 0)
expr = simple_strtol(ap[0], NULL, 10) != simple_strtol(ap[2], NULL, 10);
else if (strcmp(ap[1], "-lt") == 0)
expr = simple_strtol(ap[0], NULL, 10) < simple_strtol(ap[2], NULL, 10);
else if (strcmp(ap[1], "-le") == 0)
expr = simple_strtol(ap[0], NULL, 10) <= simple_strtol(ap[2], NULL, 10);
else if (strcmp(ap[1], "-gt") == 0)
expr = simple_strtol(ap[0], NULL, 10) > simple_strtol(ap[2], NULL, 10);
else if (strcmp(ap[1], "-ge") == 0)
expr = simple_strtol(ap[0], NULL, 10) >= simple_strtol(ap[2], NULL, 10);
else {
expr = 1;
break;
}
if (last_cmp == 0)
expr = last_expr || expr;
else if (last_cmp == 1)
expr = last_expr && expr;
last_cmp = -1;
}
ap += adv; left -= adv;
}
if (neg)
expr = !expr;
expr = !expr;
debug (": returns %d\n", expr);
return expr;
}
U_BOOT_CMD(
test, CONFIG_SYS_MAXARGS, 1, do_test,
"minimal test like /bin/sh",
"[args..]"
);
int do_false(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return 1;
}
U_BOOT_CMD(
false, CONFIG_SYS_MAXARGS, 1, do_false,
"do nothing, unsuccessfully",
NULL
);
int do_true(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
return 0;
}
U_BOOT_CMD(
true, CONFIG_SYS_MAXARGS, 1, do_true,
"do nothing, successfully",
NULL
);
|
1001-study-uboot
|
common/cmd_test.c
|
C
|
gpl3
| 3,956
|
/*
* (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>
static int mmc_nspi (const char *);
int do_dataflash_mmc_mux (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
switch (argc) {
case 2: /* on / off */
switch (mmc_nspi (argv[1])) {
case 0: AT91F_SelectSPI ();
break;
case 1: AT91F_SelectMMC ();
break;
}
case 1: /* get status */
printf ("Mux is configured to be %s\n",
AT91F_GetMuxStatus () ? "MMC" : "SPI");
return 0;
default:
return cmd_usage(cmdtp);
}
return 0;
}
static int mmc_nspi (const char *s)
{
if (strcmp (s, "mmc") == 0) {
return 1;
} else if (strcmp (s, "spi") == 0) {
return 0;
}
return -1;
}
U_BOOT_CMD(
dataflash_mmc_mux, 2, 1, do_dataflash_mmc_mux,
"enable or disable MMC or SPI\n",
"[mmc, spi]\n"
" - enable or disable MMC or SPI"
);
|
1001-study-uboot
|
common/cmd_dataflash_mmc_mux.c
|
C
|
gpl3
| 1,687
|
/*
* (C) Copyright 2003
* Kyle Harris, kharris@nexus-tech.net
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <mmc.h>
static int curr_device = -1;
#ifndef CONFIG_GENERIC_MMC
int do_mmc (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int dev;
if (argc < 2)
return cmd_usage(cmdtp);
if (strcmp(argv[1], "init") == 0) {
if (argc == 2) {
if (curr_device < 0)
dev = 1;
else
dev = curr_device;
} else if (argc == 3) {
dev = (int)simple_strtoul(argv[2], NULL, 10);
} else {
return cmd_usage(cmdtp);
}
if (mmc_legacy_init(dev) != 0) {
puts("No MMC card found\n");
return 1;
}
curr_device = dev;
printf("mmc%d is available\n", curr_device);
} else if (strcmp(argv[1], "device") == 0) {
if (argc == 2) {
if (curr_device < 0) {
puts("No MMC device available\n");
return 1;
}
} else if (argc == 3) {
dev = (int)simple_strtoul(argv[2], NULL, 10);
#ifdef CONFIG_SYS_MMC_SET_DEV
if (mmc_set_dev(dev) != 0)
return 1;
#endif
curr_device = dev;
} else {
return cmd_usage(cmdtp);
}
printf("mmc%d is current device\n", curr_device);
} else {
return cmd_usage(cmdtp);
}
return 0;
}
U_BOOT_CMD(
mmc, 3, 1, do_mmc,
"MMC sub-system",
"init [dev] - init MMC sub system\n"
"mmc device [dev] - show or set current device"
);
#else /* !CONFIG_GENERIC_MMC */
enum mmc_state {
MMC_INVALID,
MMC_READ,
MMC_WRITE,
MMC_ERASE,
};
static void print_mmcinfo(struct mmc *mmc)
{
printf("Device: %s\n", mmc->name);
printf("Manufacturer ID: %x\n", mmc->cid[0] >> 24);
printf("OEM: %x\n", (mmc->cid[0] >> 8) & 0xffff);
printf("Name: %c%c%c%c%c \n", mmc->cid[0] & 0xff,
(mmc->cid[1] >> 24), (mmc->cid[1] >> 16) & 0xff,
(mmc->cid[1] >> 8) & 0xff, mmc->cid[1] & 0xff);
printf("Tran Speed: %d\n", mmc->tran_speed);
printf("Rd Block Len: %d\n", mmc->read_bl_len);
printf("%s version %d.%d\n", IS_SD(mmc) ? "SD" : "MMC",
(mmc->version >> 4) & 0xf, mmc->version & 0xf);
printf("High Capacity: %s\n", mmc->high_capacity ? "Yes" : "No");
puts("Capacity: ");
print_size(mmc->capacity, "\n");
printf("Bus Width: %d-bit\n", mmc->bus_width);
}
int do_mmcinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
struct mmc *mmc;
if (curr_device < 0) {
if (get_mmc_num() > 0)
curr_device = 0;
else {
puts("No MMC device available\n");
return 1;
}
}
mmc = find_mmc_device(curr_device);
if (mmc) {
mmc_init(mmc);
print_mmcinfo(mmc);
return 0;
} else {
printf("no mmc device at slot %x\n", curr_device);
return 1;
}
}
U_BOOT_CMD(
mmcinfo, 1, 0, do_mmcinfo,
"display MMC info",
" - device number of the device to dislay info of\n"
""
);
int do_mmcops(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
enum mmc_state state;
if (argc < 2)
return cmd_usage(cmdtp);
if (curr_device < 0) {
if (get_mmc_num() > 0)
curr_device = 0;
else {
puts("No MMC device available\n");
return 1;
}
}
if (strcmp(argv[1], "rescan") == 0) {
struct mmc *mmc = find_mmc_device(curr_device);
if (!mmc) {
printf("no mmc device at slot %x\n", curr_device);
return 1;
}
mmc->has_init = 0;
if (mmc_init(mmc))
return 1;
else
return 0;
} else if (strncmp(argv[1], "part", 4) == 0) {
block_dev_desc_t *mmc_dev;
struct mmc *mmc = find_mmc_device(curr_device);
if (!mmc) {
printf("no mmc device at slot %x\n", curr_device);
return 1;
}
mmc_init(mmc);
mmc_dev = mmc_get_dev(curr_device);
if (mmc_dev != NULL &&
mmc_dev->type != DEV_TYPE_UNKNOWN) {
print_part(mmc_dev);
return 0;
}
puts("get mmc type error!\n");
return 1;
} else if (strcmp(argv[1], "list") == 0) {
print_mmc_devices('\n');
return 0;
} else if (strcmp(argv[1], "dev") == 0) {
int dev, part = -1;
struct mmc *mmc;
if (argc == 2)
dev = curr_device;
else if (argc == 3)
dev = simple_strtoul(argv[2], NULL, 10);
else if (argc == 4) {
dev = (int)simple_strtoul(argv[2], NULL, 10);
part = (int)simple_strtoul(argv[3], NULL, 10);
if (part > PART_ACCESS_MASK) {
printf("#part_num shouldn't be larger"
" than %d\n", PART_ACCESS_MASK);
return 1;
}
} else
return cmd_usage(cmdtp);
mmc = find_mmc_device(dev);
if (!mmc) {
printf("no mmc device at slot %x\n", dev);
return 1;
}
mmc_init(mmc);
if (part != -1) {
int ret;
if (mmc->part_config == MMCPART_NOAVAILABLE) {
printf("Card doesn't support part_switch\n");
return 1;
}
if (part != mmc->part_num) {
ret = mmc_switch_part(dev, part);
if (!ret)
mmc->part_num = part;
printf("switch to partions #%d, %s\n",
part, (!ret) ? "OK" : "ERROR");
}
}
curr_device = dev;
if (mmc->part_config == MMCPART_NOAVAILABLE)
printf("mmc%d is current device\n", curr_device);
else
printf("mmc%d(part %d) is current device\n",
curr_device, mmc->part_num);
return 0;
}
if (strcmp(argv[1], "read") == 0)
state = MMC_READ;
else if (strcmp(argv[1], "write") == 0)
state = MMC_WRITE;
else if (strcmp(argv[1], "erase") == 0)
state = MMC_ERASE;
else
state = MMC_INVALID;
if (state != MMC_INVALID) {
struct mmc *mmc = find_mmc_device(curr_device);
int idx = 2;
u32 blk, cnt, n;
void *addr;
if (state != MMC_ERASE) {
addr = (void *)simple_strtoul(argv[idx], NULL, 16);
++idx;
} else
addr = 0;
blk = simple_strtoul(argv[idx], NULL, 16);
cnt = simple_strtoul(argv[idx + 1], NULL, 16);
if (!mmc) {
printf("no mmc device at slot %x\n", curr_device);
return 1;
}
printf("\nMMC %s: dev # %d, block # %d, count %d ... ",
argv[1], curr_device, blk, cnt);
mmc_init(mmc);
switch (state) {
case MMC_READ:
n = mmc->block_dev.block_read(curr_device, blk,
cnt, addr);
/* flush cache after read */
flush_cache((ulong)addr, cnt * 512); /* FIXME */
break;
case MMC_WRITE:
n = mmc->block_dev.block_write(curr_device, blk,
cnt, addr);
break;
case MMC_ERASE:
n = mmc->block_dev.block_erase(curr_device, blk, cnt);
break;
default:
BUG();
}
printf("%d blocks %s: %s\n",
n, argv[1], (n == cnt) ? "OK" : "ERROR");
return (n == cnt) ? 0 : 1;
}
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
mmc, 6, 1, do_mmcops,
"MMC sub system",
"read addr blk# cnt\n"
"mmc write addr blk# cnt\n"
"mmc erase blk# cnt\n"
"mmc rescan\n"
"mmc part - lists available partition on current mmc device\n"
"mmc dev [dev] [part] - show or set current mmc device [partition]\n"
"mmc list - lists available devices");
#endif
|
1001-study-uboot
|
common/cmd_mmc.c
|
C
|
gpl3
| 7,346
|
/*
* U-boot - ldrinfo
*
* Copyright (c) 2010 Analog Devices Inc.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* Licensed under the GPL-2 or later.
*/
#include <config.h>
#include <common.h>
#include <command.h>
#include <asm/blackfin.h>
#include <asm/mach-common/bits/bootrom.h>
static uint32_t ldrinfo_header(const void *addr)
{
uint32_t skip = 0;
#if defined(__ADSPBF561__)
/* BF56x has a 4 byte global header */
uint32_t header, sign;
static const char * const spi_speed[] = {
"500K", "1M", "2M", "??",
};
memcpy(&header, addr, sizeof(header));
sign = (header & GFLAG_56X_SIGN_MASK) >> GFLAG_56X_SIGN_SHIFT;
printf("Header: %08X ( %s-bit-flash wait:%i hold:%i spi:%s %s)\n",
header,
(header & GFLAG_56X_16BIT_FLASH) ? "16" : "8",
(header & GFLAG_56X_WAIT_MASK) >> GFLAG_56X_WAIT_SHIFT,
(header & GFLAG_56X_HOLD_MASK) >> GFLAG_56X_HOLD_SHIFT,
spi_speed[(header & GFLAG_56X_SPI_MASK) >> GFLAG_56X_SPI_SHIFT],
sign == GFLAG_56X_SIGN_MAGIC ? "" : "!!hdrsign!! ");
skip = 4;
#endif
/* |Block @ 12345678: 12345678 12345678 12345678 12345678 | */
#if defined(__ADSPBF531__) || defined(__ADSPBF532__) || defined(__ADSPBF533__) || \
defined(__ADSPBF534__) || defined(__ADSPBF536__) || defined(__ADSPBF537__) || \
defined(__ADSPBF538__) || defined(__ADSPBF539__) || defined(__ADSPBF561__)
printf(" Address Count Flags\n");
#else
printf(" BCode Address Count Argument\n");
#endif
return skip;
}
struct ldr_flag {
uint16_t flag;
const char *desc;
};
static uint32_t ldrinfo_block(const void *base_addr)
{
uint32_t count;
printf("Block @ %08X: ", (uint32_t)base_addr);
#if defined(__ADSPBF531__) || defined(__ADSPBF532__) || defined(__ADSPBF533__) || \
defined(__ADSPBF534__) || defined(__ADSPBF536__) || defined(__ADSPBF537__) || \
defined(__ADSPBF538__) || defined(__ADSPBF539__) || defined(__ADSPBF561__)
uint32_t addr, pval;
uint16_t flags;
int i;
static const struct ldr_flag ldr_flags[] = {
{ BFLAG_53X_ZEROFILL, "zerofill" },
{ BFLAG_53X_RESVECT, "resvect" },
{ BFLAG_53X_INIT, "init" },
{ BFLAG_53X_IGNORE, "ignore" },
{ BFLAG_53X_COMPRESSED, "compressed"},
{ BFLAG_53X_FINAL, "final" },
};
memcpy(&addr, base_addr, sizeof(addr));
memcpy(&count, base_addr+4, sizeof(count));
memcpy(&flags, base_addr+8, sizeof(flags));
printf("%08X %08X %04X ( ", addr, count, flags);
for (i = 0; i < ARRAY_SIZE(ldr_flags); ++i)
if (flags & ldr_flags[i].flag)
printf("%s ", ldr_flags[i].desc);
pval = (flags & BFLAG_53X_PFLAG_MASK) >> BFLAG_53X_PFLAG_SHIFT;
if (pval)
printf("gpio%i ", pval);
pval = (flags & BFLAG_53X_PPORT_MASK) >> BFLAG_53X_PPORT_SHIFT;
if (pval)
printf("port%c ", 'e' + pval);
if (flags & BFLAG_53X_ZEROFILL)
count = 0;
if (flags & BFLAG_53X_FINAL)
count = 0;
else
count += sizeof(addr) + sizeof(count) + sizeof(flags);
#else
const uint8_t *raw8 = base_addr;
uint32_t bcode, addr, arg, sign, chk;
int i;
static const struct ldr_flag ldr_flags[] = {
{ BFLAG_SAFE, "safe" },
{ BFLAG_AUX, "aux" },
{ BFLAG_FILL, "fill" },
{ BFLAG_QUICKBOOT, "quickboot" },
{ BFLAG_CALLBACK, "callback" },
{ BFLAG_INIT, "init" },
{ BFLAG_IGNORE, "ignore" },
{ BFLAG_INDIRECT, "indirect" },
{ BFLAG_FIRST, "first" },
{ BFLAG_FINAL, "final" },
};
memcpy(&bcode, base_addr, sizeof(bcode));
memcpy(&addr, base_addr+4, sizeof(addr));
memcpy(&count, base_addr+8, sizeof(count));
memcpy(&arg, base_addr+12, sizeof(arg));
printf("%08X %08X %08X %08X ( ", bcode, addr, count, arg);
if (addr % 4)
printf("!!addralgn!! ");
if (count % 4)
printf("!!cntalgn!! ");
sign = (bcode & BFLAG_HDRSIGN_MASK) >> BFLAG_HDRSIGN_SHIFT;
if (sign != BFLAG_HDRSIGN_MAGIC)
printf("!!hdrsign!! ");
chk = 0;
for (i = 0; i < 16; ++i)
chk ^= raw8[i];
if (chk)
printf("!!hdrchk!! ");
printf("dma:%i ", bcode & BFLAG_DMACODE_MASK);
for (i = 0; i < ARRAY_SIZE(ldr_flags); ++i)
if (bcode & ldr_flags[i].flag)
printf("%s ", ldr_flags[i].desc);
if (bcode & BFLAG_FILL)
count = 0;
if (bcode & BFLAG_FINAL)
count = 0;
else
count += sizeof(bcode) + sizeof(addr) + sizeof(count) + sizeof(arg);
#endif
printf(")\n");
return count;
}
static int do_ldrinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
const void *addr;
uint32_t skip;
/* Get the address */
if (argc < 2)
addr = (void *)load_addr;
else
addr = (void *)simple_strtoul(argv[1], NULL, 16);
/* Walk the LDR */
addr += ldrinfo_header(addr);
do {
skip = ldrinfo_block(addr);
addr += skip;
} while (skip);
return 0;
}
U_BOOT_CMD(
ldrinfo, 2, 0, do_ldrinfo,
"validate ldr image in memory",
"[addr]\n"
);
|
1001-study-uboot
|
common/cmd_ldrinfo.c
|
C
|
gpl3
| 4,845
|
#include <common.h>
#include <config.h>
#include <command.h>
#ifdef YAFFS2_DEBUG
#define PRINTF(fmt,args...) printf (fmt ,##args)
#else
#define PRINTF(fmt,args...)
#endif
extern void cmd_yaffs_mount(char *mp);
extern void cmd_yaffs_umount(char *mp);
extern void cmd_yaffs_read_file(char *fn);
extern void cmd_yaffs_write_file(char *fn,char bval,int sizeOfFile);
extern void cmd_yaffs_ls(const char *mountpt, int longlist);
extern void cmd_yaffs_mwrite_file(char *fn, char *addr, int size);
extern void cmd_yaffs_mread_file(char *fn, char *addr);
extern void cmd_yaffs_mkdir(const char *dir);
extern void cmd_yaffs_rmdir(const char *dir);
extern void cmd_yaffs_rm(const char *path);
extern void cmd_yaffs_mv(const char *oldPath, const char *newPath);
extern int yaffs_DumpDevStruct(const char *path);
int do_ymount (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *mtpoint = argv[1];
cmd_yaffs_mount(mtpoint);
return(0);
}
int do_yumount (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *mtpoint = argv[1];
cmd_yaffs_umount(mtpoint);
return(0);
}
int do_yls (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *dirname = argv[argc-1];
cmd_yaffs_ls(dirname, (argc>2)?1:0);
return(0);
}
int do_yrd (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = argv[1];
printf ("Reading file %s ", filename);
cmd_yaffs_read_file(filename);
printf ("done\n");
return(0);
}
int do_ywr (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = argv[1];
ulong value = simple_strtoul(argv[2], NULL, 16);
ulong numValues = simple_strtoul(argv[3], NULL, 16);
printf ("Writing value (%lx) %lx times to %s... ", value, numValues, filename);
cmd_yaffs_write_file(filename,value,numValues);
printf ("done\n");
return(0);
}
int do_yrdm (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = argv[1];
ulong addr = simple_strtoul(argv[2], NULL, 16);
cmd_yaffs_mread_file(filename, (char *)addr);
return(0);
}
int do_ywrm (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = argv[1];
ulong addr = simple_strtoul(argv[2], NULL, 16);
ulong size = simple_strtoul(argv[3], NULL, 16);
cmd_yaffs_mwrite_file(filename, (char *)addr, size);
return(0);
}
int do_ymkdir (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *dirname = argv[1];
cmd_yaffs_mkdir(dirname);
return(0);
}
int do_yrmdir (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *dirname = argv[1];
cmd_yaffs_rmdir(dirname);
return(0);
}
int do_yrm (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *path = argv[1];
cmd_yaffs_rm(path);
return(0);
}
int do_ymv (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *oldPath = argv[1];
char *newPath = argv[2];
cmd_yaffs_mv(newPath, oldPath);
return(0);
}
int do_ydump (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *dirname = argv[1];
if (yaffs_DumpDevStruct(dirname) != 0)
printf("yaffs_DumpDevStruct returning error when dumping path: , %s\n", dirname);
return 0;
}
U_BOOT_CMD(
ymount, 3, 0, do_ymount,
"mount yaffs",
""
);
U_BOOT_CMD(
yumount, 3, 0, do_yumount,
"unmount yaffs",
""
);
U_BOOT_CMD(
yls, 4, 0, do_yls,
"yaffs ls",
"[-l] name"
);
U_BOOT_CMD(
yrd, 2, 0, do_yrd,
"read file from yaffs",
"filename"
);
U_BOOT_CMD(
ywr, 4, 0, do_ywr,
"write file to yaffs",
"filename value num_vlues"
);
U_BOOT_CMD(
yrdm, 3, 0, do_yrdm,
"read file to memory from yaffs",
"filename offset"
);
U_BOOT_CMD(
ywrm, 4, 0, do_ywrm,
"write file from memory to yaffs",
"filename offset size"
);
U_BOOT_CMD(
ymkdir, 2, 0, do_ymkdir,
"YAFFS mkdir",
"dirname"
);
U_BOOT_CMD(
yrmdir, 2, 0, do_yrmdir,
"YAFFS rmdir",
"dirname"
);
U_BOOT_CMD(
yrm, 2, 0, do_yrm,
"YAFFS rm",
"path"
);
U_BOOT_CMD(
ymv, 4, 0, do_ymv,
"YAFFS mv",
"oldPath newPath"
);
U_BOOT_CMD(
ydump, 2, 0, do_ydump,
"YAFFS device struct",
"dirname"
);
|
1001-study-uboot
|
common/cmd_yaffs2.c
|
C
|
gpl3
| 4,330
|
/*
* (C) Copyright 2011
* Andreas Pretzsch, carpe noctem engineering, apr@cn-eng.de
*
* This file is released under the terms of GPL v2 and any later version.
* See the file COPYING in the root directory of the source tree for details.
*/
#include <common.h>
#include <command.h>
#if !defined(CONFIG_UPDATE_TFTP)
#error "CONFIG_UPDATE_TFTP required"
#endif
extern int update_tftp(ulong addr);
static int do_fitupd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr = 0UL;
if (argc > 2)
return cmd_usage(cmdtp);
if (argc == 2)
addr = simple_strtoul(argv[1], NULL, 16);
return update_tftp(addr);
}
U_BOOT_CMD(fitupd, 2, 0, do_fitupd,
"update from FIT image",
"[addr]\n"
"\t- run update from FIT image at addr\n"
"\t or from tftp 'updatefile'"
);
|
1001-study-uboot
|
common/cmd_fitupd.c
|
C
|
gpl3
| 792
|
/*
* (C) Copyright 2001
* Kyle Harris, kharris@nexus-tech.net
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* The "source" command allows to define "script images", i. e. files
* that contain command sequences that can be executed by the command
* interpreter. It returns the exit status of the last command
* executed from the script. This is very similar to running a shell
* script in a UNIX shell, hence the name for the command.
*/
/* #define DEBUG */
#include <common.h>
#include <command.h>
#include <image.h>
#include <malloc.h>
#include <asm/byteorder.h>
#if defined(CONFIG_8xx)
#include <mpc8xx.h>
#endif
#ifdef CONFIG_SYS_HUSH_PARSER
#include <hush.h>
#endif
int
source (ulong addr, const char *fit_uname)
{
ulong len;
image_header_t *hdr;
ulong *data;
char *cmd;
int rcode = 0;
int verify;
#if defined(CONFIG_FIT)
const void* fit_hdr;
int noffset;
const void *fit_data;
size_t fit_len;
#endif
verify = getenv_yesno ("verify");
switch (genimg_get_format ((void *)addr)) {
case IMAGE_FORMAT_LEGACY:
hdr = (image_header_t *)addr;
if (!image_check_magic (hdr)) {
puts ("Bad magic number\n");
return 1;
}
if (!image_check_hcrc (hdr)) {
puts ("Bad header crc\n");
return 1;
}
if (verify) {
if (!image_check_dcrc (hdr)) {
puts ("Bad data crc\n");
return 1;
}
}
if (!image_check_type (hdr, IH_TYPE_SCRIPT)) {
puts ("Bad image type\n");
return 1;
}
/* get length of script */
data = (ulong *)image_get_data (hdr);
if ((len = uimage_to_cpu (*data)) == 0) {
puts ("Empty Script\n");
return 1;
}
/*
* scripts are just multi-image files with one component, seek
* past the zero-terminated sequence of image lengths to get
* to the actual image data
*/
while (*data++);
break;
#if defined(CONFIG_FIT)
case IMAGE_FORMAT_FIT:
if (fit_uname == NULL) {
puts ("No FIT subimage unit name\n");
return 1;
}
fit_hdr = (const void *)addr;
if (!fit_check_format (fit_hdr)) {
puts ("Bad FIT image format\n");
return 1;
}
/* get script 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;
}
if (!fit_image_check_type (fit_hdr, noffset, IH_TYPE_SCRIPT)) {
puts ("Not a image image\n");
return 1;
}
/* verify integrity */
if (verify) {
if (!fit_image_check_hashes (fit_hdr, noffset)) {
puts ("Bad Data Hash\n");
return 1;
}
}
/* get script 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;
}
data = (ulong *)fit_data;
len = (ulong)fit_len;
break;
#endif
default:
puts ("Wrong image format for \"source\" command\n");
return 1;
}
debug ("** Script length: %ld\n", len);
if ((cmd = malloc (len + 1)) == NULL) {
return 1;
}
/* make sure cmd is null terminated */
memmove (cmd, (char *)data, len);
*(cmd + len) = 0;
#ifdef CONFIG_SYS_HUSH_PARSER /*?? */
rcode = parse_string_outer (cmd, FLAG_PARSE_SEMICOLON);
#else
{
char *line = cmd;
char *next = cmd;
/*
* break into individual lines,
* and execute each line;
* terminate on error.
*/
while (*next) {
if (*next == '\n') {
*next = '\0';
/* run only non-empty commands */
if (*line) {
debug ("** exec: \"%s\"\n",
line);
if (run_command (line, 0) < 0) {
rcode = 1;
break;
}
}
line = next + 1;
}
++next;
}
if (rcode == 0 && *line)
rcode = (run_command(line, 0) >= 0);
}
#endif
free (cmd);
return rcode;
}
/**************************************************/
#if defined(CONFIG_CMD_SOURCE)
int
do_source (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
ulong addr;
int rcode;
const char *fit_uname = NULL;
/* Find script image */
if (argc < 2) {
addr = CONFIG_SYS_LOAD_ADDR;
debug ("* source: default load address = 0x%08lx\n", addr);
#if defined(CONFIG_FIT)
} else if (fit_parse_subimage (argv[1], load_addr, &addr, &fit_uname)) {
debug ("* source: subimage '%s' from FIT image at 0x%08lx\n",
fit_uname, addr);
#endif
} else {
addr = simple_strtoul(argv[1], NULL, 16);
debug ("* source: cmdline image address = 0x%08lx\n", addr);
}
printf ("## Executing script at %08lx\n", addr);
rcode = source (addr, fit_uname);
return rcode;
}
U_BOOT_CMD(
source, 2, 0, do_source,
"run script from memory",
"[addr]\n"
"\t- run script starting at addr\n"
"\t- A valid image header must be present"
#if defined(CONFIG_FIT)
"\n"
"For FIT format uImage addr must include subimage\n"
"unit name in the form of addr:<subimg_uname>"
#endif
);
#endif
|
1001-study-uboot
|
common/cmd_source.c
|
C
|
gpl3
| 5,516
|
/*
* (C) Copyright 2000-2002
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <command.h>
#include <net.h>
#include "nfs.h"
#include "bootp.h"
#include "rarp.h"
#include "tftp.h"
#define TIMEOUT 5000UL /* Milliseconds before trying BOOTP again */
#ifndef CONFIG_NET_RETRY_COUNT
# define TIMEOUT_COUNT 5 /* # of timeouts before giving up */
#else
# define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT)
#endif
int RarpTry;
/*
* Handle a RARP received packet.
*/
static void
RarpHandler(uchar *dummi0, unsigned dummi1, IPaddr_t sip, unsigned dummi2,
unsigned dummi3)
{
debug("Got good RARP\n");
net_auto_load();
}
/*
* Timeout on BOOTP request.
*/
static void
RarpTimeout(void)
{
if (RarpTry >= TIMEOUT_COUNT) {
puts ("\nRetry count exceeded; starting again\n");
NetStartAgain ();
} else {
NetSetTimeout (TIMEOUT, RarpTimeout);
RarpRequest ();
}
}
void
RarpRequest (void)
{
int i;
volatile uchar *pkt;
ARP_t * rarp;
printf("RARP broadcast %d\n", ++RarpTry);
pkt = NetTxPacket;
pkt += NetSetEther(pkt, NetBcastAddr, PROT_RARP);
rarp = (ARP_t *)pkt;
rarp->ar_hrd = htons (ARP_ETHER);
rarp->ar_pro = htons (PROT_IP);
rarp->ar_hln = 6;
rarp->ar_pln = 4;
rarp->ar_op = htons (RARPOP_REQUEST);
memcpy (&rarp->ar_data[0], NetOurEther, 6); /* source ET addr */
memcpy (&rarp->ar_data[6], &NetOurIP, 4); /* source IP addr */
memcpy (&rarp->ar_data[10], NetOurEther, 6); /* dest ET addr = source ET addr ??*/
/* dest. IP addr set to broadcast */
for (i = 0; i <= 3; i++) {
rarp->ar_data[16 + i] = 0xff;
}
NetSendPacket(NetTxPacket, (pkt - NetTxPacket) + ARP_HDR_SIZE);
NetSetTimeout(TIMEOUT, RarpTimeout);
NetSetHandler(RarpHandler);
}
|
1001-study-uboot
|
net/rarp.c
|
C
|
gpl3
| 2,523
|
/*
* LiMon - BOOTP/TFTP.
*
* Copyright 1994, 1995, 2000 Neil Russell.
* Copyright 2011 Comelit Group SpA
* Luca Ceresoli <luca.ceresoli@comelit.it>
* (See License)
*/
#ifndef __TFTP_H__
#define __TFTP_H__
/**********************************************************************/
/*
* Global functions and variables.
*/
/* tftp.c */
void TftpStart(enum proto_t protocol); /* Begin TFTP get/put */
#ifdef CONFIG_CMD_TFTPSRV
extern void TftpStartServer(void); /* Wait for incoming TFTP put */
#endif
/**********************************************************************/
#endif /* __TFTP_H__ */
|
1001-study-uboot
|
net/tftp.h
|
C
|
gpl3
| 623
|
/*
* (C) Masami Komiya <mkomiya@sonare.it> 2004
*
* 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, or (at
* your option) any later version.
*/
#ifndef __NFS_H__
#define __NFS_H__
#define SUNRPC_PORT 111
#define PROG_PORTMAP 100000
#define PROG_NFS 100003
#define PROG_MOUNT 100005
#define MSG_CALL 0
#define MSG_REPLY 1
#define PORTMAP_GETPORT 3
#define MOUNT_ADDENTRY 1
#define MOUNT_UMOUNTALL 4
#define NFS_LOOKUP 4
#define NFS_READLINK 5
#define NFS_READ 6
#define NFS_FHSIZE 32
#define NFSERR_PERM 1
#define NFSERR_NOENT 2
#define NFSERR_ACCES 13
#define NFSERR_ISDIR 21
#define NFSERR_INVAL 22
/* Block size used for NFS read accesses. A RPC reply packet (including all
* headers) must fit within a single Ethernet frame to avoid fragmentation.
* However, if CONFIG_IP_DEFRAG is set, the config file may want to use a
* bigger value. In any case, most NFS servers are optimized for a power of 2.
*/
#ifdef CONFIG_NFS_READ_SIZE
#define NFS_READ_SIZE CONFIG_NFS_READ_SIZE
#else
#define NFS_READ_SIZE 1024 /* biggest power of two that fits Ether frame */
#endif
#define NFS_MAXLINKDEPTH 16
struct rpc_t {
union {
uint8_t data[2048];
struct {
uint32_t id;
uint32_t type;
uint32_t rpcvers;
uint32_t prog;
uint32_t vers;
uint32_t proc;
uint32_t data[1];
} call;
struct {
uint32_t id;
uint32_t type;
uint32_t rstatus;
uint32_t verifier;
uint32_t v2;
uint32_t astatus;
uint32_t data[19];
} reply;
} u;
};
extern void NfsStart (void); /* Begin NFS */
/**********************************************************************/
#endif /* __NFS_H__ */
|
1001-study-uboot
|
net/nfs.h
|
C
|
gpl3
| 1,837
|
/*
* DNS support driver
*
* Copyright (c) 2008 Pieter Voorthuijsen <pieter.voorthuijsen@prodrive.nl>
* Copyright (c) 2009 Robin Getz <rgetz@blackfin.uclinux.org>
*
* This is a simple DNS implementation for U-Boot. It will use the first IP
* in the DNS response as NetServerIP. This can then be used for any other
* network related activities.
*
* The packet handling is partly based on TADNS, original copyrights
* follow below.
*
*/
/*
* Copyright (c) 2004-2005 Sergey Lyubka <valenok@gmail.com>
*
* "THE BEER-WARE LICENSE" (Revision 42):
* Sergey Lyubka wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
*/
#include <common.h>
#include <command.h>
#include <net.h>
#include <asm/unaligned.h>
#include "dns.h"
char *NetDNSResolve; /* The host to resolve */
char *NetDNSenvvar; /* The envvar to store the answer in */
static int DnsOurPort;
static void
DnsSend(void)
{
struct header *header;
int n, name_len;
uchar *p, *pkt;
const char *s;
const char *name;
enum dns_query_type qtype = DNS_A_RECORD;
name = NetDNSResolve;
pkt = p = (uchar *)(NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE);
/* Prepare DNS packet header */
header = (struct header *) pkt;
header->tid = 1;
header->flags = htons(0x100); /* standard query */
header->nqueries = htons(1); /* Just one query */
header->nanswers = 0;
header->nauth = 0;
header->nother = 0;
/* Encode DNS name */
name_len = strlen(name);
p = (uchar *) &header->data; /* For encoding host name into packet */
do {
s = strchr(name, '.');
if (!s)
s = name + name_len;
n = s - name; /* Chunk length */
*p++ = n; /* Copy length */
memcpy(p, name, n); /* Copy chunk */
p += n;
if (*s == '.')
n++;
name += n;
name_len -= n;
} while (*s != '\0');
*p++ = 0; /* Mark end of host name */
*p++ = 0; /* Some servers require double null */
*p++ = (unsigned char) qtype; /* Query Type */
*p++ = 0;
*p++ = 1; /* Class: inet, 0x0001 */
n = p - pkt; /* Total packet length */
debug("Packet size %d\n", n);
DnsOurPort = random_port();
NetSendUDPPacket(NetServerEther, NetOurDNSIP, DNS_SERVICE_PORT,
DnsOurPort, n);
debug("DNS packet sent\n");
}
static void
DnsTimeout(void)
{
puts("Timeout\n");
NetState = NETLOOP_FAIL;
}
static void
DnsHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src, unsigned len)
{
struct header *header;
const unsigned char *p, *e, *s;
u16 type, i;
int found, stop, dlen;
char IPStr[22];
IPaddr_t IPAddress;
debug("%s\n", __func__);
if (dest != DnsOurPort)
return;
for (i = 0; i < len; i += 4)
debug("0x%p - 0x%.2x 0x%.2x 0x%.2x 0x%.2x\n",
pkt+i, pkt[i], pkt[i+1], pkt[i+2], pkt[i+3]);
/* We sent one query. We want to have a single answer: */
header = (struct header *) pkt;
if (ntohs(header->nqueries) != 1)
return;
/* Received 0 answers */
if (header->nanswers == 0) {
puts("DNS: host not found\n");
NetState = NETLOOP_SUCCESS;
return;
}
/* Skip host name */
s = &header->data[0];
e = pkt + len;
for (p = s; p < e && *p != '\0'; p++)
continue;
/* We sent query class 1, query type 1 */
if (&p[5] > e || get_unaligned_be16(p+1) != DNS_A_RECORD) {
puts("DNS: response was not an A record\n");
NetState = NETLOOP_SUCCESS;
return;
}
/* Go to the first answer section */
p += 5;
/* Loop through the answers, we want A type answer */
for (found = stop = 0; !stop && &p[12] < e; ) {
/* Skip possible name in CNAME answer */
if (*p != 0xc0) {
while (*p && &p[12] < e)
p++;
p--;
}
debug("Name (Offset in header): %d\n", p[1]);
type = get_unaligned_be16(p+2);
debug("type = %d\n", type);
if (type == DNS_CNAME_RECORD) {
/* CNAME answer. shift to the next section */
debug("Found canonical name\n");
dlen = get_unaligned_be16(p+10);
debug("dlen = %d\n", dlen);
p += 12 + dlen;
} else if (type == DNS_A_RECORD) {
debug("Found A-record\n");
found = stop = 1;
} else {
debug("Unknown type\n");
stop = 1;
}
}
if (found && &p[12] < e) {
dlen = get_unaligned_be16(p+10);
p += 12;
memcpy(&IPAddress, p, 4);
if (p + dlen <= e) {
ip_to_string(IPAddress, IPStr);
printf("%s\n", IPStr);
if (NetDNSenvvar)
setenv(NetDNSenvvar, IPStr);
} else
puts("server responded with invalid IP number\n");
}
NetState = NETLOOP_SUCCESS;
}
void
DnsStart(void)
{
debug("%s\n", __func__);
NetSetTimeout(DNS_TIMEOUT, DnsTimeout);
NetSetHandler(DnsHandler);
DnsSend();
}
|
1001-study-uboot
|
net/dns.c
|
C
|
gpl3
| 4,635
|
/*
* Copied from LiMon - BOOTP.
*
* Copyright 1994, 1995, 2000 Neil Russell.
* (See License)
* Copyright 2000 Paolo Scaffardi
*/
#ifndef __BOOTP_H__
#define __BOOTP_H__
#ifndef __NET_H__
#include <net.h>
#endif /* __NET_H__ */
/**********************************************************************/
/*
* BOOTP header.
*/
#if defined(CONFIG_CMD_DHCP)
#define OPT_SIZE 312 /* Minimum DHCP Options size per RFC2131 - results in 576 byte pkt */
#else
#define OPT_SIZE 64
#endif
typedef struct
{
uchar bp_op; /* Operation */
# define OP_BOOTREQUEST 1
# define OP_BOOTREPLY 2
uchar bp_htype; /* Hardware type */
# define HWT_ETHER 1
uchar bp_hlen; /* Hardware address length */
# define HWL_ETHER 6
uchar bp_hops; /* Hop count (gateway thing) */
ulong bp_id; /* Transaction ID */
ushort bp_secs; /* Seconds since boot */
ushort bp_spare1; /* Alignment */
IPaddr_t bp_ciaddr; /* Client IP address */
IPaddr_t bp_yiaddr; /* Your (client) IP address */
IPaddr_t bp_siaddr; /* Server IP address */
IPaddr_t bp_giaddr; /* Gateway IP address */
uchar bp_chaddr[16]; /* Client hardware address */
char bp_sname[64]; /* Server host name */
char bp_file[128]; /* Boot file name */
char bp_vend[OPT_SIZE]; /* Vendor information */
} Bootp_t;
#define BOOTP_HDR_SIZE sizeof (Bootp_t)
#define BOOTP_SIZE (ETHER_HDR_SIZE + IP_HDR_SIZE + BOOTP_HDR_SIZE)
/**********************************************************************/
/*
* Global functions and variables.
*/
/* bootp.c */
extern ulong BootpID; /* ID of cur BOOTP request */
extern char BootFile[128]; /* Boot file name */
extern int BootpTry;
#ifdef CONFIG_BOOTP_RANDOM_DELAY
extern ulong seed1, seed2; /* seed for random BOOTP delay */
#endif
/* Send a BOOTP request */
extern void BootpRequest (void);
/****************** DHCP Support *********************/
extern void DhcpRequest(void);
/* DHCP States */
typedef enum { INIT,
INIT_REBOOT,
REBOOTING,
SELECTING,
REQUESTING,
REBINDING,
BOUND,
RENEWING } dhcp_state_t;
#define DHCP_DISCOVER 1
#define DHCP_OFFER 2
#define DHCP_REQUEST 3
#define DHCP_DECLINE 4
#define DHCP_ACK 5
#define DHCP_NAK 6
#define DHCP_RELEASE 7
#define SELECT_TIMEOUT 3000UL /* Milliseconds to wait for offers */
/**********************************************************************/
#endif /* __BOOTP_H__ */
|
1001-study-uboot
|
net/bootp.h
|
C
|
gpl3
| 2,438
|
#
# (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 += -DDEBUG
LIB = $(obj)libnet.o
COBJS-$(CONFIG_CMD_NET) += bootp.o
COBJS-$(CONFIG_CMD_DNS) += dns.o
COBJS-$(CONFIG_CMD_NET) += eth.o
COBJS-$(CONFIG_CMD_NET) += net.o
COBJS-$(CONFIG_CMD_NFS) += nfs.o
COBJS-$(CONFIG_CMD_RARP) += rarp.o
COBJS-$(CONFIG_CMD_SNTP) += sntp.o
COBJS-$(CONFIG_CMD_NET) += tftp.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
|
net/Makefile
|
Makefile
|
gpl3
| 1,608
|
/*
* (C) Masami Komiya <mkomiya@sonare.it> 2005
*
* 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, or (at
* your option) any later version.
*/
#ifndef __SNTP_H__
#define __SNTP_H__
#define NTP_SERVICE_PORT 123
#define SNTP_PACKET_LEN 48
/* Leap Indicator */
#define NTP_LI_NOLEAP 0x0
#define NTP_LI_61SECS 0x1
#define NTP_LI_59SECS 0x2
#define NTP_LI_ALARM 0x3
/* Version */
#define NTP_VERSION 4
/* Mode */
#define NTP_MODE_RESERVED 0
#define NTP_MODE_SYMACTIVE 1 /* Symmetric Active */
#define NTP_MODE_SYMPASSIVE 2 /* Symmetric Passive */
#define NTP_MODE_CLIENT 3
#define NTP_MODE_SERVER 4
#define NTP_MODE_BROADCAST 5
#define NTP_MODE_NTPCTRL 6 /* Reserved for NTP control message */
#define NTP_MODE_PRIVATE 7 /* Reserved for private use */
struct sntp_pkt_t {
#if __LITTLE_ENDIAN
uchar mode:3;
uchar vn:3;
uchar li:2;
#else
uchar li:2;
uchar vn:3;
uchar mode:3;
#endif
uchar stratum;
uchar poll;
uchar precision;
uint root_delay;
uint root_dispersion;
uint reference_id;
unsigned long long reference_timestamp;
unsigned long long originate_timestamp;
unsigned long long receive_timestamp;
unsigned long long transmit_timestamp;
};
extern void SntpStart (void); /* Begin SNTP */
#endif /* __SNTP_H__ */
|
1001-study-uboot
|
net/sntp.h
|
C
|
gpl3
| 1,393
|
/*
* Copied from Linux Monitor (LiMon) - Networking.
*
* Copyright 1994 - 2000 Neil Russell.
* (See License)
* Copyright 2000 Roland Borde
* Copyright 2000 Paolo Scaffardi
* Copyright 2000-2002 Wolfgang Denk, wd@denx.de
*/
/*
* General Desription:
*
* The user interface supports commands for BOOTP, RARP, and TFTP.
* Also, we support ARP internally. Depending on available data,
* these interact as follows:
*
* BOOTP:
*
* Prerequisites: - own ethernet address
* We want: - own IP address
* - TFTP server IP address
* - name of bootfile
* Next step: ARP
*
* RARP:
*
* Prerequisites: - own ethernet address
* We want: - own IP address
* - TFTP server IP address
* Next step: ARP
*
* ARP:
*
* Prerequisites: - own ethernet address
* - own IP address
* - TFTP server IP address
* We want: - TFTP server ethernet address
* Next step: TFTP
*
* DHCP:
*
* Prerequisites: - own ethernet address
* We want: - IP, Netmask, ServerIP, Gateway IP
* - bootfilename, lease time
* Next step: - TFTP
*
* TFTP:
*
* Prerequisites: - own ethernet address
* - own IP address
* - TFTP server IP address
* - TFTP server ethernet address
* - name of bootfile (if unknown, we use a default name
* derived from our own IP address)
* We want: - load the boot file
* Next step: none
*
* NFS:
*
* Prerequisites: - own ethernet address
* - own IP address
* - name of bootfile (if unknown, we use a default name
* derived from our own IP address)
* We want: - load the boot file
* Next step: none
*
* SNTP:
*
* Prerequisites: - own ethernet address
* - own IP address
* We want: - network time
* Next step: none
*/
#include <common.h>
#include <watchdog.h>
#include <command.h>
#include <net.h>
#include "bootp.h"
#include "tftp.h"
#ifdef CONFIG_CMD_RARP
#include "rarp.h"
#endif
#include "nfs.h"
#ifdef CONFIG_STATUS_LED
#include <status_led.h>
#include <miiphy.h>
#endif
#if defined(CONFIG_CMD_SNTP)
#include "sntp.h"
#endif
#if defined(CONFIG_CDP_VERSION)
#include <timestamp.h>
#endif
#if defined(CONFIG_CMD_DNS)
#include "dns.h"
#endif
DECLARE_GLOBAL_DATA_PTR;
#ifndef CONFIG_ARP_TIMEOUT
/* Milliseconds before trying ARP again */
# define ARP_TIMEOUT 5000UL
#else
# define ARP_TIMEOUT CONFIG_ARP_TIMEOUT
#endif
#ifndef CONFIG_NET_RETRY_COUNT
# define ARP_TIMEOUT_COUNT 5 /* # of timeouts before giving up */
#else
# define ARP_TIMEOUT_COUNT CONFIG_NET_RETRY_COUNT
#endif
/** BOOTP EXTENTIONS **/
/* Our subnet mask (0=unknown) */
IPaddr_t NetOurSubnetMask;
/* Our gateways IP address */
IPaddr_t NetOurGatewayIP;
/* Our DNS IP address */
IPaddr_t NetOurDNSIP;
#if defined(CONFIG_BOOTP_DNS2)
/* Our 2nd DNS IP address */
IPaddr_t NetOurDNS2IP;
#endif
/* Our NIS domain */
char NetOurNISDomain[32] = {0,};
/* Our hostname */
char NetOurHostName[32] = {0,};
/* Our bootpath */
char NetOurRootPath[64] = {0,};
/* Our bootfile size in blocks */
ushort NetBootFileSize;
#ifdef CONFIG_MCAST_TFTP /* Multicast TFTP */
IPaddr_t Mcast_addr;
#endif
/** END OF BOOTP EXTENTIONS **/
/* The actual transferred size of the bootfile (in bytes) */
ulong NetBootFileXferSize;
/* Our ethernet address */
uchar NetOurEther[6];
/* Boot server enet address */
uchar NetServerEther[6];
/* Our IP addr (0 = unknown) */
IPaddr_t NetOurIP;
/* Server IP addr (0 = unknown) */
IPaddr_t NetServerIP;
/* Current receive packet */
volatile uchar *NetRxPacket;
/* Current rx packet length */
int NetRxPacketLen;
/* IP packet ID */
unsigned NetIPID;
/* Ethernet bcast address */
uchar NetBcastAddr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
uchar NetEtherNullAddr[6];
#ifdef CONFIG_API
void (*push_packet)(volatile void *, int len) = 0;
#endif
#if defined(CONFIG_CMD_CDP)
/* Ethernet bcast address */
uchar NetCDPAddr[6] = { 0x01, 0x00, 0x0c, 0xcc, 0xcc, 0xcc };
#endif
/* Network loop state */
int NetState;
/* Tried all network devices */
int NetRestartWrap;
/* Network loop restarted */
static int NetRestarted;
/* At least one device configured */
static int NetDevExists;
/* XXX in both little & big endian machines 0xFFFF == ntohs(-1) */
/* default is without VLAN */
ushort NetOurVLAN = 0xFFFF;
/* ditto */
ushort NetOurNativeVLAN = 0xFFFF;
/* Boot File name */
char BootFile[128];
#if defined(CONFIG_CMD_PING)
/* the ip address to ping */
IPaddr_t NetPingIP;
static void PingStart(void);
#endif
#if defined(CONFIG_CMD_CDP)
static void CDPStart(void);
#endif
#if defined(CONFIG_CMD_SNTP)
/* NTP server IP address */
IPaddr_t NetNtpServerIP;
/* offset time from UTC */
int NetTimeOffset;
#endif
#ifdef CONFIG_NETCONSOLE
void NcStart(void);
int nc_input_packet(uchar *pkt, unsigned dest, unsigned src, unsigned len);
#endif
volatile uchar PktBuf[(PKTBUFSRX+1) * PKTSIZE_ALIGN + PKTALIGN];
/* Receive packet */
volatile uchar *NetRxPackets[PKTBUFSRX];
/* Current RX packet handler */
static rxhand_f *packetHandler;
#ifdef CONFIG_CMD_TFTPPUT
static rxhand_icmp_f *packet_icmp_handler; /* Current ICMP rx handler */
#endif
/* Current timeout handler */
static thand_f *timeHandler;
/* Time base value */
static ulong timeStart;
/* Current timeout value */
static ulong timeDelta;
/* THE transmit packet */
volatile uchar *NetTxPacket;
static int net_check_prereq(enum proto_t protocol);
static int NetTryCount;
/**********************************************************************/
IPaddr_t NetArpWaitPacketIP;
IPaddr_t NetArpWaitReplyIP;
/* MAC address of waiting packet's destination */
uchar *NetArpWaitPacketMAC;
/* THE transmit packet */
uchar *NetArpWaitTxPacket;
int NetArpWaitTxPacketSize;
uchar NetArpWaitPacketBuf[PKTSIZE_ALIGN + PKTALIGN];
ulong NetArpWaitTimerStart;
int NetArpWaitTry;
void ArpRequest(void)
{
volatile uchar *pkt;
ARP_t *arp;
debug("ARP broadcast %d\n", NetArpWaitTry);
pkt = NetTxPacket;
pkt += NetSetEther(pkt, NetBcastAddr, PROT_ARP);
arp = (ARP_t *) pkt;
arp->ar_hrd = htons(ARP_ETHER);
arp->ar_pro = htons(PROT_IP);
arp->ar_hln = 6;
arp->ar_pln = 4;
arp->ar_op = htons(ARPOP_REQUEST);
/* source ET addr */
memcpy(&arp->ar_data[0], NetOurEther, 6);
/* source IP addr */
NetWriteIP((uchar *) &arp->ar_data[6], NetOurIP);
/* dest ET addr = 0 */
memset(&arp->ar_data[10], '\0', 6);
if ((NetArpWaitPacketIP & NetOurSubnetMask) !=
(NetOurIP & NetOurSubnetMask)) {
if (NetOurGatewayIP == 0) {
puts("## Warning: gatewayip needed but not set\n");
NetArpWaitReplyIP = NetArpWaitPacketIP;
} else {
NetArpWaitReplyIP = NetOurGatewayIP;
}
} else {
NetArpWaitReplyIP = NetArpWaitPacketIP;
}
NetWriteIP((uchar *) &arp->ar_data[16], NetArpWaitReplyIP);
(void) eth_send(NetTxPacket, (pkt - NetTxPacket) + ARP_HDR_SIZE);
}
void ArpTimeoutCheck(void)
{
ulong t;
if (!NetArpWaitPacketIP)
return;
t = get_timer(0);
/* check for arp timeout */
if ((t - NetArpWaitTimerStart) > ARP_TIMEOUT) {
NetArpWaitTry++;
if (NetArpWaitTry >= ARP_TIMEOUT_COUNT) {
puts("\nARP Retry count exceeded; starting again\n");
NetArpWaitTry = 0;
NetStartAgain();
} else {
NetArpWaitTimerStart = t;
ArpRequest();
}
}
}
/*
* Check if autoload is enabled. If so, use either NFS or TFTP to download
* the boot file.
*/
void net_auto_load(void)
{
const char *s = getenv("autoload");
if (s != NULL) {
if (*s == 'n') {
/*
* Just use BOOTP/RARP to configure system;
* Do not use TFTP to load the bootfile.
*/
NetState = NETLOOP_SUCCESS;
return;
}
#if defined(CONFIG_CMD_NFS)
if (strcmp(s, "NFS") == 0) {
/*
* Use NFS to load the bootfile.
*/
NfsStart();
return;
}
#endif
}
TftpStart(TFTPGET);
}
static void NetInitLoop(enum proto_t protocol)
{
static int env_changed_id;
bd_t *bd = gd->bd;
int env_id = get_env_id();
/* update only when the environment has changed */
if (env_changed_id != env_id) {
NetOurIP = getenv_IPaddr("ipaddr");
NetCopyIP(&bd->bi_ip_addr, &NetOurIP);
NetOurGatewayIP = getenv_IPaddr("gatewayip");
NetOurSubnetMask = getenv_IPaddr("netmask");
NetServerIP = getenv_IPaddr("serverip");
NetOurNativeVLAN = getenv_VLAN("nvlan");
NetOurVLAN = getenv_VLAN("vlan");
#if defined(CONFIG_CMD_DNS)
NetOurDNSIP = getenv_IPaddr("dnsip");
#endif
env_changed_id = env_id;
}
return;
}
/**********************************************************************/
/*
* Main network processing loop.
*/
int NetLoop(enum proto_t protocol)
{
bd_t *bd = gd->bd;
int ret = -1;
NetRestarted = 0;
NetDevExists = 0;
/* XXX problem with bss workaround */
NetArpWaitPacketMAC = NULL;
NetArpWaitTxPacket = NULL;
NetArpWaitPacketIP = 0;
NetArpWaitReplyIP = 0;
NetArpWaitTxPacket = NULL;
NetTxPacket = NULL;
NetTryCount = 1;
if (!NetTxPacket) {
int i;
/*
* Setup packet buffers, aligned correctly.
*/
NetTxPacket = &PktBuf[0] + (PKTALIGN - 1);
NetTxPacket -= (ulong)NetTxPacket % PKTALIGN;
for (i = 0; i < PKTBUFSRX; i++)
NetRxPackets[i] = NetTxPacket + (i+1)*PKTSIZE_ALIGN;
}
if (!NetArpWaitTxPacket) {
NetArpWaitTxPacket = &NetArpWaitPacketBuf[0] + (PKTALIGN - 1);
NetArpWaitTxPacket -= (ulong)NetArpWaitTxPacket % PKTALIGN;
NetArpWaitTxPacketSize = 0;
}
eth_halt();
eth_set_current();
if (eth_init(bd) < 0) {
eth_halt();
return -1;
}
restart:
memcpy(NetOurEther, eth_get_dev()->enetaddr, 6);
NetState = NETLOOP_CONTINUE;
/*
* Start the ball rolling with the given start function. From
* here on, this code is a state machine driven by received
* packets and timer events.
*/
NetInitLoop(protocol);
switch (net_check_prereq(protocol)) {
case 1:
/* network not configured */
eth_halt();
return -1;
case 2:
/* network device not configured */
break;
case 0:
NetDevExists = 1;
NetBootFileXferSize = 0;
switch (protocol) {
case TFTPGET:
#ifdef CONFIG_CMD_TFTPPUT
case TFTPPUT:
#endif
/* always use ARP to get server ethernet address */
TftpStart(protocol);
break;
#ifdef CONFIG_CMD_TFTPSRV
case TFTPSRV:
TftpStartServer();
break;
#endif
#if defined(CONFIG_CMD_DHCP)
case DHCP:
BootpTry = 0;
NetOurIP = 0;
DhcpRequest(); /* Basically same as BOOTP */
break;
#endif
case BOOTP:
BootpTry = 0;
NetOurIP = 0;
BootpRequest();
break;
#if defined(CONFIG_CMD_RARP)
case RARP:
RarpTry = 0;
NetOurIP = 0;
RarpRequest();
break;
#endif
#if defined(CONFIG_CMD_PING)
case PING:
PingStart();
break;
#endif
#if defined(CONFIG_CMD_NFS)
case NFS:
NfsStart();
break;
#endif
#if defined(CONFIG_CMD_CDP)
case CDP:
CDPStart();
break;
#endif
#ifdef CONFIG_NETCONSOLE
case NETCONS:
NcStart();
break;
#endif
#if defined(CONFIG_CMD_SNTP)
case SNTP:
SntpStart();
break;
#endif
#if defined(CONFIG_CMD_DNS)
case DNS:
DnsStart();
break;
#endif
default:
break;
}
break;
}
#if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
#if defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN) && \
defined(CONFIG_STATUS_LED) && \
defined(STATUS_LED_RED)
/*
* Echo the inverted link state to the fault LED.
*/
if (miiphy_link(eth_get_dev()->name, CONFIG_SYS_FAULT_MII_ADDR))
status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
else
status_led_set(STATUS_LED_RED, STATUS_LED_ON);
#endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
#endif /* CONFIG_MII, ... */
/*
* Main packet reception loop. Loop receiving packets until
* someone sets `NetState' to a state that terminates.
*/
for (;;) {
WATCHDOG_RESET();
#ifdef CONFIG_SHOW_ACTIVITY
{
extern void show_activity(int arg);
show_activity(1);
}
#endif
/*
* Check the ethernet for a new packet. The ethernet
* receive routine will process it.
*/
eth_rx();
/*
* Abort if ctrl-c was pressed.
*/
if (ctrlc()) {
eth_halt();
puts("\nAbort\n");
goto done;
}
ArpTimeoutCheck();
/*
* Check for a timeout, and run the timeout handler
* if we have one.
*/
if (timeHandler && ((get_timer(0) - timeStart) > timeDelta)) {
thand_f *x;
#if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
#if defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN) && \
defined(CONFIG_STATUS_LED) && \
defined(STATUS_LED_RED)
/*
* Echo the inverted link state to the fault LED.
*/
if (miiphy_link(eth_get_dev()->name,
CONFIG_SYS_FAULT_MII_ADDR)) {
status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
} else {
status_led_set(STATUS_LED_RED, STATUS_LED_ON);
}
#endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
#endif /* CONFIG_MII, ... */
x = timeHandler;
timeHandler = (thand_f *)0;
(*x)();
}
switch (NetState) {
case NETLOOP_RESTART:
NetRestarted = 1;
goto restart;
case NETLOOP_SUCCESS:
if (NetBootFileXferSize > 0) {
char buf[20];
printf("Bytes transferred = %ld (%lx hex)\n",
NetBootFileXferSize,
NetBootFileXferSize);
sprintf(buf, "%lX", NetBootFileXferSize);
setenv("filesize", buf);
sprintf(buf, "%lX", (unsigned long)load_addr);
setenv("fileaddr", buf);
}
eth_halt();
ret = NetBootFileXferSize;
goto done;
case NETLOOP_FAIL:
goto done;
}
}
done:
#ifdef CONFIG_CMD_TFTPPUT
/* Clear out the handlers */
NetSetHandler(NULL);
net_set_icmp_handler(NULL);
#endif
return ret;
}
/**********************************************************************/
static void
startAgainTimeout(void)
{
NetState = NETLOOP_RESTART;
}
static void
startAgainHandler(uchar *pkt, unsigned dest, IPaddr_t sip,
unsigned src, unsigned len)
{
/* Totally ignore the packet */
}
void NetStartAgain(void)
{
char *nretry;
int retry_forever = 0;
unsigned long retrycnt = 0;
nretry = getenv("netretry");
if (nretry) {
if (!strcmp(nretry, "yes"))
retry_forever = 1;
else if (!strcmp(nretry, "no"))
retrycnt = 0;
else if (!strcmp(nretry, "once"))
retrycnt = 1;
else
retrycnt = simple_strtoul(nretry, NULL, 0);
} else
retry_forever = 1;
if ((!retry_forever) && (NetTryCount >= retrycnt)) {
eth_halt();
NetState = NETLOOP_FAIL;
return;
}
NetTryCount++;
eth_halt();
#if !defined(CONFIG_NET_DO_NOT_TRY_ANOTHER)
eth_try_another(!NetRestarted);
#endif
eth_init(gd->bd);
if (NetRestartWrap) {
NetRestartWrap = 0;
if (NetDevExists) {
NetSetTimeout(10000UL, startAgainTimeout);
NetSetHandler(startAgainHandler);
} else {
NetState = NETLOOP_FAIL;
}
} else {
NetState = NETLOOP_RESTART;
}
}
/**********************************************************************/
/*
* Miscelaneous bits.
*/
void
NetSetHandler(rxhand_f *f)
{
packetHandler = f;
}
#ifdef CONFIG_CMD_TFTPPUT
void net_set_icmp_handler(rxhand_icmp_f *f)
{
packet_icmp_handler = f;
}
#endif
void
NetSetTimeout(ulong iv, thand_f *f)
{
if (iv == 0) {
timeHandler = (thand_f *)0;
} else {
timeHandler = f;
timeStart = get_timer(0);
timeDelta = iv;
}
}
void
NetSendPacket(volatile uchar *pkt, int len)
{
(void) eth_send(pkt, len);
}
int
NetSendUDPPacket(uchar *ether, IPaddr_t dest, int dport, int sport, int len)
{
uchar *pkt;
/* convert to new style broadcast */
if (dest == 0)
dest = 0xFFFFFFFF;
/* if broadcast, make the ether address a broadcast and don't do ARP */
if (dest == 0xFFFFFFFF)
ether = NetBcastAddr;
/*
* if MAC address was not discovered yet, save the packet and do
* an ARP request
*/
if (memcmp(ether, NetEtherNullAddr, 6) == 0) {
debug("sending ARP for %08x\n", dest);
NetArpWaitPacketIP = dest;
NetArpWaitPacketMAC = ether;
pkt = NetArpWaitTxPacket;
pkt += NetSetEther(pkt, NetArpWaitPacketMAC, PROT_IP);
NetSetIP(pkt, dest, dport, sport, len);
memcpy(pkt + IP_HDR_SIZE, (uchar *)NetTxPacket +
(pkt - (uchar *)NetArpWaitTxPacket) + IP_HDR_SIZE, len);
/* size of the waiting packet */
NetArpWaitTxPacketSize = (pkt - NetArpWaitTxPacket) +
IP_HDR_SIZE + len;
/* and do the ARP request */
NetArpWaitTry = 1;
NetArpWaitTimerStart = get_timer(0);
ArpRequest();
return 1; /* waiting */
}
debug("sending UDP to %08x/%pM\n", dest, ether);
pkt = (uchar *)NetTxPacket;
pkt += NetSetEther(pkt, ether, PROT_IP);
NetSetIP(pkt, dest, dport, sport, len);
(void) eth_send(NetTxPacket, (pkt - NetTxPacket) + IP_HDR_SIZE + len);
return 0; /* transmitted */
}
#if defined(CONFIG_CMD_PING)
static ushort PingSeqNo;
int PingSend(void)
{
static uchar mac[6];
volatile IP_t *ip;
volatile ushort *s;
uchar *pkt;
/* XXX always send arp request */
memcpy(mac, NetEtherNullAddr, 6);
debug("sending ARP for %08x\n", NetPingIP);
NetArpWaitPacketIP = NetPingIP;
NetArpWaitPacketMAC = mac;
pkt = NetArpWaitTxPacket;
pkt += NetSetEther(pkt, mac, PROT_IP);
ip = (volatile IP_t *)pkt;
/*
* Construct an IP and ICMP header.
* (need to set no fragment bit - XXX)
*/
/* IP_HDR_SIZE / 4 (not including UDP) */
ip->ip_hl_v = 0x45;
ip->ip_tos = 0;
ip->ip_len = htons(IP_HDR_SIZE_NO_UDP + 8);
ip->ip_id = htons(NetIPID++);
ip->ip_off = htons(IP_FLAGS_DFRAG); /* Don't fragment */
ip->ip_ttl = 255;
ip->ip_p = 0x01; /* ICMP */
ip->ip_sum = 0;
/* already in network byte order */
NetCopyIP((void *)&ip->ip_src, &NetOurIP);
/* - "" - */
NetCopyIP((void *)&ip->ip_dst, &NetPingIP);
ip->ip_sum = ~NetCksum((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2);
s = &ip->udp_src; /* XXX ICMP starts here */
s[0] = htons(0x0800); /* echo-request, code */
s[1] = 0; /* checksum */
s[2] = 0; /* identifier */
s[3] = htons(PingSeqNo++); /* sequence number */
s[1] = ~NetCksum((uchar *)s, 8/2);
/* size of the waiting packet */
NetArpWaitTxPacketSize =
(pkt - NetArpWaitTxPacket) + IP_HDR_SIZE_NO_UDP + 8;
/* and do the ARP request */
NetArpWaitTry = 1;
NetArpWaitTimerStart = get_timer(0);
ArpRequest();
return 1; /* waiting */
}
static void
PingTimeout(void)
{
eth_halt();
NetState = NETLOOP_FAIL; /* we did not get the reply */
}
static void
PingHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
unsigned len)
{
if (sip != NetPingIP)
return;
NetState = NETLOOP_SUCCESS;
}
static void PingStart(void)
{
printf("Using %s device\n", eth_get_name());
NetSetTimeout(10000UL, PingTimeout);
NetSetHandler(PingHandler);
PingSend();
}
#endif
#if defined(CONFIG_CMD_CDP)
#define CDP_DEVICE_ID_TLV 0x0001
#define CDP_ADDRESS_TLV 0x0002
#define CDP_PORT_ID_TLV 0x0003
#define CDP_CAPABILITIES_TLV 0x0004
#define CDP_VERSION_TLV 0x0005
#define CDP_PLATFORM_TLV 0x0006
#define CDP_NATIVE_VLAN_TLV 0x000a
#define CDP_APPLIANCE_VLAN_TLV 0x000e
#define CDP_TRIGGER_TLV 0x000f
#define CDP_POWER_CONSUMPTION_TLV 0x0010
#define CDP_SYSNAME_TLV 0x0014
#define CDP_SYSOBJECT_TLV 0x0015
#define CDP_MANAGEMENT_ADDRESS_TLV 0x0016
#define CDP_TIMEOUT 250UL /* one packet every 250ms */
static int CDPSeq;
static int CDPOK;
ushort CDPNativeVLAN;
ushort CDPApplianceVLAN;
static const uchar CDP_SNAP_hdr[8] = { 0xAA, 0xAA, 0x03, 0x00, 0x00, 0x0C, 0x20,
0x00 };
static ushort CDP_compute_csum(const uchar *buff, ushort len)
{
ushort csum;
int odd;
ulong result = 0;
ushort leftover;
ushort *p;
if (len > 0) {
odd = 1 & (ulong)buff;
if (odd) {
result = *buff << 8;
len--;
buff++;
}
while (len > 1) {
p = (ushort *)buff;
result += *p++;
buff = (uchar *)p;
if (result & 0x80000000)
result = (result & 0xFFFF) + (result >> 16);
len -= 2;
}
if (len) {
leftover = (signed short)(*(const signed char *)buff);
/* CISCO SUCKS big time! (and blows too):
* CDP uses the IP checksum algorithm with a twist;
* for the last byte it *sign* extends and sums.
*/
result = (result & 0xffff0000) |
((result + leftover) & 0x0000ffff);
}
while (result >> 16)
result = (result & 0xFFFF) + (result >> 16);
if (odd)
result = ((result >> 8) & 0xff) |
((result & 0xff) << 8);
}
/* add up 16-bit and 17-bit words for 17+c bits */
result = (result & 0xffff) + (result >> 16);
/* add up 16-bit and 2-bit for 16+c bit */
result = (result & 0xffff) + (result >> 16);
/* add up carry.. */
result = (result & 0xffff) + (result >> 16);
/* negate */
csum = ~(ushort)result;
/* run time endian detection */
if (csum != htons(csum)) /* little endian */
csum = htons(csum);
return csum;
}
int CDPSendTrigger(void)
{
volatile uchar *pkt;
volatile ushort *s;
volatile ushort *cp;
Ethernet_t *et;
int len;
ushort chksum;
#if defined(CONFIG_CDP_DEVICE_ID) || defined(CONFIG_CDP_PORT_ID) || \
defined(CONFIG_CDP_VERSION) || defined(CONFIG_CDP_PLATFORM)
char buf[32];
#endif
pkt = NetTxPacket;
et = (Ethernet_t *)pkt;
/* NOTE: trigger sent not on any VLAN */
/* form ethernet header */
memcpy(et->et_dest, NetCDPAddr, 6);
memcpy(et->et_src, NetOurEther, 6);
pkt += ETHER_HDR_SIZE;
/* SNAP header */
memcpy((uchar *)pkt, CDP_SNAP_hdr, sizeof(CDP_SNAP_hdr));
pkt += sizeof(CDP_SNAP_hdr);
/* CDP header */
*pkt++ = 0x02; /* CDP version 2 */
*pkt++ = 180; /* TTL */
s = (volatile ushort *)pkt;
cp = s;
/* checksum (0 for later calculation) */
*s++ = htons(0);
/* CDP fields */
#ifdef CONFIG_CDP_DEVICE_ID
*s++ = htons(CDP_DEVICE_ID_TLV);
*s++ = htons(CONFIG_CDP_DEVICE_ID);
sprintf(buf, CONFIG_CDP_DEVICE_ID_PREFIX "%pm", NetOurEther);
memcpy((uchar *)s, buf, 16);
s += 16 / 2;
#endif
#ifdef CONFIG_CDP_PORT_ID
*s++ = htons(CDP_PORT_ID_TLV);
memset(buf, 0, sizeof(buf));
sprintf(buf, CONFIG_CDP_PORT_ID, eth_get_dev_index());
len = strlen(buf);
if (len & 1) /* make it even */
len++;
*s++ = htons(len + 4);
memcpy((uchar *)s, buf, len);
s += len / 2;
#endif
#ifdef CONFIG_CDP_CAPABILITIES
*s++ = htons(CDP_CAPABILITIES_TLV);
*s++ = htons(8);
*(ulong *)s = htonl(CONFIG_CDP_CAPABILITIES);
s += 2;
#endif
#ifdef CONFIG_CDP_VERSION
*s++ = htons(CDP_VERSION_TLV);
memset(buf, 0, sizeof(buf));
strcpy(buf, CONFIG_CDP_VERSION);
len = strlen(buf);
if (len & 1) /* make it even */
len++;
*s++ = htons(len + 4);
memcpy((uchar *)s, buf, len);
s += len / 2;
#endif
#ifdef CONFIG_CDP_PLATFORM
*s++ = htons(CDP_PLATFORM_TLV);
memset(buf, 0, sizeof(buf));
strcpy(buf, CONFIG_CDP_PLATFORM);
len = strlen(buf);
if (len & 1) /* make it even */
len++;
*s++ = htons(len + 4);
memcpy((uchar *)s, buf, len);
s += len / 2;
#endif
#ifdef CONFIG_CDP_TRIGGER
*s++ = htons(CDP_TRIGGER_TLV);
*s++ = htons(8);
*(ulong *)s = htonl(CONFIG_CDP_TRIGGER);
s += 2;
#endif
#ifdef CONFIG_CDP_POWER_CONSUMPTION
*s++ = htons(CDP_POWER_CONSUMPTION_TLV);
*s++ = htons(6);
*s++ = htons(CONFIG_CDP_POWER_CONSUMPTION);
#endif
/* length of ethernet packet */
len = (uchar *)s - ((uchar *)NetTxPacket + ETHER_HDR_SIZE);
et->et_protlen = htons(len);
len = ETHER_HDR_SIZE + sizeof(CDP_SNAP_hdr);
chksum = CDP_compute_csum((uchar *)NetTxPacket + len,
(uchar *)s - (NetTxPacket + len));
if (chksum == 0)
chksum = 0xFFFF;
*cp = htons(chksum);
(void) eth_send(NetTxPacket, (uchar *)s - NetTxPacket);
return 0;
}
static void
CDPTimeout(void)
{
CDPSeq++;
if (CDPSeq < 3) {
NetSetTimeout(CDP_TIMEOUT, CDPTimeout);
CDPSendTrigger();
return;
}
/* if not OK try again */
if (!CDPOK)
NetStartAgain();
else
NetState = NETLOOP_SUCCESS;
}
static void
CDPDummyHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
unsigned len)
{
/* nothing */
}
static void
CDPHandler(const uchar *pkt, unsigned len)
{
const uchar *t;
const ushort *ss;
ushort type, tlen;
ushort vlan, nvlan;
/* minimum size? */
if (len < sizeof(CDP_SNAP_hdr) + 4)
goto pkt_short;
/* check for valid CDP SNAP header */
if (memcmp(pkt, CDP_SNAP_hdr, sizeof(CDP_SNAP_hdr)) != 0)
return;
pkt += sizeof(CDP_SNAP_hdr);
len -= sizeof(CDP_SNAP_hdr);
/* Version of CDP protocol must be >= 2 and TTL != 0 */
if (pkt[0] < 0x02 || pkt[1] == 0)
return;
/*
* if version is greater than 0x02 maybe we'll have a problem;
* output a warning
*/
if (pkt[0] != 0x02)
printf("** WARNING: CDP packet received with a protocol version %d > 2\n",
pkt[0] & 0xff);
if (CDP_compute_csum(pkt, len) != 0)
return;
pkt += 4;
len -= 4;
vlan = htons(-1);
nvlan = htons(-1);
while (len > 0) {
if (len < 4)
goto pkt_short;
ss = (const ushort *)pkt;
type = ntohs(ss[0]);
tlen = ntohs(ss[1]);
if (tlen > len)
goto pkt_short;
pkt += tlen;
len -= tlen;
ss += 2; /* point ss to the data of the TLV */
tlen -= 4;
switch (type) {
case CDP_DEVICE_ID_TLV:
break;
case CDP_ADDRESS_TLV:
break;
case CDP_PORT_ID_TLV:
break;
case CDP_CAPABILITIES_TLV:
break;
case CDP_VERSION_TLV:
break;
case CDP_PLATFORM_TLV:
break;
case CDP_NATIVE_VLAN_TLV:
nvlan = *ss;
break;
case CDP_APPLIANCE_VLAN_TLV:
t = (const uchar *)ss;
while (tlen > 0) {
if (tlen < 3)
goto pkt_short;
ss = (const ushort *)(t + 1);
#ifdef CONFIG_CDP_APPLIANCE_VLAN_TYPE
if (t[0] == CONFIG_CDP_APPLIANCE_VLAN_TYPE)
vlan = *ss;
#else
/* XXX will this work; dunno */
vlan = ntohs(*ss);
#endif
t += 3; tlen -= 3;
}
break;
case CDP_TRIGGER_TLV:
break;
case CDP_POWER_CONSUMPTION_TLV:
break;
case CDP_SYSNAME_TLV:
break;
case CDP_SYSOBJECT_TLV:
break;
case CDP_MANAGEMENT_ADDRESS_TLV:
break;
}
}
CDPApplianceVLAN = vlan;
CDPNativeVLAN = nvlan;
CDPOK = 1;
return;
pkt_short:
printf("** CDP packet is too short\n");
return;
}
static void CDPStart(void)
{
printf("Using %s device\n", eth_get_name());
CDPSeq = 0;
CDPOK = 0;
CDPNativeVLAN = htons(-1);
CDPApplianceVLAN = htons(-1);
NetSetTimeout(CDP_TIMEOUT, CDPTimeout);
NetSetHandler(CDPDummyHandler);
CDPSendTrigger();
}
#endif
#ifdef CONFIG_IP_DEFRAG
/*
* This function collects fragments in a single packet, according
* to the algorithm in RFC815. It returns NULL or the pointer to
* a complete packet, in static storage
*/
#ifndef CONFIG_NET_MAXDEFRAG
#define CONFIG_NET_MAXDEFRAG 16384
#endif
/*
* MAXDEFRAG, above, is chosen in the config file and is real data
* so we need to add the NFS overhead, which is more than TFTP.
* To use sizeof in the internal unnamed structures, we need a real
* instance (can't do "sizeof(struct rpc_t.u.reply))", unfortunately).
* The compiler doesn't complain nor allocates the actual structure
*/
static struct rpc_t rpc_specimen;
#define IP_PKTSIZE (CONFIG_NET_MAXDEFRAG + sizeof(rpc_specimen.u.reply))
#define IP_MAXUDP (IP_PKTSIZE - IP_HDR_SIZE_NO_UDP)
/*
* this is the packet being assembled, either data or frag control.
* Fragments go by 8 bytes, so this union must be 8 bytes long
*/
struct hole {
/* first_byte is address of this structure */
u16 last_byte; /* last byte in this hole + 1 (begin of next hole) */
u16 next_hole; /* index of next (in 8-b blocks), 0 == none */
u16 prev_hole; /* index of prev, 0 == none */
u16 unused;
};
static IP_t *__NetDefragment(IP_t *ip, int *lenp)
{
static uchar pkt_buff[IP_PKTSIZE] __attribute__((aligned(PKTALIGN)));
static u16 first_hole, total_len;
struct hole *payload, *thisfrag, *h, *newh;
IP_t *localip = (IP_t *)pkt_buff;
uchar *indata = (uchar *)ip;
int offset8, start, len, done = 0;
u16 ip_off = ntohs(ip->ip_off);
/* payload starts after IP header, this fragment is in there */
payload = (struct hole *)(pkt_buff + IP_HDR_SIZE_NO_UDP);
offset8 = (ip_off & IP_OFFS);
thisfrag = payload + offset8;
start = offset8 * 8;
len = ntohs(ip->ip_len) - IP_HDR_SIZE_NO_UDP;
if (start + len > IP_MAXUDP) /* fragment extends too far */
return NULL;
if (!total_len || localip->ip_id != ip->ip_id) {
/* new (or different) packet, reset structs */
total_len = 0xffff;
payload[0].last_byte = ~0;
payload[0].next_hole = 0;
payload[0].prev_hole = 0;
first_hole = 0;
/* any IP header will work, copy the first we received */
memcpy(localip, ip, IP_HDR_SIZE_NO_UDP);
}
/*
* What follows is the reassembly algorithm. We use the payload
* array as a linked list of hole descriptors, as each hole starts
* at a multiple of 8 bytes. However, last byte can be whatever value,
* so it is represented as byte count, not as 8-byte blocks.
*/
h = payload + first_hole;
while (h->last_byte < start) {
if (!h->next_hole) {
/* no hole that far away */
return NULL;
}
h = payload + h->next_hole;
}
/* last fragment may be 1..7 bytes, the "+7" forces acceptance */
if (offset8 + ((len + 7) / 8) <= h - payload) {
/* no overlap with holes (dup fragment?) */
return NULL;
}
if (!(ip_off & IP_FLAGS_MFRAG)) {
/* no more fragmentss: truncate this (last) hole */
total_len = start + len;
h->last_byte = start + len;
}
/*
* There is some overlap: fix the hole list. This code doesn't
* deal with a fragment that overlaps with two different holes
* (thus being a superset of a previously-received fragment).
*/
if ((h >= thisfrag) && (h->last_byte <= start + len)) {
/* complete overlap with hole: remove hole */
if (!h->prev_hole && !h->next_hole) {
/* last remaining hole */
done = 1;
} else if (!h->prev_hole) {
/* first hole */
first_hole = h->next_hole;
payload[h->next_hole].prev_hole = 0;
} else if (!h->next_hole) {
/* last hole */
payload[h->prev_hole].next_hole = 0;
} else {
/* in the middle of the list */
payload[h->next_hole].prev_hole = h->prev_hole;
payload[h->prev_hole].next_hole = h->next_hole;
}
} else if (h->last_byte <= start + len) {
/* overlaps with final part of the hole: shorten this hole */
h->last_byte = start;
} else if (h >= thisfrag) {
/* overlaps with initial part of the hole: move this hole */
newh = thisfrag + (len / 8);
*newh = *h;
h = newh;
if (h->next_hole)
payload[h->next_hole].prev_hole = (h - payload);
if (h->prev_hole)
payload[h->prev_hole].next_hole = (h - payload);
else
first_hole = (h - payload);
} else {
/* fragment sits in the middle: split the hole */
newh = thisfrag + (len / 8);
*newh = *h;
h->last_byte = start;
h->next_hole = (newh - payload);
newh->prev_hole = (h - payload);
if (newh->next_hole)
payload[newh->next_hole].prev_hole = (newh - payload);
}
/* finally copy this fragment and possibly return whole packet */
memcpy((uchar *)thisfrag, indata + IP_HDR_SIZE_NO_UDP, len);
if (!done)
return NULL;
localip->ip_len = htons(total_len);
*lenp = total_len + IP_HDR_SIZE_NO_UDP;
return localip;
}
static inline IP_t *NetDefragment(IP_t *ip, int *lenp)
{
u16 ip_off = ntohs(ip->ip_off);
if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
return ip; /* not a fragment */
return __NetDefragment(ip, lenp);
}
#else /* !CONFIG_IP_DEFRAG */
static inline IP_t *NetDefragment(IP_t *ip, int *lenp)
{
u16 ip_off = ntohs(ip->ip_off);
if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
return ip; /* not a fragment */
return NULL;
}
#endif
/**
* Receive an ICMP packet. We deal with REDIRECT and PING here, and silently
* drop others.
*
* @parma ip IP packet containing the ICMP
*/
static void receive_icmp(IP_t *ip, int len, IPaddr_t src_ip, Ethernet_t *et)
{
ICMP_t *icmph = (ICMP_t *)&ip->udp_src;
switch (icmph->type) {
case ICMP_REDIRECT:
if (icmph->code != ICMP_REDIR_HOST)
return;
printf(" ICMP Host Redirect to %pI4 ",
&icmph->un.gateway);
break;
#if defined(CONFIG_CMD_PING)
case ICMP_ECHO_REPLY:
/*
* IP header OK. Pass the packet to the
* current handler.
*/
/*
* XXX point to ip packet - should this use
* packet_icmp_handler?
*/
(*packetHandler)((uchar *)ip, 0, src_ip, 0, 0);
break;
case ICMP_ECHO_REQUEST:
debug("Got ICMP ECHO REQUEST, return %d bytes\n",
ETHER_HDR_SIZE + len);
memcpy(&et->et_dest[0], &et->et_src[0], 6);
memcpy(&et->et_src[0], NetOurEther, 6);
ip->ip_sum = 0;
ip->ip_off = 0;
NetCopyIP((void *)&ip->ip_dst, &ip->ip_src);
NetCopyIP((void *)&ip->ip_src, &NetOurIP);
ip->ip_sum = ~NetCksum((uchar *)ip,
IP_HDR_SIZE_NO_UDP >> 1);
icmph->type = ICMP_ECHO_REPLY;
icmph->checksum = 0;
icmph->checksum = ~NetCksum((uchar *)icmph,
(len - IP_HDR_SIZE_NO_UDP) >> 1);
(void) eth_send((uchar *)et,
ETHER_HDR_SIZE + len);
break;
#endif
default:
#ifdef CONFIG_CMD_TFTPPUT
if (packet_icmp_handler)
packet_icmp_handler(icmph->type, icmph->code,
ntohs(ip->udp_dst), src_ip, ntohs(ip->udp_src),
icmph->un.data, ntohs(ip->udp_len));
#endif
break;
}
}
void
NetReceive(volatile uchar *inpkt, int len)
{
Ethernet_t *et;
IP_t *ip;
ARP_t *arp;
IPaddr_t tmp;
IPaddr_t src_ip;
int x;
uchar *pkt;
#if defined(CONFIG_CMD_CDP)
int iscdp;
#endif
ushort cti = 0, vlanid = VLAN_NONE, myvlanid, mynvlanid;
debug("packet received\n");
NetRxPacket = inpkt;
NetRxPacketLen = len;
et = (Ethernet_t *)inpkt;
/* too small packet? */
if (len < ETHER_HDR_SIZE)
return;
#ifdef CONFIG_API
if (push_packet) {
(*push_packet)(inpkt, len);
return;
}
#endif
#if defined(CONFIG_CMD_CDP)
/* keep track if packet is CDP */
iscdp = memcmp(et->et_dest, NetCDPAddr, 6) == 0;
#endif
myvlanid = ntohs(NetOurVLAN);
if (myvlanid == (ushort)-1)
myvlanid = VLAN_NONE;
mynvlanid = ntohs(NetOurNativeVLAN);
if (mynvlanid == (ushort)-1)
mynvlanid = VLAN_NONE;
x = ntohs(et->et_protlen);
debug("packet received\n");
if (x < 1514) {
/*
* Got a 802 packet. Check the other protocol field.
*/
x = ntohs(et->et_prot);
ip = (IP_t *)(inpkt + E802_HDR_SIZE);
len -= E802_HDR_SIZE;
} else if (x != PROT_VLAN) { /* normal packet */
ip = (IP_t *)(inpkt + ETHER_HDR_SIZE);
len -= ETHER_HDR_SIZE;
} else { /* VLAN packet */
VLAN_Ethernet_t *vet = (VLAN_Ethernet_t *)et;
debug("VLAN packet received\n");
/* too small packet? */
if (len < VLAN_ETHER_HDR_SIZE)
return;
/* if no VLAN active */
if ((ntohs(NetOurVLAN) & VLAN_IDMASK) == VLAN_NONE
#if defined(CONFIG_CMD_CDP)
&& iscdp == 0
#endif
)
return;
cti = ntohs(vet->vet_tag);
vlanid = cti & VLAN_IDMASK;
x = ntohs(vet->vet_type);
ip = (IP_t *)(inpkt + VLAN_ETHER_HDR_SIZE);
len -= VLAN_ETHER_HDR_SIZE;
}
debug("Receive from protocol 0x%x\n", x);
#if defined(CONFIG_CMD_CDP)
if (iscdp) {
CDPHandler((uchar *)ip, len);
return;
}
#endif
if ((myvlanid & VLAN_IDMASK) != VLAN_NONE) {
if (vlanid == VLAN_NONE)
vlanid = (mynvlanid & VLAN_IDMASK);
/* not matched? */
if (vlanid != (myvlanid & VLAN_IDMASK))
return;
}
switch (x) {
case PROT_ARP:
/*
* We have to deal with two types of ARP packets:
* - REQUEST packets will be answered by sending our
* IP address - if we know it.
* - REPLY packates are expected only after we asked
* for the TFTP server's or the gateway's ethernet
* address; so if we receive such a packet, we set
* the server ethernet address
*/
debug("Got ARP\n");
arp = (ARP_t *)ip;
if (len < ARP_HDR_SIZE) {
printf("bad length %d < %d\n", len, ARP_HDR_SIZE);
return;
}
if (ntohs(arp->ar_hrd) != ARP_ETHER)
return;
if (ntohs(arp->ar_pro) != PROT_IP)
return;
if (arp->ar_hln != 6)
return;
if (arp->ar_pln != 4)
return;
if (NetOurIP == 0)
return;
if (NetReadIP(&arp->ar_data[16]) != NetOurIP)
return;
switch (ntohs(arp->ar_op)) {
case ARPOP_REQUEST:
/* reply with our IP address */
debug("Got ARP REQUEST, return our IP\n");
pkt = (uchar *)et;
pkt += NetSetEther(pkt, et->et_src, PROT_ARP);
arp->ar_op = htons(ARPOP_REPLY);
memcpy(&arp->ar_data[10], &arp->ar_data[0], 6);
NetCopyIP(&arp->ar_data[16], &arp->ar_data[6]);
memcpy(&arp->ar_data[0], NetOurEther, 6);
NetCopyIP(&arp->ar_data[6], &NetOurIP);
(void) eth_send((uchar *)et,
(pkt - (uchar *)et) + ARP_HDR_SIZE);
return;
case ARPOP_REPLY: /* arp reply */
/* are we waiting for a reply */
if (!NetArpWaitPacketIP || !NetArpWaitPacketMAC)
break;
#ifdef CONFIG_KEEP_SERVERADDR
if (NetServerIP == NetArpWaitPacketIP) {
char buf[20];
sprintf(buf, "%pM", arp->ar_data);
setenv("serveraddr", buf);
}
#endif
debug("Got ARP REPLY, set server/gtwy eth addr (%pM)\n",
arp->ar_data);
tmp = NetReadIP(&arp->ar_data[6]);
/* matched waiting packet's address */
if (tmp == NetArpWaitReplyIP) {
debug("Got it\n");
/* save address for later use */
memcpy(NetArpWaitPacketMAC,
&arp->ar_data[0], 6);
#ifdef CONFIG_NETCONSOLE
(*packetHandler)(0, 0, 0, 0, 0);
#endif
/* modify header, and transmit it */
memcpy(((Ethernet_t *)NetArpWaitTxPacket)->et_dest, NetArpWaitPacketMAC, 6);
(void) eth_send(NetArpWaitTxPacket,
NetArpWaitTxPacketSize);
/* no arp request pending now */
NetArpWaitPacketIP = 0;
NetArpWaitTxPacketSize = 0;
NetArpWaitPacketMAC = NULL;
}
return;
default:
debug("Unexpected ARP opcode 0x%x\n",
ntohs(arp->ar_op));
return;
}
break;
#ifdef CONFIG_CMD_RARP
case PROT_RARP:
debug("Got RARP\n");
arp = (ARP_t *)ip;
if (len < ARP_HDR_SIZE) {
printf("bad length %d < %d\n", len, ARP_HDR_SIZE);
return;
}
if ((ntohs(arp->ar_op) != RARPOP_REPLY) ||
(ntohs(arp->ar_hrd) != ARP_ETHER) ||
(ntohs(arp->ar_pro) != PROT_IP) ||
(arp->ar_hln != 6) || (arp->ar_pln != 4)) {
puts("invalid RARP header\n");
} else {
NetCopyIP(&NetOurIP, &arp->ar_data[16]);
if (NetServerIP == 0)
NetCopyIP(&NetServerIP, &arp->ar_data[6]);
memcpy(NetServerEther, &arp->ar_data[0], 6);
(*packetHandler)(0, 0, 0, 0, 0);
}
break;
#endif
case PROT_IP:
debug("Got IP\n");
/* Before we start poking the header, make sure it is there */
if (len < IP_HDR_SIZE) {
debug("len bad %d < %lu\n", len, (ulong)IP_HDR_SIZE);
return;
}
/* Check the packet length */
if (len < ntohs(ip->ip_len)) {
printf("len bad %d < %d\n", len, ntohs(ip->ip_len));
return;
}
len = ntohs(ip->ip_len);
debug("len=%d, v=%02x\n", len, ip->ip_hl_v & 0xff);
/* Can't deal with anything except IPv4 */
if ((ip->ip_hl_v & 0xf0) != 0x40)
return;
/* Can't deal with IP options (headers != 20 bytes) */
if ((ip->ip_hl_v & 0x0f) > 0x05)
return;
/* Check the Checksum of the header */
if (!NetCksumOk((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2)) {
puts("checksum bad\n");
return;
}
/* If it is not for us, ignore it */
tmp = NetReadIP(&ip->ip_dst);
if (NetOurIP && tmp != NetOurIP && tmp != 0xFFFFFFFF) {
#ifdef CONFIG_MCAST_TFTP
if (Mcast_addr != tmp)
#endif
return;
}
/* Read source IP address for later use */
src_ip = NetReadIP(&ip->ip_src);
/*
* The function returns the unchanged packet if it's not
* a fragment, and either the complete packet or NULL if
* it is a fragment (if !CONFIG_IP_DEFRAG, it returns NULL)
*/
ip = NetDefragment(ip, &len);
if (!ip)
return;
/*
* watch for ICMP host redirects
*
* There is no real handler code (yet). We just watch
* for ICMP host redirect messages. In case anybody
* sees these messages: please contact me
* (wd@denx.de), or - even better - send me the
* necessary fixes :-)
*
* Note: in all cases where I have seen this so far
* it was a problem with the router configuration,
* for instance when a router was configured in the
* BOOTP reply, but the TFTP server was on the same
* subnet. So this is probably a warning that your
* configuration might be wrong. But I'm not really
* sure if there aren't any other situations.
*
* Simon Glass <sjg@chromium.org>: We get an ICMP when
* we send a tftp packet to a dead connection, or when
* there is no server at the other end.
*/
if (ip->ip_p == IPPROTO_ICMP) {
receive_icmp(ip, len, src_ip, et);
return;
} else if (ip->ip_p != IPPROTO_UDP) { /* Only UDP packets */
return;
}
#ifdef CONFIG_UDP_CHECKSUM
if (ip->udp_xsum != 0) {
ulong xsum;
ushort *sumptr;
ushort sumlen;
xsum = ip->ip_p;
xsum += (ntohs(ip->udp_len));
xsum += (ntohl(ip->ip_src) >> 16) & 0x0000ffff;
xsum += (ntohl(ip->ip_src) >> 0) & 0x0000ffff;
xsum += (ntohl(ip->ip_dst) >> 16) & 0x0000ffff;
xsum += (ntohl(ip->ip_dst) >> 0) & 0x0000ffff;
sumlen = ntohs(ip->udp_len);
sumptr = (ushort *) &(ip->udp_src);
while (sumlen > 1) {
ushort sumdata;
sumdata = *sumptr++;
xsum += ntohs(sumdata);
sumlen -= 2;
}
if (sumlen > 0) {
ushort sumdata;
sumdata = *(unsigned char *) sumptr;
sumdata = (sumdata << 8) & 0xff00;
xsum += sumdata;
}
while ((xsum >> 16) != 0) {
xsum = (xsum & 0x0000ffff) +
((xsum >> 16) & 0x0000ffff);
}
if ((xsum != 0x00000000) && (xsum != 0x0000ffff)) {
printf(" UDP wrong checksum %08lx %08x\n",
xsum, ntohs(ip->udp_xsum));
return;
}
}
#endif
#ifdef CONFIG_NETCONSOLE
nc_input_packet((uchar *)ip + IP_HDR_SIZE,
ntohs(ip->udp_dst),
ntohs(ip->udp_src),
ntohs(ip->udp_len) - 8);
#endif
/*
* IP header OK. Pass the packet to the current handler.
*/
(*packetHandler)((uchar *)ip + IP_HDR_SIZE,
ntohs(ip->udp_dst),
src_ip,
ntohs(ip->udp_src),
ntohs(ip->udp_len) - 8);
break;
}
}
/**********************************************************************/
static int net_check_prereq(enum proto_t protocol)
{
switch (protocol) {
/* Fall through */
#if defined(CONFIG_CMD_PING)
case PING:
if (NetPingIP == 0) {
puts("*** ERROR: ping address not given\n");
return 1;
}
goto common;
#endif
#if defined(CONFIG_CMD_SNTP)
case SNTP:
if (NetNtpServerIP == 0) {
puts("*** ERROR: NTP server address not given\n");
return 1;
}
goto common;
#endif
#if defined(CONFIG_CMD_DNS)
case DNS:
if (NetOurDNSIP == 0) {
puts("*** ERROR: DNS server address not given\n");
return 1;
}
goto common;
#endif
#if defined(CONFIG_CMD_NFS)
case NFS:
#endif
case TFTPGET:
case TFTPPUT:
if (NetServerIP == 0) {
puts("*** ERROR: `serverip' not set\n");
return 1;
}
#if defined(CONFIG_CMD_PING) || defined(CONFIG_CMD_SNTP) || \
defined(CONFIG_CMD_DNS)
common:
#endif
/* Fall through */
case NETCONS:
case TFTPSRV:
if (NetOurIP == 0) {
puts("*** ERROR: `ipaddr' not set\n");
return 1;
}
/* Fall through */
#ifdef CONFIG_CMD_RARP
case RARP:
#endif
case BOOTP:
case CDP:
case DHCP:
if (memcmp(NetOurEther, "\0\0\0\0\0\0", 6) == 0) {
extern int eth_get_dev_index(void);
int num = eth_get_dev_index();
switch (num) {
case -1:
puts("*** ERROR: No ethernet found.\n");
return 1;
case 0:
puts("*** ERROR: `ethaddr' not set\n");
break;
default:
printf("*** ERROR: `eth%daddr' not set\n",
num);
break;
}
NetStartAgain();
return 2;
}
/* Fall through */
default:
return 0;
}
return 0; /* OK */
}
/**********************************************************************/
int
NetCksumOk(uchar *ptr, int len)
{
return !((NetCksum(ptr, len) + 1) & 0xfffe);
}
unsigned
NetCksum(uchar *ptr, int len)
{
ulong xsum;
ushort *p = (ushort *)ptr;
xsum = 0;
while (len-- > 0)
xsum += *p++;
xsum = (xsum & 0xffff) + (xsum >> 16);
xsum = (xsum & 0xffff) + (xsum >> 16);
return xsum & 0xffff;
}
int
NetEthHdrSize(void)
{
ushort myvlanid;
myvlanid = ntohs(NetOurVLAN);
if (myvlanid == (ushort)-1)
myvlanid = VLAN_NONE;
return ((myvlanid & VLAN_IDMASK) == VLAN_NONE) ? ETHER_HDR_SIZE :
VLAN_ETHER_HDR_SIZE;
}
int
NetSetEther(volatile uchar *xet, uchar * addr, uint prot)
{
Ethernet_t *et = (Ethernet_t *)xet;
ushort myvlanid;
myvlanid = ntohs(NetOurVLAN);
if (myvlanid == (ushort)-1)
myvlanid = VLAN_NONE;
memcpy(et->et_dest, addr, 6);
memcpy(et->et_src, NetOurEther, 6);
if ((myvlanid & VLAN_IDMASK) == VLAN_NONE) {
et->et_protlen = htons(prot);
return ETHER_HDR_SIZE;
} else {
VLAN_Ethernet_t *vet = (VLAN_Ethernet_t *)xet;
vet->vet_vlan_type = htons(PROT_VLAN);
vet->vet_tag = htons((0 << 5) | (myvlanid & VLAN_IDMASK));
vet->vet_type = htons(prot);
return VLAN_ETHER_HDR_SIZE;
}
}
void
NetSetIP(volatile uchar *xip, IPaddr_t dest, int dport, int sport, int len)
{
IP_t *ip = (IP_t *)xip;
/*
* If the data is an odd number of bytes, zero the
* byte after the last byte so that the checksum
* will work.
*/
if (len & 1)
xip[IP_HDR_SIZE + len] = 0;
/*
* Construct an IP and UDP header.
* (need to set no fragment bit - XXX)
*/
/* IP_HDR_SIZE / 4 (not including UDP) */
ip->ip_hl_v = 0x45;
ip->ip_tos = 0;
ip->ip_len = htons(IP_HDR_SIZE + len);
ip->ip_id = htons(NetIPID++);
ip->ip_off = htons(IP_FLAGS_DFRAG); /* Don't fragment */
ip->ip_ttl = 255;
ip->ip_p = 17; /* UDP */
ip->ip_sum = 0;
/* already in network byte order */
NetCopyIP((void *)&ip->ip_src, &NetOurIP);
/* - "" - */
NetCopyIP((void *)&ip->ip_dst, &dest);
ip->udp_src = htons(sport);
ip->udp_dst = htons(dport);
ip->udp_len = htons(8 + len);
ip->udp_xsum = 0;
ip->ip_sum = ~NetCksum((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2);
}
void copy_filename(char *dst, const char *src, int size)
{
if (*src && (*src == '"')) {
++src;
--size;
}
while ((--size > 0) && *src && (*src != '"'))
*dst++ = *src++;
*dst = '\0';
}
#if defined(CONFIG_CMD_NFS) || \
defined(CONFIG_CMD_SNTP) || \
defined(CONFIG_CMD_DNS)
/*
* make port a little random (1024-17407)
* This keeps the math somewhat trivial to compute, and seems to work with
* all supported protocols/clients/servers
*/
unsigned int random_port(void)
{
return 1024 + (get_timer(0) % 0x4000);
}
#endif
void ip_to_string(IPaddr_t x, char *s)
{
x = ntohl(x);
sprintf(s, "%d.%d.%d.%d",
(int) ((x >> 24) & 0xff),
(int) ((x >> 16) & 0xff),
(int) ((x >> 8) & 0xff), (int) ((x >> 0) & 0xff)
);
}
void VLAN_to_string(ushort x, char *s)
{
x = ntohs(x);
if (x == (ushort)-1)
x = VLAN_NONE;
if (x == VLAN_NONE)
strcpy(s, "none");
else
sprintf(s, "%d", x & VLAN_IDMASK);
}
ushort string_to_VLAN(const char *s)
{
ushort id;
if (s == NULL)
return htons(VLAN_NONE);
if (*s < '0' || *s > '9')
id = VLAN_NONE;
else
id = (ushort)simple_strtoul(s, NULL, 10);
return htons(id);
}
ushort getenv_VLAN(char *var)
{
return string_to_VLAN(getenv(var));
}
|
1001-study-uboot
|
net/net.c
|
C
|
gpl3
| 45,946
|
/*
* (C) Masami Komiya <mkomiya@sonare.it> 2005
* Copyright 2009, Robin Getz <rgetz@blackfin.uclinux.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2, or (at
* your option) any later version.
*/
#ifndef __DNS_H__
#define __DNS_H__
#define DNS_SERVICE_PORT 53
#define DNS_TIMEOUT 10000UL
/* http://en.wikipedia.org/wiki/List_of_DNS_record_types */
enum dns_query_type {
DNS_A_RECORD = 0x01,
DNS_CNAME_RECORD = 0x05,
DNS_MX_RECORD = 0x0f,
};
/*
* DNS network packet
*/
struct header {
uint16_t tid; /* Transaction ID */
uint16_t flags; /* Flags */
uint16_t nqueries; /* Questions */
uint16_t nanswers; /* Answers */
uint16_t nauth; /* Authority PRs */
uint16_t nother; /* Other PRs */
unsigned char data[1]; /* Data, variable length */
};
extern void DnsStart(void); /* Begin DNS */
#endif
|
1001-study-uboot
|
net/dns.h
|
C
|
gpl3
| 974
|
/*
* (C) Copyright 2001-2010
* 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 <net.h>
#include <miiphy.h>
#include <phy.h>
void eth_parse_enetaddr(const char *addr, uchar *enetaddr)
{
char *end;
int i;
for (i = 0; i < 6; ++i) {
enetaddr[i] = addr ? simple_strtoul(addr, &end, 16) : 0;
if (addr)
addr = (*end) ? end + 1 : end;
}
}
int eth_getenv_enetaddr(char *name, uchar *enetaddr)
{
eth_parse_enetaddr(getenv(name), enetaddr);
return is_valid_ether_addr(enetaddr);
}
int eth_setenv_enetaddr(char *name, const uchar *enetaddr)
{
char buf[20];
sprintf(buf, "%pM", enetaddr);
return setenv(name, buf);
}
int eth_getenv_enetaddr_by_index(const char *base_name, int index,
uchar *enetaddr)
{
char enetvar[32];
sprintf(enetvar, index ? "%s%daddr" : "%saddr", base_name, index);
return eth_getenv_enetaddr(enetvar, enetaddr);
}
static int eth_mac_skip(int index)
{
char enetvar[15];
char *skip_state;
sprintf(enetvar, index ? "eth%dmacskip" : "ethmacskip", index);
return ((skip_state = getenv(enetvar)) != NULL);
}
/*
* CPU and board-specific Ethernet initializations. Aliased function
* signals caller to move on
*/
static int __def_eth_init(bd_t *bis)
{
return -1;
}
int cpu_eth_init(bd_t *bis) __attribute__((weak, alias("__def_eth_init")));
int board_eth_init(bd_t *bis) __attribute__((weak, alias("__def_eth_init")));
extern int mv6436x_eth_initialize(bd_t *);
extern int mv6446x_eth_initialize(bd_t *);
#ifdef CONFIG_API
extern void (*push_packet)(volatile void *, int);
static struct {
uchar data[PKTSIZE];
int length;
} eth_rcv_bufs[PKTBUFSRX];
static unsigned int eth_rcv_current = 0, eth_rcv_last = 0;
#endif
static struct eth_device *eth_devices, *eth_current;
struct eth_device *eth_get_dev(void)
{
return eth_current;
}
struct eth_device *eth_get_dev_by_name(const char *devname)
{
struct eth_device *dev, *target_dev;
BUG_ON(devname == NULL);
if (!eth_devices)
return NULL;
dev = eth_devices;
target_dev = NULL;
do {
if (strcmp(devname, dev->name) == 0) {
target_dev = dev;
break;
}
dev = dev->next;
} while (dev != eth_devices);
return target_dev;
}
struct eth_device *eth_get_dev_by_index(int index)
{
struct eth_device *dev, *target_dev;
int idx = 0;
if (!eth_devices)
return NULL;
dev = eth_devices;
target_dev = NULL;
do {
if (idx == index) {
target_dev = dev;
break;
}
dev = dev->next;
idx++;
} while (dev != eth_devices);
return target_dev;
}
int eth_get_dev_index (void)
{
struct eth_device *dev;
int num = 0;
if (!eth_devices) {
return (-1);
}
for (dev = eth_devices; dev; dev = dev->next) {
if (dev == eth_current)
break;
++num;
}
if (dev) {
return (num);
}
return (0);
}
static void eth_current_changed(void)
{
char *act = getenv("ethact");
/* update current ethernet name */
if (eth_current) {
if (act == NULL || strcmp(act, eth_current->name) != 0)
setenv("ethact", eth_current->name);
}
/*
* remove the variable completely if there is no active
* interface
*/
else if (act != NULL)
setenv("ethact", NULL);
}
int eth_write_hwaddr(struct eth_device *dev, const char *base_name,
int eth_number)
{
unsigned char env_enetaddr[6];
int ret = 0;
if (!eth_getenv_enetaddr_by_index(base_name, eth_number, env_enetaddr))
return -1;
if (memcmp(env_enetaddr, "\0\0\0\0\0\0", 6)) {
if (memcmp(dev->enetaddr, "\0\0\0\0\0\0", 6) &&
memcmp(dev->enetaddr, env_enetaddr, 6)) {
printf("\nWarning: %s MAC addresses don't match:\n",
dev->name);
printf("Address in SROM is %pM\n",
dev->enetaddr);
printf("Address in environment is %pM\n",
env_enetaddr);
}
memcpy(dev->enetaddr, env_enetaddr, 6);
}
if (dev->write_hwaddr &&
!eth_mac_skip(eth_number) &&
is_valid_ether_addr(dev->enetaddr)) {
ret = dev->write_hwaddr(dev);
}
return ret;
}
int eth_register(struct eth_device *dev)
{
struct eth_device *d;
assert(strlen(dev->name) < NAMESIZE);
if (!eth_devices) {
eth_current = eth_devices = dev;
eth_current_changed();
} else {
for (d=eth_devices; d->next!=eth_devices; d=d->next)
;
d->next = dev;
}
dev->state = ETH_STATE_INIT;
dev->next = eth_devices;
return 0;
}
int eth_initialize(bd_t *bis)
{
int eth_number = 0;
eth_devices = NULL;
eth_current = NULL;
show_boot_progress (64);
#if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
miiphy_init();
#endif
#ifdef CONFIG_PHYLIB
phy_init();
#endif
/*
* If board-specific initialization exists, call it.
* If not, call a CPU-specific one
*/
if (board_eth_init != __def_eth_init) {
if (board_eth_init(bis) < 0)
printf("Board Net Initialization Failed\n");
} else if (cpu_eth_init != __def_eth_init) {
if (cpu_eth_init(bis) < 0)
printf("CPU Net Initialization Failed\n");
} else
printf("Net Initialization Skipped\n");
#if defined(CONFIG_DB64360) || defined(CONFIG_CPCI750)
mv6436x_eth_initialize(bis);
#endif
#if defined(CONFIG_DB64460) || defined(CONFIG_P3Mx)
mv6446x_eth_initialize(bis);
#endif
if (!eth_devices) {
puts ("No ethernet found.\n");
show_boot_progress (-64);
} else {
struct eth_device *dev = eth_devices;
char *ethprime = getenv ("ethprime");
show_boot_progress (65);
do {
if (eth_number)
puts (", ");
printf("%s", dev->name);
if (ethprime && strcmp (dev->name, ethprime) == 0) {
eth_current = dev;
puts (" [PRIME]");
}
if (strchr(dev->name, ' '))
puts("\nWarning: eth device name has a space!\n");
if (eth_write_hwaddr(dev, "eth", eth_number))
puts("\nWarning: failed to set MAC address\n");
eth_number++;
dev = dev->next;
} while(dev != eth_devices);
eth_current_changed();
putc ('\n');
}
return eth_number;
}
#ifdef CONFIG_MCAST_TFTP
/* Multicast.
* mcast_addr: multicast ipaddr from which multicast Mac is made
* join: 1=join, 0=leave.
*/
int eth_mcast_join( IPaddr_t mcast_ip, u8 join)
{
u8 mcast_mac[6];
if (!eth_current || !eth_current->mcast)
return -1;
mcast_mac[5] = htonl(mcast_ip) & 0xff;
mcast_mac[4] = (htonl(mcast_ip)>>8) & 0xff;
mcast_mac[3] = (htonl(mcast_ip)>>16) & 0x7f;
mcast_mac[2] = 0x5e;
mcast_mac[1] = 0x0;
mcast_mac[0] = 0x1;
return eth_current->mcast(eth_current, mcast_mac, join);
}
/* the 'way' for ethernet-CRC-32. Spliced in from Linux lib/crc32.c
* and this is the ethernet-crc method needed for TSEC -- and perhaps
* some other adapter -- hash tables
*/
#define CRCPOLY_LE 0xedb88320
u32 ether_crc (size_t len, unsigned char const *p)
{
int i;
u32 crc;
crc = ~0;
while (len--) {
crc ^= *p++;
for (i = 0; i < 8; i++)
crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
}
/* an reverse the bits, cuz of way they arrive -- last-first */
crc = (crc >> 16) | (crc << 16);
crc = (crc >> 8 & 0x00ff00ff) | (crc << 8 & 0xff00ff00);
crc = (crc >> 4 & 0x0f0f0f0f) | (crc << 4 & 0xf0f0f0f0);
crc = (crc >> 2 & 0x33333333) | (crc << 2 & 0xcccccccc);
crc = (crc >> 1 & 0x55555555) | (crc << 1 & 0xaaaaaaaa);
return crc;
}
#endif
int eth_init(bd_t *bis)
{
int eth_number;
struct eth_device *old_current, *dev;
if (!eth_current) {
puts ("No ethernet found.\n");
return -1;
}
/* Sync environment with network devices */
eth_number = 0;
dev = eth_devices;
do {
uchar env_enetaddr[6];
if (eth_getenv_enetaddr_by_index("eth", eth_number,
env_enetaddr))
memcpy(dev->enetaddr, env_enetaddr, 6);
++eth_number;
dev = dev->next;
} while (dev != eth_devices);
old_current = eth_current;
do {
debug("Trying %s\n", eth_current->name);
if (eth_current->init(eth_current,bis) >= 0) {
eth_current->state = ETH_STATE_ACTIVE;
return 0;
}
debug("FAIL\n");
eth_try_another(0);
} while (old_current != eth_current);
return -1;
}
void eth_halt(void)
{
if (!eth_current)
return;
eth_current->halt(eth_current);
eth_current->state = ETH_STATE_PASSIVE;
}
int eth_send(volatile void *packet, int length)
{
if (!eth_current)
return -1;
return eth_current->send(eth_current, packet, length);
}
int eth_rx(void)
{
if (!eth_current)
return -1;
return eth_current->recv(eth_current);
}
#ifdef CONFIG_API
static void eth_save_packet(volatile void *packet, int length)
{
volatile char *p = packet;
int i;
if ((eth_rcv_last+1) % PKTBUFSRX == eth_rcv_current)
return;
if (PKTSIZE < length)
return;
for (i = 0; i < length; i++)
eth_rcv_bufs[eth_rcv_last].data[i] = p[i];
eth_rcv_bufs[eth_rcv_last].length = length;
eth_rcv_last = (eth_rcv_last + 1) % PKTBUFSRX;
}
int eth_receive(volatile void *packet, int length)
{
volatile char *p = packet;
void *pp = push_packet;
int i;
if (eth_rcv_current == eth_rcv_last) {
push_packet = eth_save_packet;
eth_rx();
push_packet = pp;
if (eth_rcv_current == eth_rcv_last)
return -1;
}
if (length < eth_rcv_bufs[eth_rcv_current].length)
return -1;
length = eth_rcv_bufs[eth_rcv_current].length;
for (i = 0; i < length; i++)
p[i] = eth_rcv_bufs[eth_rcv_current].data[i];
eth_rcv_current = (eth_rcv_current + 1) % PKTBUFSRX;
return length;
}
#endif /* CONFIG_API */
void eth_try_another(int first_restart)
{
static struct eth_device *first_failed = NULL;
char *ethrotate;
/*
* Do not rotate between network interfaces when
* 'ethrotate' variable is set to 'no'.
*/
if (((ethrotate = getenv ("ethrotate")) != NULL) &&
(strcmp(ethrotate, "no") == 0))
return;
if (!eth_current)
return;
if (first_restart) {
first_failed = eth_current;
}
eth_current = eth_current->next;
eth_current_changed();
if (first_failed == eth_current) {
NetRestartWrap = 1;
}
}
void eth_set_current(void)
{
static char *act = NULL;
static int env_changed_id = 0;
struct eth_device* old_current;
int env_id;
if (!eth_current) /* XXX no current */
return;
env_id = get_env_id();
if ((act == NULL) || (env_changed_id != env_id)) {
act = getenv("ethact");
env_changed_id = env_id;
}
if (act != NULL) {
old_current = eth_current;
do {
if (strcmp(eth_current->name, act) == 0)
return;
eth_current = eth_current->next;
} while (old_current != eth_current);
}
eth_current_changed();
}
char *eth_get_name (void)
{
return (eth_current ? eth_current->name : "unknown");
}
|
1001-study-uboot
|
net/eth.c
|
C
|
gpl3
| 11,064
|
/*
* SNTP support driver
*
* Masami Komiya <mkomiya@sonare.it> 2005
*
*/
#include <common.h>
#include <command.h>
#include <net.h>
#include <rtc.h>
#include "sntp.h"
#define SNTP_TIMEOUT 10000UL
static int SntpOurPort;
static void
SntpSend (void)
{
struct sntp_pkt_t pkt;
int pktlen = SNTP_PACKET_LEN;
int sport;
debug("%s\n", __func__);
memset (&pkt, 0, sizeof(pkt));
pkt.li = NTP_LI_NOLEAP;
pkt.vn = NTP_VERSION;
pkt.mode = NTP_MODE_CLIENT;
memcpy ((char *)NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE, (char *)&pkt, pktlen);
SntpOurPort = 10000 + (get_timer(0) % 4096);
sport = NTP_SERVICE_PORT;
NetSendUDPPacket (NetServerEther, NetNtpServerIP, sport, SntpOurPort, pktlen);
}
static void
SntpTimeout (void)
{
puts ("Timeout\n");
NetState = NETLOOP_FAIL;
return;
}
static void
SntpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
unsigned len)
{
struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
struct rtc_time tm;
ulong seconds;
debug("%s\n", __func__);
if (dest != SntpOurPort) return;
/*
* As the RTC's used in U-Boot sepport second resolution only
* we simply ignore the sub-second field.
*/
memcpy (&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
to_tm(ntohl(seconds) - 2208988800UL + NetTimeOffset, &tm);
#if defined(CONFIG_CMD_DATE)
rtc_set (&tm);
#endif
printf ("Date: %4d-%02d-%02d Time: %2d:%02d:%02d\n",
tm.tm_year, tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
NetState = NETLOOP_SUCCESS;
}
void
SntpStart (void)
{
debug("%s\n", __func__);
NetSetTimeout (SNTP_TIMEOUT, SntpTimeout);
NetSetHandler(SntpHandler);
memset (NetServerEther, 0, 6);
SntpSend ();
}
|
1001-study-uboot
|
net/sntp.c
|
C
|
gpl3
| 1,679
|
/*
* Copyright 1994, 1995, 2000 Neil Russell.
* (See License)
* Copyright 2000, 2001 DENX Software Engineering, Wolfgang Denk, wd@denx.de
* Copyright 2011 Comelit Group SpA,
* Luca Ceresoli <luca.ceresoli@comelit.it>
*/
#include <common.h>
#include <command.h>
#include <net.h>
#include "tftp.h"
#include "bootp.h"
/* Well known TFTP port # */
#define WELL_KNOWN_PORT 69
/* Millisecs to timeout for lost pkt */
#define TIMEOUT 5000UL
#ifndef CONFIG_NET_RETRY_COUNT
/* # of timeouts before giving up */
# define TIMEOUT_COUNT 10
#else
# define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT * 2)
#endif
/* Number of "loading" hashes per line (for checking the image size) */
#define HASHES_PER_LINE 65
/*
* TFTP operations.
*/
#define TFTP_RRQ 1
#define TFTP_WRQ 2
#define TFTP_DATA 3
#define TFTP_ACK 4
#define TFTP_ERROR 5
#define TFTP_OACK 6
static ulong TftpTimeoutMSecs = TIMEOUT;
static int TftpTimeoutCountMax = TIMEOUT_COUNT;
/*
* These globals govern the timeout behavior when attempting a connection to a
* TFTP server. TftpRRQTimeoutMSecs specifies the number of milliseconds to
* wait for the server to respond to initial connection. Second global,
* TftpRRQTimeoutCountMax, gives the number of such connection retries.
* TftpRRQTimeoutCountMax must be non-negative and TftpRRQTimeoutMSecs must be
* positive. The globals are meant to be set (and restored) by code needing
* non-standard timeout behavior when initiating a TFTP transfer.
*/
ulong TftpRRQTimeoutMSecs = TIMEOUT;
int TftpRRQTimeoutCountMax = TIMEOUT_COUNT;
enum {
TFTP_ERR_UNDEFINED = 0,
TFTP_ERR_FILE_NOT_FOUND = 1,
TFTP_ERR_ACCESS_DENIED = 2,
TFTP_ERR_DISK_FULL = 3,
TFTP_ERR_UNEXPECTED_OPCODE = 4,
TFTP_ERR_UNKNOWN_TRANSFER_ID = 5,
TFTP_ERR_FILE_ALREADY_EXISTS = 6,
};
static IPaddr_t TftpRemoteIP;
/* The UDP port at their end */
static int TftpRemotePort;
/* The UDP port at our end */
static int TftpOurPort;
static int TftpTimeoutCount;
/* packet sequence number */
static ulong TftpBlock;
/* last packet sequence number received */
static ulong TftpLastBlock;
/* count of sequence number wraparounds */
static ulong TftpBlockWrap;
/* memory offset due to wrapping */
static ulong TftpBlockWrapOffset;
static int TftpState;
#ifdef CONFIG_TFTP_TSIZE
/* The file size reported by the server */
static int TftpTsize;
/* The number of hashes we printed */
static short TftpNumchars;
#endif
#ifdef CONFIG_CMD_TFTPPUT
static int TftpWriting; /* 1 if writing, else 0 */
static int TftpFinalBlock; /* 1 if we have sent the last block */
#else
#define TftpWriting 0
#endif
#define STATE_SEND_RRQ 1
#define STATE_DATA 2
#define STATE_TOO_LARGE 3
#define STATE_BAD_MAGIC 4
#define STATE_OACK 5
#define STATE_RECV_WRQ 6
#define STATE_SEND_WRQ 7
/* default TFTP block size */
#define TFTP_BLOCK_SIZE 512
/* sequence number is 16 bit */
#define TFTP_SEQUENCE_SIZE ((ulong)(1<<16))
#define DEFAULT_NAME_LEN (8 + 4 + 1)
static char default_filename[DEFAULT_NAME_LEN];
#ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
#define MAX_LEN 128
#else
#define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
#endif
static char tftp_filename[MAX_LEN];
#ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
extern flash_info_t flash_info[];
#endif
/* 512 is poor choice for ethernet, MTU is typically 1500.
* Minus eth.hdrs thats 1468. Can get 2x better throughput with
* almost-MTU block sizes. At least try... fall back to 512 if need be.
* (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
*/
#ifdef CONFIG_TFTP_BLOCKSIZE
#define TFTP_MTU_BLOCKSIZE CONFIG_TFTP_BLOCKSIZE
#else
#define TFTP_MTU_BLOCKSIZE 1468
#endif
static unsigned short TftpBlkSize = TFTP_BLOCK_SIZE;
static unsigned short TftpBlkSizeOption = TFTP_MTU_BLOCKSIZE;
#ifdef CONFIG_MCAST_TFTP
#include <malloc.h>
#define MTFTP_BITMAPSIZE 0x1000
static unsigned *Bitmap;
static int PrevBitmapHole, Mapsize = MTFTP_BITMAPSIZE;
static uchar ProhibitMcast, MasterClient;
static uchar Multicast;
extern IPaddr_t Mcast_addr;
static int Mcast_port;
static ulong TftpEndingBlock; /* can get 'last' block before done..*/
static void parse_multicast_oack(char *pkt, int len);
static void
mcast_cleanup(void)
{
if (Mcast_addr)
eth_mcast_join(Mcast_addr, 0);
if (Bitmap)
free(Bitmap);
Bitmap = NULL;
Mcast_addr = Multicast = Mcast_port = 0;
TftpEndingBlock = -1;
}
#endif /* CONFIG_MCAST_TFTP */
static __inline__ void
store_block(unsigned block, uchar *src, unsigned len)
{
ulong offset = block * TftpBlkSize + TftpBlockWrapOffset;
ulong newsize = offset + len;
#ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
int i, rc = 0;
for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
/* start address in flash? */
if (flash_info[i].flash_id == FLASH_UNKNOWN)
continue;
if (load_addr + offset >= flash_info[i].start[0]) {
rc = 1;
break;
}
}
if (rc) { /* Flash is destination for this packet */
rc = flash_write((char *)src, (ulong)(load_addr+offset), len);
if (rc) {
flash_perror(rc);
NetState = NETLOOP_FAIL;
return;
}
}
else
#endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
{
(void)memcpy((void *)(load_addr + offset), src, len);
}
#ifdef CONFIG_MCAST_TFTP
if (Multicast)
ext2_set_bit(block, Bitmap);
#endif
if (NetBootFileXferSize < newsize)
NetBootFileXferSize = newsize;
}
/* Clear our state ready for a new transfer */
static void new_transfer(void)
{
TftpLastBlock = 0;
TftpBlockWrap = 0;
TftpBlockWrapOffset = 0;
#ifdef CONFIG_CMD_TFTPPUT
TftpFinalBlock = 0;
#endif
}
#ifdef CONFIG_CMD_TFTPPUT
/**
* Load the next block from memory to be sent over tftp.
*
* @param block Block number to send
* @param dst Destination buffer for data
* @param len Number of bytes in block (this one and every other)
* @return number of bytes loaded
*/
static int load_block(unsigned block, uchar *dst, unsigned len)
{
/* We may want to get the final block from the previous set */
ulong offset = ((int)block - 1) * len + TftpBlockWrapOffset;
ulong tosend = len;
tosend = min(NetBootFileXferSize - offset, tosend);
(void)memcpy(dst, (void *)(save_addr + offset), tosend);
debug("%s: block=%d, offset=%ld, len=%d, tosend=%ld\n", __func__,
block, offset, len, tosend);
return tosend;
}
#endif
static void TftpSend(void);
static void TftpTimeout(void);
/**********************************************************************/
static void show_block_marker(void)
{
#ifdef CONFIG_TFTP_TSIZE
if (TftpTsize) {
ulong pos = TftpBlock * TftpBlkSize + TftpBlockWrapOffset;
while (TftpNumchars < pos * 50 / TftpTsize) {
putc('#');
TftpNumchars++;
}
} else
#endif
{
if (((TftpBlock - 1) % 10) == 0)
putc('#');
else if ((TftpBlock % (10 * HASHES_PER_LINE)) == 0)
puts("\n\t ");
}
}
/**
* restart the current transfer due to an error
*
* @param msg Message to print for user
*/
static void restart(const char *msg)
{
printf("\n%s; starting again\n", msg);
#ifdef CONFIG_MCAST_TFTP
mcast_cleanup();
#endif
NetStartAgain();
}
/*
* Check if the block number has wrapped, and update progress
*
* TODO: The egregious use of global variables in this file should be tidied.
*/
static void update_block_number(void)
{
/*
* RFC1350 specifies that the first data packet will
* have sequence number 1. If we receive a sequence
* number of 0 this means that there was a wrap
* around of the (16 bit) counter.
*/
if (TftpBlock == 0) {
TftpBlockWrap++;
TftpBlockWrapOffset += TftpBlkSize * TFTP_SEQUENCE_SIZE;
TftpTimeoutCount = 0; /* we've done well, reset thhe timeout */
} else {
show_block_marker();
}
}
/* The TFTP get or put is complete */
static void tftp_complete(void)
{
#ifdef CONFIG_TFTP_TSIZE
/* Print hash marks for the last packet received */
while (TftpTsize && TftpNumchars < 49) {
putc('#');
TftpNumchars++;
}
#endif
puts("\ndone\n");
NetState = NETLOOP_SUCCESS;
}
static void
TftpSend(void)
{
uchar *pkt;
volatile uchar *xp;
int len = 0;
volatile ushort *s;
#ifdef CONFIG_MCAST_TFTP
/* Multicast TFTP.. non-MasterClients do not ACK data. */
if (Multicast
&& (TftpState == STATE_DATA)
&& (MasterClient == 0))
return;
#endif
/*
* We will always be sending some sort of packet, so
* cobble together the packet headers now.
*/
pkt = (uchar *)(NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE);
switch (TftpState) {
case STATE_SEND_RRQ:
case STATE_SEND_WRQ:
xp = pkt;
s = (ushort *)pkt;
#ifdef CONFIG_CMD_TFTPPUT
*s++ = htons(TftpState == STATE_SEND_RRQ ? TFTP_RRQ :
TFTP_WRQ);
#else
*s++ = htons(TFTP_RRQ);
#endif
pkt = (uchar *)s;
strcpy((char *)pkt, tftp_filename);
pkt += strlen(tftp_filename) + 1;
strcpy((char *)pkt, "octet");
pkt += 5 /*strlen("octet")*/ + 1;
strcpy((char *)pkt, "timeout");
pkt += 7 /*strlen("timeout")*/ + 1;
sprintf((char *)pkt, "%lu", TftpTimeoutMSecs / 1000);
debug("send option \"timeout %s\"\n", (char *)pkt);
pkt += strlen((char *)pkt) + 1;
#ifdef CONFIG_TFTP_TSIZE
pkt += sprintf((char *)pkt, "tsize%c%lu%c",
0, NetBootFileXferSize, 0);
#endif
/* try for more effic. blk size */
pkt += sprintf((char *)pkt, "blksize%c%d%c",
0, TftpBlkSizeOption, 0);
#ifdef CONFIG_MCAST_TFTP
/* Check all preconditions before even trying the option */
if (!ProhibitMcast
&& (Bitmap = malloc(Mapsize))
&& eth_get_dev()->mcast) {
free(Bitmap);
Bitmap = NULL;
pkt += sprintf((char *)pkt, "multicast%c%c", 0, 0);
}
#endif /* CONFIG_MCAST_TFTP */
len = pkt - xp;
break;
case STATE_OACK:
#ifdef CONFIG_MCAST_TFTP
/* My turn! Start at where I need blocks I missed.*/
if (Multicast)
TftpBlock = ext2_find_next_zero_bit(Bitmap,
(Mapsize*8), 0);
/*..falling..*/
#endif
case STATE_RECV_WRQ:
case STATE_DATA:
xp = pkt;
s = (ushort *)pkt;
s[0] = htons(TFTP_ACK);
s[1] = htons(TftpBlock);
pkt = (uchar *)(s + 2);
#ifdef CONFIG_CMD_TFTPPUT
if (TftpWriting) {
int toload = TftpBlkSize;
int loaded = load_block(TftpBlock, pkt, toload);
s[0] = htons(TFTP_DATA);
pkt += loaded;
TftpFinalBlock = (loaded < toload);
}
#endif
len = pkt - xp;
break;
case STATE_TOO_LARGE:
xp = pkt;
s = (ushort *)pkt;
*s++ = htons(TFTP_ERROR);
*s++ = htons(3);
pkt = (uchar *)s;
strcpy((char *)pkt, "File too large");
pkt += 14 /*strlen("File too large")*/ + 1;
len = pkt - xp;
break;
case STATE_BAD_MAGIC:
xp = pkt;
s = (ushort *)pkt;
*s++ = htons(TFTP_ERROR);
*s++ = htons(2);
pkt = (uchar *)s;
strcpy((char *)pkt, "File has bad magic");
pkt += 18 /*strlen("File has bad magic")*/ + 1;
len = pkt - xp;
break;
}
NetSendUDPPacket(NetServerEther, TftpRemoteIP, TftpRemotePort,
TftpOurPort, len);
}
#ifdef CONFIG_CMD_TFTPPUT
static void icmp_handler(unsigned type, unsigned code, unsigned dest,
IPaddr_t sip, unsigned src, uchar *pkt, unsigned len)
{
if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
/* Oh dear the other end has gone away */
restart("TFTP server died");
}
}
#endif
static void
TftpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
unsigned len)
{
ushort proto;
ushort *s;
int i;
if (dest != TftpOurPort) {
#ifdef CONFIG_MCAST_TFTP
if (Multicast
&& (!Mcast_port || (dest != Mcast_port)))
#endif
return;
}
if (TftpState != STATE_SEND_RRQ && src != TftpRemotePort &&
TftpState != STATE_RECV_WRQ && TftpState != STATE_SEND_WRQ)
return;
if (len < 2)
return;
len -= 2;
/* warning: don't use increment (++) in ntohs() macros!! */
s = (ushort *)pkt;
proto = *s++;
pkt = (uchar *)s;
switch (ntohs(proto)) {
case TFTP_RRQ:
break;
case TFTP_ACK:
#ifdef CONFIG_CMD_TFTPPUT
if (TftpWriting) {
if (TftpFinalBlock) {
tftp_complete();
} else {
/*
* Move to the next block. We want our block
* count to wrap just like the other end!
*/
int block = ntohs(*s);
int ack_ok = (TftpBlock == block);
TftpBlock = (unsigned short)(block + 1);
update_block_number();
if (ack_ok)
TftpSend(); /* Send next data block */
}
}
#endif
break;
default:
break;
#ifdef CONFIG_CMD_TFTPSRV
case TFTP_WRQ:
debug("Got WRQ\n");
TftpRemoteIP = sip;
TftpRemotePort = src;
TftpOurPort = 1024 + (get_timer(0) % 3072);
new_transfer();
TftpSend(); /* Send ACK(0) */
break;
#endif
case TFTP_OACK:
debug("Got OACK: %s %s\n",
pkt,
pkt + strlen((char *)pkt) + 1);
TftpState = STATE_OACK;
TftpRemotePort = src;
/*
* Check for 'blksize' option.
* Careful: "i" is signed, "len" is unsigned, thus
* something like "len-8" may give a *huge* number
*/
for (i = 0; i+8 < len; i++) {
if (strcmp((char *)pkt+i, "blksize") == 0) {
TftpBlkSize = (unsigned short)
simple_strtoul((char *)pkt+i+8, NULL,
10);
debug("Blocksize ack: %s, %d\n",
(char *)pkt+i+8, TftpBlkSize);
}
#ifdef CONFIG_TFTP_TSIZE
if (strcmp((char *)pkt+i, "tsize") == 0) {
TftpTsize = simple_strtoul((char *)pkt+i+6,
NULL, 10);
debug("size = %s, %d\n",
(char *)pkt+i+6, TftpTsize);
}
#endif
}
#ifdef CONFIG_MCAST_TFTP
parse_multicast_oack((char *)pkt, len-1);
if ((Multicast) && (!MasterClient))
TftpState = STATE_DATA; /* passive.. */
else
#endif
#ifdef CONFIG_CMD_TFTPPUT
if (TftpWriting) {
/* Get ready to send the first block */
TftpState = STATE_DATA;
TftpBlock++;
}
#endif
TftpSend(); /* Send ACK or first data block */
break;
case TFTP_DATA:
if (len < 2)
return;
len -= 2;
TftpBlock = ntohs(*(ushort *)pkt);
update_block_number();
if (TftpState == STATE_SEND_RRQ)
debug("Server did not acknowledge timeout option!\n");
if (TftpState == STATE_SEND_RRQ || TftpState == STATE_OACK ||
TftpState == STATE_RECV_WRQ) {
/* first block received */
TftpState = STATE_DATA;
TftpRemotePort = src;
new_transfer();
#ifdef CONFIG_MCAST_TFTP
if (Multicast) { /* start!=1 common if mcast */
TftpLastBlock = TftpBlock - 1;
} else
#endif
if (TftpBlock != 1) { /* Assertion */
printf("\nTFTP error: "
"First block is not block 1 (%ld)\n"
"Starting again\n\n",
TftpBlock);
NetStartAgain();
break;
}
}
if (TftpBlock == TftpLastBlock) {
/*
* Same block again; ignore it.
*/
break;
}
TftpLastBlock = TftpBlock;
TftpTimeoutCountMax = TIMEOUT_COUNT;
NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
store_block(TftpBlock - 1, pkt + 2, len);
/*
* Acknowledge the block just received, which will prompt
* the remote for the next one.
*/
#ifdef CONFIG_MCAST_TFTP
/* if I am the MasterClient, actively calculate what my next
* needed block is; else I'm passive; not ACKING
*/
if (Multicast) {
if (len < TftpBlkSize) {
TftpEndingBlock = TftpBlock;
} else if (MasterClient) {
TftpBlock = PrevBitmapHole =
ext2_find_next_zero_bit(
Bitmap,
(Mapsize*8),
PrevBitmapHole);
if (TftpBlock > ((Mapsize*8) - 1)) {
printf("tftpfile too big\n");
/* try to double it and retry */
Mapsize <<= 1;
mcast_cleanup();
NetStartAgain();
return;
}
TftpLastBlock = TftpBlock;
}
}
#endif
TftpSend();
#ifdef CONFIG_MCAST_TFTP
if (Multicast) {
if (MasterClient && (TftpBlock >= TftpEndingBlock)) {
puts("\nMulticast tftp done\n");
mcast_cleanup();
NetState = NETLOOP_SUCCESS;
}
}
else
#endif
if (len < TftpBlkSize)
tftp_complete();
break;
case TFTP_ERROR:
printf("\nTFTP error: '%s' (%d)\n",
pkt + 2, ntohs(*(ushort *)pkt));
switch (ntohs(*(ushort *)pkt)) {
case TFTP_ERR_FILE_NOT_FOUND:
case TFTP_ERR_ACCESS_DENIED:
puts("Not retrying...\n");
eth_halt();
NetState = NETLOOP_FAIL;
break;
case TFTP_ERR_UNDEFINED:
case TFTP_ERR_DISK_FULL:
case TFTP_ERR_UNEXPECTED_OPCODE:
case TFTP_ERR_UNKNOWN_TRANSFER_ID:
case TFTP_ERR_FILE_ALREADY_EXISTS:
default:
puts("Starting again\n\n");
#ifdef CONFIG_MCAST_TFTP
mcast_cleanup();
#endif
NetStartAgain();
break;
}
break;
}
}
static void
TftpTimeout(void)
{
if (++TftpTimeoutCount > TftpTimeoutCountMax) {
restart("Retry count exceeded");
} else {
puts("T ");
NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
if (TftpState != STATE_RECV_WRQ)
TftpSend();
}
}
void TftpStart(enum proto_t protocol)
{
char *ep; /* Environment pointer */
/*
* Allow the user to choose TFTP blocksize and timeout.
* TFTP protocol has a minimal timeout of 1 second.
*/
ep = getenv("tftpblocksize");
if (ep != NULL)
TftpBlkSizeOption = simple_strtol(ep, NULL, 10);
ep = getenv("tftptimeout");
if (ep != NULL)
TftpTimeoutMSecs = simple_strtol(ep, NULL, 10);
if (TftpTimeoutMSecs < 1000) {
printf("TFTP timeout (%ld ms) too low, "
"set minimum = 1000 ms\n",
TftpTimeoutMSecs);
TftpTimeoutMSecs = 1000;
}
debug("TFTP blocksize = %i, timeout = %ld ms\n",
TftpBlkSizeOption, TftpTimeoutMSecs);
TftpRemoteIP = NetServerIP;
if (BootFile[0] == '\0') {
sprintf(default_filename, "%02X%02X%02X%02X.img",
NetOurIP & 0xFF,
(NetOurIP >> 8) & 0xFF,
(NetOurIP >> 16) & 0xFF,
(NetOurIP >> 24) & 0xFF);
strncpy(tftp_filename, default_filename, MAX_LEN);
tftp_filename[MAX_LEN-1] = 0;
printf("*** Warning: no boot file name; using '%s'\n",
tftp_filename);
} else {
char *p = strchr(BootFile, ':');
if (p == NULL) {
strncpy(tftp_filename, BootFile, MAX_LEN);
tftp_filename[MAX_LEN-1] = 0;
} else {
TftpRemoteIP = string_to_ip(BootFile);
strncpy(tftp_filename, p + 1, MAX_LEN);
tftp_filename[MAX_LEN-1] = 0;
}
}
printf("Using %s device\n", eth_get_name());
printf("TFTP %s server %pI4; our IP address is %pI4",
#ifdef CONFIG_CMD_TFTPPUT
protocol == TFTPPUT ? "to" : "from",
#else
"from",
#endif
&TftpRemoteIP, &NetOurIP);
/* Check if we need to send across this subnet */
if (NetOurGatewayIP && NetOurSubnetMask) {
IPaddr_t OurNet = NetOurIP & NetOurSubnetMask;
IPaddr_t RemoteNet = TftpRemoteIP & NetOurSubnetMask;
if (OurNet != RemoteNet)
printf("; sending through gateway %pI4",
&NetOurGatewayIP);
}
putc('\n');
printf("Filename '%s'.", tftp_filename);
if (NetBootFileSize) {
printf(" Size is 0x%x Bytes = ", NetBootFileSize<<9);
print_size(NetBootFileSize<<9, "");
}
putc('\n');
#ifdef CONFIG_CMD_TFTPPUT
TftpWriting = (protocol == TFTPPUT);
if (TftpWriting) {
printf("Save address: 0x%lx\n", save_addr);
printf("Save size: 0x%lx\n", save_size);
NetBootFileXferSize = save_size;
puts("Saving: *\b");
TftpState = STATE_SEND_WRQ;
new_transfer();
} else
#endif
{
printf("Load address: 0x%lx\n", load_addr);
puts("Loading: *\b");
TftpState = STATE_SEND_RRQ;
}
TftpTimeoutCountMax = TftpRRQTimeoutCountMax;
NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
NetSetHandler(TftpHandler);
#ifdef CONFIG_CMD_TFTPPUT
net_set_icmp_handler(icmp_handler);
#endif
TftpRemotePort = WELL_KNOWN_PORT;
TftpTimeoutCount = 0;
/* Use a pseudo-random port unless a specific port is set */
TftpOurPort = 1024 + (get_timer(0) % 3072);
#ifdef CONFIG_TFTP_PORT
ep = getenv("tftpdstp");
if (ep != NULL)
TftpRemotePort = simple_strtol(ep, NULL, 10);
ep = getenv("tftpsrcp");
if (ep != NULL)
TftpOurPort = simple_strtol(ep, NULL, 10);
#endif
TftpBlock = 0;
/* zero out server ether in case the server ip has changed */
memset(NetServerEther, 0, 6);
/* Revert TftpBlkSize to dflt */
TftpBlkSize = TFTP_BLOCK_SIZE;
#ifdef CONFIG_MCAST_TFTP
mcast_cleanup();
#endif
#ifdef CONFIG_TFTP_TSIZE
TftpTsize = 0;
TftpNumchars = 0;
#endif
TftpSend();
}
#ifdef CONFIG_CMD_TFTPSRV
void
TftpStartServer(void)
{
tftp_filename[0] = 0;
printf("Using %s device\n", eth_get_name());
printf("Listening for TFTP transfer on %pI4\n", &NetOurIP);
printf("Load address: 0x%lx\n", load_addr);
puts("Loading: *\b");
TftpTimeoutCountMax = TIMEOUT_COUNT;
TftpTimeoutCount = 0;
TftpTimeoutMSecs = TIMEOUT;
NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
/* Revert TftpBlkSize to dflt */
TftpBlkSize = TFTP_BLOCK_SIZE;
TftpBlock = 0;
TftpOurPort = WELL_KNOWN_PORT;
#ifdef CONFIG_TFTP_TSIZE
TftpTsize = 0;
TftpNumchars = 0;
#endif
TftpState = STATE_RECV_WRQ;
NetSetHandler(TftpHandler);
}
#endif /* CONFIG_CMD_TFTPSRV */
#ifdef CONFIG_MCAST_TFTP
/* Credits: atftp project.
*/
/* pick up BcastAddr, Port, and whether I am [now] the master-client. *
* Frame:
* +-------+-----------+---+-------~~-------+---+
* | opc | multicast | 0 | addr, port, mc | 0 |
* +-------+-----------+---+-------~~-------+---+
* The multicast addr/port becomes what I listen to, and if 'mc' is '1' then
* I am the new master-client so must send ACKs to DataBlocks. If I am not
* master-client, I'm a passive client, gathering what DataBlocks I may and
* making note of which ones I got in my bitmask.
* In theory, I never go from master->passive..
* .. this comes in with pkt already pointing just past opc
*/
static void parse_multicast_oack(char *pkt, int len)
{
int i;
IPaddr_t addr;
char *mc_adr, *port, *mc;
mc_adr = port = mc = NULL;
/* march along looking for 'multicast\0', which has to start at least
* 14 bytes back from the end.
*/
for (i = 0; i < len-14; i++)
if (strcmp(pkt+i, "multicast") == 0)
break;
if (i >= (len-14)) /* non-Multicast OACK, ign. */
return;
i += 10; /* strlen multicast */
mc_adr = pkt+i;
for (; i < len; i++) {
if (*(pkt+i) == ',') {
*(pkt+i) = '\0';
if (port) {
mc = pkt+i+1;
break;
} else {
port = pkt+i+1;
}
}
}
if (!port || !mc_adr || !mc)
return;
if (Multicast && MasterClient) {
printf("I got a OACK as master Client, WRONG!\n");
return;
}
/* ..I now accept packets destined for this MCAST addr, port */
if (!Multicast) {
if (Bitmap) {
printf("Internal failure! no mcast.\n");
free(Bitmap);
Bitmap = NULL;
ProhibitMcast = 1;
return ;
}
/* I malloc instead of pre-declare; so that if the file ends
* up being too big for this bitmap I can retry
*/
Bitmap = malloc(Mapsize);
if (!Bitmap) {
printf("No Bitmap, no multicast. Sorry.\n");
ProhibitMcast = 1;
return;
}
memset(Bitmap, 0, Mapsize);
PrevBitmapHole = 0;
Multicast = 1;
}
addr = string_to_ip(mc_adr);
if (Mcast_addr != addr) {
if (Mcast_addr)
eth_mcast_join(Mcast_addr, 0);
Mcast_addr = addr;
if (eth_mcast_join(Mcast_addr, 1)) {
printf("Fail to set mcast, revert to TFTP\n");
ProhibitMcast = 1;
mcast_cleanup();
NetStartAgain();
}
}
MasterClient = (unsigned char)simple_strtoul((char *)mc, NULL, 10);
Mcast_port = (unsigned short)simple_strtoul(port, NULL, 10);
printf("Multicast: %s:%d [%d]\n", mc_adr, Mcast_port, MasterClient);
return;
}
#endif /* Multicast TFTP */
|
1001-study-uboot
|
net/tftp.c
|
C
|
gpl3
| 22,750
|
/*
* Based on LiMon - BOOTP.
*
* Copyright 1994, 1995, 2000 Neil Russell.
* (See License)
* Copyright 2000 Roland Borde
* Copyright 2000 Paolo Scaffardi
* Copyright 2000-2004 Wolfgang Denk, wd@denx.de
*/
#include <common.h>
#include <command.h>
#include <net.h>
#include "bootp.h"
#include "tftp.h"
#include "nfs.h"
#ifdef CONFIG_STATUS_LED
#include <status_led.h>
#endif
#include <linux/compiler.h>
#define BOOTP_VENDOR_MAGIC 0x63825363 /* RFC1048 Magic Cookie */
#define TIMEOUT 5000UL /* Milliseconds before trying BOOTP again */
#ifndef CONFIG_NET_RETRY_COUNT
# define TIMEOUT_COUNT 5 /* # of timeouts before giving up */
#else
# define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT)
#endif
#define PORT_BOOTPS 67 /* BOOTP server UDP port */
#define PORT_BOOTPC 68 /* BOOTP client UDP port */
#ifndef CONFIG_DHCP_MIN_EXT_LEN /* minimal length of extension list */
#define CONFIG_DHCP_MIN_EXT_LEN 64
#endif
ulong BootpID;
int BootpTry;
#ifdef CONFIG_BOOTP_RANDOM_DELAY
ulong seed1, seed2;
#endif
#if defined(CONFIG_CMD_DHCP)
dhcp_state_t dhcp_state = INIT;
unsigned long dhcp_leasetime = 0;
IPaddr_t NetDHCPServerIP = 0;
static void DhcpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
unsigned len);
/* For Debug */
#if 0
static char *dhcpmsg2str(int type)
{
switch (type) {
case 1: return "DHCPDISCOVER"; break;
case 2: return "DHCPOFFER"; break;
case 3: return "DHCPREQUEST"; break;
case 4: return "DHCPDECLINE"; break;
case 5: return "DHCPACK"; break;
case 6: return "DHCPNACK"; break;
case 7: return "DHCPRELEASE"; break;
default: return "UNKNOWN/INVALID MSG TYPE"; break;
}
}
#endif
#if defined(CONFIG_BOOTP_VENDOREX)
extern u8 *dhcp_vendorex_prep (u8 *e); /*rtn new e after add own opts. */
extern u8 *dhcp_vendorex_proc (u8 *e); /*rtn next e if mine,else NULL */
#endif
#endif
static int BootpCheckPkt(uchar *pkt, unsigned dest, unsigned src, unsigned len)
{
Bootp_t *bp = (Bootp_t *) pkt;
int retval = 0;
if (dest != PORT_BOOTPC || src != PORT_BOOTPS)
retval = -1;
else if (len < sizeof (Bootp_t) - OPT_SIZE)
retval = -2;
else if (bp->bp_op != OP_BOOTREQUEST &&
bp->bp_op != OP_BOOTREPLY &&
bp->bp_op != DHCP_OFFER &&
bp->bp_op != DHCP_ACK &&
bp->bp_op != DHCP_NAK ) {
retval = -3;
}
else if (bp->bp_htype != HWT_ETHER)
retval = -4;
else if (bp->bp_hlen != HWL_ETHER)
retval = -5;
else if (NetReadLong((ulong*)&bp->bp_id) != BootpID) {
retval = -6;
}
debug("Filtering pkt = %d\n", retval);
return retval;
}
/*
* Copy parameters of interest from BOOTP_REPLY/DHCP_OFFER packet
*/
static void BootpCopyNetParams(Bootp_t *bp)
{
__maybe_unused IPaddr_t tmp_ip;
NetCopyIP(&NetOurIP, &bp->bp_yiaddr);
#if !defined(CONFIG_BOOTP_SERVERIP)
NetCopyIP(&tmp_ip, &bp->bp_siaddr);
if (tmp_ip != 0)
NetCopyIP(&NetServerIP, &bp->bp_siaddr);
memcpy (NetServerEther, ((Ethernet_t *)NetRxPacket)->et_src, 6);
#endif
if (strlen(bp->bp_file) > 0)
copy_filename (BootFile, bp->bp_file, sizeof(BootFile));
debug("Bootfile: %s\n", BootFile);
/* Propagate to environment:
* don't delete exising entry when BOOTP / DHCP reply does
* not contain a new value
*/
if (*BootFile) {
setenv ("bootfile", BootFile);
}
}
static int truncate_sz (const char *name, int maxlen, int curlen)
{
if (curlen >= maxlen) {
printf("*** WARNING: %s is too long (%d - max: %d) - truncated\n",
name, curlen, maxlen);
curlen = maxlen - 1;
}
return (curlen);
}
#if !defined(CONFIG_CMD_DHCP)
static void BootpVendorFieldProcess (u8 * ext)
{
int size = *(ext + 1);
debug("[BOOTP] Processing extension %d... (%d bytes)\n", *ext,
*(ext + 1));
NetBootFileSize = 0;
switch (*ext) {
/* Fixed length fields */
case 1: /* Subnet mask */
if (NetOurSubnetMask == 0)
NetCopyIP (&NetOurSubnetMask, (IPaddr_t *) (ext + 2));
break;
case 2: /* Time offset - Not yet supported */
break;
/* Variable length fields */
case 3: /* Gateways list */
if (NetOurGatewayIP == 0) {
NetCopyIP (&NetOurGatewayIP, (IPaddr_t *) (ext + 2));
}
break;
case 4: /* Time server - Not yet supported */
break;
case 5: /* IEN-116 name server - Not yet supported */
break;
case 6:
if (NetOurDNSIP == 0) {
NetCopyIP (&NetOurDNSIP, (IPaddr_t *) (ext + 2));
}
#if defined(CONFIG_BOOTP_DNS2)
if ((NetOurDNS2IP == 0) && (size > 4)) {
NetCopyIP (&NetOurDNS2IP, (IPaddr_t *) (ext + 2 + 4));
}
#endif
break;
case 7: /* Log server - Not yet supported */
break;
case 8: /* Cookie/Quote server - Not yet supported */
break;
case 9: /* LPR server - Not yet supported */
break;
case 10: /* Impress server - Not yet supported */
break;
case 11: /* RPL server - Not yet supported */
break;
case 12: /* Host name */
if (NetOurHostName[0] == 0) {
size = truncate_sz ("Host Name", sizeof (NetOurHostName), size);
memcpy (&NetOurHostName, ext + 2, size);
NetOurHostName[size] = 0;
}
break;
case 13: /* Boot file size */
if (size == 2)
NetBootFileSize = ntohs (*(ushort *) (ext + 2));
else if (size == 4)
NetBootFileSize = ntohl (*(ulong *) (ext + 2));
break;
case 14: /* Merit dump file - Not yet supported */
break;
case 15: /* Domain name - Not yet supported */
break;
case 16: /* Swap server - Not yet supported */
break;
case 17: /* Root path */
if (NetOurRootPath[0] == 0) {
size = truncate_sz ("Root Path", sizeof (NetOurRootPath), size);
memcpy (&NetOurRootPath, ext + 2, size);
NetOurRootPath[size] = 0;
}
break;
case 18: /* Extension path - Not yet supported */
/*
* This can be used to send the information of the
* vendor area in another file that the client can
* access via TFTP.
*/
break;
/* IP host layer fields */
case 40: /* NIS Domain name */
if (NetOurNISDomain[0] == 0) {
size = truncate_sz ("NIS Domain Name", sizeof (NetOurNISDomain), size);
memcpy (&NetOurNISDomain, ext + 2, size);
NetOurNISDomain[size] = 0;
}
break;
#if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
case 42: /* NTP server IP */
NetCopyIP(&NetNtpServerIP, (IPaddr_t *) (ext + 2));
break;
#endif
/* Application layer fields */
case 43: /* Vendor specific info - Not yet supported */
/*
* Binary information to exchange specific
* product information.
*/
break;
/* Reserved (custom) fields (128..254) */
}
}
static void BootpVendorProcess (u8 * ext, int size)
{
u8 *end = ext + size;
debug("[BOOTP] Checking extension (%d bytes)...\n", size);
while ((ext < end) && (*ext != 0xff)) {
if (*ext == 0) {
ext++;
} else {
u8 *opt = ext;
ext += ext[1] + 2;
if (ext <= end)
BootpVendorFieldProcess (opt);
}
}
debug("[BOOTP] Received fields: \n");
if (NetOurSubnetMask)
debug("NetOurSubnetMask : %pI4\n", &NetOurSubnetMask);
if (NetOurGatewayIP)
debug("NetOurGatewayIP : %pI4", &NetOurGatewayIP);
if (NetBootFileSize)
debug("NetBootFileSize : %d\n", NetBootFileSize);
if (NetOurHostName[0])
debug("NetOurHostName : %s\n", NetOurHostName);
if (NetOurRootPath[0])
debug("NetOurRootPath : %s\n", NetOurRootPath);
if (NetOurNISDomain[0])
debug("NetOurNISDomain : %s\n", NetOurNISDomain);
if (NetBootFileSize)
debug("NetBootFileSize: %d\n", NetBootFileSize);
#if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
if (NetNtpServerIP)
debug("NetNtpServerIP : %pI4\n", &NetNtpServerIP);
#endif
}
/*
* Handle a BOOTP received packet.
*/
static void
BootpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
unsigned len)
{
Bootp_t *bp;
debug("got BOOTP packet (src=%d, dst=%d, len=%d want_len=%zu)\n",
src, dest, len, sizeof (Bootp_t));
bp = (Bootp_t *)pkt;
if (BootpCheckPkt(pkt, dest, src, len)) /* Filter out pkts we don't want */
return;
/*
* Got a good BOOTP reply. Copy the data into our variables.
*/
#ifdef CONFIG_STATUS_LED
status_led_set (STATUS_LED_BOOT, STATUS_LED_OFF);
#endif
BootpCopyNetParams(bp); /* Store net parameters from reply */
/* Retrieve extended information (we must parse the vendor area) */
if (NetReadLong((ulong*)&bp->bp_vend[0]) == htonl(BOOTP_VENDOR_MAGIC))
BootpVendorProcess((uchar *)&bp->bp_vend[4], len);
NetSetTimeout(0, (thand_f *)0);
debug("Got good BOOTP\n");
net_auto_load();
}
#endif
/*
* Timeout on BOOTP/DHCP request.
*/
static void
BootpTimeout(void)
{
if (BootpTry >= TIMEOUT_COUNT) {
puts ("\nRetry count exceeded; starting again\n");
NetStartAgain ();
} else {
NetSetTimeout (TIMEOUT, BootpTimeout);
BootpRequest ();
}
}
/*
* Initialize BOOTP extension fields in the request.
*/
#if defined(CONFIG_CMD_DHCP)
static int DhcpExtended (u8 * e, int message_type, IPaddr_t ServerID, IPaddr_t RequestedIP)
{
u8 *start = e;
u8 *cnt;
#if defined(CONFIG_BOOTP_PXE)
char *uuid;
size_t vci_strlen;
u16 clientarch;
#endif
#if defined(CONFIG_BOOTP_VENDOREX)
u8 *x;
#endif
#if defined(CONFIG_BOOTP_SEND_HOSTNAME)
char *hostname;
#endif
*e++ = 99; /* RFC1048 Magic Cookie */
*e++ = 130;
*e++ = 83;
*e++ = 99;
*e++ = 53; /* DHCP Message Type */
*e++ = 1;
*e++ = message_type;
*e++ = 57; /* Maximum DHCP Message Size */
*e++ = 2;
*e++ = (576 - 312 + OPT_SIZE) >> 8;
*e++ = (576 - 312 + OPT_SIZE) & 0xff;
if (ServerID) {
int tmp = ntohl (ServerID);
*e++ = 54; /* ServerID */
*e++ = 4;
*e++ = tmp >> 24;
*e++ = tmp >> 16;
*e++ = tmp >> 8;
*e++ = tmp & 0xff;
}
if (RequestedIP) {
int tmp = ntohl (RequestedIP);
*e++ = 50; /* Requested IP */
*e++ = 4;
*e++ = tmp >> 24;
*e++ = tmp >> 16;
*e++ = tmp >> 8;
*e++ = tmp & 0xff;
}
#if defined(CONFIG_BOOTP_SEND_HOSTNAME)
if ((hostname = getenv ("hostname"))) {
int hostnamelen = strlen (hostname);
*e++ = 12; /* Hostname */
*e++ = hostnamelen;
memcpy (e, hostname, hostnamelen);
e += hostnamelen;
}
#endif
#if defined(CONFIG_BOOTP_PXE)
clientarch = CONFIG_BOOTP_PXE_CLIENTARCH;
*e++ = 93; /* Client System Architecture */
*e++ = 2;
*e++ = (clientarch >> 8) & 0xff;
*e++ = clientarch & 0xff;
*e++ = 94; /* Client Network Interface Identifier */
*e++ = 3;
*e++ = 1; /* type field for UNDI */
*e++ = 0; /* major revision */
*e++ = 0; /* minor revision */
uuid = getenv("pxeuuid");
if (uuid) {
if (uuid_str_valid(uuid)) {
*e++ = 97; /* Client Machine Identifier */
*e++ = 17;
*e++ = 0; /* type 0 - UUID */
uuid_str_to_bin(uuid, e);
e += 16;
} else {
printf("Invalid pxeuuid: %s\n", uuid);
}
}
*e++ = 60; /* Vendor Class Identifier */
vci_strlen = strlen(CONFIG_BOOTP_VCI_STRING);
*e++ = vci_strlen;
memcpy(e, CONFIG_BOOTP_VCI_STRING, vci_strlen);
e += vci_strlen;
#endif
#if defined(CONFIG_BOOTP_VENDOREX)
if ((x = dhcp_vendorex_prep (e)))
return x - start;
#endif
*e++ = 55; /* Parameter Request List */
cnt = e++; /* Pointer to count of requested items */
*cnt = 0;
#if defined(CONFIG_BOOTP_SUBNETMASK)
*e++ = 1; /* Subnet Mask */
*cnt += 1;
#endif
#if defined(CONFIG_BOOTP_TIMEOFFSET)
*e++ = 2;
*cnt += 1;
#endif
#if defined(CONFIG_BOOTP_GATEWAY)
*e++ = 3; /* Router Option */
*cnt += 1;
#endif
#if defined(CONFIG_BOOTP_DNS)
*e++ = 6; /* DNS Server(s) */
*cnt += 1;
#endif
#if defined(CONFIG_BOOTP_HOSTNAME)
*e++ = 12; /* Hostname */
*cnt += 1;
#endif
#if defined(CONFIG_BOOTP_BOOTFILESIZE)
*e++ = 13; /* Boot File Size */
*cnt += 1;
#endif
#if defined(CONFIG_BOOTP_BOOTPATH)
*e++ = 17; /* Boot path */
*cnt += 1;
#endif
#if defined(CONFIG_BOOTP_NISDOMAIN)
*e++ = 40; /* NIS Domain name request */
*cnt += 1;
#endif
#if defined(CONFIG_BOOTP_NTPSERVER)
*e++ = 42;
*cnt += 1;
#endif
/* no options, so back up to avoid sending an empty request list */
if (*cnt == 0)
e -= 2;
*e++ = 255; /* End of the list */
/* Pad to minimal length */
#ifdef CONFIG_DHCP_MIN_EXT_LEN
while ((e - start) < CONFIG_DHCP_MIN_EXT_LEN)
*e++ = 0;
#endif
return e - start;
}
#else
/*
* Warning: no field size check - change CONFIG_BOOTP_* at your own risk!
*/
static int BootpExtended (u8 * e)
{
u8 *start = e;
*e++ = 99; /* RFC1048 Magic Cookie */
*e++ = 130;
*e++ = 83;
*e++ = 99;
#if defined(CONFIG_CMD_DHCP)
*e++ = 53; /* DHCP Message Type */
*e++ = 1;
*e++ = DHCP_DISCOVER;
*e++ = 57; /* Maximum DHCP Message Size */
*e++ = 2;
*e++ = (576 - 312 + OPT_SIZE) >> 16;
*e++ = (576 - 312 + OPT_SIZE) & 0xff;
#endif
#if defined(CONFIG_BOOTP_SUBNETMASK)
*e++ = 1; /* Subnet mask request */
*e++ = 4;
e += 4;
#endif
#if defined(CONFIG_BOOTP_GATEWAY)
*e++ = 3; /* Default gateway request */
*e++ = 4;
e += 4;
#endif
#if defined(CONFIG_BOOTP_DNS)
*e++ = 6; /* Domain Name Server */
*e++ = 4;
e += 4;
#endif
#if defined(CONFIG_BOOTP_HOSTNAME)
*e++ = 12; /* Host name request */
*e++ = 32;
e += 32;
#endif
#if defined(CONFIG_BOOTP_BOOTFILESIZE)
*e++ = 13; /* Boot file size */
*e++ = 2;
e += 2;
#endif
#if defined(CONFIG_BOOTP_BOOTPATH)
*e++ = 17; /* Boot path */
*e++ = 32;
e += 32;
#endif
#if defined(CONFIG_BOOTP_NISDOMAIN)
*e++ = 40; /* NIS Domain name request */
*e++ = 32;
e += 32;
#endif
#if defined(CONFIG_BOOTP_NTPSERVER)
*e++ = 42;
*e++ = 4;
e += 4;
#endif
*e++ = 255; /* End of the list */
return e - start;
}
#endif
void
BootpRequest (void)
{
volatile uchar *pkt, *iphdr;
Bootp_t *bp;
int ext_len, pktlen, iplen;
#if defined(CONFIG_CMD_DHCP)
dhcp_state = INIT;
#endif
#ifdef CONFIG_BOOTP_RANDOM_DELAY /* Random BOOTP delay */
unsigned char bi_enetaddr[6];
int reg;
ulong tst1, tst2, sum, m_mask, m_value = 0;
if (BootpTry ==0) {
/* get our mac */
eth_getenv_enetaddr("ethaddr", bi_enetaddr);
debug("BootpRequest => Our Mac: ");
for (reg=0; reg<6; reg++)
debug("%x%c", bi_enetaddr[reg], reg==5 ? '\n' : ':');
/* Mac-Manipulation 2 get seed1 */
tst1=0;
tst2=0;
for (reg=2; reg<6; reg++) {
tst1 = tst1 << 8;
tst1 = tst1 | bi_enetaddr[reg];
}
for (reg=0; reg<2; reg++) {
tst2 = tst2 | bi_enetaddr[reg];
tst2 = tst2 << 8;
}
seed1 = tst1^tst2;
/* Mirror seed1*/
m_mask=0x1;
for (reg=1;reg<=32;reg++) {
m_value |= (m_mask & seed1);
seed1 = seed1 >> 1;
m_value = m_value << 1;
}
seed1 = m_value;
seed2 = 0xB78D0945;
}
/* Random Number Generator */
for (reg=0;reg<=0;reg++) {
sum = seed1 + seed2;
if (sum < seed1 || sum < seed2)
sum++;
seed2 = seed1;
seed1 = sum;
if (BootpTry<=2) { /* Start with max 1024 * 1ms */
sum = sum >> (22-BootpTry);
} else { /*After 3rd BOOTP request max 8192 * 1ms */
sum = sum >> 19;
}
}
printf ("Random delay: %ld ms...\n", sum);
for (reg=0; reg <sum; reg++) {
udelay(1000); /*Wait 1ms*/
}
#endif /* CONFIG_BOOTP_RANDOM_DELAY */
printf("BOOTP broadcast %d\n", ++BootpTry);
pkt = NetTxPacket;
memset ((void*)pkt, 0, PKTSIZE);
pkt += NetSetEther(pkt, NetBcastAddr, PROT_IP);
/*
* Next line results in incorrect packet size being transmitted, resulting
* in errors in some DHCP servers, reporting missing bytes. Size must be
* set in packet header after extension length has been determined.
* C. Hallinan, DS4.COM, Inc.
*/
/* NetSetIP(pkt, 0xFFFFFFFFL, PORT_BOOTPS, PORT_BOOTPC, sizeof (Bootp_t)); */
iphdr = pkt; /* We need this later for NetSetIP() */
pkt += IP_HDR_SIZE;
bp = (Bootp_t *)pkt;
bp->bp_op = OP_BOOTREQUEST;
bp->bp_htype = HWT_ETHER;
bp->bp_hlen = HWL_ETHER;
bp->bp_hops = 0;
bp->bp_secs = htons(get_timer(0) / 1000);
NetWriteIP(&bp->bp_ciaddr, 0);
NetWriteIP(&bp->bp_yiaddr, 0);
NetWriteIP(&bp->bp_siaddr, 0);
NetWriteIP(&bp->bp_giaddr, 0);
memcpy (bp->bp_chaddr, NetOurEther, 6);
copy_filename (bp->bp_file, BootFile, sizeof(bp->bp_file));
/* Request additional information from the BOOTP/DHCP server */
#if defined(CONFIG_CMD_DHCP)
ext_len = DhcpExtended((u8 *)bp->bp_vend, DHCP_DISCOVER, 0, 0);
#else
ext_len = BootpExtended((u8 *)bp->bp_vend);
#endif
/*
* Bootp ID is the lower 4 bytes of our ethernet address
* plus the current time in ms.
*/
BootpID = ((ulong)NetOurEther[2] << 24)
| ((ulong)NetOurEther[3] << 16)
| ((ulong)NetOurEther[4] << 8)
| (ulong)NetOurEther[5];
BootpID += get_timer(0);
BootpID = htonl(BootpID);
NetCopyLong(&bp->bp_id, &BootpID);
/*
* Calculate proper packet lengths taking into account the
* variable size of the options field
*/
pktlen = ((int)(pkt-NetTxPacket)) + BOOTP_HDR_SIZE - sizeof(bp->bp_vend) + ext_len;
iplen = BOOTP_HDR_SIZE - sizeof(bp->bp_vend) + ext_len;
NetSetIP(iphdr, 0xFFFFFFFFL, PORT_BOOTPS, PORT_BOOTPC, iplen);
NetSetTimeout(SELECT_TIMEOUT, BootpTimeout);
#if defined(CONFIG_CMD_DHCP)
dhcp_state = SELECTING;
NetSetHandler(DhcpHandler);
#else
NetSetHandler(BootpHandler);
#endif
NetSendPacket(NetTxPacket, pktlen);
}
#if defined(CONFIG_CMD_DHCP)
static void DhcpOptionsProcess (uchar * popt, Bootp_t *bp)
{
uchar *end = popt + BOOTP_HDR_SIZE;
int oplen, size;
#if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_TIMEOFFSET)
int *to_ptr;
#endif
while (popt < end && *popt != 0xff) {
oplen = *(popt + 1);
switch (*popt) {
case 1:
NetCopyIP (&NetOurSubnetMask, (popt + 2));
break;
#if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_TIMEOFFSET)
case 2: /* Time offset */
to_ptr = &NetTimeOffset;
NetCopyLong ((ulong *)to_ptr, (ulong *)(popt + 2));
NetTimeOffset = ntohl (NetTimeOffset);
break;
#endif
case 3:
NetCopyIP (&NetOurGatewayIP, (popt + 2));
break;
case 6:
NetCopyIP (&NetOurDNSIP, (popt + 2));
#if defined(CONFIG_BOOTP_DNS2)
if (*(popt + 1) > 4) {
NetCopyIP (&NetOurDNS2IP, (popt + 2 + 4));
}
#endif
break;
case 12:
size = truncate_sz ("Host Name", sizeof (NetOurHostName), oplen);
memcpy (&NetOurHostName, popt + 2, size);
NetOurHostName[size] = 0;
break;
case 15: /* Ignore Domain Name Option */
break;
case 17:
size = truncate_sz ("Root Path", sizeof (NetOurRootPath), oplen);
memcpy (&NetOurRootPath, popt + 2, size);
NetOurRootPath[size] = 0;
break;
#if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
case 42: /* NTP server IP */
NetCopyIP (&NetNtpServerIP, (popt + 2));
break;
#endif
case 51:
NetCopyLong (&dhcp_leasetime, (ulong *) (popt + 2));
break;
case 53: /* Ignore Message Type Option */
break;
case 54:
NetCopyIP (&NetDHCPServerIP, (popt + 2));
break;
case 58: /* Ignore Renewal Time Option */
break;
case 59: /* Ignore Rebinding Time Option */
break;
case 66: /* Ignore TFTP server name */
break;
case 67: /* vendor opt bootfile */
/*
* I can't use dhcp_vendorex_proc here because I need
* to write into the bootp packet - even then I had to
* pass the bootp packet pointer into here as the
* second arg
*/
size = truncate_sz ("Opt Boot File",
sizeof(bp->bp_file),
oplen);
if (bp->bp_file[0] == '\0' && size > 0) {
/*
* only use vendor boot file if we didn't
* receive a boot file in the main non-vendor
* part of the packet - god only knows why
* some vendors chose not to use this perfectly
* good spot to store the boot file (join on
* Tru64 Unix) it seems mind bogglingly crazy
* to me
*/
printf("*** WARNING: using vendor "
"optional boot file\n");
memcpy(bp->bp_file, popt + 2, size);
bp->bp_file[size] = '\0';
}
break;
default:
#if defined(CONFIG_BOOTP_VENDOREX)
if (dhcp_vendorex_proc (popt))
break;
#endif
printf ("*** Unhandled DHCP Option in OFFER/ACK: %d\n", *popt);
break;
}
popt += oplen + 2; /* Process next option */
}
}
static int DhcpMessageType(unsigned char *popt)
{
if (NetReadLong((ulong*)popt) != htonl(BOOTP_VENDOR_MAGIC))
return -1;
popt += 4;
while ( *popt != 0xff ) {
if ( *popt == 53 ) /* DHCP Message Type */
return *(popt + 2);
popt += *(popt + 1) + 2; /* Scan through all options */
}
return -1;
}
static void DhcpSendRequestPkt(Bootp_t *bp_offer)
{
volatile uchar *pkt, *iphdr;
Bootp_t *bp;
int pktlen, iplen, extlen;
IPaddr_t OfferedIP;
debug("DhcpSendRequestPkt: Sending DHCPREQUEST\n");
pkt = NetTxPacket;
memset ((void*)pkt, 0, PKTSIZE);
pkt += NetSetEther(pkt, NetBcastAddr, PROT_IP);
iphdr = pkt; /* We'll need this later to set proper pkt size */
pkt += IP_HDR_SIZE;
bp = (Bootp_t *)pkt;
bp->bp_op = OP_BOOTREQUEST;
bp->bp_htype = HWT_ETHER;
bp->bp_hlen = HWL_ETHER;
bp->bp_hops = 0;
bp->bp_secs = htons(get_timer(0) / 1000);
/* Do not set the client IP, your IP, or server IP yet, since it hasn't been ACK'ed by
* the server yet */
/*
* RFC3046 requires Relay Agents to discard packets with
* nonzero and offered giaddr
*/
NetWriteIP(&bp->bp_giaddr, 0);
memcpy (bp->bp_chaddr, NetOurEther, 6);
/*
* ID is the id of the OFFER packet
*/
NetCopyLong(&bp->bp_id, &bp_offer->bp_id);
/*
* Copy options from OFFER packet if present
*/
/* Copy offered IP into the parameters request list */
NetCopyIP(&OfferedIP, &bp_offer->bp_yiaddr);
extlen = DhcpExtended((u8 *)bp->bp_vend, DHCP_REQUEST, NetDHCPServerIP, OfferedIP);
pktlen = ((int)(pkt-NetTxPacket)) + BOOTP_HDR_SIZE - sizeof(bp->bp_vend) + extlen;
iplen = BOOTP_HDR_SIZE - sizeof(bp->bp_vend) + extlen;
NetSetIP(iphdr, 0xFFFFFFFFL, PORT_BOOTPS, PORT_BOOTPC, iplen);
debug("Transmitting DHCPREQUEST packet: len = %d\n", pktlen);
#ifdef CONFIG_BOOTP_DHCP_REQUEST_DELAY
udelay(CONFIG_BOOTP_DHCP_REQUEST_DELAY);
#endif /* CONFIG_BOOTP_DHCP_REQUEST_DELAY */
NetSendPacket(NetTxPacket, pktlen);
}
/*
* Handle DHCP received packets.
*/
static void
DhcpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
unsigned len)
{
Bootp_t *bp = (Bootp_t *)pkt;
debug("DHCPHandler: got packet: (src=%d, dst=%d, len=%d) state: %d\n",
src, dest, len, dhcp_state);
if (BootpCheckPkt(pkt, dest, src, len)) /* Filter out pkts we don't want */
return;
debug("DHCPHandler: got DHCP packet: (src=%d, dst=%d, len=%d) state: %d\n",
src, dest, len, dhcp_state);
switch (dhcp_state) {
case SELECTING:
/*
* Wait an appropriate time for any potential DHCPOFFER packets
* to arrive. Then select one, and generate DHCPREQUEST response.
* If filename is in format we recognize, assume it is a valid
* OFFER from a server we want.
*/
debug("DHCP: state=SELECTING bp_file: \"%s\"\n", bp->bp_file);
#ifdef CONFIG_SYS_BOOTFILE_PREFIX
if (strncmp(bp->bp_file,
CONFIG_SYS_BOOTFILE_PREFIX,
strlen(CONFIG_SYS_BOOTFILE_PREFIX)) == 0 ) {
#endif /* CONFIG_SYS_BOOTFILE_PREFIX */
debug("TRANSITIONING TO REQUESTING STATE\n");
dhcp_state = REQUESTING;
if (NetReadLong((ulong*)&bp->bp_vend[0]) == htonl(BOOTP_VENDOR_MAGIC))
DhcpOptionsProcess((u8 *)&bp->bp_vend[4], bp);
NetSetTimeout(TIMEOUT, BootpTimeout);
DhcpSendRequestPkt(bp);
#ifdef CONFIG_SYS_BOOTFILE_PREFIX
}
#endif /* CONFIG_SYS_BOOTFILE_PREFIX */
return;
break;
case REQUESTING:
debug("DHCP State: REQUESTING\n");
if ( DhcpMessageType((u8 *)bp->bp_vend) == DHCP_ACK ) {
if (NetReadLong((ulong*)&bp->bp_vend[0]) == htonl(BOOTP_VENDOR_MAGIC))
DhcpOptionsProcess((u8 *)&bp->bp_vend[4], bp);
BootpCopyNetParams(bp); /* Store net params from reply */
dhcp_state = BOUND;
printf ("DHCP client bound to address %pI4\n", &NetOurIP);
net_auto_load();
return;
}
break;
case BOUND:
/* DHCP client bound to address */
break;
default:
puts ("DHCP: INVALID STATE\n");
break;
}
}
void DhcpRequest(void)
{
BootpRequest();
}
#endif /* CONFIG_CMD_DHCP */
|
1001-study-uboot
|
net/bootp.c
|
C
|
gpl3
| 23,484
|
/*
* (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 __RARP_H__
#define __RARP_H__
#ifndef __NET_H__
#include <net.h>
#endif /* __NET_H__ */
/**********************************************************************/
/*
* Global functions and variables.
*/
extern int RarpTry;
extern void RarpRequest (void); /* Send a RARP request */
/**********************************************************************/
#endif /* __RARP_H__ */
|
1001-study-uboot
|
net/rarp.h
|
C
|
gpl3
| 1,276
|
/*
* NFS support driver - based on etherboot and U-BOOT's tftp.c
*
* Masami Komiya <mkomiya@sonare.it> 2004
*
*/
/* NOTE: the NFS code is heavily inspired by the NetBSD netboot code (read:
* large portions are copied verbatim) as distributed in OSKit 0.97. A few
* changes were necessary to adapt the code to Etherboot and to fix several
* inconsistencies. Also the RPC message preparation is done "by hand" to
* avoid adding netsprintf() which I find hard to understand and use. */
/* NOTE 2: Etherboot does not care about things beyond the kernel image, so
* it loads the kernel image off the boot server (ARP_SERVER) and does not
* access the client root disk (root-path in dhcpd.conf), which would use
* ARP_ROOTSERVER. The root disk is something the operating system we are
* about to load needs to use. This is different from the OSKit 0.97 logic. */
/* NOTE 3: Symlink handling introduced by Anselm M Hoffmeister, 2003-July-14
* If a symlink is encountered, it is followed as far as possible (recursion
* possible, maximum 16 steps). There is no clearing of ".."'s inside the
* path, so please DON'T DO THAT. thx. */
#include <common.h>
#include <command.h>
#include <net.h>
#include <malloc.h>
#include "nfs.h"
#include "bootp.h"
#define HASHES_PER_LINE 65 /* Number of "loading" hashes per line */
#define NFS_RETRY_COUNT 30
#define NFS_TIMEOUT 2000UL
static int fs_mounted = 0;
static unsigned long rpc_id = 0;
static int nfs_offset = -1;
static int nfs_len;
static char dirfh[NFS_FHSIZE]; /* file handle of directory */
static char filefh[NFS_FHSIZE]; /* file handle of kernel image */
static int NfsDownloadState;
static IPaddr_t NfsServerIP;
static int NfsSrvMountPort;
static int NfsSrvNfsPort;
static int NfsOurPort;
static int NfsTimeoutCount;
static int NfsState;
#define STATE_PRCLOOKUP_PROG_MOUNT_REQ 1
#define STATE_PRCLOOKUP_PROG_NFS_REQ 2
#define STATE_MOUNT_REQ 3
#define STATE_UMOUNT_REQ 4
#define STATE_LOOKUP_REQ 5
#define STATE_READ_REQ 6
#define STATE_READLINK_REQ 7
static char default_filename[64];
static char *nfs_filename;
static char *nfs_path;
static char nfs_path_buff[2048];
static __inline__ int
store_block (uchar * src, unsigned offset, unsigned len)
{
ulong newsize = offset + len;
#ifdef CONFIG_SYS_DIRECT_FLASH_NFS
int i, rc = 0;
for (i=0; i<CONFIG_SYS_MAX_FLASH_BANKS; i++) {
/* start address in flash? */
if (load_addr + offset >= flash_info[i].start[0]) {
rc = 1;
break;
}
}
if (rc) { /* Flash is destination for this packet */
rc = flash_write ((uchar *)src, (ulong)(load_addr+offset), len);
if (rc) {
flash_perror (rc);
return -1;
}
} else
#endif /* CONFIG_SYS_DIRECT_FLASH_NFS */
{
(void)memcpy ((void *)(load_addr + offset), src, len);
}
if (NetBootFileXferSize < (offset+len))
NetBootFileXferSize = newsize;
return 0;
}
static char*
basename (char *path)
{
char *fname;
fname = path + strlen(path) - 1;
while (fname >= path) {
if (*fname == '/') {
fname++;
break;
}
fname--;
}
return fname;
}
static char*
dirname (char *path)
{
char *fname;
fname = basename (path);
--fname;
*fname = '\0';
return path;
}
/**************************************************************************
RPC_ADD_CREDENTIALS - Add RPC authentication/verifier entries
**************************************************************************/
static long *rpc_add_credentials (long *p)
{
int hl;
int hostnamelen;
char hostname[256];
strcpy (hostname, "");
hostnamelen=strlen (hostname);
/* Here's the executive summary on authentication requirements of the
* various NFS server implementations: Linux accepts both AUTH_NONE
* and AUTH_UNIX authentication (also accepts an empty hostname field
* in the AUTH_UNIX scheme). *BSD refuses AUTH_NONE, but accepts
* AUTH_UNIX (also accepts an empty hostname field in the AUTH_UNIX
* scheme). To be safe, use AUTH_UNIX and pass the hostname if we have
* it (if the BOOTP/DHCP reply didn't give one, just use an empty
* hostname). */
hl = (hostnamelen + 3) & ~3;
/* Provide an AUTH_UNIX credential. */
*p++ = htonl(1); /* AUTH_UNIX */
*p++ = htonl(hl+20); /* auth length */
*p++ = htonl(0); /* stamp */
*p++ = htonl(hostnamelen); /* hostname string */
if (hostnamelen & 3) {
*(p + hostnamelen / 4) = 0; /* add zero padding */
}
memcpy (p, hostname, hostnamelen);
p += hl / 4;
*p++ = 0; /* uid */
*p++ = 0; /* gid */
*p++ = 0; /* auxiliary gid list */
/* Provide an AUTH_NONE verifier. */
*p++ = 0; /* AUTH_NONE */
*p++ = 0; /* auth length */
return p;
}
/**************************************************************************
RPC_LOOKUP - Lookup RPC Port numbers
**************************************************************************/
static void
rpc_req (int rpc_prog, int rpc_proc, uint32_t *data, int datalen)
{
struct rpc_t pkt;
unsigned long id;
uint32_t *p;
int pktlen;
int sport;
id = ++rpc_id;
pkt.u.call.id = htonl(id);
pkt.u.call.type = htonl(MSG_CALL);
pkt.u.call.rpcvers = htonl(2); /* use RPC version 2 */
pkt.u.call.prog = htonl(rpc_prog);
pkt.u.call.vers = htonl(2); /* portmapper is version 2 */
pkt.u.call.proc = htonl(rpc_proc);
p = (uint32_t *)&(pkt.u.call.data);
if (datalen)
memcpy ((char *)p, (char *)data, datalen*sizeof(uint32_t));
pktlen = (char *)p + datalen*sizeof(uint32_t) - (char *)&pkt;
memcpy ((char *)NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE, (char *)&pkt, pktlen);
if (rpc_prog == PROG_PORTMAP)
sport = SUNRPC_PORT;
else if (rpc_prog == PROG_MOUNT)
sport = NfsSrvMountPort;
else
sport = NfsSrvNfsPort;
NetSendUDPPacket (NetServerEther, NfsServerIP, sport, NfsOurPort, pktlen);
}
/**************************************************************************
RPC_LOOKUP - Lookup RPC Port numbers
**************************************************************************/
static void
rpc_lookup_req (int prog, int ver)
{
uint32_t data[16];
data[0] = 0; data[1] = 0; /* auth credential */
data[2] = 0; data[3] = 0; /* auth verifier */
data[4] = htonl(prog);
data[5] = htonl(ver);
data[6] = htonl(17); /* IP_UDP */
data[7] = 0;
rpc_req (PROG_PORTMAP, PORTMAP_GETPORT, data, 8);
}
/**************************************************************************
NFS_MOUNT - Mount an NFS Filesystem
**************************************************************************/
static void
nfs_mount_req (char *path)
{
uint32_t data[1024];
uint32_t *p;
int len;
int pathlen;
pathlen = strlen (path);
p = &(data[0]);
p = (uint32_t *)rpc_add_credentials((long *)p);
*p++ = htonl(pathlen);
if (pathlen & 3) *(p + pathlen / 4) = 0;
memcpy (p, path, pathlen);
p += (pathlen + 3) / 4;
len = (uint32_t *)p - (uint32_t *)&(data[0]);
rpc_req (PROG_MOUNT, MOUNT_ADDENTRY, data, len);
}
/**************************************************************************
NFS_UMOUNTALL - Unmount all our NFS Filesystems on the Server
**************************************************************************/
static void
nfs_umountall_req (void)
{
uint32_t data[1024];
uint32_t *p;
int len;
if ((NfsSrvMountPort == -1) || (!fs_mounted)) {
/* Nothing mounted, nothing to umount */
return;
}
p = &(data[0]);
p = (uint32_t *)rpc_add_credentials ((long *)p);
len = (uint32_t *)p - (uint32_t *)&(data[0]);
rpc_req (PROG_MOUNT, MOUNT_UMOUNTALL, data, len);
}
/***************************************************************************
* NFS_READLINK (AH 2003-07-14)
* This procedure is called when read of the first block fails -
* this probably happens when it's a directory or a symlink
* In case of successful readlink(), the dirname is manipulated,
* so that inside the nfs() function a recursion can be done.
**************************************************************************/
static void
nfs_readlink_req (void)
{
uint32_t data[1024];
uint32_t *p;
int len;
p = &(data[0]);
p = (uint32_t *)rpc_add_credentials ((long *)p);
memcpy (p, filefh, NFS_FHSIZE);
p += (NFS_FHSIZE / 4);
len = (uint32_t *)p - (uint32_t *)&(data[0]);
rpc_req (PROG_NFS, NFS_READLINK, data, len);
}
/**************************************************************************
NFS_LOOKUP - Lookup Pathname
**************************************************************************/
static void
nfs_lookup_req (char *fname)
{
uint32_t data[1024];
uint32_t *p;
int len;
int fnamelen;
fnamelen = strlen (fname);
p = &(data[0]);
p = (uint32_t *)rpc_add_credentials ((long *)p);
memcpy (p, dirfh, NFS_FHSIZE);
p += (NFS_FHSIZE / 4);
*p++ = htonl(fnamelen);
if (fnamelen & 3) *(p + fnamelen / 4) = 0;
memcpy (p, fname, fnamelen);
p += (fnamelen + 3) / 4;
len = (uint32_t *)p - (uint32_t *)&(data[0]);
rpc_req (PROG_NFS, NFS_LOOKUP, data, len);
}
/**************************************************************************
NFS_READ - Read File on NFS Server
**************************************************************************/
static void
nfs_read_req (int offset, int readlen)
{
uint32_t data[1024];
uint32_t *p;
int len;
p = &(data[0]);
p = (uint32_t *)rpc_add_credentials ((long *)p);
memcpy (p, filefh, NFS_FHSIZE);
p += (NFS_FHSIZE / 4);
*p++ = htonl(offset);
*p++ = htonl(readlen);
*p++ = 0;
len = (uint32_t *)p - (uint32_t *)&(data[0]);
rpc_req (PROG_NFS, NFS_READ, data, len);
}
/**************************************************************************
RPC request dispatcher
**************************************************************************/
static void
NfsSend (void)
{
debug("%s\n", __func__);
switch (NfsState) {
case STATE_PRCLOOKUP_PROG_MOUNT_REQ:
rpc_lookup_req (PROG_MOUNT, 1);
break;
case STATE_PRCLOOKUP_PROG_NFS_REQ:
rpc_lookup_req (PROG_NFS, 2);
break;
case STATE_MOUNT_REQ:
nfs_mount_req (nfs_path);
break;
case STATE_UMOUNT_REQ:
nfs_umountall_req ();
break;
case STATE_LOOKUP_REQ:
nfs_lookup_req (nfs_filename);
break;
case STATE_READ_REQ:
nfs_read_req (nfs_offset, nfs_len);
break;
case STATE_READLINK_REQ:
nfs_readlink_req ();
break;
}
}
/**************************************************************************
Handlers for the reply from server
**************************************************************************/
static int
rpc_lookup_reply (int prog, uchar *pkt, unsigned len)
{
struct rpc_t rpc_pkt;
memcpy ((unsigned char *)&rpc_pkt, pkt, len);
debug("%s\n", __func__);
if (ntohl(rpc_pkt.u.reply.id) != rpc_id)
return -1;
if (rpc_pkt.u.reply.rstatus ||
rpc_pkt.u.reply.verifier ||
rpc_pkt.u.reply.astatus) {
return -1;
}
switch (prog) {
case PROG_MOUNT:
NfsSrvMountPort = ntohl(rpc_pkt.u.reply.data[0]);
break;
case PROG_NFS:
NfsSrvNfsPort = ntohl(rpc_pkt.u.reply.data[0]);
break;
}
return 0;
}
static int
nfs_mount_reply (uchar *pkt, unsigned len)
{
struct rpc_t rpc_pkt;
debug("%s\n", __func__);
memcpy ((unsigned char *)&rpc_pkt, pkt, len);
if (ntohl(rpc_pkt.u.reply.id) != rpc_id)
return -1;
if (rpc_pkt.u.reply.rstatus ||
rpc_pkt.u.reply.verifier ||
rpc_pkt.u.reply.astatus ||
rpc_pkt.u.reply.data[0]) {
return -1;
}
fs_mounted = 1;
memcpy (dirfh, rpc_pkt.u.reply.data + 1, NFS_FHSIZE);
return 0;
}
static int
nfs_umountall_reply (uchar *pkt, unsigned len)
{
struct rpc_t rpc_pkt;
debug("%s\n", __func__);
memcpy ((unsigned char *)&rpc_pkt, pkt, len);
if (ntohl(rpc_pkt.u.reply.id) != rpc_id)
return -1;
if (rpc_pkt.u.reply.rstatus ||
rpc_pkt.u.reply.verifier ||
rpc_pkt.u.reply.astatus) {
return -1;
}
fs_mounted = 0;
memset (dirfh, 0, sizeof(dirfh));
return 0;
}
static int
nfs_lookup_reply (uchar *pkt, unsigned len)
{
struct rpc_t rpc_pkt;
debug("%s\n", __func__);
memcpy ((unsigned char *)&rpc_pkt, pkt, len);
if (ntohl(rpc_pkt.u.reply.id) != rpc_id)
return -1;
if (rpc_pkt.u.reply.rstatus ||
rpc_pkt.u.reply.verifier ||
rpc_pkt.u.reply.astatus ||
rpc_pkt.u.reply.data[0]) {
return -1;
}
memcpy (filefh, rpc_pkt.u.reply.data + 1, NFS_FHSIZE);
return 0;
}
static int
nfs_readlink_reply (uchar *pkt, unsigned len)
{
struct rpc_t rpc_pkt;
int rlen;
debug("%s\n", __func__);
memcpy ((unsigned char *)&rpc_pkt, pkt, len);
if (ntohl(rpc_pkt.u.reply.id) != rpc_id)
return -1;
if (rpc_pkt.u.reply.rstatus ||
rpc_pkt.u.reply.verifier ||
rpc_pkt.u.reply.astatus ||
rpc_pkt.u.reply.data[0]) {
return -1;
}
rlen = ntohl (rpc_pkt.u.reply.data[1]); /* new path length */
if (*((char *)&(rpc_pkt.u.reply.data[2])) != '/') {
int pathlen;
strcat (nfs_path, "/");
pathlen = strlen(nfs_path);
memcpy (nfs_path+pathlen, (uchar *)&(rpc_pkt.u.reply.data[2]), rlen);
nfs_path[pathlen + rlen] = 0;
} else {
memcpy (nfs_path, (uchar *)&(rpc_pkt.u.reply.data[2]), rlen);
nfs_path[rlen] = 0;
}
return 0;
}
static int
nfs_read_reply (uchar *pkt, unsigned len)
{
struct rpc_t rpc_pkt;
int rlen;
debug("%s\n", __func__);
memcpy ((uchar *)&rpc_pkt, pkt, sizeof(rpc_pkt.u.reply));
if (ntohl(rpc_pkt.u.reply.id) != rpc_id)
return -1;
if (rpc_pkt.u.reply.rstatus ||
rpc_pkt.u.reply.verifier ||
rpc_pkt.u.reply.astatus ||
rpc_pkt.u.reply.data[0]) {
if (rpc_pkt.u.reply.rstatus) {
return -9999;
}
if (rpc_pkt.u.reply.astatus) {
return -9999;
}
return -ntohl(rpc_pkt.u.reply.data[0]);;
}
if ((nfs_offset!=0) && !((nfs_offset) % (NFS_READ_SIZE/2*10*HASHES_PER_LINE))) {
puts ("\n\t ");
}
if (!(nfs_offset % ((NFS_READ_SIZE/2)*10))) {
putc ('#');
}
rlen = ntohl(rpc_pkt.u.reply.data[18]);
if ( store_block ((uchar *)pkt+sizeof(rpc_pkt.u.reply), nfs_offset, rlen) )
return -9999;
return rlen;
}
/**************************************************************************
Interfaces of U-BOOT
**************************************************************************/
static void
NfsTimeout (void)
{
if ( ++NfsTimeoutCount > NFS_RETRY_COUNT ) {
puts ("\nRetry count exceeded; starting again\n");
NetStartAgain ();
} else {
puts("T ");
NetSetTimeout (NFS_TIMEOUT, NfsTimeout);
NfsSend ();
}
}
static void
NfsHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src, unsigned len)
{
int rlen;
debug("%s\n", __func__);
if (dest != NfsOurPort) return;
switch (NfsState) {
case STATE_PRCLOOKUP_PROG_MOUNT_REQ:
rpc_lookup_reply (PROG_MOUNT, pkt, len);
NfsState = STATE_PRCLOOKUP_PROG_NFS_REQ;
NfsSend ();
break;
case STATE_PRCLOOKUP_PROG_NFS_REQ:
rpc_lookup_reply (PROG_NFS, pkt, len);
NfsState = STATE_MOUNT_REQ;
NfsSend ();
break;
case STATE_MOUNT_REQ:
if (nfs_mount_reply(pkt, len)) {
puts ("*** ERROR: Cannot mount\n");
/* just to be sure... */
NfsState = STATE_UMOUNT_REQ;
NfsSend ();
} else {
NfsState = STATE_LOOKUP_REQ;
NfsSend ();
}
break;
case STATE_UMOUNT_REQ:
if (nfs_umountall_reply(pkt, len)) {
puts ("*** ERROR: Cannot umount\n");
NetState = NETLOOP_FAIL;
} else {
puts ("\ndone\n");
NetState = NfsDownloadState;
}
break;
case STATE_LOOKUP_REQ:
if (nfs_lookup_reply(pkt, len)) {
puts ("*** ERROR: File lookup fail\n");
NfsState = STATE_UMOUNT_REQ;
NfsSend ();
} else {
NfsState = STATE_READ_REQ;
nfs_offset = 0;
nfs_len = NFS_READ_SIZE;
NfsSend ();
}
break;
case STATE_READLINK_REQ:
if (nfs_readlink_reply(pkt, len)) {
puts ("*** ERROR: Symlink fail\n");
NfsState = STATE_UMOUNT_REQ;
NfsSend ();
} else {
debug("Symlink --> %s\n", nfs_path);
nfs_filename = basename (nfs_path);
nfs_path = dirname (nfs_path);
NfsState = STATE_MOUNT_REQ;
NfsSend ();
}
break;
case STATE_READ_REQ:
rlen = nfs_read_reply (pkt, len);
NetSetTimeout (NFS_TIMEOUT, NfsTimeout);
if (rlen > 0) {
nfs_offset += rlen;
NfsSend ();
}
else if ((rlen == -NFSERR_ISDIR)||(rlen == -NFSERR_INVAL)) {
/* symbolic link */
NfsState = STATE_READLINK_REQ;
NfsSend ();
} else {
if ( ! rlen ) NfsDownloadState = NETLOOP_SUCCESS;
NfsState = STATE_UMOUNT_REQ;
NfsSend ();
}
break;
}
}
void
NfsStart (void)
{
debug("%s\n", __func__);
NfsDownloadState = NETLOOP_FAIL;
NfsServerIP = NetServerIP;
nfs_path = (char *)nfs_path_buff;
if (nfs_path == NULL) {
NetState = NETLOOP_FAIL;
puts ("*** ERROR: Fail allocate memory\n");
return;
}
if (BootFile[0] == '\0') {
sprintf(default_filename, "/nfsroot/%02X%02X%02X%02X.img",
NetOurIP & 0xFF,
(NetOurIP >> 8) & 0xFF,
(NetOurIP >> 16) & 0xFF,
(NetOurIP >> 24) & 0xFF );
strcpy (nfs_path, default_filename);
printf ("*** Warning: no boot file name; using '%s'\n",
nfs_path);
} else {
char *p=BootFile;
p = strchr (p, ':');
if (p != NULL) {
NfsServerIP = string_to_ip (BootFile);
++p;
strcpy (nfs_path, p);
} else {
strcpy (nfs_path, BootFile);
}
}
nfs_filename = basename (nfs_path);
nfs_path = dirname (nfs_path);
printf ("Using %s device\n", eth_get_name());
printf("File transfer via NFS from server %pI4"
"; our IP address is %pI4", &NfsServerIP, &NetOurIP);
/* Check if we need to send across this subnet */
if (NetOurGatewayIP && NetOurSubnetMask) {
IPaddr_t OurNet = NetOurIP & NetOurSubnetMask;
IPaddr_t ServerNet = NetServerIP & NetOurSubnetMask;
if (OurNet != ServerNet)
printf("; sending through gateway %pI4", &NetOurGatewayIP);
}
printf ("\nFilename '%s/%s'.", nfs_path, nfs_filename);
if (NetBootFileSize) {
printf (" Size is 0x%x Bytes = ", NetBootFileSize<<9);
print_size (NetBootFileSize<<9, "");
}
printf ("\nLoad address: 0x%lx\n"
"Loading: *\b", load_addr);
NetSetTimeout (NFS_TIMEOUT, NfsTimeout);
NetSetHandler (NfsHandler);
NfsTimeoutCount = 0;
NfsState = STATE_PRCLOOKUP_PROG_MOUNT_REQ;
/*NfsOurPort = 4096 + (get_ticks() % 3072);*/
/*FIX ME !!!*/
NfsOurPort = 1000;
/* zero out server ether in case the server ip has changed */
memset (NetServerEther, 0, 6);
NfsSend ();
}
|
1001-study-uboot
|
net/nfs.c
|
C
|
gpl3
| 17,929
|
#include <config.h>
/*-------------------------------------------------------------*/
/*--- Table for randomising repetitive blocks ---*/
/*--- randtable.c ---*/
/*-------------------------------------------------------------*/
/*--
This file is a part of bzip2 and/or libbzip2, a program and
library for lossless, block-sorting data compression.
Copyright (C) 1996-2002 Julian R Seward. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Julian Seward, Cambridge, UK.
jseward@acm.org
bzip2/libbzip2 version 1.0 of 21 March 2000
This program is based on (at least) the work of:
Mike Burrows
David Wheeler
Peter Fenwick
Alistair Moffat
Radford Neal
Ian H. Witten
Robert Sedgewick
Jon L. Bentley
For more information on these sources, see the manual.
--*/
#include "bzlib_private.h"
/*---------------------------------------------*/
Int32 BZ2_rNums[512] = {
619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
936, 638
};
/*-------------------------------------------------------------*/
/*--- end randtable.c ---*/
/*-------------------------------------------------------------*/
|
1001-study-uboot
|
lib/bzlib_randtable.c
|
C
|
gpl3
| 5,402
|
/*
* Procedures for maintaining information about logical memory blocks.
*
* Peter Bergner, IBM Corp. June 2001.
* Copyright (C) 2001 Peter Bergner.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <common.h>
#include <lmb.h>
#define LMB_ALLOC_ANYWHERE 0
void lmb_dump_all(struct lmb *lmb)
{
#ifdef DEBUG
unsigned long i;
debug("lmb_dump_all:\n");
debug(" memory.cnt = 0x%lx\n", lmb->memory.cnt);
debug(" memory.size = 0x%llx\n",
(unsigned long long)lmb->memory.size);
for (i=0; i < lmb->memory.cnt ;i++) {
debug(" memory.reg[0x%lx].base = 0x%llx\n", i,
(long long unsigned)lmb->memory.region[i].base);
debug(" .size = 0x%llx\n",
(long long unsigned)lmb->memory.region[i].size);
}
debug("\n reserved.cnt = 0x%lx\n",
lmb->reserved.cnt);
debug(" reserved.size = 0x%llx\n",
(long long unsigned)lmb->reserved.size);
for (i=0; i < lmb->reserved.cnt ;i++) {
debug(" reserved.reg[0x%lx].base = 0x%llx\n", i,
(long long unsigned)lmb->reserved.region[i].base);
debug(" .size = 0x%llx\n",
(long long unsigned)lmb->reserved.region[i].size);
}
#endif /* DEBUG */
}
static long lmb_addrs_overlap(phys_addr_t base1,
phys_size_t size1, phys_addr_t base2, phys_size_t size2)
{
return ((base1 < (base2+size2)) && (base2 < (base1+size1)));
}
static long lmb_addrs_adjacent(phys_addr_t base1, phys_size_t size1,
phys_addr_t base2, phys_size_t size2)
{
if (base2 == base1 + size1)
return 1;
else if (base1 == base2 + size2)
return -1;
return 0;
}
static long lmb_regions_adjacent(struct lmb_region *rgn,
unsigned long r1, unsigned long r2)
{
phys_addr_t base1 = rgn->region[r1].base;
phys_size_t size1 = rgn->region[r1].size;
phys_addr_t base2 = rgn->region[r2].base;
phys_size_t size2 = rgn->region[r2].size;
return lmb_addrs_adjacent(base1, size1, base2, size2);
}
static void lmb_remove_region(struct lmb_region *rgn, unsigned long r)
{
unsigned long i;
for (i = r; i < rgn->cnt - 1; i++) {
rgn->region[i].base = rgn->region[i + 1].base;
rgn->region[i].size = rgn->region[i + 1].size;
}
rgn->cnt--;
}
/* Assumption: base addr of region 1 < base addr of region 2 */
static void lmb_coalesce_regions(struct lmb_region *rgn,
unsigned long r1, unsigned long r2)
{
rgn->region[r1].size += rgn->region[r2].size;
lmb_remove_region(rgn, r2);
}
void lmb_init(struct lmb *lmb)
{
/* Create a dummy zero size LMB which will get coalesced away later.
* This simplifies the lmb_add() code below...
*/
lmb->memory.region[0].base = 0;
lmb->memory.region[0].size = 0;
lmb->memory.cnt = 1;
lmb->memory.size = 0;
/* Ditto. */
lmb->reserved.region[0].base = 0;
lmb->reserved.region[0].size = 0;
lmb->reserved.cnt = 1;
lmb->reserved.size = 0;
}
/* This routine called with relocation disabled. */
static long lmb_add_region(struct lmb_region *rgn, phys_addr_t base, phys_size_t size)
{
unsigned long coalesced = 0;
long adjacent, i;
if ((rgn->cnt == 1) && (rgn->region[0].size == 0)) {
rgn->region[0].base = base;
rgn->region[0].size = size;
return 0;
}
/* First try and coalesce this LMB with another. */
for (i=0; i < rgn->cnt; i++) {
phys_addr_t rgnbase = rgn->region[i].base;
phys_size_t rgnsize = rgn->region[i].size;
if ((rgnbase == base) && (rgnsize == size))
/* Already have this region, so we're done */
return 0;
adjacent = lmb_addrs_adjacent(base,size,rgnbase,rgnsize);
if ( adjacent > 0 ) {
rgn->region[i].base -= size;
rgn->region[i].size += size;
coalesced++;
break;
}
else if ( adjacent < 0 ) {
rgn->region[i].size += size;
coalesced++;
break;
}
}
if ((i < rgn->cnt-1) && lmb_regions_adjacent(rgn, i, i+1) ) {
lmb_coalesce_regions(rgn, i, i+1);
coalesced++;
}
if (coalesced)
return coalesced;
if (rgn->cnt >= MAX_LMB_REGIONS)
return -1;
/* Couldn't coalesce the LMB, so add it to the sorted table. */
for (i = rgn->cnt-1; i >= 0; i--) {
if (base < rgn->region[i].base) {
rgn->region[i+1].base = rgn->region[i].base;
rgn->region[i+1].size = rgn->region[i].size;
} else {
rgn->region[i+1].base = base;
rgn->region[i+1].size = size;
break;
}
}
if (base < rgn->region[0].base) {
rgn->region[0].base = base;
rgn->region[0].size = size;
}
rgn->cnt++;
return 0;
}
/* This routine may be called with relocation disabled. */
long lmb_add(struct lmb *lmb, phys_addr_t base, phys_size_t size)
{
struct lmb_region *_rgn = &(lmb->memory);
return lmb_add_region(_rgn, base, size);
}
long lmb_free(struct lmb *lmb, phys_addr_t base, phys_size_t size)
{
struct lmb_region *rgn = &(lmb->reserved);
phys_addr_t rgnbegin, rgnend;
phys_addr_t end = base + size;
int i;
rgnbegin = rgnend = 0; /* supress gcc warnings */
/* Find the region where (base, size) belongs to */
for (i=0; i < rgn->cnt; i++) {
rgnbegin = rgn->region[i].base;
rgnend = rgnbegin + rgn->region[i].size;
if ((rgnbegin <= base) && (end <= rgnend))
break;
}
/* Didn't find the region */
if (i == rgn->cnt)
return -1;
/* Check to see if we are removing entire region */
if ((rgnbegin == base) && (rgnend == end)) {
lmb_remove_region(rgn, i);
return 0;
}
/* Check to see if region is matching at the front */
if (rgnbegin == base) {
rgn->region[i].base = end;
rgn->region[i].size -= size;
return 0;
}
/* Check to see if the region is matching at the end */
if (rgnend == end) {
rgn->region[i].size -= size;
return 0;
}
/*
* We need to split the entry - adjust the current one to the
* beginging of the hole and add the region after hole.
*/
rgn->region[i].size = base - rgn->region[i].base;
return lmb_add_region(rgn, end, rgnend - end);
}
long lmb_reserve(struct lmb *lmb, phys_addr_t base, phys_size_t size)
{
struct lmb_region *_rgn = &(lmb->reserved);
return lmb_add_region(_rgn, base, size);
}
long lmb_overlaps_region(struct lmb_region *rgn, phys_addr_t base,
phys_size_t size)
{
unsigned long i;
for (i=0; i < rgn->cnt; i++) {
phys_addr_t rgnbase = rgn->region[i].base;
phys_size_t rgnsize = rgn->region[i].size;
if ( lmb_addrs_overlap(base,size,rgnbase,rgnsize) ) {
break;
}
}
return (i < rgn->cnt) ? i : -1;
}
phys_addr_t lmb_alloc(struct lmb *lmb, phys_size_t size, ulong align)
{
return lmb_alloc_base(lmb, size, align, LMB_ALLOC_ANYWHERE);
}
phys_addr_t lmb_alloc_base(struct lmb *lmb, phys_size_t size, ulong align, phys_addr_t max_addr)
{
phys_addr_t alloc;
alloc = __lmb_alloc_base(lmb, size, align, max_addr);
if (alloc == 0)
printf("ERROR: Failed to allocate 0x%lx bytes below 0x%lx.\n",
(ulong)size, (ulong)max_addr);
return alloc;
}
static phys_addr_t lmb_align_down(phys_addr_t addr, phys_size_t size)
{
return addr & ~(size - 1);
}
static phys_addr_t lmb_align_up(phys_addr_t addr, ulong size)
{
return (addr + (size - 1)) & ~(size - 1);
}
phys_addr_t __lmb_alloc_base(struct lmb *lmb, phys_size_t size, ulong align, phys_addr_t max_addr)
{
long i, j;
phys_addr_t base = 0;
phys_addr_t res_base;
for (i = lmb->memory.cnt-1; i >= 0; i--) {
phys_addr_t lmbbase = lmb->memory.region[i].base;
phys_size_t lmbsize = lmb->memory.region[i].size;
if (lmbsize < size)
continue;
if (max_addr == LMB_ALLOC_ANYWHERE)
base = lmb_align_down(lmbbase + lmbsize - size, align);
else if (lmbbase < max_addr) {
base = min(lmbbase + lmbsize, max_addr);
base = lmb_align_down(base - size, align);
} else
continue;
while (base && lmbbase <= base) {
j = lmb_overlaps_region(&lmb->reserved, base, size);
if (j < 0) {
/* This area isn't reserved, take it */
if (lmb_add_region(&lmb->reserved, base,
lmb_align_up(size,
align)) < 0)
return 0;
return base;
}
res_base = lmb->reserved.region[j].base;
if (res_base < size)
break;
base = lmb_align_down(res_base - size, align);
}
}
return 0;
}
int lmb_is_reserved(struct lmb *lmb, phys_addr_t addr)
{
int i;
for (i = 0; i < lmb->reserved.cnt; i++) {
phys_addr_t upper = lmb->reserved.region[i].base +
lmb->reserved.region[i].size - 1;
if ((addr >= lmb->reserved.region[i].base) && (addr <= upper))
return 1;
}
return 0;
}
void __board_lmb_reserve(struct lmb *lmb)
{
/* please define platform specific board_lmb_reserve() */
}
void board_lmb_reserve(struct lmb *lmb) __attribute__((weak, alias("__board_lmb_reserve")));
void __arch_lmb_reserve(struct lmb *lmb)
{
/* please define platform specific arch_lmb_reserve() */
}
void arch_lmb_reserve(struct lmb *lmb) __attribute__((weak, alias("__arch_lmb_reserve")));
|
1001-study-uboot
|
lib/lmb.c
|
C
|
gpl3
| 8,809
|
/*
* This file is a modified version of bzlib_private.h from the bzip2-1.0.2
* distribution which can be found at http://sources.redhat.com/bzip2/
*/
/*-------------------------------------------------------------*/
/*--- Private header file for the library. ---*/
/*--- bzlib_private.h ---*/
/*-------------------------------------------------------------*/
/*--
This file is a part of bzip2 and/or libbzip2, a program and
library for lossless, block-sorting data compression.
Copyright (C) 1996-2002 Julian R Seward. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Julian Seward, Cambridge, UK.
jseward@acm.org
bzip2/libbzip2 version 1.0 of 21 March 2000
This program is based on (at least) the work of:
Mike Burrows
David Wheeler
Peter Fenwick
Alistair Moffat
Radford Neal
Ian H. Witten
Robert Sedgewick
Jon L. Bentley
For more information on these sources, see the manual.
--*/
#ifndef _BZLIB_PRIVATE_H
#define _BZLIB_PRIVATE_H
#include <malloc.h>
#include "bzlib.h"
#ifndef BZ_NO_STDIO
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#endif
/*-- General stuff. --*/
#define BZ_VERSION "1.0.2, 30-Dec-2001"
typedef char Char;
typedef unsigned char Bool;
typedef unsigned char UChar;
typedef int Int32;
typedef unsigned int UInt32;
typedef short Int16;
typedef unsigned short UInt16;
#define True ((Bool)1)
#define False ((Bool)0)
#ifndef __GNUC__
#define __inline__ /* */
#endif
#ifndef BZ_NO_STDIO
extern void BZ2_bz__AssertH__fail ( int errcode );
#define AssertH(cond,errcode) \
{ if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); }
#if BZ_DEBUG
#define AssertD(cond,msg) \
{ if (!(cond)) { \
fprintf ( stderr, \
"\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\
exit(1); \
}}
#else
#define AssertD(cond,msg) /* */
#endif
#define VPrintf0(zf) \
fprintf(stderr,zf)
#define VPrintf1(zf,za1) \
fprintf(stderr,zf,za1)
#define VPrintf2(zf,za1,za2) \
fprintf(stderr,zf,za1,za2)
#define VPrintf3(zf,za1,za2,za3) \
fprintf(stderr,zf,za1,za2,za3)
#define VPrintf4(zf,za1,za2,za3,za4) \
fprintf(stderr,zf,za1,za2,za3,za4)
#define VPrintf5(zf,za1,za2,za3,za4,za5) \
fprintf(stderr,zf,za1,za2,za3,za4,za5)
#else
extern void bz_internal_error ( int errcode );
#define AssertH(cond,errcode) \
{ if (!(cond)) bz_internal_error ( errcode ); }
#define AssertD(cond,msg) /* */
#define VPrintf0(zf) /* */
#define VPrintf1(zf,za1) /* */
#define VPrintf2(zf,za1,za2) /* */
#define VPrintf3(zf,za1,za2,za3) /* */
#define VPrintf4(zf,za1,za2,za3,za4) /* */
#define VPrintf5(zf,za1,za2,za3,za4,za5) /* */
#endif
#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1)
#define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp))
/*-- Header bytes. --*/
#define BZ_HDR_B 0x42 /* 'B' */
#define BZ_HDR_Z 0x5a /* 'Z' */
#define BZ_HDR_h 0x68 /* 'h' */
#define BZ_HDR_0 0x30 /* '0' */
/*-- Constants for the back end. --*/
#define BZ_MAX_ALPHA_SIZE 258
#define BZ_MAX_CODE_LEN 23
#define BZ_RUNA 0
#define BZ_RUNB 1
#define BZ_N_GROUPS 6
#define BZ_G_SIZE 50
#define BZ_N_ITERS 4
#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE))
/*-- Stuff for randomising repetitive blocks. --*/
extern Int32 BZ2_rNums[512];
#define BZ_RAND_DECLS \
Int32 rNToGo; \
Int32 rTPos \
#define BZ_RAND_INIT_MASK \
s->rNToGo = 0; \
s->rTPos = 0 \
#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0)
#define BZ_RAND_UPD_MASK \
if (s->rNToGo == 0) { \
s->rNToGo = BZ2_rNums[s->rTPos]; \
s->rTPos++; \
if (s->rTPos == 512) s->rTPos = 0; \
} \
s->rNToGo--;
/*-- Stuff for doing CRCs. --*/
extern UInt32 BZ2_crc32Table[256];
#define BZ_INITIALISE_CRC(crcVar) \
{ \
crcVar = 0xffffffffL; \
}
#define BZ_FINALISE_CRC(crcVar) \
{ \
crcVar = ~(crcVar); \
}
#define BZ_UPDATE_CRC(crcVar,cha) \
{ \
crcVar = (crcVar << 8) ^ \
BZ2_crc32Table[(crcVar >> 24) ^ \
((UChar)cha)]; \
}
/*-- States and modes for compression. --*/
#define BZ_M_IDLE 1
#define BZ_M_RUNNING 2
#define BZ_M_FLUSHING 3
#define BZ_M_FINISHING 4
#define BZ_S_OUTPUT 1
#define BZ_S_INPUT 2
#define BZ_N_RADIX 2
#define BZ_N_QSORT 12
#define BZ_N_SHELL 18
#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2)
/*-- Structure holding all the compression-side stuff. --*/
typedef
struct {
/* pointer back to the struct bz_stream */
bz_stream* strm;
/* mode this stream is in, and whether inputting */
/* or outputting data */
Int32 mode;
Int32 state;
/* remembers avail_in when flush/finish requested */
UInt32 avail_in_expect;
/* for doing the block sorting */
UInt32* arr1;
UInt32* arr2;
UInt32* ftab;
Int32 origPtr;
/* aliases for arr1 and arr2 */
UInt32* ptr;
UChar* block;
UInt16* mtfv;
UChar* zbits;
/* for deciding when to use the fallback sorting algorithm */
Int32 workFactor;
/* run-length-encoding of the input */
UInt32 state_in_ch;
Int32 state_in_len;
BZ_RAND_DECLS;
/* input and output limits and current posns */
Int32 nblock;
Int32 nblockMAX;
Int32 numZ;
Int32 state_out_pos;
/* map of bytes used in block */
Int32 nInUse;
Bool inUse[256];
UChar unseqToSeq[256];
/* the buffer for bit stream creation */
UInt32 bsBuff;
Int32 bsLive;
/* block and combined CRCs */
UInt32 blockCRC;
UInt32 combinedCRC;
/* misc administratium */
Int32 verbosity;
Int32 blockNo;
Int32 blockSize100k;
/* stuff for coding the MTF values */
Int32 nMTF;
Int32 mtfFreq [BZ_MAX_ALPHA_SIZE];
UChar selector [BZ_MAX_SELECTORS];
UChar selectorMtf[BZ_MAX_SELECTORS];
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
/* second dimension: only 3 needed; 4 makes index calculations faster */
UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4];
}
EState;
/*-- externs for compression. --*/
extern void
BZ2_blockSort ( EState* );
extern void
BZ2_compressBlock ( EState*, Bool );
extern void
BZ2_bsInitWrite ( EState* );
extern void
BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 );
extern void
BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 );
/*-- states for decompression. --*/
#define BZ_X_IDLE 1
#define BZ_X_OUTPUT 2
#define BZ_X_MAGIC_1 10
#define BZ_X_MAGIC_2 11
#define BZ_X_MAGIC_3 12
#define BZ_X_MAGIC_4 13
#define BZ_X_BLKHDR_1 14
#define BZ_X_BLKHDR_2 15
#define BZ_X_BLKHDR_3 16
#define BZ_X_BLKHDR_4 17
#define BZ_X_BLKHDR_5 18
#define BZ_X_BLKHDR_6 19
#define BZ_X_BCRC_1 20
#define BZ_X_BCRC_2 21
#define BZ_X_BCRC_3 22
#define BZ_X_BCRC_4 23
#define BZ_X_RANDBIT 24
#define BZ_X_ORIGPTR_1 25
#define BZ_X_ORIGPTR_2 26
#define BZ_X_ORIGPTR_3 27
#define BZ_X_MAPPING_1 28
#define BZ_X_MAPPING_2 29
#define BZ_X_SELECTOR_1 30
#define BZ_X_SELECTOR_2 31
#define BZ_X_SELECTOR_3 32
#define BZ_X_CODING_1 33
#define BZ_X_CODING_2 34
#define BZ_X_CODING_3 35
#define BZ_X_MTF_1 36
#define BZ_X_MTF_2 37
#define BZ_X_MTF_3 38
#define BZ_X_MTF_4 39
#define BZ_X_MTF_5 40
#define BZ_X_MTF_6 41
#define BZ_X_ENDHDR_2 42
#define BZ_X_ENDHDR_3 43
#define BZ_X_ENDHDR_4 44
#define BZ_X_ENDHDR_5 45
#define BZ_X_ENDHDR_6 46
#define BZ_X_CCRC_1 47
#define BZ_X_CCRC_2 48
#define BZ_X_CCRC_3 49
#define BZ_X_CCRC_4 50
/*-- Constants for the fast MTF decoder. --*/
#define MTFA_SIZE 4096
#define MTFL_SIZE 16
/*-- Structure holding all the decompression-side stuff. --*/
typedef
struct {
/* pointer back to the struct bz_stream */
bz_stream* strm;
/* state indicator for this stream */
Int32 state;
/* for doing the final run-length decoding */
UChar state_out_ch;
Int32 state_out_len;
Bool blockRandomised;
BZ_RAND_DECLS;
/* the buffer for bit stream reading */
UInt32 bsBuff;
Int32 bsLive;
/* misc administratium */
Int32 blockSize100k;
Bool smallDecompress;
Int32 currBlockNo;
Int32 verbosity;
/* for undoing the Burrows-Wheeler transform */
Int32 origPtr;
UInt32 tPos;
Int32 k0;
Int32 unzftab[256];
Int32 nblock_used;
Int32 cftab[257];
Int32 cftabCopy[257];
/* for undoing the Burrows-Wheeler transform (FAST) */
UInt32 *tt;
/* for undoing the Burrows-Wheeler transform (SMALL) */
UInt16 *ll16;
UChar *ll4;
/* stored and calculated CRCs */
UInt32 storedBlockCRC;
UInt32 storedCombinedCRC;
UInt32 calculatedBlockCRC;
UInt32 calculatedCombinedCRC;
/* map of bytes used in block */
Int32 nInUse;
Bool inUse[256];
Bool inUse16[16];
UChar seqToUnseq[256];
/* for decoding the MTF values */
UChar mtfa [MTFA_SIZE];
Int32 mtfbase[256 / MTFL_SIZE];
UChar selector [BZ_MAX_SELECTORS];
UChar selectorMtf[BZ_MAX_SELECTORS];
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 minLens[BZ_N_GROUPS];
/* save area for scalars in the main decompress code */
Int32 save_i;
Int32 save_j;
Int32 save_t;
Int32 save_alphaSize;
Int32 save_nGroups;
Int32 save_nSelectors;
Int32 save_EOB;
Int32 save_groupNo;
Int32 save_groupPos;
Int32 save_nextSym;
Int32 save_nblockMAX;
Int32 save_nblock;
Int32 save_es;
Int32 save_N;
Int32 save_curr;
Int32 save_zt;
Int32 save_zn;
Int32 save_zvec;
Int32 save_zj;
Int32 save_gSel;
Int32 save_gMinlen;
Int32* save_gLimit;
Int32* save_gBase;
Int32* save_gPerm;
}
DState;
/*-- Macros for decompression. --*/
#define BZ_GET_FAST(cccc) \
s->tPos = s->tt[s->tPos]; \
cccc = (UChar)(s->tPos & 0xff); \
s->tPos >>= 8;
#define BZ_GET_FAST_C(cccc) \
c_tPos = c_tt[c_tPos]; \
cccc = (UChar)(c_tPos & 0xff); \
c_tPos >>= 8;
#define SET_LL4(i,n) \
{ if (((i) & 0x1) == 0) \
s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \
s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \
}
#define GET_LL4(i) \
((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF)
#define SET_LL(i,n) \
{ s->ll16[i] = (UInt16)(n & 0x0000ffff); \
SET_LL4(i, n >> 16); \
}
#define GET_LL(i) \
(((UInt32)s->ll16[i]) | (GET_LL4(i) << 16))
#define BZ_GET_SMALL(cccc) \
cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \
s->tPos = GET_LL(s->tPos);
/*-- externs for decompression. --*/
extern Int32
BZ2_indexIntoF ( Int32, Int32* );
extern Int32
BZ2_decompress ( DState* );
extern void
BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*,
Int32, Int32, Int32 );
#endif
/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/
#ifdef BZ_NO_STDIO
#ifndef NULL
#define NULL 0
#endif
#endif
/*-------------------------------------------------------------*/
/*--- end bzlib_private.h ---*/
/*-------------------------------------------------------------*/
|
1001-study-uboot
|
lib/bzlib_private.h
|
C
|
gpl3
| 14,311
|
/*
* This file is derived from crc32.c from the zlib-1.1.3 distribution
* by Jean-loup Gailly and Mark Adler.
*/
/* crc32.c -- compute the CRC-32 of a data stream
* Copyright (C) 1995-1998 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifndef USE_HOSTCC
#include <common.h>
#endif
#include <compiler.h>
#include <u-boot/crc.h>
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
#include <watchdog.h>
#endif
#include "u-boot/zlib.h"
#define local static
#define ZEXPORT /* empty */
#define tole(x) cpu_to_le32(x)
#ifdef DYNAMIC_CRC_TABLE
local int crc_table_empty = 1;
local uint32_t crc_table[256];
local void make_crc_table OF((void));
/*
Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
Polynomials over GF(2) are represented in binary, one bit per coefficient,
with the lowest powers in the most significant bit. Then adding polynomials
is just exclusive-or, and multiplying a polynomial by x is a right shift by
one. If we call the above polynomial p, and represent a byte as the
polynomial q, also with the lowest power in the most significant bit (so the
byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
where a mod b means the remainder after dividing a by b.
This calculation is done using the shift-register method of multiplying and
taking the remainder. The register is initialized to zero, and for each
incoming bit, x^32 is added mod p to the register if the bit is a one (where
x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
x (which is shifting right by one and adding x^32 mod p if the bit shifted
out is a one). We start with the highest power (least significant bit) of
q and repeat for all eight bits of q.
The table is simply the CRC of all possible eight bit values. This is all
the information needed to generate CRC's on data a byte at a time for all
combinations of CRC register values and incoming bytes.
*/
local void make_crc_table()
{
uint32_t c;
int n, k;
uLong poly; /* polynomial exclusive-or pattern */
/* terms of polynomial defining this crc (except x^32): */
static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
/* make exclusive-or pattern from polynomial (0xedb88320L) */
poly = 0L;
for (n = 0; n < sizeof(p)/sizeof(Byte); n++)
poly |= 1L << (31 - p[n]);
for (n = 0; n < 256; n++)
{
c = (uLong)n;
for (k = 0; k < 8; k++)
c = c & 1 ? poly ^ (c >> 1) : c >> 1;
crc_table[n] = tole(c);
}
crc_table_empty = 0;
}
#else
/* ========================================================================
* Table of CRC-32's of all single-byte values (made by make_crc_table)
*/
local const uint32_t crc_table[256] = {
tole(0x00000000L), tole(0x77073096L), tole(0xee0e612cL), tole(0x990951baL),
tole(0x076dc419L), tole(0x706af48fL), tole(0xe963a535L), tole(0x9e6495a3L),
tole(0x0edb8832L), tole(0x79dcb8a4L), tole(0xe0d5e91eL), tole(0x97d2d988L),
tole(0x09b64c2bL), tole(0x7eb17cbdL), tole(0xe7b82d07L), tole(0x90bf1d91L),
tole(0x1db71064L), tole(0x6ab020f2L), tole(0xf3b97148L), tole(0x84be41deL),
tole(0x1adad47dL), tole(0x6ddde4ebL), tole(0xf4d4b551L), tole(0x83d385c7L),
tole(0x136c9856L), tole(0x646ba8c0L), tole(0xfd62f97aL), tole(0x8a65c9ecL),
tole(0x14015c4fL), tole(0x63066cd9L), tole(0xfa0f3d63L), tole(0x8d080df5L),
tole(0x3b6e20c8L), tole(0x4c69105eL), tole(0xd56041e4L), tole(0xa2677172L),
tole(0x3c03e4d1L), tole(0x4b04d447L), tole(0xd20d85fdL), tole(0xa50ab56bL),
tole(0x35b5a8faL), tole(0x42b2986cL), tole(0xdbbbc9d6L), tole(0xacbcf940L),
tole(0x32d86ce3L), tole(0x45df5c75L), tole(0xdcd60dcfL), tole(0xabd13d59L),
tole(0x26d930acL), tole(0x51de003aL), tole(0xc8d75180L), tole(0xbfd06116L),
tole(0x21b4f4b5L), tole(0x56b3c423L), tole(0xcfba9599L), tole(0xb8bda50fL),
tole(0x2802b89eL), tole(0x5f058808L), tole(0xc60cd9b2L), tole(0xb10be924L),
tole(0x2f6f7c87L), tole(0x58684c11L), tole(0xc1611dabL), tole(0xb6662d3dL),
tole(0x76dc4190L), tole(0x01db7106L), tole(0x98d220bcL), tole(0xefd5102aL),
tole(0x71b18589L), tole(0x06b6b51fL), tole(0x9fbfe4a5L), tole(0xe8b8d433L),
tole(0x7807c9a2L), tole(0x0f00f934L), tole(0x9609a88eL), tole(0xe10e9818L),
tole(0x7f6a0dbbL), tole(0x086d3d2dL), tole(0x91646c97L), tole(0xe6635c01L),
tole(0x6b6b51f4L), tole(0x1c6c6162L), tole(0x856530d8L), tole(0xf262004eL),
tole(0x6c0695edL), tole(0x1b01a57bL), tole(0x8208f4c1L), tole(0xf50fc457L),
tole(0x65b0d9c6L), tole(0x12b7e950L), tole(0x8bbeb8eaL), tole(0xfcb9887cL),
tole(0x62dd1ddfL), tole(0x15da2d49L), tole(0x8cd37cf3L), tole(0xfbd44c65L),
tole(0x4db26158L), tole(0x3ab551ceL), tole(0xa3bc0074L), tole(0xd4bb30e2L),
tole(0x4adfa541L), tole(0x3dd895d7L), tole(0xa4d1c46dL), tole(0xd3d6f4fbL),
tole(0x4369e96aL), tole(0x346ed9fcL), tole(0xad678846L), tole(0xda60b8d0L),
tole(0x44042d73L), tole(0x33031de5L), tole(0xaa0a4c5fL), tole(0xdd0d7cc9L),
tole(0x5005713cL), tole(0x270241aaL), tole(0xbe0b1010L), tole(0xc90c2086L),
tole(0x5768b525L), tole(0x206f85b3L), tole(0xb966d409L), tole(0xce61e49fL),
tole(0x5edef90eL), tole(0x29d9c998L), tole(0xb0d09822L), tole(0xc7d7a8b4L),
tole(0x59b33d17L), tole(0x2eb40d81L), tole(0xb7bd5c3bL), tole(0xc0ba6cadL),
tole(0xedb88320L), tole(0x9abfb3b6L), tole(0x03b6e20cL), tole(0x74b1d29aL),
tole(0xead54739L), tole(0x9dd277afL), tole(0x04db2615L), tole(0x73dc1683L),
tole(0xe3630b12L), tole(0x94643b84L), tole(0x0d6d6a3eL), tole(0x7a6a5aa8L),
tole(0xe40ecf0bL), tole(0x9309ff9dL), tole(0x0a00ae27L), tole(0x7d079eb1L),
tole(0xf00f9344L), tole(0x8708a3d2L), tole(0x1e01f268L), tole(0x6906c2feL),
tole(0xf762575dL), tole(0x806567cbL), tole(0x196c3671L), tole(0x6e6b06e7L),
tole(0xfed41b76L), tole(0x89d32be0L), tole(0x10da7a5aL), tole(0x67dd4accL),
tole(0xf9b9df6fL), tole(0x8ebeeff9L), tole(0x17b7be43L), tole(0x60b08ed5L),
tole(0xd6d6a3e8L), tole(0xa1d1937eL), tole(0x38d8c2c4L), tole(0x4fdff252L),
tole(0xd1bb67f1L), tole(0xa6bc5767L), tole(0x3fb506ddL), tole(0x48b2364bL),
tole(0xd80d2bdaL), tole(0xaf0a1b4cL), tole(0x36034af6L), tole(0x41047a60L),
tole(0xdf60efc3L), tole(0xa867df55L), tole(0x316e8eefL), tole(0x4669be79L),
tole(0xcb61b38cL), tole(0xbc66831aL), tole(0x256fd2a0L), tole(0x5268e236L),
tole(0xcc0c7795L), tole(0xbb0b4703L), tole(0x220216b9L), tole(0x5505262fL),
tole(0xc5ba3bbeL), tole(0xb2bd0b28L), tole(0x2bb45a92L), tole(0x5cb36a04L),
tole(0xc2d7ffa7L), tole(0xb5d0cf31L), tole(0x2cd99e8bL), tole(0x5bdeae1dL),
tole(0x9b64c2b0L), tole(0xec63f226L), tole(0x756aa39cL), tole(0x026d930aL),
tole(0x9c0906a9L), tole(0xeb0e363fL), tole(0x72076785L), tole(0x05005713L),
tole(0x95bf4a82L), tole(0xe2b87a14L), tole(0x7bb12baeL), tole(0x0cb61b38L),
tole(0x92d28e9bL), tole(0xe5d5be0dL), tole(0x7cdcefb7L), tole(0x0bdbdf21L),
tole(0x86d3d2d4L), tole(0xf1d4e242L), tole(0x68ddb3f8L), tole(0x1fda836eL),
tole(0x81be16cdL), tole(0xf6b9265bL), tole(0x6fb077e1L), tole(0x18b74777L),
tole(0x88085ae6L), tole(0xff0f6a70L), tole(0x66063bcaL), tole(0x11010b5cL),
tole(0x8f659effL), tole(0xf862ae69L), tole(0x616bffd3L), tole(0x166ccf45L),
tole(0xa00ae278L), tole(0xd70dd2eeL), tole(0x4e048354L), tole(0x3903b3c2L),
tole(0xa7672661L), tole(0xd06016f7L), tole(0x4969474dL), tole(0x3e6e77dbL),
tole(0xaed16a4aL), tole(0xd9d65adcL), tole(0x40df0b66L), tole(0x37d83bf0L),
tole(0xa9bcae53L), tole(0xdebb9ec5L), tole(0x47b2cf7fL), tole(0x30b5ffe9L),
tole(0xbdbdf21cL), tole(0xcabac28aL), tole(0x53b39330L), tole(0x24b4a3a6L),
tole(0xbad03605L), tole(0xcdd70693L), tole(0x54de5729L), tole(0x23d967bfL),
tole(0xb3667a2eL), tole(0xc4614ab8L), tole(0x5d681b02L), tole(0x2a6f2b94L),
tole(0xb40bbe37L), tole(0xc30c8ea1L), tole(0x5a05df1bL), tole(0x2d02ef8dL)
};
#endif
#if 0
/* =========================================================================
* This function can be used by asm versions of crc32()
*/
const uint32_t * ZEXPORT get_crc_table()
{
#ifdef DYNAMIC_CRC_TABLE
if (crc_table_empty) make_crc_table();
#endif
return (const uint32_t *)crc_table;
}
#endif
/* ========================================================================= */
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define DO_CRC(x) crc = tab[(crc ^ (x)) & 255] ^ (crc >> 8)
# else
# define DO_CRC(x) crc = tab[((crc >> 24) ^ (x)) & 255] ^ (crc << 8)
# endif
/* ========================================================================= */
/* No ones complement version. JFFS2 (and other things ?)
* don't use ones compliment in their CRC calculations.
*/
uint32_t ZEXPORT crc32_no_comp(uint32_t crc, const Bytef *buf, uInt len)
{
const uint32_t *tab = crc_table;
const uint32_t *b =(const uint32_t *)buf;
size_t rem_len;
#ifdef DYNAMIC_CRC_TABLE
if (crc_table_empty)
make_crc_table();
#endif
crc = cpu_to_le32(crc);
/* Align it */
if (((long)b) & 3 && len) {
uint8_t *p = (uint8_t *)b;
do {
DO_CRC(*p++);
} while ((--len) && ((long)p)&3);
b = (uint32_t *)p;
}
rem_len = len & 3;
len = len >> 2;
for (--b; len; --len) {
/* load data 32 bits wide, xor data 32 bits wide. */
crc ^= *++b; /* use pre increment for speed */
DO_CRC(0);
DO_CRC(0);
DO_CRC(0);
DO_CRC(0);
}
len = rem_len;
/* And the last few bytes */
if (len) {
uint8_t *p = (uint8_t *)(b + 1) - 1;
do {
DO_CRC(*++p); /* use pre increment for speed */
} while (--len);
}
return le32_to_cpu(crc);
}
#undef DO_CRC
uint32_t ZEXPORT crc32 (uint32_t crc, const Bytef *p, uInt len)
{
return crc32_no_comp(crc ^ 0xffffffffL, p, len) ^ 0xffffffffL;
}
/*
* Calculate the crc32 checksum triggering the watchdog every 'chunk_sz' bytes
* of input.
*/
uint32_t ZEXPORT crc32_wd (uint32_t crc,
const unsigned char *buf,
uInt len, uInt chunk_sz)
{
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
const unsigned char *end, *curr;
int chunk;
curr = buf;
end = buf + len;
while (curr < end) {
chunk = end - curr;
if (chunk > chunk_sz)
chunk = chunk_sz;
crc = crc32 (crc, curr, chunk);
curr += chunk;
WATCHDOG_RESET ();
}
#else
crc = crc32 (crc, buf, len);
#endif
return crc;
}
|
1001-study-uboot
|
lib/crc32.c
|
C
|
gpl3
| 10,137
|
/*
* This file was transplanted with slight modifications from Linux sources
* (fs/cifs/md5.c) into U-Boot by Bartlomiej Sieka <tur@semihalf.com>.
*/
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
/* This code slightly modified to fit into Samba by
abartlet@samba.org Jun 2001
and to fit the cifs vfs by
Steve French sfrench@us.ibm.com */
#include "compiler.h"
#ifndef USE_HOSTCC
#include <common.h>
#include <watchdog.h>
#endif /* USE_HOSTCC */
#include <u-boot/md5.h>
static void
MD5Transform(__u32 buf[4], __u32 const in[16]);
/*
* Note: this code is harmless on little-endian machines.
*/
static void
byteReverse(unsigned char *buf, unsigned longs)
{
__u32 t;
do {
t = (__u32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(__u32 *) buf = t;
buf += 4;
} while (--longs);
}
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
static void
MD5Init(struct MD5Context *ctx)
{
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
/*
* Update context to reflect the concatenation of another buffer full
* of bytes.
*/
static void
MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len)
{
register __u32 t;
/* Update bitcount */
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((__u32) len << 3)) < t)
ctx->bits[1]++; /* Carry from low to high */
ctx->bits[1] += len >> 29;
t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
/* Handle any leading odd-sized chunks */
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
t = 64 - t;
if (len < t) {
memmove(p, buf, len);
return;
}
memmove(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (__u32 *) ctx->in);
buf += t;
len -= t;
}
/* Process data in 64-byte chunks */
while (len >= 64) {
memmove(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (__u32 *) ctx->in);
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
memmove(ctx->in, buf, len);
}
/*
* Final wrapup - pad to 64-byte boundary with the bit pattern
* 1 0* (64-bit count of bits processed, MSB-first)
*/
static void
MD5Final(unsigned char digest[16], struct MD5Context *ctx)
{
unsigned int count;
unsigned char *p;
/* Compute number of bytes mod 64 */
count = (ctx->bits[0] >> 3) & 0x3F;
/* Set the first char of padding to 0x80. This is safe since there is
always at least one byte free */
p = ctx->in + count;
*p++ = 0x80;
/* Bytes of padding needed to make 64 bytes */
count = 64 - 1 - count;
/* Pad out to 56 mod 64 */
if (count < 8) {
/* Two lots of padding: Pad the first block to 64 bytes */
memset(p, 0, count);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (__u32 *) ctx->in);
/* Now fill the next block with 56 bytes */
memset(ctx->in, 0, 56);
} else {
/* Pad block to 56 bytes */
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
/* Append length in bits and transform */
((__u32 *) ctx->in)[14] = ctx->bits[0];
((__u32 *) ctx->in)[15] = ctx->bits[1];
MD5Transform(ctx->buf, (__u32 *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
memmove(digest, ctx->buf, 16);
memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */
}
/* The four core functions - F1 is optimized somewhat */
/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s) \
( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
/*
* The core of the MD5 algorithm, this alters an existing MD5 hash to
* reflect the addition of 16 longwords of new data. MD5Update blocks
* the data and converts bytes into longwords for this routine.
*/
static void
MD5Transform(__u32 buf[4], __u32 const in[16])
{
register __u32 a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
/*
* Calculate and store in 'output' the MD5 digest of 'len' bytes at
* 'input'. 'output' must have enough space to hold 16 bytes.
*/
void
md5 (unsigned char *input, int len, unsigned char output[16])
{
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, input, len);
MD5Final(output, &context);
}
/*
* Calculate and store in 'output' the MD5 digest of 'len' bytes at 'input'.
* 'output' must have enough space to hold 16 bytes. If 'chunk' Trigger the
* watchdog every 'chunk_sz' bytes of input processed.
*/
void
md5_wd (unsigned char *input, int len, unsigned char output[16],
unsigned int chunk_sz)
{
struct MD5Context context;
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
unsigned char *end, *curr;
int chunk;
#endif
MD5Init(&context);
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
curr = input;
end = input + len;
while (curr < end) {
chunk = end - curr;
if (chunk > chunk_sz)
chunk = chunk_sz;
MD5Update(&context, curr, chunk);
curr += chunk;
WATCHDOG_RESET ();
}
#else
MD5Update(&context, input, len);
#endif
MD5Final(output, &context);
}
|
1001-study-uboot
|
lib/md5.c
|
C
|
gpl3
| 9,167
|
/*
* (C) Copyright 2002-2006
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
char *strmhz (char *buf, unsigned long hz)
{
long l, n;
long m;
n = DIV_ROUND(hz, 1000) / 1000L;
l = sprintf (buf, "%ld", n);
hz -= n * 1000000L;
m = DIV_ROUND(hz, 1000L);
if (m != 0)
sprintf (buf + l, ".%03ld", m);
return (buf);
}
|
1001-study-uboot
|
lib/strmhz.c
|
C
|
gpl3
| 1,151
|
/*
* Heiko Schocher, DENX Software Engineering, hs@denx.de.
* based on:
* FIPS-180-1 compliant SHA-1 implementation
*
* Copyright (C) 2003-2006 Christophe Devine
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License, version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
/*
* The SHA-1 standard was published by NIST in 1993.
*
* http://www.itl.nist.gov/fipspubs/fip180-1.htm
*/
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
#ifndef USE_HOSTCC
#include <common.h>
#include <linux/string.h>
#else
#include <string.h>
#endif /* USE_HOSTCC */
#include <watchdog.h>
#include "sha1.h"
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT32_BE
#define GET_UINT32_BE(n,b,i) { \
(n) = ( (unsigned long) (b)[(i) ] << 24 ) \
| ( (unsigned long) (b)[(i) + 1] << 16 ) \
| ( (unsigned long) (b)[(i) + 2] << 8 ) \
| ( (unsigned long) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_UINT32_BE
#define PUT_UINT32_BE(n,b,i) { \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
/*
* SHA-1 context setup
*/
void sha1_starts (sha1_context * ctx)
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xC3D2E1F0;
}
static void sha1_process (sha1_context * ctx, unsigned char data[64])
{
unsigned long temp, W[16], A, B, C, D, E;
GET_UINT32_BE (W[0], data, 0);
GET_UINT32_BE (W[1], data, 4);
GET_UINT32_BE (W[2], data, 8);
GET_UINT32_BE (W[3], data, 12);
GET_UINT32_BE (W[4], data, 16);
GET_UINT32_BE (W[5], data, 20);
GET_UINT32_BE (W[6], data, 24);
GET_UINT32_BE (W[7], data, 28);
GET_UINT32_BE (W[8], data, 32);
GET_UINT32_BE (W[9], data, 36);
GET_UINT32_BE (W[10], data, 40);
GET_UINT32_BE (W[11], data, 44);
GET_UINT32_BE (W[12], data, 48);
GET_UINT32_BE (W[13], data, 52);
GET_UINT32_BE (W[14], data, 56);
GET_UINT32_BE (W[15], data, 60);
#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
#define R(t) ( \
temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ \
W[(t - 14) & 0x0F] ^ W[ t & 0x0F], \
( W[t & 0x0F] = S(temp,1) ) \
)
#define P(a,b,c,d,e,x) { \
e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \
}
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
E = ctx->state[4];
#define F(x,y,z) (z ^ (x & (y ^ z)))
#define K 0x5A827999
P (A, B, C, D, E, W[0]);
P (E, A, B, C, D, W[1]);
P (D, E, A, B, C, W[2]);
P (C, D, E, A, B, W[3]);
P (B, C, D, E, A, W[4]);
P (A, B, C, D, E, W[5]);
P (E, A, B, C, D, W[6]);
P (D, E, A, B, C, W[7]);
P (C, D, E, A, B, W[8]);
P (B, C, D, E, A, W[9]);
P (A, B, C, D, E, W[10]);
P (E, A, B, C, D, W[11]);
P (D, E, A, B, C, W[12]);
P (C, D, E, A, B, W[13]);
P (B, C, D, E, A, W[14]);
P (A, B, C, D, E, W[15]);
P (E, A, B, C, D, R (16));
P (D, E, A, B, C, R (17));
P (C, D, E, A, B, R (18));
P (B, C, D, E, A, R (19));
#undef K
#undef F
#define F(x,y,z) (x ^ y ^ z)
#define K 0x6ED9EBA1
P (A, B, C, D, E, R (20));
P (E, A, B, C, D, R (21));
P (D, E, A, B, C, R (22));
P (C, D, E, A, B, R (23));
P (B, C, D, E, A, R (24));
P (A, B, C, D, E, R (25));
P (E, A, B, C, D, R (26));
P (D, E, A, B, C, R (27));
P (C, D, E, A, B, R (28));
P (B, C, D, E, A, R (29));
P (A, B, C, D, E, R (30));
P (E, A, B, C, D, R (31));
P (D, E, A, B, C, R (32));
P (C, D, E, A, B, R (33));
P (B, C, D, E, A, R (34));
P (A, B, C, D, E, R (35));
P (E, A, B, C, D, R (36));
P (D, E, A, B, C, R (37));
P (C, D, E, A, B, R (38));
P (B, C, D, E, A, R (39));
#undef K
#undef F
#define F(x,y,z) ((x & y) | (z & (x | y)))
#define K 0x8F1BBCDC
P (A, B, C, D, E, R (40));
P (E, A, B, C, D, R (41));
P (D, E, A, B, C, R (42));
P (C, D, E, A, B, R (43));
P (B, C, D, E, A, R (44));
P (A, B, C, D, E, R (45));
P (E, A, B, C, D, R (46));
P (D, E, A, B, C, R (47));
P (C, D, E, A, B, R (48));
P (B, C, D, E, A, R (49));
P (A, B, C, D, E, R (50));
P (E, A, B, C, D, R (51));
P (D, E, A, B, C, R (52));
P (C, D, E, A, B, R (53));
P (B, C, D, E, A, R (54));
P (A, B, C, D, E, R (55));
P (E, A, B, C, D, R (56));
P (D, E, A, B, C, R (57));
P (C, D, E, A, B, R (58));
P (B, C, D, E, A, R (59));
#undef K
#undef F
#define F(x,y,z) (x ^ y ^ z)
#define K 0xCA62C1D6
P (A, B, C, D, E, R (60));
P (E, A, B, C, D, R (61));
P (D, E, A, B, C, R (62));
P (C, D, E, A, B, R (63));
P (B, C, D, E, A, R (64));
P (A, B, C, D, E, R (65));
P (E, A, B, C, D, R (66));
P (D, E, A, B, C, R (67));
P (C, D, E, A, B, R (68));
P (B, C, D, E, A, R (69));
P (A, B, C, D, E, R (70));
P (E, A, B, C, D, R (71));
P (D, E, A, B, C, R (72));
P (C, D, E, A, B, R (73));
P (B, C, D, E, A, R (74));
P (A, B, C, D, E, R (75));
P (E, A, B, C, D, R (76));
P (D, E, A, B, C, R (77));
P (C, D, E, A, B, R (78));
P (B, C, D, E, A, R (79));
#undef K
#undef F
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
ctx->state[4] += E;
}
/*
* SHA-1 process buffer
*/
void sha1_update (sha1_context * ctx, unsigned char *input, int ilen)
{
int fill;
unsigned long left;
if (ilen <= 0)
return;
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += ilen;
ctx->total[0] &= 0xFFFFFFFF;
if (ctx->total[0] < (unsigned long) ilen)
ctx->total[1]++;
if (left && ilen >= fill) {
memcpy ((void *) (ctx->buffer + left), (void *) input, fill);
sha1_process (ctx, ctx->buffer);
input += fill;
ilen -= fill;
left = 0;
}
while (ilen >= 64) {
sha1_process (ctx, input);
input += 64;
ilen -= 64;
}
if (ilen > 0) {
memcpy ((void *) (ctx->buffer + left), (void *) input, ilen);
}
}
static const unsigned char sha1_padding[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
* SHA-1 final digest
*/
void sha1_finish (sha1_context * ctx, unsigned char output[20])
{
unsigned long last, padn;
unsigned long high, low;
unsigned char msglen[8];
high = (ctx->total[0] >> 29)
| (ctx->total[1] << 3);
low = (ctx->total[0] << 3);
PUT_UINT32_BE (high, msglen, 0);
PUT_UINT32_BE (low, msglen, 4);
last = ctx->total[0] & 0x3F;
padn = (last < 56) ? (56 - last) : (120 - last);
sha1_update (ctx, (unsigned char *) sha1_padding, padn);
sha1_update (ctx, msglen, 8);
PUT_UINT32_BE (ctx->state[0], output, 0);
PUT_UINT32_BE (ctx->state[1], output, 4);
PUT_UINT32_BE (ctx->state[2], output, 8);
PUT_UINT32_BE (ctx->state[3], output, 12);
PUT_UINT32_BE (ctx->state[4], output, 16);
}
/*
* Output = SHA-1( input buffer )
*/
void sha1_csum (unsigned char *input, int ilen, unsigned char output[20])
{
sha1_context ctx;
sha1_starts (&ctx);
sha1_update (&ctx, input, ilen);
sha1_finish (&ctx, output);
}
/*
* Output = SHA-1( input buffer ). Trigger the watchdog every 'chunk_sz'
* bytes of input processed.
*/
void sha1_csum_wd (unsigned char *input, int ilen, unsigned char output[20],
unsigned int chunk_sz)
{
sha1_context ctx;
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
unsigned char *end, *curr;
int chunk;
#endif
sha1_starts (&ctx);
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
curr = input;
end = input + ilen;
while (curr < end) {
chunk = end - curr;
if (chunk > chunk_sz)
chunk = chunk_sz;
sha1_update (&ctx, curr, chunk);
curr += chunk;
WATCHDOG_RESET ();
}
#else
sha1_update (&ctx, input, ilen);
#endif
sha1_finish (&ctx, output);
}
/*
* Output = HMAC-SHA-1( input buffer, hmac key )
*/
void sha1_hmac (unsigned char *key, int keylen,
unsigned char *input, int ilen, unsigned char output[20])
{
int i;
sha1_context ctx;
unsigned char k_ipad[64];
unsigned char k_opad[64];
unsigned char tmpbuf[20];
memset (k_ipad, 0x36, 64);
memset (k_opad, 0x5C, 64);
for (i = 0; i < keylen; i++) {
if (i >= 64)
break;
k_ipad[i] ^= key[i];
k_opad[i] ^= key[i];
}
sha1_starts (&ctx);
sha1_update (&ctx, k_ipad, 64);
sha1_update (&ctx, input, ilen);
sha1_finish (&ctx, tmpbuf);
sha1_starts (&ctx);
sha1_update (&ctx, k_opad, 64);
sha1_update (&ctx, tmpbuf, 20);
sha1_finish (&ctx, output);
memset (k_ipad, 0, 64);
memset (k_opad, 0, 64);
memset (tmpbuf, 0, 20);
memset (&ctx, 0, sizeof (sha1_context));
}
static const char _sha1_src[] = "_sha1_src";
#ifdef SELF_TEST
/*
* FIPS-180-1 test vectors
*/
static const char sha1_test_str[3][57] = {
{"abc"},
{"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"},
{""}
};
static const unsigned char sha1_test_sum[3][20] = {
{0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E,
0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D},
{0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE,
0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1},
{0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E,
0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F}
};
/*
* Checkup routine
*/
int sha1_self_test (void)
{
int i, j;
unsigned char buf[1000];
unsigned char sha1sum[20];
sha1_context ctx;
for (i = 0; i < 3; i++) {
printf (" SHA-1 test #%d: ", i + 1);
sha1_starts (&ctx);
if (i < 2)
sha1_update (&ctx, (unsigned char *) sha1_test_str[i],
strlen (sha1_test_str[i]));
else {
memset (buf, 'a', 1000);
for (j = 0; j < 1000; j++)
sha1_update (&ctx, buf, 1000);
}
sha1_finish (&ctx, sha1sum);
if (memcmp (sha1sum, sha1_test_sum[i], 20) != 0) {
printf ("failed\n");
return (1);
}
printf ("passed\n");
}
printf ("\n");
return (0);
}
#else
int sha1_self_test (void)
{
return (0);
}
#endif
|
1001-study-uboot
|
lib/sha1.c
|
C
|
gpl3
| 10,457
|
/*
* (C) Copyright 2000-2006
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <watchdog.h>
#include <command.h>
#include <image.h>
#include <malloc.h>
#include <u-boot/zlib.h>
#define ZALLOC_ALIGNMENT 16
#define HEAD_CRC 2
#define EXTRA_FIELD 4
#define ORIG_NAME 8
#define COMMENT 0x10
#define RESERVED 0xe0
#define DEFLATED 8
void *zalloc(void *, unsigned, unsigned);
void zfree(void *, void *, unsigned);
void *zalloc(void *x, unsigned items, unsigned size)
{
void *p;
size *= items;
size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
p = malloc (size);
return (p);
}
void zfree(void *x, void *addr, unsigned nb)
{
free (addr);
}
int gunzip(void *dst, int dstlen, unsigned char *src, unsigned long *lenp)
{
int i, flags;
/* skip header */
i = 10;
flags = src[3];
if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
puts ("Error: Bad gzipped data\n");
return (-1);
}
if ((flags & EXTRA_FIELD) != 0)
i = 12 + src[10] + (src[11] << 8);
if ((flags & ORIG_NAME) != 0)
while (src[i++] != 0)
;
if ((flags & COMMENT) != 0)
while (src[i++] != 0)
;
if ((flags & HEAD_CRC) != 0)
i += 2;
if (i >= *lenp) {
puts ("Error: gunzip out of data in header\n");
return (-1);
}
return zunzip(dst, dstlen, src, lenp, 1, i);
}
/*
* Uncompress blocks compressed with zlib without headers
*/
int zunzip(void *dst, int dstlen, unsigned char *src, unsigned long *lenp,
int stoponerr, int offset)
{
z_stream s;
int r;
s.zalloc = zalloc;
s.zfree = zfree;
r = inflateInit2(&s, -MAX_WBITS);
if (r != Z_OK) {
printf ("Error: inflateInit2() returned %d\n", r);
return -1;
}
s.next_in = src + offset;
s.avail_in = *lenp - offset;
s.next_out = dst;
s.avail_out = dstlen;
do {
r = inflate(&s, Z_FINISH);
if (r != Z_STREAM_END && r != Z_BUF_ERROR && stoponerr == 1) {
printf("Error: inflate() returned %d\n", r);
inflateEnd(&s);
return -1;
}
s.avail_in = *lenp - offset - (int)(s.next_out - (unsigned char*)dst);
s.avail_out = dstlen;
} while (r == Z_BUF_ERROR);
*lenp = s.next_out - (unsigned char *) dst;
inflateEnd(&s);
return 0;
}
|
1001-study-uboot
|
lib/gunzip.c
|
C
|
gpl3
| 2,961
|
/*
* linux/lib/string.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* stupid library routines.. The optimized versions should generally be found
* as inline code in <asm-xx/string.h>
*
* These are buggy as well..
*
* * Fri Jun 25 1999, Ingo Oeser <ioe@informatik.tu-chemnitz.de>
* - Added strsep() which will replace strtok() soon (because strsep() is
* reentrant and should be faster). Use only strsep() in new code, please.
*/
#include <linux/types.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <malloc.h>
#if 0 /* not used - was: #ifndef __HAVE_ARCH_STRNICMP */
/**
* strnicmp - Case insensitive, length-limited string comparison
* @s1: One string
* @s2: The other string
* @len: the maximum number of characters to compare
*/
int strnicmp(const char *s1, const char *s2, size_t len)
{
/* Yes, Virginia, it had better be unsigned */
unsigned char c1, c2;
c1 = 0; c2 = 0;
if (len) {
do {
c1 = *s1; c2 = *s2;
s1++; s2++;
if (!c1)
break;
if (!c2)
break;
if (c1 == c2)
continue;
c1 = tolower(c1);
c2 = tolower(c2);
if (c1 != c2)
break;
} while (--len);
}
return (int)c1 - (int)c2;
}
#endif
char * ___strtok;
#ifndef __HAVE_ARCH_STRCPY
/**
* strcpy - Copy a %NUL terminated string
* @dest: Where to copy the string to
* @src: Where to copy the string from
*/
char * strcpy(char * dest,const char *src)
{
char *tmp = dest;
while ((*dest++ = *src++) != '\0')
/* nothing */;
return tmp;
}
#endif
#ifndef __HAVE_ARCH_STRNCPY
/**
* strncpy - Copy a length-limited, %NUL-terminated string
* @dest: Where to copy the string to
* @src: Where to copy the string from
* @count: The maximum number of bytes to copy
*
* Note that unlike userspace strncpy, this does not %NUL-pad the buffer.
* However, the result is not %NUL-terminated if the source exceeds
* @count bytes.
*/
char * strncpy(char * dest,const char *src,size_t count)
{
char *tmp = dest;
while (count-- && (*dest++ = *src++) != '\0')
/* nothing */;
return tmp;
}
#endif
#ifndef __HAVE_ARCH_STRCAT
/**
* strcat - Append one %NUL-terminated string to another
* @dest: The string to be appended to
* @src: The string to append to it
*/
char * strcat(char * dest, const char * src)
{
char *tmp = dest;
while (*dest)
dest++;
while ((*dest++ = *src++) != '\0')
;
return tmp;
}
#endif
#ifndef __HAVE_ARCH_STRNCAT
/**
* strncat - Append a length-limited, %NUL-terminated string to another
* @dest: The string to be appended to
* @src: The string to append to it
* @count: The maximum numbers of bytes to copy
*
* Note that in contrast to strncpy, strncat ensures the result is
* terminated.
*/
char * strncat(char *dest, const char *src, size_t count)
{
char *tmp = dest;
if (count) {
while (*dest)
dest++;
while ((*dest++ = *src++)) {
if (--count == 0) {
*dest = '\0';
break;
}
}
}
return tmp;
}
#endif
#ifndef __HAVE_ARCH_STRCMP
/**
* strcmp - Compare two strings
* @cs: One string
* @ct: Another string
*/
int strcmp(const char * cs,const char * ct)
{
register signed char __res;
while (1) {
if ((__res = *cs - *ct++) != 0 || !*cs++)
break;
}
return __res;
}
#endif
#ifndef __HAVE_ARCH_STRNCMP
/**
* strncmp - Compare two length-limited strings
* @cs: One string
* @ct: Another string
* @count: The maximum number of bytes to compare
*/
int strncmp(const char * cs,const char * ct,size_t count)
{
register signed char __res = 0;
while (count) {
if ((__res = *cs - *ct++) != 0 || !*cs++)
break;
count--;
}
return __res;
}
#endif
#ifndef __HAVE_ARCH_STRCHR
/**
* strchr - Find the first occurrence of a character in a string
* @s: The string to be searched
* @c: The character to search for
*/
char * strchr(const char * s, int c)
{
for(; *s != (char) c; ++s)
if (*s == '\0')
return NULL;
return (char *) s;
}
#endif
#ifndef __HAVE_ARCH_STRRCHR
/**
* strrchr - Find the last occurrence of a character in a string
* @s: The string to be searched
* @c: The character to search for
*/
char * strrchr(const char * s, int c)
{
const char *p = s + strlen(s);
do {
if (*p == (char)c)
return (char *)p;
} while (--p >= s);
return NULL;
}
#endif
#ifndef __HAVE_ARCH_STRLEN
/**
* strlen - Find the length of a string
* @s: The string to be sized
*/
size_t strlen(const char * s)
{
const char *sc;
for (sc = s; *sc != '\0'; ++sc)
/* nothing */;
return sc - s;
}
#endif
#ifndef __HAVE_ARCH_STRNLEN
/**
* strnlen - Find the length of a length-limited string
* @s: The string to be sized
* @count: The maximum number of bytes to search
*/
size_t strnlen(const char * s, size_t count)
{
const char *sc;
for (sc = s; count-- && *sc != '\0'; ++sc)
/* nothing */;
return sc - s;
}
#endif
#ifndef __HAVE_ARCH_STRDUP
char * strdup(const char *s)
{
char *new;
if ((s == NULL) ||
((new = malloc (strlen(s) + 1)) == NULL) ) {
return NULL;
}
strcpy (new, s);
return new;
}
#endif
#ifndef __HAVE_ARCH_STRSPN
/**
* strspn - Calculate the length of the initial substring of @s which only
* contain letters in @accept
* @s: The string to be searched
* @accept: The string to search for
*/
size_t strspn(const char *s, const char *accept)
{
const char *p;
const char *a;
size_t count = 0;
for (p = s; *p != '\0'; ++p) {
for (a = accept; *a != '\0'; ++a) {
if (*p == *a)
break;
}
if (*a == '\0')
return count;
++count;
}
return count;
}
#endif
#ifndef __HAVE_ARCH_STRPBRK
/**
* strpbrk - Find the first occurrence of a set of characters
* @cs: The string to be searched
* @ct: The characters to search for
*/
char * strpbrk(const char * cs,const char * ct)
{
const char *sc1,*sc2;
for( sc1 = cs; *sc1 != '\0'; ++sc1) {
for( sc2 = ct; *sc2 != '\0'; ++sc2) {
if (*sc1 == *sc2)
return (char *) sc1;
}
}
return NULL;
}
#endif
#ifndef __HAVE_ARCH_STRTOK
/**
* strtok - Split a string into tokens
* @s: The string to be searched
* @ct: The characters to search for
*
* WARNING: strtok is deprecated, use strsep instead.
*/
char * strtok(char * s,const char * ct)
{
char *sbegin, *send;
sbegin = s ? s : ___strtok;
if (!sbegin) {
return NULL;
}
sbegin += strspn(sbegin,ct);
if (*sbegin == '\0') {
___strtok = NULL;
return( NULL );
}
send = strpbrk( sbegin, ct);
if (send && *send != '\0')
*send++ = '\0';
___strtok = send;
return (sbegin);
}
#endif
#ifndef __HAVE_ARCH_STRSEP
/**
* strsep - Split a string into tokens
* @s: The string to be searched
* @ct: The characters to search for
*
* strsep() updates @s to point after the token, ready for the next call.
*
* It returns empty tokens, too, behaving exactly like the libc function
* of that name. In fact, it was stolen from glibc2 and de-fancy-fied.
* Same semantics, slimmer shape. ;)
*/
char * strsep(char **s, const char *ct)
{
char *sbegin = *s, *end;
if (sbegin == NULL)
return NULL;
end = strpbrk(sbegin, ct);
if (end)
*end++ = '\0';
*s = end;
return sbegin;
}
#endif
#ifndef __HAVE_ARCH_STRSWAB
/**
* strswab - swap adjacent even and odd bytes in %NUL-terminated string
* s: address of the string
*
* returns the address of the swapped string or NULL on error. If
* string length is odd, last byte is untouched.
*/
char *strswab(const char *s)
{
char *p, *q;
if ((NULL == s) || ('\0' == *s)) {
return (NULL);
}
for (p=(char *)s, q=p+1; (*p != '\0') && (*q != '\0'); p+=2, q+=2) {
char tmp;
tmp = *p;
*p = *q;
*q = tmp;
}
return (char *) s;
}
#endif
#ifndef __HAVE_ARCH_MEMSET
/**
* memset - Fill a region of memory with the given value
* @s: Pointer to the start of the area.
* @c: The byte to fill the area with
* @count: The size of the area.
*
* Do not use memset() to access IO space, use memset_io() instead.
*/
void * memset(void * s,int c,size_t count)
{
unsigned long *sl = (unsigned long *) s;
unsigned long cl = 0;
char *s8;
int i;
/* do it one word at a time (32 bits or 64 bits) while possible */
if ( ((ulong)s & (sizeof(*sl) - 1)) == 0) {
for (i = 0; i < sizeof(*sl); i++) {
cl <<= 8;
cl |= c & 0xff;
}
while (count >= sizeof(*sl)) {
*sl++ = cl;
count -= sizeof(*sl);
}
}
/* fill 8 bits at a time */
s8 = (char *)sl;
while (count--)
*s8++ = c;
return s;
}
#endif
#ifndef __HAVE_ARCH_BCOPY
/**
* bcopy - Copy one area of memory to another
* @src: Where to copy from
* @dest: Where to copy to
* @count: The size of the area.
*
* Note that this is the same as memcpy(), with the arguments reversed.
* memcpy() is the standard, bcopy() is a legacy BSD function.
*
* You should not use this function to access IO space, use memcpy_toio()
* or memcpy_fromio() instead.
*/
char * bcopy(const char * src, char * dest, int count)
{
char *tmp = dest;
while (count--)
*tmp++ = *src++;
return dest;
}
#endif
#ifndef __HAVE_ARCH_MEMCPY
/**
* memcpy - Copy one area of memory to another
* @dest: Where to copy to
* @src: Where to copy from
* @count: The size of the area.
*
* You should not use this function to access IO space, use memcpy_toio()
* or memcpy_fromio() instead.
*/
void * memcpy(void *dest, const void *src, size_t count)
{
unsigned long *dl = (unsigned long *)dest, *sl = (unsigned long *)src;
char *d8, *s8;
if (src == dest)
return dest;
/* while all data is aligned (common case), copy a word at a time */
if ( (((ulong)dest | (ulong)src) & (sizeof(*dl) - 1)) == 0) {
while (count >= sizeof(*dl)) {
*dl++ = *sl++;
count -= sizeof(*dl);
}
}
/* copy the reset one byte at a time */
d8 = (char *)dl;
s8 = (char *)sl;
while (count--)
*d8++ = *s8++;
return dest;
}
#endif
#ifndef __HAVE_ARCH_MEMMOVE
/**
* memmove - Copy one area of memory to another
* @dest: Where to copy to
* @src: Where to copy from
* @count: The size of the area.
*
* Unlike memcpy(), memmove() copes with overlapping areas.
*/
void * memmove(void * dest,const void *src,size_t count)
{
char *tmp, *s;
if (src == dest)
return dest;
if (dest <= src) {
tmp = (char *) dest;
s = (char *) src;
while (count--)
*tmp++ = *s++;
}
else {
tmp = (char *) dest + count;
s = (char *) src + count;
while (count--)
*--tmp = *--s;
}
return dest;
}
#endif
#ifndef __HAVE_ARCH_MEMCMP
/**
* memcmp - Compare two areas of memory
* @cs: One area of memory
* @ct: Another area of memory
* @count: The size of the area.
*/
int memcmp(const void * cs,const void * ct,size_t count)
{
const unsigned char *su1, *su2;
int res = 0;
for( su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
if ((res = *su1 - *su2) != 0)
break;
return res;
}
#endif
#ifndef __HAVE_ARCH_MEMSCAN
/**
* memscan - Find a character in an area of memory.
* @addr: The memory area
* @c: The byte to search for
* @size: The size of the area.
*
* returns the address of the first occurrence of @c, or 1 byte past
* the area if @c is not found
*/
void * memscan(void * addr, int c, size_t size)
{
unsigned char * p = (unsigned char *) addr;
while (size) {
if (*p == c)
return (void *) p;
p++;
size--;
}
return (void *) p;
}
#endif
#ifndef __HAVE_ARCH_STRSTR
/**
* strstr - Find the first substring in a %NUL terminated string
* @s1: The string to be searched
* @s2: The string to search for
*/
char * strstr(const char * s1,const char * s2)
{
int l1, l2;
l2 = strlen(s2);
if (!l2)
return (char *) s1;
l1 = strlen(s1);
while (l1 >= l2) {
l1--;
if (!memcmp(s1,s2,l2))
return (char *) s1;
s1++;
}
return NULL;
}
#endif
#ifndef __HAVE_ARCH_MEMCHR
/**
* memchr - Find a character in an area of memory.
* @s: The memory area
* @c: The byte to search for
* @n: The size of the area.
*
* returns the address of the first occurrence of @c, or %NULL
* if @c is not found
*/
void *memchr(const void *s, int c, size_t n)
{
const unsigned char *p = s;
while (n-- != 0) {
if ((unsigned char)c == *p++) {
return (void *)(p-1);
}
}
return NULL;
}
#endif
|
1001-study-uboot
|
lib/string.c
|
C
|
gpl3
| 12,010
|
#include <config.h>
#include <common.h>
#include <watchdog.h>
/*-------------------------------------------------------------*/
/*--- Decompression machinery ---*/
/*--- decompress.c ---*/
/*-------------------------------------------------------------*/
/*--
This file is a part of bzip2 and/or libbzip2, a program and
library for lossless, block-sorting data compression.
Copyright (C) 1996-2002 Julian R Seward. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Julian Seward, Cambridge, UK.
jseward@acm.org
bzip2/libbzip2 version 1.0 of 21 March 2000
This program is based on (at least) the work of:
Mike Burrows
David Wheeler
Peter Fenwick
Alistair Moffat
Radford Neal
Ian H. Witten
Robert Sedgewick
Jon L. Bentley
For more information on these sources, see the manual.
--*/
#include "bzlib_private.h"
/*---------------------------------------------------*/
static
void makeMaps_d ( DState* s )
{
Int32 i;
s->nInUse = 0;
for (i = 0; i < 256; i++)
if (s->inUse[i]) {
s->seqToUnseq[s->nInUse] = i;
s->nInUse++;
}
}
/*---------------------------------------------------*/
#define RETURN(rrr) \
{ retVal = rrr; goto save_state_and_return; };
#define GET_BITS(lll,vvv,nnn) \
case lll: s->state = lll; \
while (True) { \
if (s->bsLive >= nnn) { \
UInt32 v; \
v = (s->bsBuff >> \
(s->bsLive-nnn)) & ((1 << nnn)-1); \
s->bsLive -= nnn; \
vvv = v; \
break; \
} \
if (s->strm->avail_in == 0) RETURN(BZ_OK); \
s->bsBuff \
= (s->bsBuff << 8) | \
((UInt32) \
(*((UChar*)(s->strm->next_in)))); \
s->bsLive += 8; \
s->strm->next_in++; \
s->strm->avail_in--; \
s->strm->total_in_lo32++; \
if (s->strm->total_in_lo32 == 0) \
s->strm->total_in_hi32++; \
}
#define GET_UCHAR(lll,uuu) \
GET_BITS(lll,uuu,8)
#define GET_BIT(lll,uuu) \
GET_BITS(lll,uuu,1)
/*---------------------------------------------------*/
#define GET_MTF_VAL(label1,label2,lval) \
{ \
if (groupPos == 0) { \
groupNo++; \
if (groupNo >= nSelectors) \
RETURN(BZ_DATA_ERROR); \
groupPos = BZ_G_SIZE; \
gSel = s->selector[groupNo]; \
gMinlen = s->minLens[gSel]; \
gLimit = &(s->limit[gSel][0]); \
gPerm = &(s->perm[gSel][0]); \
gBase = &(s->base[gSel][0]); \
} \
groupPos--; \
zn = gMinlen; \
GET_BITS(label1, zvec, zn); \
while (1) { \
if (zn > 20 /* the longest code */) \
RETURN(BZ_DATA_ERROR); \
if (zvec <= gLimit[zn]) break; \
zn++; \
GET_BIT(label2, zj); \
zvec = (zvec << 1) | zj; \
}; \
if (zvec - gBase[zn] < 0 \
|| zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \
RETURN(BZ_DATA_ERROR); \
lval = gPerm[zvec - gBase[zn]]; \
}
/*---------------------------------------------------*/
Int32 BZ2_decompress ( DState* s )
{
UChar uc;
Int32 retVal;
Int32 minLen, maxLen;
bz_stream* strm = s->strm;
/* stuff that needs to be saved/restored */
Int32 i;
Int32 j;
Int32 t;
Int32 alphaSize;
Int32 nGroups;
Int32 nSelectors;
Int32 EOB;
Int32 groupNo;
Int32 groupPos;
Int32 nextSym;
Int32 nblockMAX;
Int32 nblock;
Int32 es;
Int32 N;
Int32 curr;
Int32 zt;
Int32 zn;
Int32 zvec;
Int32 zj;
Int32 gSel;
Int32 gMinlen;
Int32* gLimit;
Int32* gBase;
Int32* gPerm;
if (s->state == BZ_X_MAGIC_1) {
/*initialise the save area*/
s->save_i = 0;
s->save_j = 0;
s->save_t = 0;
s->save_alphaSize = 0;
s->save_nGroups = 0;
s->save_nSelectors = 0;
s->save_EOB = 0;
s->save_groupNo = 0;
s->save_groupPos = 0;
s->save_nextSym = 0;
s->save_nblockMAX = 0;
s->save_nblock = 0;
s->save_es = 0;
s->save_N = 0;
s->save_curr = 0;
s->save_zt = 0;
s->save_zn = 0;
s->save_zvec = 0;
s->save_zj = 0;
s->save_gSel = 0;
s->save_gMinlen = 0;
s->save_gLimit = NULL;
s->save_gBase = NULL;
s->save_gPerm = NULL;
}
/*restore from the save area*/
i = s->save_i;
j = s->save_j;
t = s->save_t;
alphaSize = s->save_alphaSize;
nGroups = s->save_nGroups;
nSelectors = s->save_nSelectors;
EOB = s->save_EOB;
groupNo = s->save_groupNo;
groupPos = s->save_groupPos;
nextSym = s->save_nextSym;
nblockMAX = s->save_nblockMAX;
nblock = s->save_nblock;
es = s->save_es;
N = s->save_N;
curr = s->save_curr;
zt = s->save_zt;
zn = s->save_zn;
zvec = s->save_zvec;
zj = s->save_zj;
gSel = s->save_gSel;
gMinlen = s->save_gMinlen;
gLimit = s->save_gLimit;
gBase = s->save_gBase;
gPerm = s->save_gPerm;
retVal = BZ_OK;
switch (s->state) {
GET_UCHAR(BZ_X_MAGIC_1, uc);
if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);
GET_UCHAR(BZ_X_MAGIC_2, uc);
if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);
GET_UCHAR(BZ_X_MAGIC_3, uc)
if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);
GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)
if (s->blockSize100k < (BZ_HDR_0 + 1) ||
s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);
s->blockSize100k -= BZ_HDR_0;
if (s->smallDecompress) {
s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );
s->ll4 = BZALLOC(
((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar)
);
if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);
} else {
s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );
if (s->tt == NULL) RETURN(BZ_MEM_ERROR);
}
GET_UCHAR(BZ_X_BLKHDR_1, uc);
if (uc == 0x17) goto endhdr_2;
if (uc != 0x31) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_2, uc);
if (uc != 0x41) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_3, uc);
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_4, uc);
if (uc != 0x26) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_5, uc);
if (uc != 0x53) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_6, uc);
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
s->currBlockNo++;
if (s->verbosity >= 2)
VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo );
s->storedBlockCRC = 0;
GET_UCHAR(BZ_X_BCRC_1, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_2, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_3, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_4, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);
s->origPtr = 0;
GET_UCHAR(BZ_X_ORIGPTR_1, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
GET_UCHAR(BZ_X_ORIGPTR_2, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
GET_UCHAR(BZ_X_ORIGPTR_3, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
if (s->origPtr < 0)
RETURN(BZ_DATA_ERROR);
if (s->origPtr > 10 + 100000*s->blockSize100k)
RETURN(BZ_DATA_ERROR);
/*--- Receive the mapping table ---*/
for (i = 0; i < 16; i++) {
GET_BIT(BZ_X_MAPPING_1, uc);
if (uc == 1)
s->inUse16[i] = True; else
s->inUse16[i] = False;
}
for (i = 0; i < 256; i++) s->inUse[i] = False;
for (i = 0; i < 16; i++)
if (s->inUse16[i])
for (j = 0; j < 16; j++) {
GET_BIT(BZ_X_MAPPING_2, uc);
if (uc == 1) s->inUse[i * 16 + j] = True;
}
makeMaps_d ( s );
if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);
alphaSize = s->nInUse+2;
/*--- Now the selectors ---*/
GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);
if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);
GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);
if (nSelectors < 1) RETURN(BZ_DATA_ERROR);
for (i = 0; i < nSelectors; i++) {
j = 0;
while (True) {
GET_BIT(BZ_X_SELECTOR_3, uc);
if (uc == 0) break;
j++;
if (j >= nGroups) RETURN(BZ_DATA_ERROR);
}
s->selectorMtf[i] = j;
}
/*--- Undo the MTF values for the selectors. ---*/
{
UChar pos[BZ_N_GROUPS], tmp, v;
for (v = 0; v < nGroups; v++) pos[v] = v;
for (i = 0; i < nSelectors; i++) {
v = s->selectorMtf[i];
tmp = pos[v];
while (v > 0) { pos[v] = pos[v-1]; v--; }
pos[0] = tmp;
s->selector[i] = tmp;
}
}
/*--- Now the coding tables ---*/
for (t = 0; t < nGroups; t++) {
GET_BITS(BZ_X_CODING_1, curr, 5);
for (i = 0; i < alphaSize; i++) {
while (True) {
if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);
GET_BIT(BZ_X_CODING_2, uc);
if (uc == 0) break;
GET_BIT(BZ_X_CODING_3, uc);
if (uc == 0) curr++; else curr--;
}
s->len[t][i] = curr;
}
}
/*--- Create the Huffman decoding tables ---*/
for (t = 0; t < nGroups; t++) {
minLen = 32;
maxLen = 0;
for (i = 0; i < alphaSize; i++) {
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
if (s->len[t][i] < minLen) minLen = s->len[t][i];
}
BZ2_hbCreateDecodeTables (
&(s->limit[t][0]),
&(s->base[t][0]),
&(s->perm[t][0]),
&(s->len[t][0]),
minLen, maxLen, alphaSize
);
s->minLens[t] = minLen;
}
/*--- Now the MTF values ---*/
EOB = s->nInUse+1;
nblockMAX = 100000 * s->blockSize100k;
groupNo = -1;
groupPos = 0;
for (i = 0; i <= 255; i++) s->unzftab[i] = 0;
/*-- MTF init --*/
{
Int32 ii, jj, kk;
kk = MTFA_SIZE-1;
for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);
kk--;
}
s->mtfbase[ii] = kk + 1;
}
}
/*-- end MTF init --*/
nblock = 0;
GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);
while (True) {
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
WATCHDOG_RESET();
#endif
if (nextSym == EOB) break;
if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {
es = -1;
N = 1;
do {
if (nextSym == BZ_RUNA) es = es + (0+1) * N; else
if (nextSym == BZ_RUNB) es = es + (1+1) * N;
N = N * 2;
GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);
}
while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);
es++;
uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];
s->unzftab[uc] += es;
if (s->smallDecompress)
while (es > 0) {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
s->ll16[nblock] = (UInt16)uc;
nblock++;
es--;
}
else
while (es > 0) {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
s->tt[nblock] = (UInt32)uc;
nblock++;
es--;
};
continue;
} else {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
/*-- uc = MTF ( nextSym-1 ) --*/
{
Int32 ii, jj, kk, pp, lno, off;
UInt32 nn;
nn = (UInt32)(nextSym - 1);
if (nn < MTFL_SIZE) {
/* avoid general-case expense */
pp = s->mtfbase[0];
uc = s->mtfa[pp+nn];
while (nn > 3) {
Int32 z = pp+nn;
s->mtfa[(z) ] = s->mtfa[(z)-1];
s->mtfa[(z)-1] = s->mtfa[(z)-2];
s->mtfa[(z)-2] = s->mtfa[(z)-3];
s->mtfa[(z)-3] = s->mtfa[(z)-4];
nn -= 4;
}
while (nn > 0) {
s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--;
};
s->mtfa[pp] = uc;
} else {
/* general case */
lno = nn / MTFL_SIZE;
off = nn % MTFL_SIZE;
pp = s->mtfbase[lno] + off;
uc = s->mtfa[pp];
while (pp > s->mtfbase[lno]) {
s->mtfa[pp] = s->mtfa[pp-1]; pp--;
};
s->mtfbase[lno]++;
while (lno > 0) {
s->mtfbase[lno]--;
s->mtfa[s->mtfbase[lno]]
= s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];
lno--;
}
s->mtfbase[0]--;
s->mtfa[s->mtfbase[0]] = uc;
if (s->mtfbase[0] == 0) {
kk = MTFA_SIZE-1;
for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
WATCHDOG_RESET();
#endif
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];
kk--;
}
s->mtfbase[ii] = kk + 1;
}
}
}
}
/*-- end uc = MTF ( nextSym-1 ) --*/
s->unzftab[s->seqToUnseq[uc]]++;
if (s->smallDecompress)
s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else
s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);
nblock++;
GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);
continue;
}
}
/* Now we know what nblock is, we can do a better sanity
check on s->origPtr.
*/
if (s->origPtr < 0 || s->origPtr >= nblock)
RETURN(BZ_DATA_ERROR);
s->state_out_len = 0;
s->state_out_ch = 0;
BZ_INITIALISE_CRC ( s->calculatedBlockCRC );
s->state = BZ_X_OUTPUT;
if (s->verbosity >= 2) VPrintf0 ( "rt+rld" );
/*-- Set up cftab to facilitate generation of T^(-1) --*/
s->cftab[0] = 0;
for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];
for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];
if (s->smallDecompress) {
/*-- Make a copy of cftab, used in generation of T --*/
for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];
/*-- compute the T vector --*/
for (i = 0; i < nblock; i++) {
uc = (UChar)(s->ll16[i]);
SET_LL(i, s->cftabCopy[uc]);
s->cftabCopy[uc]++;
}
/*-- Compute T^(-1) by pointer reversal on T --*/
i = s->origPtr;
j = GET_LL(i);
do {
Int32 tmp = GET_LL(j);
SET_LL(j, i);
i = j;
j = tmp;
}
while (i != s->origPtr);
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
WATCHDOG_RESET();
#endif
s->tPos = s->origPtr;
s->nblock_used = 0;
if (s->blockRandomised) {
BZ_RAND_INIT_MASK;
BZ_GET_SMALL(s->k0); s->nblock_used++;
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else {
BZ_GET_SMALL(s->k0); s->nblock_used++;
}
} else {
#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
WATCHDOG_RESET();
#endif
/*-- compute the T^(-1) vector --*/
for (i = 0; i < nblock; i++) {
uc = (UChar)(s->tt[i] & 0xff);
s->tt[s->cftab[uc]] |= (i << 8);
s->cftab[uc]++;
}
s->tPos = s->tt[s->origPtr] >> 8;
s->nblock_used = 0;
if (s->blockRandomised) {
BZ_RAND_INIT_MASK;
BZ_GET_FAST(s->k0); s->nblock_used++;
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else {
BZ_GET_FAST(s->k0); s->nblock_used++;
}
}
RETURN(BZ_OK);
endhdr_2:
GET_UCHAR(BZ_X_ENDHDR_2, uc);
if (uc != 0x72) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_3, uc);
if (uc != 0x45) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_4, uc);
if (uc != 0x38) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_5, uc);
if (uc != 0x50) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_6, uc);
if (uc != 0x90) RETURN(BZ_DATA_ERROR);
s->storedCombinedCRC = 0;
GET_UCHAR(BZ_X_CCRC_1, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_2, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_3, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_4, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
s->state = BZ_X_IDLE;
RETURN(BZ_STREAM_END);
default: AssertH ( False, 4001 );
}
AssertH ( False, 4002 );
save_state_and_return:
s->save_i = i;
s->save_j = j;
s->save_t = t;
s->save_alphaSize = alphaSize;
s->save_nGroups = nGroups;
s->save_nSelectors = nSelectors;
s->save_EOB = EOB;
s->save_groupNo = groupNo;
s->save_groupPos = groupPos;
s->save_nextSym = nextSym;
s->save_nblockMAX = nblockMAX;
s->save_nblock = nblock;
s->save_es = es;
s->save_N = N;
s->save_curr = curr;
s->save_zt = zt;
s->save_zn = zn;
s->save_zvec = zvec;
s->save_zj = zj;
s->save_gSel = gSel;
s->save_gMinlen = gMinlen;
s->save_gLimit = gLimit;
s->save_gBase = gBase;
s->save_gPerm = gPerm;
return retVal;
}
/*-------------------------------------------------------------*/
/*--- end decompress.c ---*/
/*-------------------------------------------------------------*/
|
1001-study-uboot
|
lib/bzlib_decompress.c
|
C
|
gpl3
| 19,833
|
/*
* Copyright 2011 Calxeda, 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 <linux/ctype.h>
#include "common.h"
/*
* This is what a UUID string looks like.
*
* x is a hexadecimal character. fields are separated by '-'s. When converting
* to a binary UUID, le means the field should be converted to little endian,
* and be means it should be converted to big endian.
*
* 0 9 14 19 24
* xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
* le le le be be
*/
int uuid_str_valid(const char *uuid)
{
int i, valid;
if (uuid == NULL)
return 0;
for (i = 0, valid = 1; uuid[i] && valid; i++) {
switch (i) {
case 8: case 13: case 18: case 23:
valid = (uuid[i] == '-');
break;
default:
valid = isxdigit(uuid[i]);
break;
}
}
if (i != 36 || !valid)
return 0;
return 1;
}
void uuid_str_to_bin(const char *uuid, unsigned char *out)
{
uint16_t tmp16;
uint32_t tmp32;
uint64_t tmp64;
if (!uuid || !out)
return;
tmp32 = cpu_to_le32(simple_strtoul(uuid, NULL, 16));
memcpy(out, &tmp32, 4);
tmp16 = cpu_to_le16(simple_strtoul(uuid + 9, NULL, 16));
memcpy(out + 4, &tmp16, 2);
tmp16 = cpu_to_le16(simple_strtoul(uuid + 14, NULL, 16));
memcpy(out + 6, &tmp16, 2);
tmp16 = cpu_to_be16(simple_strtoul(uuid + 19, NULL, 16));
memcpy(out + 8, &tmp16, 2);
tmp64 = cpu_to_be64(simple_strtoull(uuid + 24, NULL, 16));
memcpy(out + 10, (char *)&tmp64 + 2, 6);
}
|
1001-study-uboot
|
lib/uuid.c
|
C
|
gpl3
| 2,184
|
/*
* (C) Copyright 2000-2002
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <config.h>
#include <common.h>
#include <version.h>
#include <linux/ctype.h>
#include <asm/io.h>
int display_options (void)
{
#if defined(BUILD_TAG)
printf ("\n\n%s, Build: %s\n\n", version_string, BUILD_TAG);
#else
printf ("\n\n%s\n\n", version_string);
#endif
return 0;
}
/*
* print sizes as "xxx KiB", "xxx.y KiB", "xxx MiB", "xxx.y MiB",
* xxx GiB, xxx.y GiB, etc as needed; allow for optional trailing string
* (like "\n")
*/
void print_size(unsigned long long size, const char *s)
{
unsigned long m = 0, n;
unsigned long long f;
static const char names[] = {'E', 'P', 'T', 'G', 'M', 'K'};
unsigned long d = 10 * ARRAY_SIZE(names);
char c = 0;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(names); i++, d -= 10) {
if (size >> d) {
c = names[i];
break;
}
}
if (!c) {
printf("%llu Bytes%s", size, s);
return;
}
n = size >> d;
f = size & ((1ULL << d) - 1);
/* If there's a remainder, deal with it */
if (f) {
m = (10ULL * f + (1ULL << (d - 1))) >> d;
if (m >= 10) {
m -= 10;
n += 1;
}
}
printf ("%lu", n);
if (m) {
printf (".%ld", m);
}
printf (" %ciB%s", c, s);
}
/*
* Print data buffer in hex and ascii form to the terminal.
*
* data reads are buffered so that each memory address is only read once.
* Useful when displaying the contents of volatile registers.
*
* parameters:
* addr: Starting address to display at start of line
* data: pointer to data buffer
* width: data value width. May be 1, 2, or 4.
* count: number of values to display
* linelen: Number of values to print per line; specify 0 for default length
*/
#define MAX_LINE_LENGTH_BYTES (64)
#define DEFAULT_LINE_LENGTH_BYTES (16)
int print_buffer (ulong addr, void* data, uint width, uint count, uint linelen)
{
/* linebuf as a union causes proper alignment */
union linebuf {
uint32_t ui[MAX_LINE_LENGTH_BYTES/sizeof(uint32_t) + 1];
uint16_t us[MAX_LINE_LENGTH_BYTES/sizeof(uint16_t) + 1];
uint8_t uc[MAX_LINE_LENGTH_BYTES/sizeof(uint8_t) + 1];
} lb;
int i;
if (linelen*width > MAX_LINE_LENGTH_BYTES)
linelen = MAX_LINE_LENGTH_BYTES / width;
if (linelen < 1)
linelen = DEFAULT_LINE_LENGTH_BYTES / width;
while (count) {
printf("%08lx:", addr);
/* check for overflow condition */
if (count < linelen)
linelen = count;
/* Copy from memory into linebuf and print hex values */
for (i = 0; i < linelen; i++) {
uint32_t x;
if (width == 4)
x = lb.ui[i] = *(volatile uint32_t *)data;
else if (width == 2)
x = lb.us[i] = *(volatile uint16_t *)data;
else
x = lb.uc[i] = *(volatile uint8_t *)data;
printf(" %0*x", width * 2, x);
data += width;
}
/* Print data in ASCII characters */
for (i = 0; i < linelen * width; i++) {
if (!isprint(lb.uc[i]) || lb.uc[i] >= 0x80)
lb.uc[i] = '.';
}
lb.uc[i] = '\0';
printf(" %s\n", lb.uc);
/* update references */
addr += linelen * width;
count -= linelen;
if (ctrlc())
return -1;
}
return 0;
}
|
1001-study-uboot
|
lib/display_options.c
|
C
|
gpl3
| 3,881
|