repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
RaspberryPi-CM/android_kernel_raspberry_pi2 | drivers/tty/tty_io.c | 2 | 91446 | /*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* 'tty_io.c' gives an orthogonal feeling to tty's, be they consoles
* or rs-channels. It also implements echoing, cooked mode etc.
*
* Kill-line thanks to John T Kohl, who also corrected VMIN = VTIME = 0.
*
* Modified by Theodore Ts'o, 9/14/92, to dynamically allocate the
* tty_struct and tty_queue structures. Previously there was an array
* of 256 tty_struct's which was statically allocated, and the
* tty_queue structures were allocated at boot time. Both are now
* dynamically allocated only when the tty is open.
*
* Also restructured routines so that there is more of a separation
* between the high-level tty routines (tty_io.c and tty_ioctl.c) and
* the low-level tty routines (serial.c, pty.c, console.c). This
* makes for cleaner and more compact code. -TYT, 9/17/92
*
* Modified by Fred N. van Kempen, 01/29/93, to add line disciplines
* which can be dynamically activated and de-activated by the line
* discipline handling modules (like SLIP).
*
* NOTE: pay no attention to the line discipline code (yet); its
* interface is still subject to change in this version...
* -- TYT, 1/31/92
*
* Added functionality to the OPOST tty handling. No delays, but all
* other bits should be there.
* -- Nick Holloway <alfie@dcs.warwick.ac.uk>, 27th May 1993.
*
* Rewrote canonical mode and added more termios flags.
* -- julian@uhunix.uhcc.hawaii.edu (J. Cowley), 13Jan94
*
* Reorganized FASYNC support so mouse code can share it.
* -- ctm@ardi.com, 9Sep95
*
* New TIOCLINUX variants added.
* -- mj@k332.feld.cvut.cz, 19-Nov-95
*
* Restrict vt switching via ioctl()
* -- grif@cs.ucr.edu, 5-Dec-95
*
* Move console and virtual terminal code to more appropriate files,
* implement CONFIG_VT and generalize console device interface.
* -- Marko Kohtala <Marko.Kohtala@hut.fi>, March 97
*
* Rewrote tty_init_dev and tty_release_dev to eliminate races.
* -- Bill Hawes <whawes@star.net>, June 97
*
* Added devfs support.
* -- C. Scott Ananian <cananian@alumni.princeton.edu>, 13-Jan-1998
*
* Added support for a Unix98-style ptmx device.
* -- C. Scott Ananian <cananian@alumni.princeton.edu>, 14-Jan-1998
*
* Reduced memory usage for older ARM systems
* -- Russell King <rmk@arm.linux.org.uk>
*
* Move do_SAK() into process context. Less stack use in devfs functions.
* alloc_tty_struct() always uses kmalloc()
* -- Andrew Morton <andrewm@uow.edu.eu> 17Mar01
*/
#include <linux/types.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/fcntl.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/devpts_fs.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/console.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/kd.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/seq_file.h>
#include <linux/serial.h>
#include <linux/ratelimit.h>
#include <linux/uaccess.h>
#include <linux/kbd_kern.h>
#include <linux/vt_kern.h>
#include <linux/selection.h>
#include <linux/kmod.h>
#include <linux/nsproxy.h>
#undef TTY_DEBUG_HANGUP
#define TTY_PARANOIA_CHECK 1
#define CHECK_TTY_COUNT 1
struct ktermios tty_std_termios = { /* for the benefit of tty drivers */
.c_iflag = ICRNL | IXON,
.c_oflag = OPOST | ONLCR,
.c_cflag = B38400 | CS8 | CREAD | HUPCL,
.c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK |
ECHOCTL | ECHOKE | IEXTEN,
.c_cc = INIT_C_CC,
.c_ispeed = 38400,
.c_ospeed = 38400
};
EXPORT_SYMBOL(tty_std_termios);
/* This list gets poked at by procfs and various bits of boot up code. This
could do with some rationalisation such as pulling the tty proc function
into this file */
LIST_HEAD(tty_drivers); /* linked list of tty drivers */
/* Mutex to protect creating and releasing a tty. This is shared with
vt.c for deeply disgusting hack reasons */
DEFINE_MUTEX(tty_mutex);
EXPORT_SYMBOL(tty_mutex);
/* Spinlock to protect the tty->tty_files list */
DEFINE_SPINLOCK(tty_files_lock);
static ssize_t tty_read(struct file *, char __user *, size_t, loff_t *);
static ssize_t tty_write(struct file *, const char __user *, size_t, loff_t *);
ssize_t redirected_tty_write(struct file *, const char __user *,
size_t, loff_t *);
static unsigned int tty_poll(struct file *, poll_table *);
static int tty_open(struct inode *, struct file *);
long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
#ifdef CONFIG_COMPAT
static long tty_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg);
#else
#define tty_compat_ioctl NULL
#endif
static int __tty_fasync(int fd, struct file *filp, int on);
static int tty_fasync(int fd, struct file *filp, int on);
static void release_tty(struct tty_struct *tty, int idx);
/**
* free_tty_struct - free a disused tty
* @tty: tty struct to free
*
* Free the write buffers, tty queue and tty memory itself.
*
* Locking: none. Must be called after tty is definitely unused
*/
void free_tty_struct(struct tty_struct *tty)
{
if (!tty)
return;
put_device(tty->dev);
kfree(tty->write_buf);
tty->magic = 0xDEADDEAD;
kfree(tty);
}
static inline struct tty_struct *file_tty(struct file *file)
{
return ((struct tty_file_private *)file->private_data)->tty;
}
int tty_alloc_file(struct file *file)
{
struct tty_file_private *priv;
priv = kmalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
file->private_data = priv;
return 0;
}
/* Associate a new file with the tty structure */
void tty_add_file(struct tty_struct *tty, struct file *file)
{
struct tty_file_private *priv = file->private_data;
priv->tty = tty;
priv->file = file;
spin_lock(&tty_files_lock);
list_add(&priv->list, &tty->tty_files);
spin_unlock(&tty_files_lock);
}
/**
* tty_free_file - free file->private_data
*
* This shall be used only for fail path handling when tty_add_file was not
* called yet.
*/
void tty_free_file(struct file *file)
{
struct tty_file_private *priv = file->private_data;
file->private_data = NULL;
kfree(priv);
}
/* Delete file from its tty */
static void tty_del_file(struct file *file)
{
struct tty_file_private *priv = file->private_data;
spin_lock(&tty_files_lock);
list_del(&priv->list);
spin_unlock(&tty_files_lock);
tty_free_file(file);
}
#define TTY_NUMBER(tty) ((tty)->index + (tty)->driver->name_base)
/**
* tty_name - return tty naming
* @tty: tty structure
*
* Convert a tty structure into a name. The name reflects the kernel
* naming policy and if udev is in use may not reflect user space
*
* Locking: none
*/
const char *tty_name(const struct tty_struct *tty)
{
if (!tty) /* Hmm. NULL pointer. That's fun. */
return "NULL tty";
return tty->name;
}
EXPORT_SYMBOL(tty_name);
int tty_paranoia_check(struct tty_struct *tty, struct inode *inode,
const char *routine)
{
#ifdef TTY_PARANOIA_CHECK
if (!tty) {
printk(KERN_WARNING
"null TTY for (%d:%d) in %s\n",
imajor(inode), iminor(inode), routine);
return 1;
}
if (tty->magic != TTY_MAGIC) {
printk(KERN_WARNING
"bad magic number for tty struct (%d:%d) in %s\n",
imajor(inode), iminor(inode), routine);
return 1;
}
#endif
return 0;
}
/* Caller must hold tty_lock */
static int check_tty_count(struct tty_struct *tty, const char *routine)
{
#ifdef CHECK_TTY_COUNT
struct list_head *p;
int count = 0;
spin_lock(&tty_files_lock);
list_for_each(p, &tty->tty_files) {
count++;
}
spin_unlock(&tty_files_lock);
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_SLAVE &&
tty->link && tty->link->count)
count++;
if (tty->count != count) {
printk(KERN_WARNING "Warning: dev (%s) tty->count(%d) "
"!= #fd's(%d) in %s\n",
tty->name, tty->count, count, routine);
return count;
}
#endif
return 0;
}
/**
* get_tty_driver - find device of a tty
* @dev_t: device identifier
* @index: returns the index of the tty
*
* This routine returns a tty driver structure, given a device number
* and also passes back the index number.
*
* Locking: caller must hold tty_mutex
*/
static struct tty_driver *get_tty_driver(dev_t device, int *index)
{
struct tty_driver *p;
list_for_each_entry(p, &tty_drivers, tty_drivers) {
dev_t base = MKDEV(p->major, p->minor_start);
if (device < base || device >= base + p->num)
continue;
*index = device - base;
return tty_driver_kref_get(p);
}
return NULL;
}
#ifdef CONFIG_CONSOLE_POLL
/**
* tty_find_polling_driver - find device of a polled tty
* @name: name string to match
* @line: pointer to resulting tty line nr
*
* This routine returns a tty driver structure, given a name
* and the condition that the tty driver is capable of polled
* operation.
*/
struct tty_driver *tty_find_polling_driver(char *name, int *line)
{
struct tty_driver *p, *res = NULL;
int tty_line = 0;
int len;
char *str, *stp;
for (str = name; *str; str++)
if ((*str >= '0' && *str <= '9') || *str == ',')
break;
if (!*str)
return NULL;
len = str - name;
tty_line = simple_strtoul(str, &str, 10);
mutex_lock(&tty_mutex);
/* Search through the tty devices to look for a match */
list_for_each_entry(p, &tty_drivers, tty_drivers) {
if (strncmp(name, p->name, len) != 0)
continue;
stp = str;
if (*stp == ',')
stp++;
if (*stp == '\0')
stp = NULL;
if (tty_line >= 0 && tty_line < p->num && p->ops &&
p->ops->poll_init && !p->ops->poll_init(p, tty_line, stp)) {
res = tty_driver_kref_get(p);
*line = tty_line;
break;
}
}
mutex_unlock(&tty_mutex);
return res;
}
EXPORT_SYMBOL_GPL(tty_find_polling_driver);
#endif
/**
* tty_check_change - check for POSIX terminal changes
* @tty: tty to check
*
* If we try to write to, or set the state of, a terminal and we're
* not in the foreground, send a SIGTTOU. If the signal is blocked or
* ignored, go ahead and perform the operation. (POSIX 7.2)
*
* Locking: ctrl_lock
*/
int tty_check_change(struct tty_struct *tty)
{
unsigned long flags;
int ret = 0;
if (current->signal->tty != tty)
return 0;
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (!tty->pgrp) {
printk(KERN_WARNING "tty_check_change: tty->pgrp == NULL!\n");
goto out_unlock;
}
if (task_pgrp(current) == tty->pgrp)
goto out_unlock;
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
if (is_ignored(SIGTTOU))
goto out;
if (is_current_pgrp_orphaned()) {
ret = -EIO;
goto out;
}
kill_pgrp(task_pgrp(current), SIGTTOU, 1);
set_thread_flag(TIF_SIGPENDING);
ret = -ERESTARTSYS;
out:
return ret;
out_unlock:
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
return ret;
}
EXPORT_SYMBOL(tty_check_change);
static ssize_t hung_up_tty_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return 0;
}
static ssize_t hung_up_tty_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return -EIO;
}
/* No kernel lock held - none needed ;) */
static unsigned int hung_up_tty_poll(struct file *filp, poll_table *wait)
{
return POLLIN | POLLOUT | POLLERR | POLLHUP | POLLRDNORM | POLLWRNORM;
}
static long hung_up_tty_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
}
static long hung_up_tty_compat_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
}
static const struct file_operations tty_fops = {
.llseek = no_llseek,
.read = tty_read,
.write = tty_write,
.poll = tty_poll,
.unlocked_ioctl = tty_ioctl,
.compat_ioctl = tty_compat_ioctl,
.open = tty_open,
.release = tty_release,
.fasync = tty_fasync,
};
static const struct file_operations console_fops = {
.llseek = no_llseek,
.read = tty_read,
.write = redirected_tty_write,
.poll = tty_poll,
.unlocked_ioctl = tty_ioctl,
.compat_ioctl = tty_compat_ioctl,
.open = tty_open,
.release = tty_release,
.fasync = tty_fasync,
};
static const struct file_operations hung_up_tty_fops = {
.llseek = no_llseek,
.read = hung_up_tty_read,
.write = hung_up_tty_write,
.poll = hung_up_tty_poll,
.unlocked_ioctl = hung_up_tty_ioctl,
.compat_ioctl = hung_up_tty_compat_ioctl,
.release = tty_release,
};
static DEFINE_SPINLOCK(redirect_lock);
static struct file *redirect;
void proc_clear_tty(struct task_struct *p)
{
unsigned long flags;
struct tty_struct *tty;
spin_lock_irqsave(&p->sighand->siglock, flags);
tty = p->signal->tty;
p->signal->tty = NULL;
spin_unlock_irqrestore(&p->sighand->siglock, flags);
tty_kref_put(tty);
}
/**
* proc_set_tty - set the controlling terminal
*
* Only callable by the session leader and only if it does not already have
* a controlling terminal.
*
* Caller must hold: tty_lock()
* a readlock on tasklist_lock
* sighand lock
*/
static void __proc_set_tty(struct tty_struct *tty)
{
unsigned long flags;
spin_lock_irqsave(&tty->ctrl_lock, flags);
/*
* The session and fg pgrp references will be non-NULL if
* tiocsctty() is stealing the controlling tty
*/
put_pid(tty->session);
put_pid(tty->pgrp);
tty->pgrp = get_pid(task_pgrp(current));
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
tty->session = get_pid(task_session(current));
if (current->signal->tty) {
printk(KERN_DEBUG "tty not NULL!!\n");
tty_kref_put(current->signal->tty);
}
put_pid(current->signal->tty_old_pgrp);
current->signal->tty = tty_kref_get(tty);
current->signal->tty_old_pgrp = NULL;
}
static void proc_set_tty(struct tty_struct *tty)
{
spin_lock_irq(¤t->sighand->siglock);
__proc_set_tty(tty);
spin_unlock_irq(¤t->sighand->siglock);
}
struct tty_struct *get_current_tty(void)
{
struct tty_struct *tty;
unsigned long flags;
spin_lock_irqsave(¤t->sighand->siglock, flags);
tty = tty_kref_get(current->signal->tty);
spin_unlock_irqrestore(¤t->sighand->siglock, flags);
return tty;
}
EXPORT_SYMBOL_GPL(get_current_tty);
static void session_clear_tty(struct pid *session)
{
struct task_struct *p;
do_each_pid_task(session, PIDTYPE_SID, p) {
proc_clear_tty(p);
} while_each_pid_task(session, PIDTYPE_SID, p);
}
/**
* tty_wakeup - request more data
* @tty: terminal
*
* Internal and external helper for wakeups of tty. This function
* informs the line discipline if present that the driver is ready
* to receive more output data.
*/
void tty_wakeup(struct tty_struct *tty)
{
struct tty_ldisc *ld;
if (test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) {
ld = tty_ldisc_ref(tty);
if (ld) {
if (ld->ops->write_wakeup)
ld->ops->write_wakeup(tty);
tty_ldisc_deref(ld);
}
}
wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
}
EXPORT_SYMBOL_GPL(tty_wakeup);
/**
* tty_signal_session_leader - sends SIGHUP to session leader
* @tty controlling tty
* @exit_session if non-zero, signal all foreground group processes
*
* Send SIGHUP and SIGCONT to the session leader and its process group.
* Optionally, signal all processes in the foreground process group.
*
* Returns the number of processes in the session with this tty
* as their controlling terminal. This value is used to drop
* tty references for those processes.
*/
static int tty_signal_session_leader(struct tty_struct *tty, int exit_session)
{
struct task_struct *p;
int refs = 0;
struct pid *tty_pgrp = NULL;
read_lock(&tasklist_lock);
if (tty->session) {
do_each_pid_task(tty->session, PIDTYPE_SID, p) {
spin_lock_irq(&p->sighand->siglock);
if (p->signal->tty == tty) {
p->signal->tty = NULL;
/* We defer the dereferences outside fo
the tasklist lock */
refs++;
}
if (!p->signal->leader) {
spin_unlock_irq(&p->sighand->siglock);
continue;
}
__group_send_sig_info(SIGHUP, SEND_SIG_PRIV, p);
__group_send_sig_info(SIGCONT, SEND_SIG_PRIV, p);
put_pid(p->signal->tty_old_pgrp); /* A noop */
spin_lock(&tty->ctrl_lock);
tty_pgrp = get_pid(tty->pgrp);
if (tty->pgrp)
p->signal->tty_old_pgrp = get_pid(tty->pgrp);
spin_unlock(&tty->ctrl_lock);
spin_unlock_irq(&p->sighand->siglock);
} while_each_pid_task(tty->session, PIDTYPE_SID, p);
}
read_unlock(&tasklist_lock);
if (tty_pgrp) {
if (exit_session)
kill_pgrp(tty_pgrp, SIGHUP, exit_session);
put_pid(tty_pgrp);
}
return refs;
}
/**
* __tty_hangup - actual handler for hangup events
* @work: tty device
*
* This can be called by a "kworker" kernel thread. That is process
* synchronous but doesn't hold any locks, so we need to make sure we
* have the appropriate locks for what we're doing.
*
* The hangup event clears any pending redirections onto the hung up
* device. It ensures future writes will error and it does the needed
* line discipline hangup and signal delivery. The tty object itself
* remains intact.
*
* Locking:
* BTM
* redirect lock for undoing redirection
* file list lock for manipulating list of ttys
* tty_ldiscs_lock from called functions
* termios_rwsem resetting termios data
* tasklist_lock to walk task list for hangup event
* ->siglock to protect ->signal/->sighand
*/
static void __tty_hangup(struct tty_struct *tty, int exit_session)
{
struct file *cons_filp = NULL;
struct file *filp, *f = NULL;
struct tty_file_private *priv;
int closecount = 0, n;
int refs;
if (!tty)
return;
spin_lock(&redirect_lock);
if (redirect && file_tty(redirect) == tty) {
f = redirect;
redirect = NULL;
}
spin_unlock(&redirect_lock);
tty_lock(tty);
if (test_bit(TTY_HUPPED, &tty->flags)) {
tty_unlock(tty);
return;
}
/* inuse_filps is protected by the single tty lock,
this really needs to change if we want to flush the
workqueue with the lock held */
check_tty_count(tty, "tty_hangup");
spin_lock(&tty_files_lock);
/* This breaks for file handles being sent over AF_UNIX sockets ? */
list_for_each_entry(priv, &tty->tty_files, list) {
filp = priv->file;
if (filp->f_op->write == redirected_tty_write)
cons_filp = filp;
if (filp->f_op->write != tty_write)
continue;
closecount++;
__tty_fasync(-1, filp, 0); /* can't block */
filp->f_op = &hung_up_tty_fops;
}
spin_unlock(&tty_files_lock);
refs = tty_signal_session_leader(tty, exit_session);
/* Account for the p->signal references we killed */
while (refs--)
tty_kref_put(tty);
tty_ldisc_hangup(tty);
spin_lock_irq(&tty->ctrl_lock);
clear_bit(TTY_THROTTLED, &tty->flags);
clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
put_pid(tty->session);
put_pid(tty->pgrp);
tty->session = NULL;
tty->pgrp = NULL;
tty->ctrl_status = 0;
spin_unlock_irq(&tty->ctrl_lock);
/*
* If one of the devices matches a console pointer, we
* cannot just call hangup() because that will cause
* tty->count and state->count to go out of sync.
* So we just call close() the right number of times.
*/
if (cons_filp) {
if (tty->ops->close)
for (n = 0; n < closecount; n++)
tty->ops->close(tty, cons_filp);
} else if (tty->ops->hangup)
tty->ops->hangup(tty);
/*
* We don't want to have driver/ldisc interactions beyond
* the ones we did here. The driver layer expects no
* calls after ->hangup() from the ldisc side. However we
* can't yet guarantee all that.
*/
set_bit(TTY_HUPPED, &tty->flags);
tty_unlock(tty);
if (f)
fput(f);
}
static void do_tty_hangup(struct work_struct *work)
{
struct tty_struct *tty =
container_of(work, struct tty_struct, hangup_work);
__tty_hangup(tty, 0);
}
/**
* tty_hangup - trigger a hangup event
* @tty: tty to hangup
*
* A carrier loss (virtual or otherwise) has occurred on this like
* schedule a hangup sequence to run after this event.
*/
void tty_hangup(struct tty_struct *tty)
{
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "%s hangup...\n", tty_name(tty));
#endif
schedule_work(&tty->hangup_work);
}
EXPORT_SYMBOL(tty_hangup);
/**
* tty_vhangup - process vhangup
* @tty: tty to hangup
*
* The user has asked via system call for the terminal to be hung up.
* We do this synchronously so that when the syscall returns the process
* is complete. That guarantee is necessary for security reasons.
*/
void tty_vhangup(struct tty_struct *tty)
{
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "%s vhangup...\n", tty_name(tty));
#endif
__tty_hangup(tty, 0);
}
EXPORT_SYMBOL(tty_vhangup);
/**
* tty_vhangup_self - process vhangup for own ctty
*
* Perform a vhangup on the current controlling tty
*/
void tty_vhangup_self(void)
{
struct tty_struct *tty;
tty = get_current_tty();
if (tty) {
tty_vhangup(tty);
tty_kref_put(tty);
}
}
/**
* tty_vhangup_session - hangup session leader exit
* @tty: tty to hangup
*
* The session leader is exiting and hanging up its controlling terminal.
* Every process in the foreground process group is signalled SIGHUP.
*
* We do this synchronously so that when the syscall returns the process
* is complete. That guarantee is necessary for security reasons.
*/
static void tty_vhangup_session(struct tty_struct *tty)
{
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "%s vhangup session...\n", tty_name(tty));
#endif
__tty_hangup(tty, 1);
}
/**
* tty_hung_up_p - was tty hung up
* @filp: file pointer of tty
*
* Return true if the tty has been subject to a vhangup or a carrier
* loss
*/
int tty_hung_up_p(struct file *filp)
{
return (filp->f_op == &hung_up_tty_fops);
}
EXPORT_SYMBOL(tty_hung_up_p);
/**
* disassociate_ctty - disconnect controlling tty
* @on_exit: true if exiting so need to "hang up" the session
*
* This function is typically called only by the session leader, when
* it wants to disassociate itself from its controlling tty.
*
* It performs the following functions:
* (1) Sends a SIGHUP and SIGCONT to the foreground process group
* (2) Clears the tty from being controlling the session
* (3) Clears the controlling tty for all processes in the
* session group.
*
* The argument on_exit is set to 1 if called when a process is
* exiting; it is 0 if called by the ioctl TIOCNOTTY.
*
* Locking:
* BTM is taken for hysterical raisins, and held when
* called from no_tty().
* tty_mutex is taken to protect tty
* ->siglock is taken to protect ->signal/->sighand
* tasklist_lock is taken to walk process list for sessions
* ->siglock is taken to protect ->signal/->sighand
*/
void disassociate_ctty(int on_exit)
{
struct tty_struct *tty;
if (!current->signal->leader)
return;
tty = get_current_tty();
if (tty) {
if (on_exit && tty->driver->type != TTY_DRIVER_TYPE_PTY) {
tty_vhangup_session(tty);
} else {
struct pid *tty_pgrp = tty_get_pgrp(tty);
if (tty_pgrp) {
kill_pgrp(tty_pgrp, SIGHUP, on_exit);
if (!on_exit)
kill_pgrp(tty_pgrp, SIGCONT, on_exit);
put_pid(tty_pgrp);
}
}
tty_kref_put(tty);
} else if (on_exit) {
struct pid *old_pgrp;
spin_lock_irq(¤t->sighand->siglock);
old_pgrp = current->signal->tty_old_pgrp;
current->signal->tty_old_pgrp = NULL;
spin_unlock_irq(¤t->sighand->siglock);
if (old_pgrp) {
kill_pgrp(old_pgrp, SIGHUP, on_exit);
kill_pgrp(old_pgrp, SIGCONT, on_exit);
put_pid(old_pgrp);
}
return;
}
spin_lock_irq(¤t->sighand->siglock);
put_pid(current->signal->tty_old_pgrp);
current->signal->tty_old_pgrp = NULL;
tty = tty_kref_get(current->signal->tty);
if (tty) {
unsigned long flags;
spin_lock_irqsave(&tty->ctrl_lock, flags);
put_pid(tty->session);
put_pid(tty->pgrp);
tty->session = NULL;
tty->pgrp = NULL;
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
tty_kref_put(tty);
} else {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "error attempted to write to tty [0x%p]"
" = NULL", tty);
#endif
}
spin_unlock_irq(¤t->sighand->siglock);
/* Now clear signal->tty under the lock */
read_lock(&tasklist_lock);
session_clear_tty(task_session(current));
read_unlock(&tasklist_lock);
}
/**
*
* no_tty - Ensure the current process does not have a controlling tty
*/
void no_tty(void)
{
/* FIXME: Review locking here. The tty_lock never covered any race
between a new association and proc_clear_tty but possible we need
to protect against this anyway */
struct task_struct *tsk = current;
disassociate_ctty(0);
proc_clear_tty(tsk);
}
/**
* stop_tty - propagate flow control
* @tty: tty to stop
*
* Perform flow control to the driver. May be called
* on an already stopped device and will not re-call the driver
* method.
*
* This functionality is used by both the line disciplines for
* halting incoming flow and by the driver. It may therefore be
* called from any context, may be under the tty atomic_write_lock
* but not always.
*
* Locking:
* flow_lock
*/
void __stop_tty(struct tty_struct *tty)
{
if (tty->stopped)
return;
tty->stopped = 1;
if (tty->ops->stop)
tty->ops->stop(tty);
}
void stop_tty(struct tty_struct *tty)
{
unsigned long flags;
spin_lock_irqsave(&tty->flow_lock, flags);
__stop_tty(tty);
spin_unlock_irqrestore(&tty->flow_lock, flags);
}
EXPORT_SYMBOL(stop_tty);
/**
* start_tty - propagate flow control
* @tty: tty to start
*
* Start a tty that has been stopped if at all possible. If this
* tty was previous stopped and is now being started, the driver
* start method is invoked and the line discipline woken.
*
* Locking:
* flow_lock
*/
void __start_tty(struct tty_struct *tty)
{
if (!tty->stopped || tty->flow_stopped)
return;
tty->stopped = 0;
if (tty->ops->start)
tty->ops->start(tty);
tty_wakeup(tty);
}
void start_tty(struct tty_struct *tty)
{
unsigned long flags;
spin_lock_irqsave(&tty->flow_lock, flags);
__start_tty(tty);
spin_unlock_irqrestore(&tty->flow_lock, flags);
}
EXPORT_SYMBOL(start_tty);
static void tty_update_time(struct timespec *time)
{
unsigned long sec = get_seconds();
/*
* We only care if the two values differ in anything other than the
* lower three bits (i.e every 8 seconds). If so, then we can update
* the time of the tty device, otherwise it could be construded as a
* security leak to let userspace know the exact timing of the tty.
*/
if ((sec ^ time->tv_sec) & ~7)
time->tv_sec = sec;
}
/**
* tty_read - read method for tty device files
* @file: pointer to tty file
* @buf: user buffer
* @count: size of user buffer
* @ppos: unused
*
* Perform the read system call function on this terminal device. Checks
* for hung up devices before calling the line discipline method.
*
* Locking:
* Locks the line discipline internally while needed. Multiple
* read calls may be outstanding in parallel.
*/
static ssize_t tty_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
int i;
struct inode *inode = file_inode(file);
struct tty_struct *tty = file_tty(file);
struct tty_ldisc *ld;
if (tty_paranoia_check(tty, inode, "tty_read"))
return -EIO;
if (!tty || (test_bit(TTY_IO_ERROR, &tty->flags)))
return -EIO;
/* We want to wait for the line discipline to sort out in this
situation */
ld = tty_ldisc_ref_wait(tty);
if (ld->ops->read)
i = ld->ops->read(tty, file, buf, count);
else
i = -EIO;
tty_ldisc_deref(ld);
if (i > 0)
tty_update_time(&inode->i_atime);
return i;
}
static void tty_write_unlock(struct tty_struct *tty)
{
mutex_unlock(&tty->atomic_write_lock);
wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
}
static int tty_write_lock(struct tty_struct *tty, int ndelay)
{
if (!mutex_trylock(&tty->atomic_write_lock)) {
if (ndelay)
return -EAGAIN;
if (mutex_lock_interruptible(&tty->atomic_write_lock))
return -ERESTARTSYS;
}
return 0;
}
/*
* Split writes up in sane blocksizes to avoid
* denial-of-service type attacks
*/
static inline ssize_t do_tty_write(
ssize_t (*write)(struct tty_struct *, struct file *, const unsigned char *, size_t),
struct tty_struct *tty,
struct file *file,
const char __user *buf,
size_t count)
{
ssize_t ret, written = 0;
unsigned int chunk;
ret = tty_write_lock(tty, file->f_flags & O_NDELAY);
if (ret < 0)
return ret;
/*
* We chunk up writes into a temporary buffer. This
* simplifies low-level drivers immensely, since they
* don't have locking issues and user mode accesses.
*
* But if TTY_NO_WRITE_SPLIT is set, we should use a
* big chunk-size..
*
* The default chunk-size is 2kB, because the NTTY
* layer has problems with bigger chunks. It will
* claim to be able to handle more characters than
* it actually does.
*
* FIXME: This can probably go away now except that 64K chunks
* are too likely to fail unless switched to vmalloc...
*/
chunk = 2048;
if (test_bit(TTY_NO_WRITE_SPLIT, &tty->flags))
chunk = 65536;
if (count < chunk)
chunk = count;
/* write_buf/write_cnt is protected by the atomic_write_lock mutex */
if (tty->write_cnt < chunk) {
unsigned char *buf_chunk;
if (chunk < 1024)
chunk = 1024;
buf_chunk = kmalloc(chunk, GFP_KERNEL);
if (!buf_chunk) {
ret = -ENOMEM;
goto out;
}
kfree(tty->write_buf);
tty->write_cnt = chunk;
tty->write_buf = buf_chunk;
}
/* Do the write .. */
for (;;) {
size_t size = count;
if (size > chunk)
size = chunk;
ret = -EFAULT;
if (copy_from_user(tty->write_buf, buf, size))
break;
ret = write(tty, file, tty->write_buf, size);
if (ret <= 0)
break;
written += ret;
buf += ret;
count -= ret;
if (!count)
break;
ret = -ERESTARTSYS;
if (signal_pending(current))
break;
cond_resched();
}
if (written) {
tty_update_time(&file_inode(file)->i_mtime);
ret = written;
}
out:
tty_write_unlock(tty);
return ret;
}
/**
* tty_write_message - write a message to a certain tty, not just the console.
* @tty: the destination tty_struct
* @msg: the message to write
*
* This is used for messages that need to be redirected to a specific tty.
* We don't put it into the syslog queue right now maybe in the future if
* really needed.
*
* We must still hold the BTM and test the CLOSING flag for the moment.
*/
void tty_write_message(struct tty_struct *tty, char *msg)
{
if (tty) {
mutex_lock(&tty->atomic_write_lock);
tty_lock(tty);
if (tty->ops->write && tty->count > 0) {
tty_unlock(tty);
tty->ops->write(tty, msg, strlen(msg));
} else
tty_unlock(tty);
tty_write_unlock(tty);
}
return;
}
/**
* tty_write - write method for tty device file
* @file: tty file pointer
* @buf: user data to write
* @count: bytes to write
* @ppos: unused
*
* Write data to a tty device via the line discipline.
*
* Locking:
* Locks the line discipline as required
* Writes to the tty driver are serialized by the atomic_write_lock
* and are then processed in chunks to the device. The line discipline
* write method will not be invoked in parallel for each device.
*/
static ssize_t tty_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct tty_struct *tty = file_tty(file);
struct tty_ldisc *ld;
ssize_t ret;
if (tty_paranoia_check(tty, file_inode(file), "tty_write"))
return -EIO;
if (!tty || !tty->ops->write ||
(test_bit(TTY_IO_ERROR, &tty->flags)))
return -EIO;
/* Short term debug to catch buggy drivers */
if (tty->ops->write_room == NULL)
printk(KERN_ERR "tty driver %s lacks a write_room method.\n",
tty->driver->name);
ld = tty_ldisc_ref_wait(tty);
if (!ld->ops->write)
ret = -EIO;
else
ret = do_tty_write(ld->ops->write, tty, file, buf, count);
tty_ldisc_deref(ld);
return ret;
}
ssize_t redirected_tty_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct file *p = NULL;
spin_lock(&redirect_lock);
if (redirect)
p = get_file(redirect);
spin_unlock(&redirect_lock);
if (p) {
ssize_t res;
res = vfs_write(p, buf, count, &p->f_pos);
fput(p);
return res;
}
return tty_write(file, buf, count, ppos);
}
/**
* tty_send_xchar - send priority character
*
* Send a high priority character to the tty even if stopped
*
* Locking: none for xchar method, write ordering for write method.
*/
int tty_send_xchar(struct tty_struct *tty, char ch)
{
int was_stopped = tty->stopped;
if (tty->ops->send_xchar) {
down_read(&tty->termios_rwsem);
tty->ops->send_xchar(tty, ch);
up_read(&tty->termios_rwsem);
return 0;
}
if (tty_write_lock(tty, 0) < 0)
return -ERESTARTSYS;
down_read(&tty->termios_rwsem);
if (was_stopped)
start_tty(tty);
tty->ops->write(tty, &ch, 1);
if (was_stopped)
stop_tty(tty);
up_read(&tty->termios_rwsem);
tty_write_unlock(tty);
return 0;
}
static char ptychar[] = "pqrstuvwxyzabcde";
/**
* pty_line_name - generate name for a pty
* @driver: the tty driver in use
* @index: the minor number
* @p: output buffer of at least 6 bytes
*
* Generate a name from a driver reference and write it to the output
* buffer.
*
* Locking: None
*/
static void pty_line_name(struct tty_driver *driver, int index, char *p)
{
int i = index + driver->name_base;
/* ->name is initialized to "ttyp", but "tty" is expected */
sprintf(p, "%s%c%x",
driver->subtype == PTY_TYPE_SLAVE ? "tty" : driver->name,
ptychar[i >> 4 & 0xf], i & 0xf);
}
/**
* tty_line_name - generate name for a tty
* @driver: the tty driver in use
* @index: the minor number
* @p: output buffer of at least 7 bytes
*
* Generate a name from a driver reference and write it to the output
* buffer.
*
* Locking: None
*/
static ssize_t tty_line_name(struct tty_driver *driver, int index, char *p)
{
if (driver->flags & TTY_DRIVER_UNNUMBERED_NODE)
return sprintf(p, "%s", driver->name);
else
return sprintf(p, "%s%d", driver->name,
index + driver->name_base);
}
/**
* tty_driver_lookup_tty() - find an existing tty, if any
* @driver: the driver for the tty
* @idx: the minor number
*
* Return the tty, if found. If not found, return NULL or ERR_PTR() if the
* driver lookup() method returns an error.
*
* Locking: tty_mutex must be held. If the tty is found, bump the tty kref.
*/
static struct tty_struct *tty_driver_lookup_tty(struct tty_driver *driver,
struct inode *inode, int idx)
{
struct tty_struct *tty;
if (driver->ops->lookup)
tty = driver->ops->lookup(driver, inode, idx);
else
tty = driver->ttys[idx];
if (!IS_ERR(tty))
tty_kref_get(tty);
return tty;
}
/**
* tty_init_termios - helper for termios setup
* @tty: the tty to set up
*
* Initialise the termios structures for this tty. Thus runs under
* the tty_mutex currently so we can be relaxed about ordering.
*/
int tty_init_termios(struct tty_struct *tty)
{
struct ktermios *tp;
int idx = tty->index;
if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
tty->termios = tty->driver->init_termios;
else {
/* Check for lazy saved data */
tp = tty->driver->termios[idx];
if (tp != NULL)
tty->termios = *tp;
else
tty->termios = tty->driver->init_termios;
}
/* Compatibility until drivers always set this */
tty->termios.c_ispeed = tty_termios_input_baud_rate(&tty->termios);
tty->termios.c_ospeed = tty_termios_baud_rate(&tty->termios);
return 0;
}
EXPORT_SYMBOL_GPL(tty_init_termios);
int tty_standard_install(struct tty_driver *driver, struct tty_struct *tty)
{
int ret = tty_init_termios(tty);
if (ret)
return ret;
tty_driver_kref_get(driver);
tty->count++;
driver->ttys[tty->index] = tty;
return 0;
}
EXPORT_SYMBOL_GPL(tty_standard_install);
/**
* tty_driver_install_tty() - install a tty entry in the driver
* @driver: the driver for the tty
* @tty: the tty
*
* Install a tty object into the driver tables. The tty->index field
* will be set by the time this is called. This method is responsible
* for ensuring any need additional structures are allocated and
* configured.
*
* Locking: tty_mutex for now
*/
static int tty_driver_install_tty(struct tty_driver *driver,
struct tty_struct *tty)
{
return driver->ops->install ? driver->ops->install(driver, tty) :
tty_standard_install(driver, tty);
}
/**
* tty_driver_remove_tty() - remove a tty from the driver tables
* @driver: the driver for the tty
* @idx: the minor number
*
* Remvoe a tty object from the driver tables. The tty->index field
* will be set by the time this is called.
*
* Locking: tty_mutex for now
*/
void tty_driver_remove_tty(struct tty_driver *driver, struct tty_struct *tty)
{
if (driver->ops->remove)
driver->ops->remove(driver, tty);
else
driver->ttys[tty->index] = NULL;
}
/*
* tty_reopen() - fast re-open of an open tty
* @tty - the tty to open
*
* Return 0 on success, -errno on error.
* Re-opens on master ptys are not allowed and return -EIO.
*
* Locking: Caller must hold tty_lock
*/
static int tty_reopen(struct tty_struct *tty)
{
struct tty_driver *driver = tty->driver;
if (!tty->count)
return -EIO;
if (driver->type == TTY_DRIVER_TYPE_PTY &&
driver->subtype == PTY_TYPE_MASTER)
return -EIO;
if (test_bit(TTY_EXCLUSIVE, &tty->flags) && !capable(CAP_SYS_ADMIN))
return -EBUSY;
tty->count++;
WARN_ON(!tty->ldisc);
return 0;
}
/**
* tty_init_dev - initialise a tty device
* @driver: tty driver we are opening a device on
* @idx: device index
* @ret_tty: returned tty structure
*
* Prepare a tty device. This may not be a "new" clean device but
* could also be an active device. The pty drivers require special
* handling because of this.
*
* Locking:
* The function is called under the tty_mutex, which
* protects us from the tty struct or driver itself going away.
*
* On exit the tty device has the line discipline attached and
* a reference count of 1. If a pair was created for pty/tty use
* and the other was a pty master then it too has a reference count of 1.
*
* WSH 06/09/97: Rewritten to remove races and properly clean up after a
* failed open. The new code protects the open with a mutex, so it's
* really quite straightforward. The mutex locking can probably be
* relaxed for the (most common) case of reopening a tty.
*/
struct tty_struct *tty_init_dev(struct tty_driver *driver, int idx)
{
struct tty_struct *tty;
int retval;
/*
* First time open is complex, especially for PTY devices.
* This code guarantees that either everything succeeds and the
* TTY is ready for operation, or else the table slots are vacated
* and the allocated memory released. (Except that the termios
* and locked termios may be retained.)
*/
if (!try_module_get(driver->owner))
return ERR_PTR(-ENODEV);
tty = alloc_tty_struct(driver, idx);
if (!tty) {
retval = -ENOMEM;
goto err_module_put;
}
tty_lock(tty);
retval = tty_driver_install_tty(driver, tty);
if (retval < 0)
goto err_deinit_tty;
if (!tty->port)
tty->port = driver->ports[idx];
WARN_RATELIMIT(!tty->port,
"%s: %s driver does not set tty->port. This will crash the kernel later. Fix the driver!\n",
__func__, tty->driver->name);
tty->port->itty = tty;
/*
* Structures all installed ... call the ldisc open routines.
* If we fail here just call release_tty to clean up. No need
* to decrement the use counts, as release_tty doesn't care.
*/
retval = tty_ldisc_setup(tty, tty->link);
if (retval)
goto err_release_tty;
/* Return the tty locked so that it cannot vanish under the caller */
return tty;
err_deinit_tty:
tty_unlock(tty);
deinitialize_tty_struct(tty);
free_tty_struct(tty);
err_module_put:
module_put(driver->owner);
return ERR_PTR(retval);
/* call the tty release_tty routine to clean out this slot */
err_release_tty:
tty_unlock(tty);
printk_ratelimited(KERN_INFO "tty_init_dev: ldisc open failed, "
"clearing slot %d\n", idx);
release_tty(tty, idx);
return ERR_PTR(retval);
}
void tty_free_termios(struct tty_struct *tty)
{
struct ktermios *tp;
int idx = tty->index;
/* If the port is going to reset then it has no termios to save */
if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
return;
/* Stash the termios data */
tp = tty->driver->termios[idx];
if (tp == NULL) {
tp = kmalloc(sizeof(struct ktermios), GFP_KERNEL);
if (tp == NULL) {
pr_warn("tty: no memory to save termios state.\n");
return;
}
tty->driver->termios[idx] = tp;
}
*tp = tty->termios;
}
EXPORT_SYMBOL(tty_free_termios);
/**
* tty_flush_works - flush all works of a tty/pty pair
* @tty: tty device to flush works for (or either end of a pty pair)
*
* Sync flush all works belonging to @tty (and the 'other' tty).
*/
static void tty_flush_works(struct tty_struct *tty)
{
flush_work(&tty->SAK_work);
flush_work(&tty->hangup_work);
if (tty->link) {
flush_work(&tty->link->SAK_work);
flush_work(&tty->link->hangup_work);
}
}
/**
* release_one_tty - release tty structure memory
* @kref: kref of tty we are obliterating
*
* Releases memory associated with a tty structure, and clears out the
* driver table slots. This function is called when a device is no longer
* in use. It also gets called when setup of a device fails.
*
* Locking:
* takes the file list lock internally when working on the list
* of ttys that the driver keeps.
*
* This method gets called from a work queue so that the driver private
* cleanup ops can sleep (needed for USB at least)
*/
static void release_one_tty(struct work_struct *work)
{
struct tty_struct *tty =
container_of(work, struct tty_struct, hangup_work);
struct tty_driver *driver = tty->driver;
struct module *owner = driver->owner;
if (tty->ops->cleanup)
tty->ops->cleanup(tty);
tty->magic = 0;
tty_driver_kref_put(driver);
module_put(owner);
spin_lock(&tty_files_lock);
list_del_init(&tty->tty_files);
spin_unlock(&tty_files_lock);
put_pid(tty->pgrp);
put_pid(tty->session);
free_tty_struct(tty);
}
static void queue_release_one_tty(struct kref *kref)
{
struct tty_struct *tty = container_of(kref, struct tty_struct, kref);
/* The hangup queue is now free so we can reuse it rather than
waste a chunk of memory for each port */
INIT_WORK(&tty->hangup_work, release_one_tty);
schedule_work(&tty->hangup_work);
}
/**
* tty_kref_put - release a tty kref
* @tty: tty device
*
* Release a reference to a tty device and if need be let the kref
* layer destruct the object for us
*/
void tty_kref_put(struct tty_struct *tty)
{
if (tty)
kref_put(&tty->kref, queue_release_one_tty);
}
EXPORT_SYMBOL(tty_kref_put);
/**
* release_tty - release tty structure memory
*
* Release both @tty and a possible linked partner (think pty pair),
* and decrement the refcount of the backing module.
*
* Locking:
* tty_mutex
* takes the file list lock internally when working on the list
* of ttys that the driver keeps.
*
*/
static void release_tty(struct tty_struct *tty, int idx)
{
/* This should always be true but check for the moment */
WARN_ON(tty->index != idx);
WARN_ON(!mutex_is_locked(&tty_mutex));
if (tty->ops->shutdown)
tty->ops->shutdown(tty);
tty_free_termios(tty);
tty_driver_remove_tty(tty->driver, tty);
tty->port->itty = NULL;
if (tty->link)
tty->link->port->itty = NULL;
cancel_work_sync(&tty->port->buf.work);
tty_kref_put(tty->link);
tty_kref_put(tty);
}
/**
* tty_release_checks - check a tty before real release
* @tty: tty to check
* @o_tty: link of @tty (if any)
* @idx: index of the tty
*
* Performs some paranoid checking before true release of the @tty.
* This is a no-op unless TTY_PARANOIA_CHECK is defined.
*/
static int tty_release_checks(struct tty_struct *tty, int idx)
{
#ifdef TTY_PARANOIA_CHECK
if (idx < 0 || idx >= tty->driver->num) {
printk(KERN_DEBUG "%s: bad idx when trying to free (%s)\n",
__func__, tty->name);
return -1;
}
/* not much to check for devpts */
if (tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)
return 0;
if (tty != tty->driver->ttys[idx]) {
printk(KERN_DEBUG "%s: driver.table[%d] not tty for (%s)\n",
__func__, idx, tty->name);
return -1;
}
if (tty->driver->other) {
struct tty_struct *o_tty = tty->link;
if (o_tty != tty->driver->other->ttys[idx]) {
printk(KERN_DEBUG "%s: other->table[%d] not o_tty for (%s)\n",
__func__, idx, tty->name);
return -1;
}
if (o_tty->link != tty) {
printk(KERN_DEBUG "%s: bad pty pointers\n", __func__);
return -1;
}
}
#endif
return 0;
}
/**
* tty_release - vfs callback for close
* @inode: inode of tty
* @filp: file pointer for handle to tty
*
* Called the last time each file handle is closed that references
* this tty. There may however be several such references.
*
* Locking:
* Takes bkl. See tty_release_dev
*
* Even releasing the tty structures is a tricky business.. We have
* to be very careful that the structures are all released at the
* same time, as interrupts might otherwise get the wrong pointers.
*
* WSH 09/09/97: rewritten to avoid some nasty race conditions that could
* lead to double frees or releasing memory still in use.
*/
int tty_release(struct inode *inode, struct file *filp)
{
struct tty_struct *tty = file_tty(filp);
struct tty_struct *o_tty = NULL;
int do_sleep, final;
int idx;
long timeout = 0;
int once = 1;
if (tty_paranoia_check(tty, inode, __func__))
return 0;
tty_lock(tty);
check_tty_count(tty, __func__);
__tty_fasync(-1, filp, 0);
idx = tty->index;
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
o_tty = tty->link;
if (tty_release_checks(tty, idx)) {
tty_unlock(tty);
return 0;
}
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "%s: %s (tty count=%d)...\n", __func__,
tty_name(tty), tty->count);
#endif
if (tty->ops->close)
tty->ops->close(tty, filp);
/* If tty is pty master, lock the slave pty (stable lock order) */
tty_lock_slave(o_tty);
/*
* Sanity check: if tty->count is going to zero, there shouldn't be
* any waiters on tty->read_wait or tty->write_wait. We test the
* wait queues and kick everyone out _before_ actually starting to
* close. This ensures that we won't block while releasing the tty
* structure.
*
* The test for the o_tty closing is necessary, since the master and
* slave sides may close in any order. If the slave side closes out
* first, its count will be one, since the master side holds an open.
* Thus this test wouldn't be triggered at the time the slave closed,
* so we do it now.
*/
while (1) {
do_sleep = 0;
if (tty->count <= 1) {
if (waitqueue_active(&tty->read_wait)) {
wake_up_poll(&tty->read_wait, POLLIN);
do_sleep++;
}
if (waitqueue_active(&tty->write_wait)) {
wake_up_poll(&tty->write_wait, POLLOUT);
do_sleep++;
}
}
if (o_tty && o_tty->count <= 1) {
if (waitqueue_active(&o_tty->read_wait)) {
wake_up_poll(&o_tty->read_wait, POLLIN);
do_sleep++;
}
if (waitqueue_active(&o_tty->write_wait)) {
wake_up_poll(&o_tty->write_wait, POLLOUT);
do_sleep++;
}
}
if (!do_sleep)
break;
if (once) {
once = 0;
printk(KERN_WARNING "%s: %s: read/write wait queue active!\n",
__func__, tty_name(tty));
}
schedule_timeout_killable(timeout);
if (timeout < 120 * HZ)
timeout = 2 * timeout + 1;
else
timeout = MAX_SCHEDULE_TIMEOUT;
}
if (o_tty) {
if (--o_tty->count < 0) {
printk(KERN_WARNING "%s: bad pty slave count (%d) for %s\n",
__func__, o_tty->count, tty_name(o_tty));
o_tty->count = 0;
}
}
if (--tty->count < 0) {
printk(KERN_WARNING "%s: bad tty->count (%d) for %s\n",
__func__, tty->count, tty_name(tty));
tty->count = 0;
}
/*
* We've decremented tty->count, so we need to remove this file
* descriptor off the tty->tty_files list; this serves two
* purposes:
* - check_tty_count sees the correct number of file descriptors
* associated with this tty.
* - do_tty_hangup no longer sees this file descriptor as
* something that needs to be handled for hangups.
*/
tty_del_file(filp);
/*
* Perform some housekeeping before deciding whether to return.
*
* If _either_ side is closing, make sure there aren't any
* processes that still think tty or o_tty is their controlling
* tty.
*/
if (!tty->count) {
read_lock(&tasklist_lock);
session_clear_tty(tty->session);
if (o_tty)
session_clear_tty(o_tty->session);
read_unlock(&tasklist_lock);
}
/* check whether both sides are closing ... */
final = !tty->count && !(o_tty && o_tty->count);
tty_unlock_slave(o_tty);
tty_unlock(tty);
/* At this point, the tty->count == 0 should ensure a dead tty
cannot be re-opened by a racing opener */
if (!final)
return 0;
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "%s: %s: final close\n", __func__, tty_name(tty));
#endif
/*
* Ask the line discipline code to release its structures
*/
tty_ldisc_release(tty);
/* Wait for pending work before tty destruction commmences */
tty_flush_works(tty);
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "%s: %s: freeing structure...\n", __func__,
tty_name(tty));
#endif
/*
* The release_tty function takes care of the details of clearing
* the slots and preserving the termios structure. The tty_unlock_pair
* should be safe as we keep a kref while the tty is locked (so the
* unlock never unlocks a freed tty).
*/
mutex_lock(&tty_mutex);
release_tty(tty, idx);
mutex_unlock(&tty_mutex);
return 0;
}
/**
* tty_open_current_tty - get locked tty of current task
* @device: device number
* @filp: file pointer to tty
* @return: locked tty of the current task iff @device is /dev/tty
*
* Performs a re-open of the current task's controlling tty.
*
* We cannot return driver and index like for the other nodes because
* devpts will not work then. It expects inodes to be from devpts FS.
*/
static struct tty_struct *tty_open_current_tty(dev_t device, struct file *filp)
{
struct tty_struct *tty;
int retval;
if (device != MKDEV(TTYAUX_MAJOR, 0))
return NULL;
tty = get_current_tty();
if (!tty)
return ERR_PTR(-ENXIO);
filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
/* noctty = 1; */
tty_lock(tty);
tty_kref_put(tty); /* safe to drop the kref now */
retval = tty_reopen(tty);
if (retval < 0) {
tty_unlock(tty);
tty = ERR_PTR(retval);
}
return tty;
}
/**
* tty_lookup_driver - lookup a tty driver for a given device file
* @device: device number
* @filp: file pointer to tty
* @noctty: set if the device should not become a controlling tty
* @index: index for the device in the @return driver
* @return: driver for this inode (with increased refcount)
*
* If @return is not erroneous, the caller is responsible to decrement the
* refcount by tty_driver_kref_put.
*
* Locking: tty_mutex protects get_tty_driver
*/
static struct tty_driver *tty_lookup_driver(dev_t device, struct file *filp,
int *noctty, int *index)
{
struct tty_driver *driver;
switch (device) {
#ifdef CONFIG_VT
case MKDEV(TTY_MAJOR, 0): {
extern struct tty_driver *console_driver;
driver = tty_driver_kref_get(console_driver);
*index = fg_console;
*noctty = 1;
break;
}
#endif
case MKDEV(TTYAUX_MAJOR, 1): {
struct tty_driver *console_driver = console_device(index);
if (console_driver) {
driver = tty_driver_kref_get(console_driver);
if (driver) {
/* Don't let /dev/console block */
filp->f_flags |= O_NONBLOCK;
*noctty = 1;
break;
}
}
return ERR_PTR(-ENODEV);
}
default:
driver = get_tty_driver(device, index);
if (!driver)
return ERR_PTR(-ENODEV);
break;
}
return driver;
}
/**
* tty_open - open a tty device
* @inode: inode of device file
* @filp: file pointer to tty
*
* tty_open and tty_release keep up the tty count that contains the
* number of opens done on a tty. We cannot use the inode-count, as
* different inodes might point to the same tty.
*
* Open-counting is needed for pty masters, as well as for keeping
* track of serial lines: DTR is dropped when the last close happens.
* (This is not done solely through tty->count, now. - Ted 1/27/92)
*
* The termios state of a pty is reset on first open so that
* settings don't persist across reuse.
*
* Locking: tty_mutex protects tty, tty_lookup_driver and tty_init_dev.
* tty->count should protect the rest.
* ->siglock protects ->signal/->sighand
*
* Note: the tty_unlock/lock cases without a ref are only safe due to
* tty_mutex
*/
static int tty_open(struct inode *inode, struct file *filp)
{
struct tty_struct *tty;
int noctty, retval;
struct tty_driver *driver = NULL;
int index;
dev_t device = inode->i_rdev;
unsigned saved_flags = filp->f_flags;
nonseekable_open(inode, filp);
retry_open:
retval = tty_alloc_file(filp);
if (retval)
return -ENOMEM;
noctty = filp->f_flags & O_NOCTTY;
index = -1;
retval = 0;
tty = tty_open_current_tty(device, filp);
if (!tty) {
mutex_lock(&tty_mutex);
driver = tty_lookup_driver(device, filp, &noctty, &index);
if (IS_ERR(driver)) {
retval = PTR_ERR(driver);
goto err_unlock;
}
/* check whether we're reopening an existing tty */
tty = tty_driver_lookup_tty(driver, inode, index);
if (IS_ERR(tty)) {
retval = PTR_ERR(tty);
goto err_unlock;
}
if (tty) {
mutex_unlock(&tty_mutex);
tty_lock(tty);
/* safe to drop the kref from tty_driver_lookup_tty() */
tty_kref_put(tty);
retval = tty_reopen(tty);
if (retval < 0) {
tty_unlock(tty);
tty = ERR_PTR(retval);
}
} else { /* Returns with the tty_lock held for now */
tty = tty_init_dev(driver, index);
mutex_unlock(&tty_mutex);
}
tty_driver_kref_put(driver);
}
if (IS_ERR(tty)) {
retval = PTR_ERR(tty);
goto err_file;
}
tty_add_file(tty, filp);
check_tty_count(tty, __func__);
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
noctty = 1;
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "%s: opening %s...\n", __func__, tty->name);
#endif
if (tty->ops->open)
retval = tty->ops->open(tty, filp);
else
retval = -ENODEV;
filp->f_flags = saved_flags;
if (retval) {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "%s: error %d in opening %s...\n", __func__,
retval, tty->name);
#endif
tty_unlock(tty); /* need to call tty_release without BTM */
tty_release(inode, filp);
if (retval != -ERESTARTSYS)
return retval;
if (signal_pending(current))
return retval;
schedule();
/*
* Need to reset f_op in case a hangup happened.
*/
if (tty_hung_up_p(filp))
filp->f_op = &tty_fops;
goto retry_open;
}
clear_bit(TTY_HUPPED, &tty->flags);
read_lock(&tasklist_lock);
spin_lock_irq(¤t->sighand->siglock);
if (!noctty &&
current->signal->leader &&
!current->signal->tty &&
tty->session == NULL) {
/*
* Don't let a process that only has write access to the tty
* obtain the privileges associated with having a tty as
* controlling terminal (being able to reopen it with full
* access through /dev/tty, being able to perform pushback).
* Many distributions set the group of all ttys to "tty" and
* grant write-only access to all terminals for setgid tty
* binaries, which should not imply full privileges on all ttys.
*
* This could theoretically break old code that performs open()
* on a write-only file descriptor. In that case, it might be
* necessary to also permit this if
* inode_permission(inode, MAY_READ) == 0.
*/
if (filp->f_mode & FMODE_READ)
__proc_set_tty(tty);
}
spin_unlock_irq(¤t->sighand->siglock);
read_unlock(&tasklist_lock);
tty_unlock(tty);
return 0;
err_unlock:
mutex_unlock(&tty_mutex);
/* after locks to avoid deadlock */
if (!IS_ERR_OR_NULL(driver))
tty_driver_kref_put(driver);
err_file:
tty_free_file(filp);
return retval;
}
/**
* tty_poll - check tty status
* @filp: file being polled
* @wait: poll wait structures to update
*
* Call the line discipline polling method to obtain the poll
* status of the device.
*
* Locking: locks called line discipline but ldisc poll method
* may be re-entered freely by other callers.
*/
static unsigned int tty_poll(struct file *filp, poll_table *wait)
{
struct tty_struct *tty = file_tty(filp);
struct tty_ldisc *ld;
int ret = 0;
if (tty_paranoia_check(tty, file_inode(filp), "tty_poll"))
return 0;
ld = tty_ldisc_ref_wait(tty);
if (ld->ops->poll)
ret = ld->ops->poll(tty, filp, wait);
tty_ldisc_deref(ld);
return ret;
}
static int __tty_fasync(int fd, struct file *filp, int on)
{
struct tty_struct *tty = file_tty(filp);
struct tty_ldisc *ldisc;
unsigned long flags;
int retval = 0;
if (tty_paranoia_check(tty, file_inode(filp), "tty_fasync"))
goto out;
retval = fasync_helper(fd, filp, on, &tty->fasync);
if (retval <= 0)
goto out;
ldisc = tty_ldisc_ref(tty);
if (ldisc) {
if (ldisc->ops->fasync)
ldisc->ops->fasync(tty, on);
tty_ldisc_deref(ldisc);
}
if (on) {
enum pid_type type;
struct pid *pid;
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (tty->pgrp) {
pid = tty->pgrp;
type = PIDTYPE_PGID;
} else {
pid = task_pid(current);
type = PIDTYPE_PID;
}
get_pid(pid);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
__f_setown(filp, pid, type, 0);
put_pid(pid);
retval = 0;
}
out:
return retval;
}
static int tty_fasync(int fd, struct file *filp, int on)
{
struct tty_struct *tty = file_tty(filp);
int retval;
tty_lock(tty);
retval = __tty_fasync(fd, filp, on);
tty_unlock(tty);
return retval;
}
/**
* tiocsti - fake input character
* @tty: tty to fake input into
* @p: pointer to character
*
* Fake input to a tty device. Does the necessary locking and
* input management.
*
* FIXME: does not honour flow control ??
*
* Locking:
* Called functions take tty_ldiscs_lock
* current->signal->tty check is safe without locks
*
* FIXME: may race normal receive processing
*/
static int tiocsti(struct tty_struct *tty, char __user *p)
{
char ch, mbz = 0;
struct tty_ldisc *ld;
if ((current->signal->tty != tty) && !capable(CAP_SYS_ADMIN))
return -EPERM;
if (get_user(ch, p))
return -EFAULT;
tty_audit_tiocsti(tty, ch);
ld = tty_ldisc_ref_wait(tty);
ld->ops->receive_buf(tty, &ch, &mbz, 1);
tty_ldisc_deref(ld);
return 0;
}
/**
* tiocgwinsz - implement window query ioctl
* @tty; tty
* @arg: user buffer for result
*
* Copies the kernel idea of the window size into the user buffer.
*
* Locking: tty->winsize_mutex is taken to ensure the winsize data
* is consistent.
*/
static int tiocgwinsz(struct tty_struct *tty, struct winsize __user *arg)
{
int err;
mutex_lock(&tty->winsize_mutex);
err = copy_to_user(arg, &tty->winsize, sizeof(*arg));
mutex_unlock(&tty->winsize_mutex);
return err ? -EFAULT: 0;
}
/**
* tty_do_resize - resize event
* @tty: tty being resized
* @rows: rows (character)
* @cols: cols (character)
*
* Update the termios variables and send the necessary signals to
* peform a terminal resize correctly
*/
int tty_do_resize(struct tty_struct *tty, struct winsize *ws)
{
struct pid *pgrp;
/* Lock the tty */
mutex_lock(&tty->winsize_mutex);
if (!memcmp(ws, &tty->winsize, sizeof(*ws)))
goto done;
/* Signal the foreground process group */
pgrp = tty_get_pgrp(tty);
if (pgrp)
kill_pgrp(pgrp, SIGWINCH, 1);
put_pid(pgrp);
tty->winsize = *ws;
done:
mutex_unlock(&tty->winsize_mutex);
return 0;
}
EXPORT_SYMBOL(tty_do_resize);
/**
* tiocswinsz - implement window size set ioctl
* @tty; tty side of tty
* @arg: user buffer for result
*
* Copies the user idea of the window size to the kernel. Traditionally
* this is just advisory information but for the Linux console it
* actually has driver level meaning and triggers a VC resize.
*
* Locking:
* Driver dependent. The default do_resize method takes the
* tty termios mutex and ctrl_lock. The console takes its own lock
* then calls into the default method.
*/
static int tiocswinsz(struct tty_struct *tty, struct winsize __user *arg)
{
struct winsize tmp_ws;
if (copy_from_user(&tmp_ws, arg, sizeof(*arg)))
return -EFAULT;
if (tty->ops->resize)
return tty->ops->resize(tty, &tmp_ws);
else
return tty_do_resize(tty, &tmp_ws);
}
/**
* tioccons - allow admin to move logical console
* @file: the file to become console
*
* Allow the administrator to move the redirected console device
*
* Locking: uses redirect_lock to guard the redirect information
*/
static int tioccons(struct file *file)
{
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (file->f_op->write == redirected_tty_write) {
struct file *f;
spin_lock(&redirect_lock);
f = redirect;
redirect = NULL;
spin_unlock(&redirect_lock);
if (f)
fput(f);
return 0;
}
spin_lock(&redirect_lock);
if (redirect) {
spin_unlock(&redirect_lock);
return -EBUSY;
}
redirect = get_file(file);
spin_unlock(&redirect_lock);
return 0;
}
/**
* fionbio - non blocking ioctl
* @file: file to set blocking value
* @p: user parameter
*
* Historical tty interfaces had a blocking control ioctl before
* the generic functionality existed. This piece of history is preserved
* in the expected tty API of posix OS's.
*
* Locking: none, the open file handle ensures it won't go away.
*/
static int fionbio(struct file *file, int __user *p)
{
int nonblock;
if (get_user(nonblock, p))
return -EFAULT;
spin_lock(&file->f_lock);
if (nonblock)
file->f_flags |= O_NONBLOCK;
else
file->f_flags &= ~O_NONBLOCK;
spin_unlock(&file->f_lock);
return 0;
}
/**
* tiocsctty - set controlling tty
* @tty: tty structure
* @arg: user argument
*
* This ioctl is used to manage job control. It permits a session
* leader to set this tty as the controlling tty for the session.
*
* Locking:
* Takes tty_lock() to serialize proc_set_tty() for this tty
* Takes tasklist_lock internally to walk sessions
* Takes ->siglock() when updating signal->tty
*/
static int tiocsctty(struct tty_struct *tty, struct file *file, int arg)
{
int ret = 0;
tty_lock(tty);
read_lock(&tasklist_lock);
if (current->signal->leader && (task_session(current) == tty->session))
goto unlock;
/*
* The process must be a session leader and
* not have a controlling tty already.
*/
if (!current->signal->leader || current->signal->tty) {
ret = -EPERM;
goto unlock;
}
if (tty->session) {
/*
* This tty is already the controlling
* tty for another session group!
*/
if (arg == 1 && capable(CAP_SYS_ADMIN)) {
/*
* Steal it away
*/
session_clear_tty(tty->session);
} else {
ret = -EPERM;
goto unlock;
}
}
/* See the comment in tty_open(). */
if ((file->f_mode & FMODE_READ) == 0 && !capable(CAP_SYS_ADMIN)) {
ret = -EPERM;
goto unlock;
}
proc_set_tty(tty);
unlock:
read_unlock(&tasklist_lock);
tty_unlock(tty);
return ret;
}
/**
* tty_get_pgrp - return a ref counted pgrp pid
* @tty: tty to read
*
* Returns a refcounted instance of the pid struct for the process
* group controlling the tty.
*/
struct pid *tty_get_pgrp(struct tty_struct *tty)
{
unsigned long flags;
struct pid *pgrp;
spin_lock_irqsave(&tty->ctrl_lock, flags);
pgrp = get_pid(tty->pgrp);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
return pgrp;
}
EXPORT_SYMBOL_GPL(tty_get_pgrp);
/*
* This checks not only the pgrp, but falls back on the pid if no
* satisfactory pgrp is found. I dunno - gdb doesn't work correctly
* without this...
*
* The caller must hold rcu lock or the tasklist lock.
*/
static struct pid *session_of_pgrp(struct pid *pgrp)
{
struct task_struct *p;
struct pid *sid = NULL;
p = pid_task(pgrp, PIDTYPE_PGID);
if (p == NULL)
p = pid_task(pgrp, PIDTYPE_PID);
if (p != NULL)
sid = task_session(p);
return sid;
}
/**
* tiocgpgrp - get process group
* @tty: tty passed by user
* @real_tty: tty side of the tty passed by the user if a pty else the tty
* @p: returned pid
*
* Obtain the process group of the tty. If there is no process group
* return an error.
*
* Locking: none. Reference to current->signal->tty is safe.
*/
static int tiocgpgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
{
struct pid *pid;
int ret;
/*
* (tty == real_tty) is a cheap way of
* testing if the tty is NOT a master pty.
*/
if (tty == real_tty && current->signal->tty != real_tty)
return -ENOTTY;
pid = tty_get_pgrp(real_tty);
ret = put_user(pid_vnr(pid), p);
put_pid(pid);
return ret;
}
/**
* tiocspgrp - attempt to set process group
* @tty: tty passed by user
* @real_tty: tty side device matching tty passed by user
* @p: pid pointer
*
* Set the process group of the tty to the session passed. Only
* permitted where the tty session is our session.
*
* Locking: RCU, ctrl lock
*/
static int tiocspgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
{
struct pid *pgrp;
pid_t pgrp_nr;
int retval = tty_check_change(real_tty);
unsigned long flags;
if (retval == -EIO)
return -ENOTTY;
if (retval)
return retval;
if (!current->signal->tty ||
(current->signal->tty != real_tty) ||
(real_tty->session != task_session(current)))
return -ENOTTY;
if (get_user(pgrp_nr, p))
return -EFAULT;
if (pgrp_nr < 0)
return -EINVAL;
rcu_read_lock();
pgrp = find_vpid(pgrp_nr);
retval = -ESRCH;
if (!pgrp)
goto out_unlock;
retval = -EPERM;
if (session_of_pgrp(pgrp) != task_session(current))
goto out_unlock;
retval = 0;
spin_lock_irqsave(&tty->ctrl_lock, flags);
put_pid(real_tty->pgrp);
real_tty->pgrp = get_pid(pgrp);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
out_unlock:
rcu_read_unlock();
return retval;
}
/**
* tiocgsid - get session id
* @tty: tty passed by user
* @real_tty: tty side of the tty passed by the user if a pty else the tty
* @p: pointer to returned session id
*
* Obtain the session id of the tty. If there is no session
* return an error.
*
* Locking: none. Reference to current->signal->tty is safe.
*/
static int tiocgsid(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
{
/*
* (tty == real_tty) is a cheap way of
* testing if the tty is NOT a master pty.
*/
if (tty == real_tty && current->signal->tty != real_tty)
return -ENOTTY;
if (!real_tty->session)
return -ENOTTY;
return put_user(pid_vnr(real_tty->session), p);
}
/**
* tiocsetd - set line discipline
* @tty: tty device
* @p: pointer to user data
*
* Set the line discipline according to user request.
*
* Locking: see tty_set_ldisc, this function is just a helper
*/
static int tiocsetd(struct tty_struct *tty, int __user *p)
{
int ldisc;
int ret;
if (get_user(ldisc, p))
return -EFAULT;
ret = tty_set_ldisc(tty, ldisc);
return ret;
}
/**
* send_break - performed time break
* @tty: device to break on
* @duration: timeout in mS
*
* Perform a timed break on hardware that lacks its own driver level
* timed break functionality.
*
* Locking:
* atomic_write_lock serializes
*
*/
static int send_break(struct tty_struct *tty, unsigned int duration)
{
int retval;
if (tty->ops->break_ctl == NULL)
return 0;
if (tty->driver->flags & TTY_DRIVER_HARDWARE_BREAK)
retval = tty->ops->break_ctl(tty, duration);
else {
/* Do the work ourselves */
if (tty_write_lock(tty, 0) < 0)
return -EINTR;
retval = tty->ops->break_ctl(tty, -1);
if (retval)
goto out;
if (!signal_pending(current))
msleep_interruptible(duration);
retval = tty->ops->break_ctl(tty, 0);
out:
tty_write_unlock(tty);
if (signal_pending(current))
retval = -EINTR;
}
return retval;
}
/**
* tty_tiocmget - get modem status
* @tty: tty device
* @file: user file pointer
* @p: pointer to result
*
* Obtain the modem status bits from the tty driver if the feature
* is supported. Return -EINVAL if it is not available.
*
* Locking: none (up to the driver)
*/
static int tty_tiocmget(struct tty_struct *tty, int __user *p)
{
int retval = -EINVAL;
if (tty->ops->tiocmget) {
retval = tty->ops->tiocmget(tty);
if (retval >= 0)
retval = put_user(retval, p);
}
return retval;
}
/**
* tty_tiocmset - set modem status
* @tty: tty device
* @cmd: command - clear bits, set bits or set all
* @p: pointer to desired bits
*
* Set the modem status bits from the tty driver if the feature
* is supported. Return -EINVAL if it is not available.
*
* Locking: none (up to the driver)
*/
static int tty_tiocmset(struct tty_struct *tty, unsigned int cmd,
unsigned __user *p)
{
int retval;
unsigned int set, clear, val;
if (tty->ops->tiocmset == NULL)
return -EINVAL;
retval = get_user(val, p);
if (retval)
return retval;
set = clear = 0;
switch (cmd) {
case TIOCMBIS:
set = val;
break;
case TIOCMBIC:
clear = val;
break;
case TIOCMSET:
set = val;
clear = ~val;
break;
}
set &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
clear &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
return tty->ops->tiocmset(tty, set, clear);
}
static int tty_tiocgicount(struct tty_struct *tty, void __user *arg)
{
int retval = -EINVAL;
struct serial_icounter_struct icount;
memset(&icount, 0, sizeof(icount));
if (tty->ops->get_icount)
retval = tty->ops->get_icount(tty, &icount);
if (retval != 0)
return retval;
if (copy_to_user(arg, &icount, sizeof(icount)))
return -EFAULT;
return 0;
}
static void tty_warn_deprecated_flags(struct serial_struct __user *ss)
{
static DEFINE_RATELIMIT_STATE(depr_flags,
DEFAULT_RATELIMIT_INTERVAL,
DEFAULT_RATELIMIT_BURST);
char comm[TASK_COMM_LEN];
int flags;
if (get_user(flags, &ss->flags))
return;
flags &= ASYNC_DEPRECATED;
if (flags && __ratelimit(&depr_flags))
pr_warning("%s: '%s' is using deprecated serial flags (with no effect): %.8x\n",
__func__, get_task_comm(comm, current), flags);
}
/*
* if pty, return the slave side (real_tty)
* otherwise, return self
*/
static struct tty_struct *tty_pair_get_tty(struct tty_struct *tty)
{
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
tty = tty->link;
return tty;
}
/*
* Split this up, as gcc can choke on it otherwise..
*/
long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct tty_struct *tty = file_tty(file);
struct tty_struct *real_tty;
void __user *p = (void __user *)arg;
int retval;
struct tty_ldisc *ld;
if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
return -EINVAL;
real_tty = tty_pair_get_tty(tty);
/*
* Factor out some common prep work
*/
switch (cmd) {
case TIOCSETD:
case TIOCSBRK:
case TIOCCBRK:
case TCSBRK:
case TCSBRKP:
retval = tty_check_change(tty);
if (retval)
return retval;
if (cmd != TIOCCBRK) {
tty_wait_until_sent(tty, 0);
if (signal_pending(current))
return -EINTR;
}
break;
}
/*
* Now do the stuff.
*/
switch (cmd) {
case TIOCSTI:
return tiocsti(tty, p);
case TIOCGWINSZ:
return tiocgwinsz(real_tty, p);
case TIOCSWINSZ:
return tiocswinsz(real_tty, p);
case TIOCCONS:
return real_tty != tty ? -EINVAL : tioccons(file);
case FIONBIO:
return fionbio(file, p);
case TIOCEXCL:
set_bit(TTY_EXCLUSIVE, &tty->flags);
return 0;
case TIOCNXCL:
clear_bit(TTY_EXCLUSIVE, &tty->flags);
return 0;
case TIOCGEXCL:
{
int excl = test_bit(TTY_EXCLUSIVE, &tty->flags);
return put_user(excl, (int __user *)p);
}
case TIOCNOTTY:
if (current->signal->tty != tty)
return -ENOTTY;
no_tty();
return 0;
case TIOCSCTTY:
return tiocsctty(tty, file, arg);
case TIOCGPGRP:
return tiocgpgrp(tty, real_tty, p);
case TIOCSPGRP:
return tiocspgrp(tty, real_tty, p);
case TIOCGSID:
return tiocgsid(tty, real_tty, p);
case TIOCGETD:
return put_user(tty->ldisc->ops->num, (int __user *)p);
case TIOCSETD:
return tiocsetd(tty, p);
case TIOCVHANGUP:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
tty_vhangup(tty);
return 0;
case TIOCGDEV:
{
unsigned int ret = new_encode_dev(tty_devnum(real_tty));
return put_user(ret, (unsigned int __user *)p);
}
/*
* Break handling
*/
case TIOCSBRK: /* Turn break on, unconditionally */
if (tty->ops->break_ctl)
return tty->ops->break_ctl(tty, -1);
return 0;
case TIOCCBRK: /* Turn break off, unconditionally */
if (tty->ops->break_ctl)
return tty->ops->break_ctl(tty, 0);
return 0;
case TCSBRK: /* SVID version: non-zero arg --> no break */
/* non-zero arg means wait for all output data
* to be sent (performed above) but don't send break.
* This is used by the tcdrain() termios function.
*/
if (!arg)
return send_break(tty, 250);
return 0;
case TCSBRKP: /* support for POSIX tcsendbreak() */
return send_break(tty, arg ? arg*100 : 250);
case TIOCMGET:
return tty_tiocmget(tty, p);
case TIOCMSET:
case TIOCMBIC:
case TIOCMBIS:
return tty_tiocmset(tty, cmd, p);
case TIOCGICOUNT:
retval = tty_tiocgicount(tty, p);
/* For the moment allow fall through to the old method */
if (retval != -EINVAL)
return retval;
break;
case TCFLSH:
switch (arg) {
case TCIFLUSH:
case TCIOFLUSH:
/* flush tty buffer and allow ldisc to process ioctl */
tty_buffer_flush(tty, NULL);
break;
}
break;
case TIOCSSERIAL:
tty_warn_deprecated_flags(p);
break;
}
if (tty->ops->ioctl) {
retval = tty->ops->ioctl(tty, cmd, arg);
if (retval != -ENOIOCTLCMD)
return retval;
}
ld = tty_ldisc_ref_wait(tty);
retval = -EINVAL;
if (ld->ops->ioctl) {
retval = ld->ops->ioctl(tty, file, cmd, arg);
if (retval == -ENOIOCTLCMD)
retval = -ENOTTY;
}
tty_ldisc_deref(ld);
return retval;
}
#ifdef CONFIG_COMPAT
static long tty_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct tty_struct *tty = file_tty(file);
struct tty_ldisc *ld;
int retval = -ENOIOCTLCMD;
if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
return -EINVAL;
if (tty->ops->compat_ioctl) {
retval = tty->ops->compat_ioctl(tty, cmd, arg);
if (retval != -ENOIOCTLCMD)
return retval;
}
ld = tty_ldisc_ref_wait(tty);
if (ld->ops->compat_ioctl)
retval = ld->ops->compat_ioctl(tty, file, cmd, arg);
else
retval = n_tty_compat_ioctl_helper(tty, file, cmd, arg);
tty_ldisc_deref(ld);
return retval;
}
#endif
static int this_tty(const void *t, struct file *file, unsigned fd)
{
if (likely(file->f_op->read != tty_read))
return 0;
return file_tty(file) != t ? 0 : fd + 1;
}
/*
* This implements the "Secure Attention Key" --- the idea is to
* prevent trojan horses by killing all processes associated with this
* tty when the user hits the "Secure Attention Key". Required for
* super-paranoid applications --- see the Orange Book for more details.
*
* This code could be nicer; ideally it should send a HUP, wait a few
* seconds, then send a INT, and then a KILL signal. But you then
* have to coordinate with the init process, since all processes associated
* with the current tty must be dead before the new getty is allowed
* to spawn.
*
* Now, if it would be correct ;-/ The current code has a nasty hole -
* it doesn't catch files in flight. We may send the descriptor to ourselves
* via AF_UNIX socket, close it and later fetch from socket. FIXME.
*
* Nasty bug: do_SAK is being called in interrupt context. This can
* deadlock. We punt it up to process context. AKPM - 16Mar2001
*/
void __do_SAK(struct tty_struct *tty)
{
#ifdef TTY_SOFT_SAK
tty_hangup(tty);
#else
struct task_struct *g, *p;
struct pid *session;
int i;
if (!tty)
return;
session = tty->session;
tty_ldisc_flush(tty);
tty_driver_flush_buffer(tty);
read_lock(&tasklist_lock);
/* Kill the entire session */
do_each_pid_task(session, PIDTYPE_SID, p) {
printk(KERN_NOTICE "SAK: killed process %d"
" (%s): task_session(p)==tty->session\n",
task_pid_nr(p), p->comm);
send_sig(SIGKILL, p, 1);
} while_each_pid_task(session, PIDTYPE_SID, p);
/* Now kill any processes that happen to have the
* tty open.
*/
do_each_thread(g, p) {
if (p->signal->tty == tty) {
printk(KERN_NOTICE "SAK: killed process %d"
" (%s): task_session(p)==tty->session\n",
task_pid_nr(p), p->comm);
send_sig(SIGKILL, p, 1);
continue;
}
task_lock(p);
i = iterate_fd(p->files, 0, this_tty, tty);
if (i != 0) {
printk(KERN_NOTICE "SAK: killed process %d"
" (%s): fd#%d opened to the tty\n",
task_pid_nr(p), p->comm, i - 1);
force_sig(SIGKILL, p);
}
task_unlock(p);
} while_each_thread(g, p);
read_unlock(&tasklist_lock);
#endif
}
static void do_SAK_work(struct work_struct *work)
{
struct tty_struct *tty =
container_of(work, struct tty_struct, SAK_work);
__do_SAK(tty);
}
/*
* The tq handling here is a little racy - tty->SAK_work may already be queued.
* Fortunately we don't need to worry, because if ->SAK_work is already queued,
* the values which we write to it will be identical to the values which it
* already has. --akpm
*/
void do_SAK(struct tty_struct *tty)
{
if (!tty)
return;
schedule_work(&tty->SAK_work);
}
EXPORT_SYMBOL(do_SAK);
static int dev_match_devt(struct device *dev, const void *data)
{
const dev_t *devt = data;
return dev->devt == *devt;
}
/* Must put_device() after it's unused! */
static struct device *tty_get_device(struct tty_struct *tty)
{
dev_t devt = tty_devnum(tty);
return class_find_device(tty_class, NULL, &devt, dev_match_devt);
}
/**
* alloc_tty_struct
*
* This subroutine allocates and initializes a tty structure.
*
* Locking: none - tty in question is not exposed at this point
*/
struct tty_struct *alloc_tty_struct(struct tty_driver *driver, int idx)
{
struct tty_struct *tty;
tty = kzalloc(sizeof(*tty), GFP_KERNEL);
if (!tty)
return NULL;
kref_init(&tty->kref);
tty->magic = TTY_MAGIC;
tty_ldisc_init(tty);
tty->session = NULL;
tty->pgrp = NULL;
mutex_init(&tty->legacy_mutex);
mutex_init(&tty->throttle_mutex);
init_rwsem(&tty->termios_rwsem);
mutex_init(&tty->winsize_mutex);
init_ldsem(&tty->ldisc_sem);
init_waitqueue_head(&tty->write_wait);
init_waitqueue_head(&tty->read_wait);
INIT_WORK(&tty->hangup_work, do_tty_hangup);
mutex_init(&tty->atomic_write_lock);
spin_lock_init(&tty->ctrl_lock);
spin_lock_init(&tty->flow_lock);
INIT_LIST_HEAD(&tty->tty_files);
INIT_WORK(&tty->SAK_work, do_SAK_work);
tty->driver = driver;
tty->ops = driver->ops;
tty->index = idx;
tty_line_name(driver, idx, tty->name);
tty->dev = tty_get_device(tty);
return tty;
}
/**
* deinitialize_tty_struct
* @tty: tty to deinitialize
*
* This subroutine deinitializes a tty structure that has been newly
* allocated but tty_release cannot be called on that yet.
*
* Locking: none - tty in question must not be exposed at this point
*/
void deinitialize_tty_struct(struct tty_struct *tty)
{
tty_ldisc_deinit(tty);
}
/**
* tty_put_char - write one character to a tty
* @tty: tty
* @ch: character
*
* Write one byte to the tty using the provided put_char method
* if present. Returns the number of characters successfully output.
*
* Note: the specific put_char operation in the driver layer may go
* away soon. Don't call it directly, use this method
*/
int tty_put_char(struct tty_struct *tty, unsigned char ch)
{
if (tty->ops->put_char)
return tty->ops->put_char(tty, ch);
return tty->ops->write(tty, &ch, 1);
}
EXPORT_SYMBOL_GPL(tty_put_char);
struct class *tty_class;
static int tty_cdev_add(struct tty_driver *driver, dev_t dev,
unsigned int index, unsigned int count)
{
/* init here, since reused cdevs cause crashes */
cdev_init(&driver->cdevs[index], &tty_fops);
driver->cdevs[index].owner = driver->owner;
return cdev_add(&driver->cdevs[index], dev, count);
}
/**
* tty_register_device - register a tty device
* @driver: the tty driver that describes the tty device
* @index: the index in the tty driver for this tty device
* @device: a struct device that is associated with this tty device.
* This field is optional, if there is no known struct device
* for this tty device it can be set to NULL safely.
*
* Returns a pointer to the struct device for this tty device
* (or ERR_PTR(-EFOO) on error).
*
* This call is required to be made to register an individual tty device
* if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set. If
* that bit is not set, this function should not be called by a tty
* driver.
*
* Locking: ??
*/
struct device *tty_register_device(struct tty_driver *driver, unsigned index,
struct device *device)
{
return tty_register_device_attr(driver, index, device, NULL, NULL);
}
EXPORT_SYMBOL(tty_register_device);
static void tty_device_create_release(struct device *dev)
{
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
kfree(dev);
}
/**
* tty_register_device_attr - register a tty device
* @driver: the tty driver that describes the tty device
* @index: the index in the tty driver for this tty device
* @device: a struct device that is associated with this tty device.
* This field is optional, if there is no known struct device
* for this tty device it can be set to NULL safely.
* @drvdata: Driver data to be set to device.
* @attr_grp: Attribute group to be set on device.
*
* Returns a pointer to the struct device for this tty device
* (or ERR_PTR(-EFOO) on error).
*
* This call is required to be made to register an individual tty device
* if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set. If
* that bit is not set, this function should not be called by a tty
* driver.
*
* Locking: ??
*/
struct device *tty_register_device_attr(struct tty_driver *driver,
unsigned index, struct device *device,
void *drvdata,
const struct attribute_group **attr_grp)
{
char name[64];
dev_t devt = MKDEV(driver->major, driver->minor_start) + index;
struct device *dev = NULL;
int retval = -ENODEV;
bool cdev = false;
if (index >= driver->num) {
printk(KERN_ERR "Attempt to register invalid tty line number "
" (%d).\n", index);
return ERR_PTR(-EINVAL);
}
if (driver->type == TTY_DRIVER_TYPE_PTY)
pty_line_name(driver, index, name);
else
tty_line_name(driver, index, name);
if (!(driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
retval = tty_cdev_add(driver, devt, index, 1);
if (retval)
goto error;
cdev = true;
}
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
retval = -ENOMEM;
goto error;
}
dev->devt = devt;
dev->class = tty_class;
dev->parent = device;
dev->release = tty_device_create_release;
dev_set_name(dev, "%s", name);
dev->groups = attr_grp;
dev_set_drvdata(dev, drvdata);
retval = device_register(dev);
if (retval)
goto error;
return dev;
error:
put_device(dev);
if (cdev)
cdev_del(&driver->cdevs[index]);
return ERR_PTR(retval);
}
EXPORT_SYMBOL_GPL(tty_register_device_attr);
/**
* tty_unregister_device - unregister a tty device
* @driver: the tty driver that describes the tty device
* @index: the index in the tty driver for this tty device
*
* If a tty device is registered with a call to tty_register_device() then
* this function must be called when the tty device is gone.
*
* Locking: ??
*/
void tty_unregister_device(struct tty_driver *driver, unsigned index)
{
device_destroy(tty_class,
MKDEV(driver->major, driver->minor_start) + index);
if (!(driver->flags & TTY_DRIVER_DYNAMIC_ALLOC))
cdev_del(&driver->cdevs[index]);
}
EXPORT_SYMBOL(tty_unregister_device);
/**
* __tty_alloc_driver -- allocate tty driver
* @lines: count of lines this driver can handle at most
* @owner: module which is repsonsible for this driver
* @flags: some of TTY_DRIVER_* flags, will be set in driver->flags
*
* This should not be called directly, some of the provided macros should be
* used instead. Use IS_ERR and friends on @retval.
*/
struct tty_driver *__tty_alloc_driver(unsigned int lines, struct module *owner,
unsigned long flags)
{
struct tty_driver *driver;
unsigned int cdevs = 1;
int err;
if (!lines || (flags & TTY_DRIVER_UNNUMBERED_NODE && lines > 1))
return ERR_PTR(-EINVAL);
driver = kzalloc(sizeof(struct tty_driver), GFP_KERNEL);
if (!driver)
return ERR_PTR(-ENOMEM);
kref_init(&driver->kref);
driver->magic = TTY_DRIVER_MAGIC;
driver->num = lines;
driver->owner = owner;
driver->flags = flags;
if (!(flags & TTY_DRIVER_DEVPTS_MEM)) {
driver->ttys = kcalloc(lines, sizeof(*driver->ttys),
GFP_KERNEL);
driver->termios = kcalloc(lines, sizeof(*driver->termios),
GFP_KERNEL);
if (!driver->ttys || !driver->termios) {
err = -ENOMEM;
goto err_free_all;
}
}
if (!(flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
driver->ports = kcalloc(lines, sizeof(*driver->ports),
GFP_KERNEL);
if (!driver->ports) {
err = -ENOMEM;
goto err_free_all;
}
cdevs = lines;
}
driver->cdevs = kcalloc(cdevs, sizeof(*driver->cdevs), GFP_KERNEL);
if (!driver->cdevs) {
err = -ENOMEM;
goto err_free_all;
}
return driver;
err_free_all:
kfree(driver->ports);
kfree(driver->ttys);
kfree(driver->termios);
kfree(driver);
return ERR_PTR(err);
}
EXPORT_SYMBOL(__tty_alloc_driver);
static void destruct_tty_driver(struct kref *kref)
{
struct tty_driver *driver = container_of(kref, struct tty_driver, kref);
int i;
struct ktermios *tp;
if (driver->flags & TTY_DRIVER_INSTALLED) {
/*
* Free the termios and termios_locked structures because
* we don't want to get memory leaks when modular tty
* drivers are removed from the kernel.
*/
for (i = 0; i < driver->num; i++) {
tp = driver->termios[i];
if (tp) {
driver->termios[i] = NULL;
kfree(tp);
}
if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV))
tty_unregister_device(driver, i);
}
proc_tty_unregister_driver(driver);
if (driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)
cdev_del(&driver->cdevs[0]);
}
kfree(driver->cdevs);
kfree(driver->ports);
kfree(driver->termios);
kfree(driver->ttys);
kfree(driver);
}
void tty_driver_kref_put(struct tty_driver *driver)
{
kref_put(&driver->kref, destruct_tty_driver);
}
EXPORT_SYMBOL(tty_driver_kref_put);
void tty_set_operations(struct tty_driver *driver,
const struct tty_operations *op)
{
driver->ops = op;
};
EXPORT_SYMBOL(tty_set_operations);
void put_tty_driver(struct tty_driver *d)
{
tty_driver_kref_put(d);
}
EXPORT_SYMBOL(put_tty_driver);
/*
* Called by a tty driver to register itself.
*/
int tty_register_driver(struct tty_driver *driver)
{
int error;
int i;
dev_t dev;
struct device *d;
if (!driver->major) {
error = alloc_chrdev_region(&dev, driver->minor_start,
driver->num, driver->name);
if (!error) {
driver->major = MAJOR(dev);
driver->minor_start = MINOR(dev);
}
} else {
dev = MKDEV(driver->major, driver->minor_start);
error = register_chrdev_region(dev, driver->num, driver->name);
}
if (error < 0)
goto err;
if (driver->flags & TTY_DRIVER_DYNAMIC_ALLOC) {
error = tty_cdev_add(driver, dev, 0, driver->num);
if (error)
goto err_unreg_char;
}
mutex_lock(&tty_mutex);
list_add(&driver->tty_drivers, &tty_drivers);
mutex_unlock(&tty_mutex);
if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV)) {
for (i = 0; i < driver->num; i++) {
d = tty_register_device(driver, i, NULL);
if (IS_ERR(d)) {
error = PTR_ERR(d);
goto err_unreg_devs;
}
}
}
proc_tty_register_driver(driver);
driver->flags |= TTY_DRIVER_INSTALLED;
return 0;
err_unreg_devs:
for (i--; i >= 0; i--)
tty_unregister_device(driver, i);
mutex_lock(&tty_mutex);
list_del(&driver->tty_drivers);
mutex_unlock(&tty_mutex);
err_unreg_char:
unregister_chrdev_region(dev, driver->num);
err:
return error;
}
EXPORT_SYMBOL(tty_register_driver);
/*
* Called by a tty driver to unregister itself.
*/
int tty_unregister_driver(struct tty_driver *driver)
{
#if 0
/* FIXME */
if (driver->refcount)
return -EBUSY;
#endif
unregister_chrdev_region(MKDEV(driver->major, driver->minor_start),
driver->num);
mutex_lock(&tty_mutex);
list_del(&driver->tty_drivers);
mutex_unlock(&tty_mutex);
return 0;
}
EXPORT_SYMBOL(tty_unregister_driver);
dev_t tty_devnum(struct tty_struct *tty)
{
return MKDEV(tty->driver->major, tty->driver->minor_start) + tty->index;
}
EXPORT_SYMBOL(tty_devnum);
void tty_default_fops(struct file_operations *fops)
{
*fops = tty_fops;
}
/*
* Initialize the console device. This is called *early*, so
* we can't necessarily depend on lots of kernel help here.
* Just do some early initializations, and do the complex setup
* later.
*/
void __init console_init(void)
{
initcall_t *call;
/* Setup the default TTY line discipline. */
tty_ldisc_begin();
/*
* set up the console device so that later boot sequences can
* inform about problems etc..
*/
call = __con_initcall_start;
while (call < __con_initcall_end) {
(*call)();
call++;
}
}
static char *tty_devnode(struct device *dev, umode_t *mode)
{
if (!mode)
return NULL;
if (dev->devt == MKDEV(TTYAUX_MAJOR, 0) ||
dev->devt == MKDEV(TTYAUX_MAJOR, 2))
*mode = 0666;
return NULL;
}
static int __init tty_class_init(void)
{
tty_class = class_create(THIS_MODULE, "tty");
if (IS_ERR(tty_class))
return PTR_ERR(tty_class);
tty_class->devnode = tty_devnode;
return 0;
}
postcore_initcall(tty_class_init);
/* 3/2004 jmc: why do these devices exist? */
static struct cdev tty_cdev, console_cdev;
static ssize_t show_cons_active(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct console *cs[16];
int i = 0;
struct console *c;
ssize_t count = 0;
console_lock();
for_each_console(c) {
if (!c->device)
continue;
if (!c->write)
continue;
if ((c->flags & CON_ENABLED) == 0)
continue;
cs[i++] = c;
if (i >= ARRAY_SIZE(cs))
break;
}
while (i--) {
int index = cs[i]->index;
struct tty_driver *drv = cs[i]->device(cs[i], &index);
/* don't resolve tty0 as some programs depend on it */
if (drv && (cs[i]->index > 0 || drv->major != TTY_MAJOR))
count += tty_line_name(drv, index, buf + count);
else
count += sprintf(buf + count, "%s%d",
cs[i]->name, cs[i]->index);
count += sprintf(buf + count, "%c", i ? ' ':'\n');
}
console_unlock();
return count;
}
static DEVICE_ATTR(active, S_IRUGO, show_cons_active, NULL);
static struct attribute *cons_dev_attrs[] = {
&dev_attr_active.attr,
NULL
};
ATTRIBUTE_GROUPS(cons_dev);
static struct device *consdev;
void console_sysfs_notify(void)
{
if (consdev)
sysfs_notify(&consdev->kobj, NULL, "active");
}
/*
* Ok, now we can initialize the rest of the tty devices and can count
* on memory allocations, interrupts etc..
*/
int __init tty_init(void)
{
cdev_init(&tty_cdev, &tty_fops);
if (cdev_add(&tty_cdev, MKDEV(TTYAUX_MAJOR, 0), 1) ||
register_chrdev_region(MKDEV(TTYAUX_MAJOR, 0), 1, "/dev/tty") < 0)
panic("Couldn't register /dev/tty driver\n");
device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 0), NULL, "tty");
cdev_init(&console_cdev, &console_fops);
if (cdev_add(&console_cdev, MKDEV(TTYAUX_MAJOR, 1), 1) ||
register_chrdev_region(MKDEV(TTYAUX_MAJOR, 1), 1, "/dev/console") < 0)
panic("Couldn't register /dev/console driver\n");
consdev = device_create_with_groups(tty_class, NULL,
MKDEV(TTYAUX_MAJOR, 1), NULL,
cons_dev_groups, "console");
if (IS_ERR(consdev))
consdev = NULL;
#ifdef CONFIG_VT
vty_init(&console_fops);
#endif
return 0;
}
| gpl-2.0 |
chenhuacai/ltp | testcases/open_posix_testsuite/conformance/interfaces/sigaction/25-4.c | 2 | 2465 | /*
* Copyright (c) 2002-2003, Intel Corporation. All rights reserved.
* Created by: rusty.lynch REMOVE-THIS AT intel DOT com
* This file is licensed under the GPL license. For the full content
* of this license, see the COPYING file at the top level of this
* source tree.
Test case for assertion #25 of the sigaction system call that verifies
that when the sa_sigaction signal-catching function is entered, then
the signal that was caught is added to the signal mask by raising that
signal in the signal handler and verifying that the handler is not
reentered.
Steps:
1. Fork a new process
2. (parent) wait for child
3. (child) Setup a signal handler for SIGCHLD
4. (child) raise SIGCHLD
5. (child, signal handler) increment handler count
6. (child, signal handler) if count is 1 then raise SIGCHLD
7. (child, signal handler) if count is 2 then set error variable
8. (child) if error is set then return -1, else return 0
6. (parent - returning from wait) If child returned 0 then exit 0,
otherwise exit -1.
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include "posixtest.h"
int handler_count = 0;
int handler_error = 0;
void handler(int signo LTP_ATTRIBUTE_UNUSED)
{
static int inside_handler = 0;
printf("SIGCHLD caught\n");
if (inside_handler) {
printf("Signal caught while inside handler\n");
handler_error++;
exit(-1);
}
inside_handler++;
handler_count++;
if (handler_count == 1) {
printf("Raising SIGCHLD\n");
raise(SIGCHLD);
printf("Returning from raising SIGCHLD\n");
}
inside_handler--;
}
int main(void)
{
if (fork() == 0) {
/* child */
struct sigaction act;
act.sa_handler = handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
if (sigaction(SIGCHLD, &act, 0) == -1) {
perror("Unexpected error while attempting to "
"setup test pre-conditions");
return PTS_UNRESOLVED;
}
if (raise(SIGCHLD) == -1) {
perror("Unexpected error while attempting to "
"setup test pre-conditions");
return PTS_UNRESOLVED;
}
if (handler_error)
return PTS_UNRESOLVED;
return PTS_PASS;
} else {
int s;
/* parent */
if (wait(&s) == -1) {
perror("Unexpected error while setting up test "
"pre-conditions");
return PTS_UNRESOLVED;
}
if (!WEXITSTATUS(s)) {
printf("Test PASSED\n");
return PTS_PASS;
}
}
printf("Test FAILED\n");
return PTS_FAIL;
}
| gpl-2.0 |
samkwok3/Beginning-Linux-Programming | Chapter04 The Linux Environment/environ.c | 2 | 1614 | // 1 The first few lines after the declaration of main ensure that the program, environ.c, has been called correctly.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *var, *value;
if(argc == 1 || argc > 3) {
fprintf(stderr,"usage: environ var [value]\n");
exit(1);
}
// 2 That done, we fetch the value of the variable from the environment, using getenv.
var = argv[1];
value = getenv(var);
if(value)
printf("Variable %s has value %s\n", var, value);
else
printf("Variable %s has no value\n", var);
// 3 Next, we check whether the program was called with a second argument. If it was, we set the variable to the value of that argument by constructing a string of the form name=value and then calling putenv.
if(argc == 3) {
char *string;
value = argv[2];
string = malloc(strlen(var)+strlen(value)+2);
if(!string) {
fprintf(stderr,"out of memory\n");
exit(1);
}
strcpy(string,var);
strcat(string,"=");
strcat(string,value);
printf("Calling putenv with: %s\n",string);
if(putenv(string) != 0) {
fprintf(stderr,"putenv failed\n");
free(string);
exit(1);
}
// 4 Finally, we discover the new value of the variable by calling getenv once again.
value = getenv(var);
if(value)
printf("New value of %s is %s\n", var, value);
else
printf("New value of %s is null??\n", var);
}
exit(0);
}
| gpl-2.0 |
sos22/FT | callgrind/threads.c | 2 | 12840 | /*--------------------------------------------------------------------*/
/*--- Callgrind ---*/
/*--- ct_threads.c ---*/
/*--------------------------------------------------------------------*/
/*
This file is part of Callgrind, a Valgrind tool for call tracing.
Copyright (C) 2002-2008, Josef Weidendorfer (Josef.Weidendorfer@gmx.de)
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 GNU General Public License is contained in the file COPYING.
*/
#include "global.h"
#include <pub_tool_threadstate.h>
/* forward decls */
static exec_state* exec_state_save(void);
static exec_state* exec_state_restore(void);
static exec_state* push_exec_state(int);
static exec_state* top_exec_state(void);
static exec_stack current_states;
/*------------------------------------------------------------*/
/*--- Support for multi-threading ---*/
/*------------------------------------------------------------*/
/*
* For Valgrind, MT is cooperative (no preemting in our code),
* so we don't need locks...
*
* Per-thread data:
* - BBCCs
* - call stack
* - call hash
* - event counters: last, current
*
* Even when ignoring MT, we need this functions to set up some
* datastructures for the process (= Thread 1).
*/
/* current running thread */
ThreadId CLG_(current_tid);
static thread_info* thread[VG_N_THREADS];
thread_info** CLG_(get_threads)()
{
return thread;
}
thread_info* CLG_(get_current_thread)()
{
return thread[CLG_(current_tid)];
}
void CLG_(init_threads)()
{
Int i;
for(i=0;i<VG_N_THREADS;i++)
thread[i] = 0;
CLG_(current_tid) = VG_INVALID_THREADID;
}
/* switches through all threads and calls func */
void CLG_(forall_threads)(void (*func)(thread_info*))
{
Int t, orig_tid = CLG_(current_tid);
for(t=1;t<VG_N_THREADS;t++) {
if (!thread[t]) continue;
CLG_(switch_thread)(t);
(*func)(thread[t]);
}
CLG_(switch_thread)(orig_tid);
}
static
thread_info* new_thread(void)
{
thread_info* t;
t = (thread_info*) CLG_MALLOC("cl.threads.nt.1",
sizeof(thread_info));
/* init state */
CLG_(init_exec_stack)( &(t->states) );
CLG_(init_call_stack)( &(t->calls) );
CLG_(init_fn_stack) ( &(t->fns) );
/* t->states.entry[0]->cxt = CLG_(get_cxt)(t->fns.bottom); */
/* event counters */
t->lastdump_cost = CLG_(get_eventset_cost)( CLG_(sets).full );
t->sighandler_cost = CLG_(get_eventset_cost)( CLG_(sets).full );
CLG_(init_cost)( CLG_(sets).full, t->lastdump_cost );
CLG_(init_cost)( CLG_(sets).full, t->sighandler_cost );
/* init data containers */
CLG_(init_fn_array)( &(t->fn_active) );
CLG_(init_bbcc_hash)( &(t->bbccs) );
CLG_(init_jcc_hash)( &(t->jccs) );
return t;
}
void CLG_(switch_thread)(ThreadId tid)
{
if (tid == CLG_(current_tid)) return;
CLG_DEBUG(0, ">> thread %d (was %d)\n", tid, CLG_(current_tid));
if (CLG_(current_tid) != VG_INVALID_THREADID) {
/* save thread state */
thread_info* t = thread[CLG_(current_tid)];
CLG_ASSERT(t != 0);
/* current context (including signal handler contexts) */
exec_state_save();
CLG_(copy_current_exec_stack)( &(t->states) );
CLG_(copy_current_call_stack)( &(t->calls) );
CLG_(copy_current_fn_stack) ( &(t->fns) );
CLG_(copy_current_fn_array) ( &(t->fn_active) );
/* If we cumulate costs of threads, use TID 1 for all jccs/bccs */
if (!CLG_(clo).separate_threads) t = thread[1];
CLG_(copy_current_bbcc_hash)( &(t->bbccs) );
CLG_(copy_current_jcc_hash) ( &(t->jccs) );
}
CLG_(current_tid) = tid;
CLG_ASSERT(tid < VG_N_THREADS);
if (tid != VG_INVALID_THREADID) {
thread_info* t;
/* load thread state */
if (thread[tid] == 0) thread[tid] = new_thread();
t = thread[tid];
/* current context (including signal handler contexts) */
CLG_(set_current_exec_stack)( &(t->states) );
exec_state_restore();
CLG_(set_current_call_stack)( &(t->calls) );
CLG_(set_current_fn_stack) ( &(t->fns) );
CLG_(set_current_fn_array) ( &(t->fn_active) );
/* If we cumulate costs of threads, use TID 1 for all jccs/bccs */
if (!CLG_(clo).separate_threads) t = thread[1];
CLG_(set_current_bbcc_hash) ( &(t->bbccs) );
CLG_(set_current_jcc_hash) ( &(t->jccs) );
}
}
void CLG_(run_thread)(ThreadId tid)
{
/* check for dumps needed */
static ULong bbs_done = 0;
static Char buf[512];
if (CLG_(clo).dump_every_bb >0) {
if (CLG_(stat).bb_executions - bbs_done > CLG_(clo).dump_every_bb) {
VG_(sprintf)(buf, "--dump-every-bb=%llu", CLG_(clo).dump_every_bb);
CLG_(dump_profile)(buf, False);
bbs_done = CLG_(stat).bb_executions;
}
}
CLG_(check_command)();
/* now check for thread switch */
CLG_(switch_thread)(tid);
}
void CLG_(pre_signal)(ThreadId tid, Int sigNum, Bool alt_stack)
{
exec_state *es;
CLG_DEBUG(0, ">> pre_signal(TID %d, sig %d, alt_st %s)\n",
tid, sigNum, alt_stack ? "yes":"no");
/* switch to the thread the handler runs in */
CLG_(run_thread)(tid);
/* save current execution state */
exec_state_save();
/* setup current state for a spontaneous call */
CLG_(init_exec_state)( &CLG_(current_state) );
CLG_(push_cxt)(0);
/* setup new cxtinfo struct for this signal handler */
es = push_exec_state(sigNum);
CLG_(init_cost)( CLG_(sets).full, es->cost);
CLG_(current_state).cost = es->cost;
es->call_stack_bottom = CLG_(current_call_stack).sp;
CLG_(current_state).sig = sigNum;
}
/* Run post-signal if the stackpointer for call stack is at
* the bottom in current exec state (e.g. a signal handler)
*
* Called from CLG_(pop_call_stack)
*/
void CLG_(run_post_signal_on_call_stack_bottom)()
{
exec_state* es = top_exec_state();
CLG_ASSERT(es != 0);
CLG_ASSERT(CLG_(current_state).sig >0);
if (CLG_(current_call_stack).sp == es->call_stack_bottom)
CLG_(post_signal)( CLG_(current_tid), CLG_(current_state).sig );
}
void CLG_(post_signal)(ThreadId tid, Int sigNum)
{
exec_state* es;
UInt fn_number, *pactive;
CLG_DEBUG(0, ">> post_signal(TID %d, sig %d)\n",
tid, sigNum);
CLG_ASSERT(tid == CLG_(current_tid));
CLG_ASSERT(sigNum == CLG_(current_state).sig);
/* Unwind call stack of this signal handler.
* This should only be needed at finalisation time
*/
es = top_exec_state();
CLG_ASSERT(es != 0);
while(CLG_(current_call_stack).sp > es->call_stack_bottom)
CLG_(pop_call_stack)();
if (CLG_(current_state).cxt) {
/* correct active counts */
fn_number = CLG_(current_state).cxt->fn[0]->number;
pactive = CLG_(get_fn_entry)(fn_number);
(*pactive)--;
CLG_DEBUG(0, " set active count of %s back to %d\n",
CLG_(current_state).cxt->fn[0]->name, *pactive);
}
if (CLG_(current_fn_stack).top > CLG_(current_fn_stack).bottom) {
/* set fn_stack_top back.
* top can point to 0 if nothing was executed in the signal handler;
* this is possible at end on unwinding handlers.
*/
if (*(CLG_(current_fn_stack).top) != 0) {
CLG_(current_fn_stack).top--;
CLG_ASSERT(*(CLG_(current_fn_stack).top) == 0);
}
if (CLG_(current_fn_stack).top > CLG_(current_fn_stack).bottom)
CLG_(current_fn_stack).top--;
}
/* sum up costs */
CLG_ASSERT(CLG_(current_state).cost == es->cost);
CLG_(add_and_zero_cost)( CLG_(sets).full,
thread[CLG_(current_tid)]->sighandler_cost,
CLG_(current_state).cost );
/* restore previous context */
es->sig = -1;
current_states.sp--;
es = top_exec_state();
CLG_(current_state).sig = es->sig;
exec_state_restore();
/* There is no way to reliable get the thread ID we are switching to
* after this handler returns. So we sync with actual TID at start of
* CLG_(setup_bb)(), which should be the next for callgrind.
*/
}
/*------------------------------------------------------------*/
/*--- Execution states in a thread & signal handlers ---*/
/*------------------------------------------------------------*/
/* Each thread can be interrupted by a signal handler, and they
* themselves again. But as there's no scheduling among handlers
* of the same thread, we don't need additional stacks.
* So storing execution contexts and
* adding separators in the callstack(needed to not intermix normal/handler
* functions in contexts) should be enough.
*/
/* not initialized: call_stack_bottom, sig */
void CLG_(init_exec_state)(exec_state* es)
{
es->collect = CLG_(clo).collect_atstart;
es->cxt = 0;
es->jmps_passed = 0;
es->bbcc = 0;
es->nonskipped = 0;
}
static exec_state* new_exec_state(Int sigNum)
{
exec_state* es;
es = (exec_state*) CLG_MALLOC("cl.threads.nes.1",
sizeof(exec_state));
/* allocate real cost space: needed as incremented by
* simulation functions */
es->cost = CLG_(get_eventset_cost)(CLG_(sets).full);
CLG_(init_cost)( CLG_(sets).full, es->cost );
CLG_(init_exec_state)(es);
es->sig = sigNum;
es->call_stack_bottom = 0;
return es;
}
void CLG_(init_exec_stack)(exec_stack* es)
{
Int i;
/* The first element is for the main thread */
es->entry[0] = new_exec_state(0);
for(i=1;i<MAX_SIGHANDLERS;i++)
es->entry[i] = 0;
es->sp = 0;
}
void CLG_(copy_current_exec_stack)(exec_stack* dst)
{
Int i;
dst->sp = current_states.sp;
for(i=0;i<MAX_SIGHANDLERS;i++)
dst->entry[i] = current_states.entry[i];
}
void CLG_(set_current_exec_stack)(exec_stack* dst)
{
Int i;
current_states.sp = dst->sp;
for(i=0;i<MAX_SIGHANDLERS;i++)
current_states.entry[i] = dst->entry[i];
}
/* Get top context info struct of current thread */
static
exec_state* top_exec_state(void)
{
Int sp = current_states.sp;
exec_state* es;
CLG_ASSERT((sp >= 0) && (sp < MAX_SIGHANDLERS));
es = current_states.entry[sp];
CLG_ASSERT(es != 0);
return es;
}
/* Allocates a free context info structure for a new entered
* signal handler, putting it on the context stack.
* Returns a pointer to the structure.
*/
static exec_state* push_exec_state(int sigNum)
{
Int sp;
exec_state* es;
current_states.sp++;
sp = current_states.sp;
CLG_ASSERT((sigNum > 0) && (sigNum <= _VKI_NSIG));
CLG_ASSERT((sp > 0) && (sp < MAX_SIGHANDLERS));
es = current_states.entry[sp];
if (!es) {
es = new_exec_state(sigNum);
current_states.entry[sp] = es;
}
else
es->sig = sigNum;
return es;
}
/* Save current context to top cxtinfo struct */
static
exec_state* exec_state_save(void)
{
exec_state* es = top_exec_state();
es->cxt = CLG_(current_state).cxt;
es->collect = CLG_(current_state).collect;
es->jmps_passed = CLG_(current_state).jmps_passed;
es->bbcc = CLG_(current_state).bbcc;
es->nonskipped = CLG_(current_state).nonskipped;
CLG_DEBUGIF(1) {
CLG_DEBUG(1, " cxtinfo_save(sig %d): collect %s, jmps_passed %d\n",
es->sig, es->collect ? "Yes": "No", es->jmps_passed);
CLG_(print_bbcc)(-9, es->bbcc, False);
CLG_(print_cost)(-9, CLG_(sets).full, es->cost);
}
/* signal number does not need to be saved */
CLG_ASSERT(CLG_(current_state).sig == es->sig);
return es;
}
static
exec_state* exec_state_restore(void)
{
exec_state* es = top_exec_state();
CLG_(current_state).cxt = es->cxt;
CLG_(current_state).collect = es->collect;
CLG_(current_state).jmps_passed = es->jmps_passed;
CLG_(current_state).bbcc = es->bbcc;
CLG_(current_state).nonskipped = es->nonskipped;
CLG_(current_state).cost = es->cost;
CLG_(current_state).sig = es->sig;
CLG_DEBUGIF(1) {
CLG_DEBUG(1, " exec_state_restore(sig %d): collect %s, jmps_passed %d\n",
es->sig, es->collect ? "Yes": "No", es->jmps_passed);
CLG_(print_bbcc)(-9, es->bbcc, False);
CLG_(print_cxt)(-9, es->cxt, 0);
CLG_(print_cost)(-9, CLG_(sets).full, es->cost);
}
return es;
}
| gpl-2.0 |
exynosS5/android_kernel_samsung_universal5422-stock | drivers/gpu/arm/midgard_wk04/mali_kbase_mmu.c | 258 | 53004 | /*
*
* (C) COPYRIGHT ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation, and any use by you of this program is subject to the terms
* of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained
* from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
/**
* @file mali_kbase_mmu.c
* Base kernel MMU management.
*/
/* #define DEBUG 1 */
#include <mali_kbase.h>
#include <mali_midg_regmap.h>
#include <mali_kbase_gator.h>
#define beenthere(f, a...) KBASE_DEBUG_PRINT_INFO(KBASE_MMU, "%s:" f, __func__, ##a)
#include <mali_kbase_defs.h>
#include <mali_kbase_hw.h>
#define KBASE_MMU_PAGE_ENTRIES 512
/*
* Definitions:
* - PGD: Page Directory.
* - PTE: Page Table Entry. A 64bit value pointing to the next
* level of translation
* - ATE: Address Transation Entry. A 64bit value pointing to
* a 4kB physical page.
*/
static void kbase_mmu_report_fault_and_kill(kbase_context *kctx, kbase_as *as);
static u64 lock_region(kbase_device *kbdev, u64 pfn, size_t num_pages);
/* Helper Function to perform assignment of page table entries, to ensure the use of
* strd, which is required on LPAE systems.
*/
static inline void page_table_entry_set( kbase_device * kbdev, u64 * pte, u64 phy )
{
#ifdef CONFIG_64BIT
*pte = phy;
#elif defined(CONFIG_ARM)
/*
*
* In order to prevent the compiler keeping cached copies of memory, we have to explicitly
* say that we have updated memory.
*
* Note: We could manually move the data ourselves into R0 and R1 by specifying
* register variables that are explicitly given registers assignments, the down side of
* this is that we have to assume cpu endianess. To avoid this we can use the ldrd to read the
* data from memory into R0 and R1 which will respect the cpu endianess, we then use strd to
* make the 64 bit assignment to the page table entry.
*
*/
asm volatile("ldrd r0, r1, [%[ptemp]]\n\t"
"strd r0, r1, [%[pte]]\n\t"
: "=m" (*pte)
: [ptemp] "r" (&phy), [pte] "r" (pte), "m" (phy)
: "r0", "r1" );
#else
#error "64-bit atomic write must be implemented for your architecture"
#endif
}
static void ksync_kern_vrange_gpu(phys_addr_t paddr, void *vaddr, size_t size)
{
kbase_sync_to_memory(paddr, vaddr, size);
}
static size_t make_multiple(size_t minimum, size_t multiple)
{
size_t remainder = minimum % multiple;
if (remainder == 0)
return minimum;
else
return minimum + multiple - remainder;
}
static void mmu_mask_reenable(kbase_device *kbdev, kbase_context *kctx, kbase_as *as)
{
unsigned long flags;
u32 mask;
spin_lock_irqsave(&kbdev->mmu_mask_change, flags);
mask = kbase_reg_read(kbdev, MMU_REG(MMU_IRQ_MASK), kctx);
mask |= ((1UL << as->number) | (1UL << (MMU_REGS_BUS_ERROR_FLAG(as->number))));
kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_MASK), mask, kctx);
spin_unlock_irqrestore(&kbdev->mmu_mask_change, flags);
}
static void page_fault_worker(struct work_struct *data)
{
u64 fault_pfn;
size_t new_pages;
size_t fault_rel_pfn;
kbase_as *faulting_as;
int as_no;
kbase_context *kctx;
kbase_device *kbdev;
kbase_va_region *region;
mali_error err;
faulting_as = container_of(data, kbase_as, work_pagefault);
fault_pfn = faulting_as->fault_addr >> PAGE_SHIFT;
as_no = faulting_as->number;
kbdev = container_of(faulting_as, kbase_device, as[as_no]);
/* Grab the context that was already refcounted in kbase_mmu_interrupt().
* Therefore, it cannot be scheduled out of this AS until we explicitly release it
*
* NOTE: NULL can be returned here if we're gracefully handling a spurious interrupt */
kctx = kbasep_js_runpool_lookup_ctx_noretain(kbdev, as_no);
if (kctx == NULL) {
/* Only handle this if not already suspended */
if ( !kbase_pm_context_active_handle_suspend(kbdev, KBASE_PM_SUSPEND_HANDLER_DONT_REACTIVATE)) {
/* Address space has no context, terminate the work */
u32 reg;
/* AS transaction begin */
mutex_lock(&faulting_as->transaction_mutex);
reg = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), NULL);
reg = (reg & (~(u32) MMU_TRANSTAB_ADRMODE_MASK)) | ASn_TRANSTAB_ADRMODE_UNMAPPED;
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), reg, NULL);
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_UPDATE, NULL);
mutex_unlock(&faulting_as->transaction_mutex);
/* AS transaction end */
mmu_mask_reenable(kbdev, NULL, faulting_as);
kbase_pm_context_idle(kbdev);
}
return;
}
KBASE_DEBUG_ASSERT(kctx->kbdev == kbdev);
kbase_gpu_vm_lock(kctx);
/* find the region object for this VA */
region = kbase_region_tracker_find_region_enclosing_address(kctx, faulting_as->fault_addr);
if (NULL == region || (GROWABLE_FLAGS_REQUIRED != (region->flags & GROWABLE_FLAGS_MASK))) {
kbase_gpu_vm_unlock(kctx);
/* failed to find the region or mismatch of the flags */
kbase_mmu_report_fault_and_kill(kctx, faulting_as);
goto fault_done;
}
if ((((faulting_as->fault_status & ASn_FAULTSTATUS_ACCESS_TYPE_MASK) == ASn_FAULTSTATUS_ACCESS_TYPE_READ) && !(region->flags & KBASE_REG_GPU_RD)) || (((faulting_as->fault_status & ASn_FAULTSTATUS_ACCESS_TYPE_MASK) == ASn_FAULTSTATUS_ACCESS_TYPE_WRITE) && !(region->flags & KBASE_REG_GPU_WR)) || (((faulting_as->fault_status & ASn_FAULTSTATUS_ACCESS_TYPE_MASK) == ASn_FAULTSTATUS_ACCESS_TYPE_EX) && (region->flags & KBASE_REG_GPU_NX))) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Access permissions don't match: region->flags=0x%lx", region->flags);
kbase_gpu_vm_unlock(kctx);
kbase_mmu_report_fault_and_kill(kctx, faulting_as);
goto fault_done;
}
/* find the size we need to grow it by */
/* we know the result fit in a size_t due to kbase_region_tracker_find_region_enclosing_address
* validating the fault_adress to be within a size_t from the start_pfn */
fault_rel_pfn = fault_pfn - region->start_pfn;
if (fault_rel_pfn < kbase_reg_current_backed_size(region)) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Page fault in allocated region of growable TMEM: Ignoring");
mmu_mask_reenable(kbdev, kctx, faulting_as);
kbase_gpu_vm_unlock(kctx);
goto fault_done;
}
new_pages = make_multiple(fault_rel_pfn - kbase_reg_current_backed_size(region) + 1, region->extent);
if (new_pages + kbase_reg_current_backed_size(region) > region->nr_pages) {
/* cap to max vsize */
new_pages = region->nr_pages - kbase_reg_current_backed_size(region);
}
if (0 == new_pages) {
/* Duplicate of a fault we've already handled, nothing to do */
mmu_mask_reenable(kbdev, kctx, faulting_as);
kbase_gpu_vm_unlock(kctx);
goto fault_done;
}
if (MALI_ERROR_NONE == kbase_alloc_phy_pages_helper(region->alloc, new_pages)) {
/* alloc success */
mali_addr64 lock_addr;
KBASE_DEBUG_ASSERT(kbase_reg_current_backed_size(region) <= region->nr_pages);
/* AS transaction begin */
mutex_lock(&faulting_as->transaction_mutex);
/* Lock the VA region we're about to update */
lock_addr = lock_region(kbdev, faulting_as->fault_addr >> PAGE_SHIFT, new_pages);
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_LOCKADDR_LO), lock_addr & 0xFFFFFFFFUL, kctx);
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_LOCKADDR_HI), lock_addr >> 32, kctx);
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_LOCK, kctx);
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_T76X_3285)) {
kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_CLEAR), (1UL << as_no), NULL);
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_LOCK, kctx);
}
/* set up the new pages */
err = kbase_mmu_insert_pages(kctx, region->start_pfn + kbase_reg_current_backed_size(region) - new_pages, &kbase_get_phy_pages(region)[kbase_reg_current_backed_size(region) - new_pages], new_pages, region->flags);
if (MALI_ERROR_NONE != err) {
/* failed to insert pages, handle as a normal PF */
mutex_unlock(&faulting_as->transaction_mutex);
kbase_free_phy_pages_helper(region->alloc, new_pages);
kbase_gpu_vm_unlock(kctx);
/* The locked VA region will be unlocked and the cache invalidated in here */
kbase_mmu_report_fault_and_kill(kctx, faulting_as);
goto fault_done;
}
#ifdef CONFIG_MALI_GATOR_SUPPORT
kbase_trace_mali_page_fault_insert_pages(as_no, new_pages);
#endif /* CONFIG_MALI_GATOR_SUPPORT */
/* flush L2 and unlock the VA (resumes the MMU) */
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_6367))
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_FLUSH, kctx);
else
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_FLUSH_PT, kctx);
/* wait for the flush to complete */
while (kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_STATUS), kctx) & 1)
;
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_9630)) {
/* Issue an UNLOCK command to ensure that valid page tables are re-read by the GPU after an update.
Note that, the FLUSH command should perform all the actions necessary, however the bus logs show
that if multiple page faults occur within an 8 page region the MMU does not always re-read the
updated page table entries for later faults or is only partially read, it subsequently raises the
page fault IRQ for the same addresses, the unlock ensures that the MMU cache is flushed, so updates
can be re-read. As the region is now unlocked we need to issue 2 UNLOCK commands in order to flush the
MMU/uTLB, see PRLAM-8812.
*/
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_UNLOCK, kctx);
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_UNLOCK, kctx);
}
mutex_unlock(&faulting_as->transaction_mutex);
/* AS transaction end */
/* reenable this in the mask */
mmu_mask_reenable(kbdev, kctx, faulting_as);
kbase_gpu_vm_unlock(kctx);
} else {
/* failed to extend, handle as a normal PF */
kbase_gpu_vm_unlock(kctx);
kbase_mmu_report_fault_and_kill(kctx, faulting_as);
}
fault_done:
/* By this point, the fault was handled in some way, so release the ctx refcount */
kbasep_js_runpool_release_ctx(kbdev, kctx);
}
phys_addr_t kbase_mmu_alloc_pgd(kbase_context *kctx)
{
phys_addr_t pgd;
u64 *page;
int i;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbase_atomic_add_pages(1, &kctx->used_pages);
kbase_atomic_add_pages(1, &kctx->kbdev->memdev.used_pages);
if (MALI_ERROR_NONE != kbase_mem_allocator_alloc(kctx->pgd_allocator, 1, &pgd))
goto sub_pages;
page = kmap(pfn_to_page(PFN_DOWN(pgd)));
if (NULL == page)
goto alloc_free;
kbase_process_page_usage_inc(kctx, 1);
for (i = 0; i < KBASE_MMU_PAGE_ENTRIES; i++)
page_table_entry_set( kctx->kbdev, &page[i], ENTRY_IS_INVAL );
/* Clean the full page */
ksync_kern_vrange_gpu(pgd, page, KBASE_MMU_PAGE_ENTRIES * sizeof(u64));
kunmap(pfn_to_page(PFN_DOWN(pgd)));
return pgd;
alloc_free:
kbase_mem_allocator_free(kctx->pgd_allocator, 1, &pgd, MALI_FALSE);
sub_pages:
kbase_atomic_sub_pages(1, &kctx->used_pages);
kbase_atomic_sub_pages(1, &kctx->kbdev->memdev.used_pages);
return 0;
}
KBASE_EXPORT_TEST_API(kbase_mmu_alloc_pgd)
static phys_addr_t mmu_pte_to_phy_addr(u64 entry)
{
if (!(entry & 1))
return 0;
return entry & ~0xFFF;
}
static u64 mmu_phyaddr_to_pte(phys_addr_t phy)
{
return (phy & ~0xFFF) | ENTRY_IS_PTE;
}
static u64 mmu_phyaddr_to_ate(phys_addr_t phy, u64 flags)
{
return (phy & ~0xFFF) | (flags & ENTRY_FLAGS_MASK) | ENTRY_IS_ATE;
}
/* Given PGD PFN for level N, return PGD PFN for level N+1 */
static phys_addr_t mmu_get_next_pgd(kbase_context *kctx, phys_addr_t pgd, u64 vpfn, int level)
{
u64 *page;
phys_addr_t target_pgd;
KBASE_DEBUG_ASSERT(pgd);
KBASE_DEBUG_ASSERT(NULL != kctx);
lockdep_assert_held(&kctx->reg_lock);
/*
* Architecture spec defines level-0 as being the top-most.
* This is a bit unfortunate here, but we keep the same convention.
*/
vpfn >>= (3 - level) * 9;
vpfn &= 0x1FF;
page = kmap(pfn_to_page(PFN_DOWN(pgd)));
if (NULL == page) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "mmu_get_next_pgd: kmap failure\n");
return 0;
}
target_pgd = mmu_pte_to_phy_addr(page[vpfn]);
if (!target_pgd) {
target_pgd = kbase_mmu_alloc_pgd(kctx);
if (!target_pgd) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "mmu_get_next_pgd: kbase_mmu_alloc_pgd failure\n");
kunmap(pfn_to_page(PFN_DOWN(pgd)));
return 0;
}
page_table_entry_set( kctx->kbdev, &page[vpfn], mmu_phyaddr_to_pte(target_pgd) );
ksync_kern_vrange_gpu(pgd + (vpfn * sizeof(u64)), page + vpfn, sizeof(u64));
/* Rely on the caller to update the address space flags. */
}
kunmap(pfn_to_page(PFN_DOWN(pgd)));
return target_pgd;
}
static phys_addr_t mmu_get_bottom_pgd(kbase_context *kctx, u64 vpfn)
{
phys_addr_t pgd;
int l;
pgd = kctx->pgd;
for (l = MIDGARD_MMU_TOPLEVEL; l < 3; l++) {
pgd = mmu_get_next_pgd(kctx, pgd, vpfn, l);
/* Handle failure condition */
if (!pgd) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "mmu_get_bottom_pgd: mmu_get_next_pgd failure\n");
return 0;
}
}
return pgd;
}
static phys_addr_t mmu_insert_pages_recover_get_next_pgd(kbase_context *kctx, phys_addr_t pgd, u64 vpfn, int level)
{
u64 *page;
phys_addr_t target_pgd;
KBASE_DEBUG_ASSERT(pgd);
KBASE_DEBUG_ASSERT(NULL != kctx);
lockdep_assert_held(&kctx->reg_lock);
/*
* Architecture spec defines level-0 as being the top-most.
* This is a bit unfortunate here, but we keep the same convention.
*/
vpfn >>= (3 - level) * 9;
vpfn &= 0x1FF;
page = kmap_atomic(pfn_to_page(PFN_DOWN(pgd)));
/* kmap_atomic should NEVER fail */
KBASE_DEBUG_ASSERT(NULL != page);
target_pgd = mmu_pte_to_phy_addr(page[vpfn]);
/* As we are recovering from what has already been set up, we should have a target_pgd */
KBASE_DEBUG_ASSERT(0 != target_pgd);
kunmap_atomic(page);
return target_pgd;
}
static phys_addr_t mmu_insert_pages_recover_get_bottom_pgd(kbase_context *kctx, u64 vpfn)
{
phys_addr_t pgd;
int l;
pgd = kctx->pgd;
for (l = MIDGARD_MMU_TOPLEVEL; l < 3; l++) {
pgd = mmu_insert_pages_recover_get_next_pgd(kctx, pgd, vpfn, l);
/* Should never fail */
KBASE_DEBUG_ASSERT(0 != pgd);
}
return pgd;
}
static void mmu_insert_pages_failure_recovery(kbase_context *kctx, u64 vpfn,
size_t nr)
{
phys_addr_t pgd;
u64 *pgd_page;
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(0 != vpfn);
/* 64-bit address range is the max */
KBASE_DEBUG_ASSERT(vpfn <= (UINT64_MAX / PAGE_SIZE));
lockdep_assert_held(&kctx->reg_lock);
while (nr) {
unsigned int i;
unsigned int index = vpfn & 0x1FF;
unsigned int count = KBASE_MMU_PAGE_ENTRIES - index;
if (count > nr)
count = nr;
pgd = mmu_insert_pages_recover_get_bottom_pgd(kctx, vpfn);
KBASE_DEBUG_ASSERT(0 != pgd);
pgd_page = kmap_atomic(pfn_to_page(PFN_DOWN(pgd)));
KBASE_DEBUG_ASSERT(NULL != pgd_page);
/* Invalidate the entries we added */
for (i = 0; i < count; i++)
page_table_entry_set(kctx->kbdev, &pgd_page[index + i],
ENTRY_IS_INVAL);
vpfn += count;
nr -= count;
ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)),
pgd_page + index, count * sizeof(u64));
kunmap_atomic(pgd_page);
}
}
/**
* Map KBASE_REG flags to MMU flags
*/
static u64 kbase_mmu_get_mmu_flags(unsigned long flags)
{
u64 mmu_flags;
/* store mem_attr index as 4:2 (macro called ensures 3 bits already) */
mmu_flags = KBASE_REG_MEMATTR_VALUE(flags) << 2;
/* write perm if requested */
mmu_flags |= (flags & KBASE_REG_GPU_WR) ? ENTRY_WR_BIT : 0;
/* read perm if requested */
mmu_flags |= (flags & KBASE_REG_GPU_RD) ? ENTRY_RD_BIT : 0;
/* nx if requested */
mmu_flags |= (flags & KBASE_REG_GPU_NX) ? ENTRY_NX_BIT : 0;
if (flags & KBASE_REG_SHARE_BOTH) {
/* inner and outer shareable */
mmu_flags |= SHARE_BOTH_BITS;
} else if (flags & KBASE_REG_SHARE_IN) {
/* inner shareable coherency */
mmu_flags |= SHARE_INNER_BITS;
}
return mmu_flags;
}
/*
* Map the single page 'phys' 'nr' of times, starting at GPU PFN 'vpfn'
*/
mali_error kbase_mmu_insert_single_page(kbase_context *kctx, u64 vpfn,
phys_addr_t phys, size_t nr,
unsigned long flags)
{
phys_addr_t pgd;
u64 *pgd_page;
u64 pte_entry;
/* In case the insert_single_page only partially completes we need to be
* able to recover */
mali_bool recover_required = MALI_FALSE;
u64 recover_vpfn = vpfn;
size_t recover_count = 0;
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(0 != vpfn);
/* 64-bit address range is the max */
KBASE_DEBUG_ASSERT(vpfn <= (UINT64_MAX / PAGE_SIZE));
lockdep_assert_held(&kctx->reg_lock);
/* the one entry we'll populate everywhere */
pte_entry = mmu_phyaddr_to_ate(phys, kbase_mmu_get_mmu_flags(flags));
while (nr) {
unsigned int i;
unsigned int index = vpfn & 0x1FF;
unsigned int count = KBASE_MMU_PAGE_ENTRIES - index;
if (count > nr)
count = nr;
/*
* Repeatedly calling mmu_get_bottom_pte() is clearly
* suboptimal. We don't have to re-parse the whole tree
* each time (just cache the l0-l2 sequence).
* On the other hand, it's only a gain when we map more than
* 256 pages at once (on average). Do we really care?
*/
pgd = mmu_get_bottom_pgd(kctx, vpfn);
if (!pgd) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU,
"kbase_mmu_insert_pages: "
"mmu_get_bottom_pgd failure\n");
if (recover_required) {
/* Invalidate the pages we have partially
* completed */
mmu_insert_pages_failure_recovery(kctx,
recover_vpfn,
recover_count);
}
return MALI_ERROR_FUNCTION_FAILED;
}
pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
if (!pgd_page) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU,
"kbase_mmu_insert_pages: "
"kmap failure\n");
if (recover_required) {
/* Invalidate the pages we have partially
* completed */
mmu_insert_pages_failure_recovery(kctx,
recover_vpfn,
recover_count);
}
return MALI_ERROR_OUT_OF_MEMORY;
}
for (i = 0; i < count; i++) {
unsigned int ofs = index + i;
KBASE_DEBUG_ASSERT(0 == (pgd_page[ofs] & 1UL));
page_table_entry_set(kctx->kbdev, &pgd_page[ofs],
pte_entry);
}
vpfn += count;
nr -= count;
ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)),
pgd_page + index, count * sizeof(u64));
kunmap(pfn_to_page(PFN_DOWN(pgd)));
/* We have started modifying the page table.
* If further pages need inserting and fail we need to undo what
* has already taken place */
recover_required = MALI_TRUE;
recover_count += count;
}
return MALI_ERROR_NONE;
}
/*
* Map 'nr' pages pointed to by 'phys' at GPU PFN 'vpfn'
*/
mali_error kbase_mmu_insert_pages(kbase_context *kctx, u64 vpfn,
phys_addr_t *phys, size_t nr,
unsigned long flags)
{
phys_addr_t pgd;
u64 *pgd_page;
u64 mmu_flags = 0;
/* In case the insert_pages only partially completes we need to be able
* to recover */
mali_bool recover_required = MALI_FALSE;
u64 recover_vpfn = vpfn;
size_t recover_count = 0;
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(0 != vpfn);
/* 64-bit address range is the max */
KBASE_DEBUG_ASSERT(vpfn <= (UINT64_MAX / PAGE_SIZE));
lockdep_assert_held(&kctx->reg_lock);
mmu_flags = kbase_mmu_get_mmu_flags(flags);
while (nr) {
unsigned int i;
unsigned int index = vpfn & 0x1FF;
unsigned int count = KBASE_MMU_PAGE_ENTRIES - index;
if (count > nr)
count = nr;
/*
* Repeatedly calling mmu_get_bottom_pte() is clearly
* suboptimal. We don't have to re-parse the whole tree
* each time (just cache the l0-l2 sequence).
* On the other hand, it's only a gain when we map more than
* 256 pages at once (on average). Do we really care?
*/
pgd = mmu_get_bottom_pgd(kctx, vpfn);
if (!pgd) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU,
"kbase_mmu_insert_pages: "
"mmu_get_bottom_pgd failure\n");
if (recover_required) {
/* Invalidate the pages we have partially
* completed */
mmu_insert_pages_failure_recovery(kctx,
recover_vpfn,
recover_count);
}
return MALI_ERROR_FUNCTION_FAILED;
}
pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
if (!pgd_page) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU,
"kbase_mmu_insert_pages: "
"kmap failure\n");
if (recover_required) {
/* Invalidate the pages we have partially
* completed */
mmu_insert_pages_failure_recovery(kctx,
recover_vpfn,
recover_count);
}
return MALI_ERROR_OUT_OF_MEMORY;
}
for (i = 0; i < count; i++) {
unsigned int ofs = index + i;
KBASE_DEBUG_ASSERT(0 == (pgd_page[ofs] & 1UL));
page_table_entry_set(kctx->kbdev, &pgd_page[ofs],
mmu_phyaddr_to_ate(phys[i],
mmu_flags)
);
}
phys += count;
vpfn += count;
nr -= count;
ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)),
pgd_page + index, count * sizeof(u64));
kunmap(pfn_to_page(PFN_DOWN(pgd)));
/* We have started modifying the page table. If further pages
* need inserting and fail we need to undo what has already
* taken place */
recover_required = MALI_TRUE;
recover_count += count;
}
return MALI_ERROR_NONE;
}
KBASE_EXPORT_TEST_API(kbase_mmu_insert_pages)
/**
* This function is responsible for validating the MMU PTs
* triggering reguired flushes.
*
* * IMPORTANT: This uses kbasep_js_runpool_release_ctx() when the context is
* currently scheduled into the runpool, and so potentially uses a lot of locks.
* These locks must be taken in the correct order with respect to others
* already held by the caller. Refer to kbasep_js_runpool_release_ctx() for more
* information.
*/
static void kbase_mmu_flush(kbase_context *kctx, u64 vpfn, size_t nr)
{
kbase_device *kbdev;
mali_bool ctx_is_in_runpool;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
/* We must flush if we're currently running jobs. At the very least, we need to retain the
* context to ensure it doesn't schedule out whilst we're trying to flush it */
ctx_is_in_runpool = kbasep_js_runpool_retain_ctx(kbdev, kctx);
if (ctx_is_in_runpool) {
KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID);
/* Second level check is to try to only do this when jobs are running. The refcount is
* a heuristic for this. */
if (kbdev->js_data.runpool_irq.per_as_data[kctx->as_nr].as_busy_refcount >= 2) {
/* Lock the VA region we're about to update */
u64 lock_addr = lock_region(kbdev, vpfn, nr);
unsigned int max_loops = KBASE_AS_FLUSH_MAX_LOOPS;
/* AS transaction begin */
mutex_lock(&kbdev->as[kctx->as_nr].transaction_mutex);
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_LOCKADDR_LO), lock_addr & 0xFFFFFFFFUL, kctx);
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_LOCKADDR_HI), lock_addr >> 32, kctx);
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_LOCK, kctx);
/* flush L2 and unlock the VA */
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_6367))
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_FLUSH, kctx);
else
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_FLUSH_MEM, kctx);
/* wait for the flush to complete */
while (--max_loops && kbase_reg_read(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_STATUS), kctx) & ASn_STATUS_FLUSH_ACTIVE)
;
if (!max_loops) {
/* Flush failed to complete, assume the GPU has hung and perform a reset to recover */
KBASE_DEBUG_PRINT_ERROR(KBASE_MMU, "Flush for GPU page table update did not complete. Issueing GPU soft-reset to recover\n");
if (kbase_prepare_to_reset_gpu(kbdev))
kbase_reset_gpu(kbdev);
}
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_9630)) {
/* Issue an UNLOCK command to ensure that valid page tables are re-read by the GPU after an update.
Note that, the FLUSH command should perform all the actions necessary, however the bus logs show
that if multiple page faults occur within an 8 page region the MMU does not always re-read the
updated page table entries for later faults or is only partially read, it subsequently raises the
page fault IRQ for the same addresses, the unlock ensures that the MMU cache is flushed, so updates
can be re-read. As the region is now unlocked we need to issue 2 UNLOCK commands in order to flush the
MMU/uTLB, see PRLAM-8812.
*/
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_UNLOCK, kctx);
kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_UNLOCK, kctx);
}
mutex_unlock(&kbdev->as[kctx->as_nr].transaction_mutex);
/* AS transaction end */
}
kbasep_js_runpool_release_ctx(kbdev, kctx);
}
}
/*
* We actually only discard the ATE, and not the page table
* pages. There is a potential DoS here, as we'll leak memory by
* having PTEs that are potentially unused. Will require physical
* page accounting, so MMU pages are part of the process allocation.
*
* IMPORTANT: This uses kbasep_js_runpool_release_ctx() when the context is
* currently scheduled into the runpool, and so potentially uses a lot of locks.
* These locks must be taken in the correct order with respect to others
* already held by the caller. Refer to kbasep_js_runpool_release_ctx() for more
* information.
*/
mali_error kbase_mmu_teardown_pages(kbase_context *kctx, u64 vpfn, size_t nr)
{
phys_addr_t pgd;
u64 *pgd_page;
kbase_device *kbdev;
size_t requested_nr = nr;
beenthere("kctx %p vpfn %lx nr %d", (void *)kctx, (unsigned long)vpfn, nr);
KBASE_DEBUG_ASSERT(NULL != kctx);
lockdep_assert_held(&kctx->reg_lock);
if (0 == nr) {
/* early out if nothing to do */
return MALI_ERROR_NONE;
}
kbdev = kctx->kbdev;
while (nr) {
unsigned int i;
unsigned int index = vpfn & 0x1FF;
unsigned int count = KBASE_MMU_PAGE_ENTRIES - index;
if (count > nr)
count = nr;
pgd = mmu_get_bottom_pgd(kctx, vpfn);
if (!pgd) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kbase_mmu_teardown_pages: mmu_get_bottom_pgd failure\n");
return MALI_ERROR_FUNCTION_FAILED;
}
pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
if (!pgd_page) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kbase_mmu_teardown_pages: kmap failure\n");
return MALI_ERROR_OUT_OF_MEMORY;
}
for (i = 0; i < count; i++) {
page_table_entry_set( kctx->kbdev, &pgd_page[index + i], ENTRY_IS_INVAL );
}
vpfn += count;
nr -= count;
ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)), pgd_page + index, count * sizeof(u64));
kunmap(pfn_to_page(PFN_DOWN(pgd)));
}
kbase_mmu_flush(kctx,vpfn,requested_nr);
return MALI_ERROR_NONE;
}
KBASE_EXPORT_TEST_API(kbase_mmu_teardown_pages)
/**
* Update the entries for specified number of pages pointed to by 'phys' at GPU PFN 'vpfn'.
* This call is being triggered as a response to the changes of the mem attributes
*
* @pre : The caller is responsible for validating the memory attributes
*
* IMPORTANT: This uses kbasep_js_runpool_release_ctx() when the context is
* currently scheduled into the runpool, and so potentially uses a lot of locks.
* These locks must be taken in the correct order with respect to others
* already held by the caller. Refer to kbasep_js_runpool_release_ctx() for more
* information.
*/
mali_error kbase_mmu_update_pages(kbase_context* kctx, u64 vpfn, phys_addr_t* phys, size_t nr, unsigned long flags)
{
phys_addr_t pgd;
u64* pgd_page;
u64 mmu_flags = 0;
size_t requested_nr = nr;
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(0 != vpfn);
KBASE_DEBUG_ASSERT(vpfn <= (UINT64_MAX / PAGE_SIZE));
lockdep_assert_held(&kctx->reg_lock);
mmu_flags = kbase_mmu_get_mmu_flags(flags);
dev_warn( kctx->kbdev->osdev.dev, "kbase_mmu_update_pages(): updating page share flags "\
"on GPU PFN 0x%llx from phys %p, %zu pages",
vpfn, phys, nr);
while(nr)
{
unsigned int i;
unsigned int index = vpfn & 0x1FF;
size_t count = KBASE_MMU_PAGE_ENTRIES - index;
if (count > nr)
count = nr;
pgd = mmu_get_bottom_pgd(kctx, vpfn);
if (!pgd) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "mmu_get_bottom_pgd failure\n");
return MALI_ERROR_FUNCTION_FAILED;
}
pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
if (!pgd_page) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kmap failure\n");
return MALI_ERROR_OUT_OF_MEMORY;
}
for (i = 0; i < count; i++) {
page_table_entry_set( kctx->kbdev, &pgd_page[index + i], mmu_phyaddr_to_ate(phys[i], mmu_flags) );
}
phys += count;
vpfn += count;
nr -= count;
ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)), pgd_page + index, count * sizeof(u64));
kunmap(pfn_to_page(PFN_DOWN(pgd)));
}
kbase_mmu_flush(kctx,vpfn,requested_nr);
return MALI_ERROR_NONE;
}
static int mmu_pte_is_valid(u64 pte)
{
return ((pte & 3) == ENTRY_IS_ATE);
}
/* This is a debug feature only */
static void mmu_check_unused(kbase_context *kctx, phys_addr_t pgd)
{
u64 *page;
int i;
CSTD_UNUSED(kctx);
page = kmap_atomic(pfn_to_page(PFN_DOWN(pgd)));
/* kmap_atomic should NEVER fail. */
KBASE_DEBUG_ASSERT(NULL != page);
for (i = 0; i < KBASE_MMU_PAGE_ENTRIES; i++) {
if (mmu_pte_is_valid(page[i]))
beenthere("live pte %016lx", (unsigned long)page[i]);
}
kunmap_atomic(page);
}
static void mmu_teardown_level(kbase_context *kctx, phys_addr_t pgd, int level, int zap, u64 *pgd_page_buffer)
{
phys_addr_t target_pgd;
u64 *pgd_page;
int i;
KBASE_DEBUG_ASSERT(NULL != kctx);
lockdep_assert_held(&kctx->reg_lock);
pgd_page = kmap_atomic(pfn_to_page(PFN_DOWN(pgd)));
/* kmap_atomic should NEVER fail. */
KBASE_DEBUG_ASSERT(NULL != pgd_page);
/* Copy the page to our preallocated buffer so that we can minimize kmap_atomic usage */
memcpy(pgd_page_buffer, pgd_page, PAGE_SIZE);
kunmap_atomic(pgd_page);
pgd_page = pgd_page_buffer;
for (i = 0; i < KBASE_MMU_PAGE_ENTRIES; i++) {
target_pgd = mmu_pte_to_phy_addr(pgd_page[i]);
if (target_pgd) {
if (level < 2) {
mmu_teardown_level(kctx, target_pgd, level + 1, zap, pgd_page_buffer + (PAGE_SIZE / sizeof(u64)));
} else {
/*
* So target_pte is a level-3 page.
* As a leaf, it is safe to free it.
* Unless we have live pages attached to it!
*/
mmu_check_unused(kctx, target_pgd);
}
beenthere("pte %lx level %d", (unsigned long)target_pgd, level + 1);
if (zap) {
kbase_mem_allocator_free(kctx->pgd_allocator, 1, &target_pgd, MALI_TRUE);
kbase_process_page_usage_dec(kctx, 1 );
kbase_atomic_sub_pages(1, &kctx->used_pages);
kbase_atomic_sub_pages(1, &kctx->kbdev->memdev.used_pages);
}
}
}
}
mali_error kbase_mmu_init(kbase_context *kctx)
{
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(NULL == kctx->mmu_teardown_pages);
/* Preallocate MMU depth of four pages for mmu_teardown_level to use */
kctx->mmu_teardown_pages = kmalloc(PAGE_SIZE * 4, GFP_KERNEL);
kctx->mem_attrs = (ASn_MEMATTR_IMPL_DEF_CACHE_POLICY <<
(ASn_MEMATTR_INDEX_IMPL_DEF_CACHE_POLICY * 8)) |
(ASn_MEMATTR_FORCE_TO_CACHE_ALL <<
(ASn_MEMATTR_INDEX_FORCE_TO_CACHE_ALL * 8)) |
(ASn_MEMATTR_WRITE_ALLOC <<
(ASn_MEMATTR_INDEX_WRITE_ALLOC * 8)) |
0; /* The other indices are unused for now */
if (NULL == kctx->mmu_teardown_pages)
return MALI_ERROR_OUT_OF_MEMORY;
return MALI_ERROR_NONE;
}
void kbase_mmu_term(kbase_context *kctx)
{
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(NULL != kctx->mmu_teardown_pages);
kfree(kctx->mmu_teardown_pages);
kctx->mmu_teardown_pages = NULL;
}
void kbase_mmu_free_pgd(kbase_context *kctx)
{
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(NULL != kctx->mmu_teardown_pages);
lockdep_assert_held(&kctx->reg_lock);
mmu_teardown_level(kctx, kctx->pgd, MIDGARD_MMU_TOPLEVEL, 1, kctx->mmu_teardown_pages);
beenthere("pgd %lx", (unsigned long)kctx->pgd);
kbase_mem_allocator_free(kctx->pgd_allocator, 1, &kctx->pgd, MALI_TRUE);
kbase_process_page_usage_dec(kctx, 1 );
kbase_atomic_sub_pages(1, &kctx->used_pages);
kbase_atomic_sub_pages(1, &kctx->kbdev->memdev.used_pages);
}
KBASE_EXPORT_TEST_API(kbase_mmu_free_pgd)
static size_t kbasep_mmu_dump_level(kbase_context *kctx, phys_addr_t pgd, int level, char ** const buffer, size_t *size_left)
{
phys_addr_t target_pgd;
u64 *pgd_page;
int i;
size_t size = KBASE_MMU_PAGE_ENTRIES * sizeof(u64) + sizeof(u64);
size_t dump_size;
KBASE_DEBUG_ASSERT(NULL != kctx);
lockdep_assert_held(&kctx->reg_lock);
pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
if (!pgd_page) {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kbasep_mmu_dump_level: kmap failure\n");
return 0;
}
if (*size_left >= size) {
/* A modified physical address that contains the page table level */
u64 m_pgd = pgd | level;
/* Put the modified physical address in the output buffer */
memcpy(*buffer, &m_pgd, sizeof(m_pgd));
*buffer += sizeof(m_pgd);
/* Followed by the page table itself */
memcpy(*buffer, pgd_page, sizeof(u64) * KBASE_MMU_PAGE_ENTRIES);
*buffer += sizeof(u64) * KBASE_MMU_PAGE_ENTRIES;
*size_left -= size;
}
for (i = 0; i < KBASE_MMU_PAGE_ENTRIES; i++) {
if ((pgd_page[i] & ENTRY_IS_PTE) == ENTRY_IS_PTE) {
target_pgd = mmu_pte_to_phy_addr(pgd_page[i]);
dump_size = kbasep_mmu_dump_level(kctx, target_pgd, level + 1, buffer, size_left);
if (!dump_size) {
kunmap(pfn_to_page(PFN_DOWN(pgd)));
return 0;
}
size += dump_size;
}
}
kunmap(pfn_to_page(PFN_DOWN(pgd)));
return size;
}
void *kbase_mmu_dump(kbase_context *kctx, int nr_pages)
{
void *kaddr;
size_t size_left;
KBASE_DEBUG_ASSERT(kctx);
lockdep_assert_held(&kctx->reg_lock);
if (0 == nr_pages) {
/* can't find in a 0 sized buffer, early out */
return NULL;
}
size_left = nr_pages * PAGE_SIZE;
KBASE_DEBUG_ASSERT(0 != size_left);
kaddr = vmalloc_user(size_left);
if (kaddr) {
u64 end_marker = 0xFFULL;
char *buffer = (char *)kaddr;
size_t size = kbasep_mmu_dump_level(kctx, kctx->pgd, MIDGARD_MMU_TOPLEVEL, &buffer, &size_left);
if (!size) {
vfree(kaddr);
return NULL;
}
/* Add on the size for the end marker */
size += sizeof(u64);
if (size > nr_pages * PAGE_SIZE || size_left < sizeof(u64)) {
/* The buffer isn't big enough - free the memory and return failure */
vfree(kaddr);
return NULL;
}
/* Add the end marker */
memcpy(buffer, &end_marker, sizeof(u64));
}
return kaddr;
}
KBASE_EXPORT_TEST_API(kbase_mmu_dump)
static u64 lock_region(kbase_device *kbdev, u64 pfn, size_t num_pages)
{
u64 region;
/* can't lock a zero sized range */
KBASE_DEBUG_ASSERT(num_pages);
region = pfn << PAGE_SHIFT;
/*
* fls returns (given the ASSERT above):
* 32-bit: 1 .. 32
* 64-bit: 1 .. 32
*
* 32-bit: 10 + fls(num_pages)
* results in the range (11 .. 42)
* 64-bit: 10 + fls(num_pages)
* results in the range (11 .. 42)
*/
/* gracefully handle num_pages being zero */
if (0 == num_pages) {
region |= 11;
} else {
u8 region_width;
region_width = 10 + fls(num_pages);
if (num_pages != (1ul << (region_width - 11))) {
/* not pow2, so must go up to the next pow2 */
region_width += 1;
}
KBASE_DEBUG_ASSERT(region_width <= KBASE_LOCK_REGION_MAX_SIZE);
KBASE_DEBUG_ASSERT(region_width >= KBASE_LOCK_REGION_MIN_SIZE);
region |= region_width;
}
return region;
}
static void bus_fault_worker(struct work_struct *data)
{
kbase_as *faulting_as;
int as_no;
kbase_context *kctx;
kbase_device *kbdev;
u32 reg;
mali_bool reset_status = MALI_FALSE;
faulting_as = container_of(data, kbase_as, work_busfault);
as_no = faulting_as->number;
kbdev = container_of(faulting_as, kbase_device, as[as_no]);
/* Grab the context that was already refcounted in kbase_mmu_interrupt().
* Therefore, it cannot be scheduled out of this AS until we explicitly release it
*
* NOTE: NULL can be returned here if we're gracefully handling a spurious interrupt */
kctx = kbasep_js_runpool_lookup_ctx_noretain(kbdev, as_no);
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8245)) {
/* Due to H/W issue 8245 we need to reset the GPU after using UNMAPPED mode.
* We start the reset before switching to UNMAPPED to ensure that unrelated jobs
* are evicted from the GPU before the switch.
*/
KBASE_DEBUG_PRINT_ERROR(KBASE_MMU, "GPU bus error occurred. For this GPU version we now soft-reset as part of bus error recovery\n");
reset_status = kbase_prepare_to_reset_gpu(kbdev);
}
/* NOTE: If GPU already powered off for suspend, we don't need to switch to unmapped */
if (!kbase_pm_context_active_handle_suspend(kbdev, KBASE_PM_SUSPEND_HANDLER_DONT_REACTIVATE)) {
/* switch to UNMAPPED mode, will abort all jobs and stop any hw counter dumping */
/* AS transaction begin */
mutex_lock(&kbdev->as[as_no].transaction_mutex);
reg = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), kctx);
reg &= ~3;
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), reg, kctx);
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_UPDATE, kctx);
mutex_unlock(&kbdev->as[as_no].transaction_mutex);
/* AS transaction end */
mmu_mask_reenable(kbdev, kctx, faulting_as);
kbase_pm_context_idle(kbdev);
}
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8245) && reset_status)
kbase_reset_gpu(kbdev);
/* By this point, the fault was handled in some way, so release the ctx refcount */
if (kctx != NULL)
kbasep_js_runpool_release_ctx(kbdev, kctx);
}
void kbase_mmu_interrupt(kbase_device *kbdev, u32 irq_stat)
{
unsigned long flags;
const int num_as = 16;
const int busfault_shift = 16;
const int pf_shift = 0;
const unsigned long mask = (1UL << num_as) - 1;
kbasep_js_device_data *js_devdata;
u32 new_mask;
u32 tmp;
u32 bf_bits = (irq_stat >> busfault_shift) & mask; /* bus faults */
/* Ignore ASes with both pf and bf */
u32 pf_bits = ((irq_stat >> pf_shift) & mask) & ~bf_bits; /* page faults */
KBASE_DEBUG_ASSERT(NULL != kbdev);
js_devdata = &kbdev->js_data;
/* remember current mask */
spin_lock_irqsave(&kbdev->mmu_mask_change, flags);
new_mask = kbase_reg_read(kbdev, MMU_REG(MMU_IRQ_MASK), NULL);
/* mask interrupts for now */
kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_MASK), 0, NULL);
spin_unlock_irqrestore(&kbdev->mmu_mask_change, flags);
while (bf_bits) {
/* the while logic ensures we have a bit set, no need to check for not-found here */
int as_no = ffs(bf_bits) - 1;
kbase_as *as = &kbdev->as[as_no];
kbase_context *kctx;
/* Refcount the kctx ASAP - it shouldn't disappear anyway, since Bus/Page faults
* _should_ only occur whilst jobs are running, and a job causing the Bus/Page fault
* shouldn't complete until the MMU is updated */
kctx = kbasep_js_runpool_lookup_ctx(kbdev, as_no);
/* mark as handled */
bf_bits &= ~(1UL << as_no);
/* find faulting address & status */
as->fault_addr = ((u64)kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTADDRESS_HI), kctx) << 32) |
kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTADDRESS_LO), kctx);
as->fault_status = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTSTATUS), kctx);
/* Clear the internal JM mask first before clearing the internal MMU mask */
kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_CLEAR), 1UL << MMU_REGS_BUS_ERROR_FLAG(as_no), kctx);
if (kctx) {
/* hw counters dumping in progress, signal the other thread that it failed */
if ((kbdev->hwcnt.kctx == kctx) && (kbdev->hwcnt.state == KBASE_INSTR_STATE_DUMPING))
kbdev->hwcnt.state = KBASE_INSTR_STATE_FAULT;
/* Stop the kctx from submitting more jobs and cause it to be scheduled
* out/rescheduled when all references to it are released */
spin_lock_irqsave(&js_devdata->runpool_irq.lock, flags);
kbasep_js_clear_submit_allowed(js_devdata, kctx);
spin_unlock_irqrestore(&js_devdata->runpool_irq.lock, flags);
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Bus error in AS%d at 0x%016llx\n", as_no, as->fault_addr);
} else {
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Bus error in AS%d at 0x%016llx with no context present! " "Suprious IRQ or SW Design Error?\n", as_no, as->fault_addr);
}
/* remove the queued BFs from the mask */
new_mask &= ~(1UL << (as_no + num_as));
/* We need to switch to UNMAPPED mode - but we do this in a worker so that we can sleep */
KBASE_DEBUG_ASSERT(0 == object_is_on_stack(&as->work_busfault));
INIT_WORK(&as->work_busfault, bus_fault_worker);
queue_work(as->pf_wq, &as->work_busfault);
}
/*
* pf_bits is non-zero if we have at least one AS with a page fault and no bus fault.
* Handle the PFs in our worker thread.
*/
while (pf_bits) {
/* the while logic ensures we have a bit set, no need to check for not-found here */
int as_no = ffs(pf_bits) - 1;
kbase_as *as = &kbdev->as[as_no];
kbase_context *kctx;
/* Refcount the kctx ASAP - it shouldn't disappear anyway, since Bus/Page faults
* _should_ only occur whilst jobs are running, and a job causing the Bus/Page fault
* shouldn't complete until the MMU is updated */
kctx = kbasep_js_runpool_lookup_ctx(kbdev, as_no);
/* mark as handled */
pf_bits &= ~(1UL << as_no);
/* find faulting address & status */
as->fault_addr = ((u64)kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTADDRESS_HI), kctx) << 32) |
kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTADDRESS_LO), kctx);
as->fault_status = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTSTATUS), kctx);
/* Clear the internal JM mask first before clearing the internal MMU mask */
kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_CLEAR), 1UL << MMU_REGS_PAGE_FAULT_FLAG(as_no), kctx);
if (kctx == NULL)
KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Page fault in AS%d at 0x%016llx with no context present! " "Suprious IRQ or SW Design Error?\n", as_no, as->fault_addr);
/* remove the queued PFs from the mask */
new_mask &= ~((1UL << as_no) | (1UL << (as_no + num_as)));
/* queue work pending for this AS */
KBASE_DEBUG_ASSERT(0 == object_is_on_stack(&as->work_pagefault));
INIT_WORK(&as->work_pagefault, page_fault_worker);
queue_work(as->pf_wq, &as->work_pagefault);
}
/* reenable interrupts */
spin_lock_irqsave(&kbdev->mmu_mask_change, flags);
tmp = kbase_reg_read(kbdev, MMU_REG(MMU_IRQ_MASK), NULL);
new_mask |= tmp;
kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_MASK), new_mask, NULL);
spin_unlock_irqrestore(&kbdev->mmu_mask_change, flags);
}
KBASE_EXPORT_TEST_API(kbase_mmu_interrupt)
const char *kbase_exception_name(u32 exception_code)
{
const char *e;
switch (exception_code) {
/* Non-Fault Status code */
case 0x00:
e = "NOT_STARTED/IDLE/OK";
break;
case 0x01:
e = "DONE";
break;
case 0x02:
e = "INTERRUPTED";
break;
case 0x03:
e = "STOPPED";
break;
case 0x04:
e = "TERMINATED";
break;
case 0x08:
e = "ACTIVE";
break;
/* Job exceptions */
case 0x40:
e = "JOB_CONFIG_FAULT";
break;
case 0x41:
e = "JOB_POWER_FAULT";
break;
case 0x42:
e = "JOB_READ_FAULT";
break;
case 0x43:
e = "JOB_WRITE_FAULT";
break;
case 0x44:
e = "JOB_AFFINITY_FAULT";
break;
case 0x48:
e = "JOB_BUS_FAULT";
break;
case 0x50:
e = "INSTR_INVALID_PC";
break;
case 0x51:
e = "INSTR_INVALID_ENC";
break;
case 0x52:
e = "INSTR_TYPE_MISMATCH";
break;
case 0x53:
e = "INSTR_OPERAND_FAULT";
break;
case 0x54:
e = "INSTR_TLS_FAULT";
break;
case 0x55:
e = "INSTR_BARRIER_FAULT";
break;
case 0x56:
e = "INSTR_ALIGN_FAULT";
break;
case 0x58:
e = "DATA_INVALID_FAULT";
break;
case 0x59:
e = "TILE_RANGE_FAULT";
break;
case 0x5A:
e = "ADDR_RANGE_FAULT";
break;
case 0x60:
e = "OUT_OF_MEMORY";
break;
/* GPU exceptions */
case 0x80:
e = "DELAYED_BUS_FAULT";
break;
case 0x81:
e = "SHAREABILITY_FAULT";
break;
/* MMU exceptions */
case 0xC0:
case 0xC1:
case 0xC2:
case 0xC3:
case 0xC4:
case 0xC5:
case 0xC6:
case 0xC7:
e = "TRANSLATION_FAULT";
break;
case 0xC8:
e = "PERMISSION_FAULT";
break;
case 0xD0:
case 0xD1:
case 0xD2:
case 0xD3:
case 0xD4:
case 0xD5:
case 0xD6:
case 0xD7:
e = "TRANSTAB_BUS_FAULT";
break;
case 0xD8:
e = "ACCESS_FLAG";
break;
default:
e = "UNKNOWN";
break;
};
return e;
}
/**
* The caller must ensure it's retained the ctx to prevent it from being scheduled out whilst it's being worked on.
*/
static void kbase_mmu_report_fault_and_kill(kbase_context *kctx, kbase_as *as)
{
unsigned long flags;
u32 reg;
int exception_type;
int access_type;
int source_id;
int as_no;
kbase_device *kbdev;
kbasep_js_device_data *js_devdata;
mali_bool reset_status = MALI_FALSE;
static const char * const access_type_names[] = { "RESERVED", "EXECUTE", "READ", "WRITE" };
KBASE_DEBUG_ASSERT(as);
KBASE_DEBUG_ASSERT(kctx);
as_no = as->number;
kbdev = kctx->kbdev;
js_devdata = &kbdev->js_data;
/* ASSERT that the context won't leave the runpool */
KBASE_DEBUG_ASSERT(kbasep_js_debug_check_ctx_refcount(kbdev, kctx) > 0);
/* decode the fault status */
exception_type = as->fault_status & 0xFF;
access_type = (as->fault_status >> 8) & 0x3;
source_id = (as->fault_status >> 16);
/* terminal fault, print info about the fault */
KBASE_DEBUG_PRINT_ERROR(KBASE_MMU, "Unhandled Page fault in AS%d at VA 0x%016llX\n"
"raw fault status 0x%X\n"
"decoded fault status: %s\n"
"exception type 0x%X: %s\n"
"access type 0x%X: %s\n"
"source id 0x%X\n",
as_no, as->fault_addr,
as->fault_status,
(as->fault_status & (1 << 10) ? "DECODER FAULT" : "SLAVE FAULT"),
exception_type, kbase_exception_name(exception_type),
access_type, access_type_names[access_type],
source_id);
/* hardware counters dump fault handling */
if ((kbdev->hwcnt.kctx) && (kbdev->hwcnt.kctx->as_nr == as_no) && (kbdev->hwcnt.state == KBASE_INSTR_STATE_DUMPING)) {
unsigned int num_core_groups = kbdev->gpu_props.num_core_groups;
if ((as->fault_addr >= kbdev->hwcnt.addr) && (as->fault_addr < (kbdev->hwcnt.addr + (num_core_groups * 2048))))
kbdev->hwcnt.state = KBASE_INSTR_STATE_FAULT;
}
/* Stop the kctx from submitting more jobs and cause it to be scheduled
* out/rescheduled - this will occur on releasing the context's refcount */
spin_lock_irqsave(&js_devdata->runpool_irq.lock, flags);
kbasep_js_clear_submit_allowed(js_devdata, kctx);
spin_unlock_irqrestore(&js_devdata->runpool_irq.lock, flags);
/* Kill any running jobs from the context. Submit is disallowed, so no more jobs from this
* context can appear in the job slots from this point on */
kbase_job_kill_jobs_from_context(kctx);
/* AS transaction begin */
mutex_lock(&as->transaction_mutex);
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8245)) {
/* Due to H/W issue 8245 we need to reset the GPU after using UNMAPPED mode.
* We start the reset before switching to UNMAPPED to ensure that unrelated jobs
* are evicted from the GPU before the switch.
*/
KBASE_DEBUG_PRINT_ERROR(KBASE_MMU, "Unhandled page fault. For this GPU version we now soft-reset the GPU as part of page fault recovery.");
reset_status = kbase_prepare_to_reset_gpu(kbdev);
}
/* switch to UNMAPPED mode, will abort all jobs and stop any hw counter dumping */
reg = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), kctx);
reg &= ~3;
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), reg, kctx);
kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_UPDATE, kctx);
mutex_unlock(&as->transaction_mutex);
/* AS transaction end */
mmu_mask_reenable(kbdev, kctx, as);
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8245) && reset_status)
kbase_reset_gpu(kbdev);
}
void kbasep_as_do_poke(struct work_struct *work)
{
kbase_as *as;
kbase_device *kbdev;
unsigned long flags;
KBASE_DEBUG_ASSERT(work);
as = container_of(work, kbase_as, poke_work);
kbdev = container_of(as, kbase_device, as[as->number]);
KBASE_DEBUG_ASSERT(as->poke_state & KBASE_AS_POKE_STATE_IN_FLIGHT);
/* GPU power will already be active by virtue of the caller holding a JS
* reference on the address space, and will not release it until this worker
* has finished */
/* AS transaction begin */
mutex_lock(&as->transaction_mutex);
/* Force a uTLB invalidate */
kbase_reg_write(kbdev, MMU_AS_REG(as->number, ASn_COMMAND), ASn_COMMAND_UNLOCK, NULL);
mutex_unlock(&as->transaction_mutex);
/* AS transaction end */
spin_lock_irqsave(&kbdev->js_data.runpool_irq.lock, flags);
if (as->poke_refcount &&
!(as->poke_state & KBASE_AS_POKE_STATE_KILLING_POKE)) {
/* Only queue up the timer if we need it, and we're not trying to kill it */
hrtimer_start(&as->poke_timer, HR_TIMER_DELAY_MSEC(5), HRTIMER_MODE_REL);
}
spin_unlock_irqrestore(&kbdev->js_data.runpool_irq.lock, flags);
}
enum hrtimer_restart kbasep_as_poke_timer_callback(struct hrtimer *timer)
{
kbase_as *as;
int queue_work_ret;
KBASE_DEBUG_ASSERT(NULL != timer);
as = container_of(timer, kbase_as, poke_timer);
KBASE_DEBUG_ASSERT(as->poke_state & KBASE_AS_POKE_STATE_IN_FLIGHT);
queue_work_ret = queue_work(as->poke_wq, &as->poke_work);
KBASE_DEBUG_ASSERT(queue_work_ret);
return HRTIMER_NORESTART;
}
/**
* Retain the poking timer on an atom's context (if the atom hasn't already
* done so), and start the timer (if it's not already started).
*
* This must only be called on a context that's scheduled in, and an atom
* that's running on the GPU.
*
* The caller must hold kbasep_js_device_data::runpool_irq::lock
*
* This can be called safely from atomic context
*/
void kbase_as_poking_timer_retain_atom(kbase_device *kbdev, kbase_context *kctx, kbase_jd_atom *katom)
{
kbase_as *as;
KBASE_DEBUG_ASSERT(kbdev);
KBASE_DEBUG_ASSERT(kctx);
KBASE_DEBUG_ASSERT(katom);
KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID);
lockdep_assert_held(&kbdev->js_data.runpool_irq.lock);
if (katom->poking)
return;
katom->poking = 1;
/* It's safe to work on the as/as_nr without an explicit reference,
* because the caller holds the runpool_irq lock, and the atom itself
* was also running and had already taken a reference */
as = &kbdev->as[kctx->as_nr];
if (++(as->poke_refcount) == 1) {
/* First refcount for poke needed: check if not already in flight */
if (!as->poke_state) {
/* need to start poking */
as->poke_state |= KBASE_AS_POKE_STATE_IN_FLIGHT;
queue_work(as->poke_wq, &as->poke_work);
}
}
}
/**
* If an atom holds a poking timer, release it and wait for it to finish
*
* This must only be called on a context that's scheduled in, and an atom
* that still has a JS reference on the context
*
* This must \b not be called from atomic context, since it can sleep.
*/
void kbase_as_poking_timer_release_atom(kbase_device *kbdev, kbase_context *kctx, kbase_jd_atom *katom)
{
kbase_as *as;
unsigned long flags;
KBASE_DEBUG_ASSERT(kbdev);
KBASE_DEBUG_ASSERT(kctx);
KBASE_DEBUG_ASSERT(katom);
KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID);
if (!katom->poking)
return;
as = &kbdev->as[kctx->as_nr];
spin_lock_irqsave(&kbdev->js_data.runpool_irq.lock, flags);
KBASE_DEBUG_ASSERT(as->poke_refcount > 0);
KBASE_DEBUG_ASSERT(as->poke_state & KBASE_AS_POKE_STATE_IN_FLIGHT);
if (--(as->poke_refcount) == 0) {
as->poke_state |= KBASE_AS_POKE_STATE_KILLING_POKE;
spin_unlock_irqrestore(&kbdev->js_data.runpool_irq.lock, flags);
hrtimer_cancel(&as->poke_timer);
flush_workqueue(as->poke_wq);
spin_lock_irqsave(&kbdev->js_data.runpool_irq.lock, flags);
/* Re-check whether it's still needed */
if (as->poke_refcount) {
int queue_work_ret;
/* Poking still needed:
* - Another retain will not be starting the timer or queueing work,
* because it's still marked as in-flight
* - The hrtimer has finished, and has not started a new timer or
* queued work because it's been marked as killing
*
* So whatever happens now, just queue the work again */
as->poke_state &= ~((kbase_as_poke_state)KBASE_AS_POKE_STATE_KILLING_POKE);
queue_work_ret = queue_work(as->poke_wq, &as->poke_work);
KBASE_DEBUG_ASSERT(queue_work_ret);
} else {
/* It isn't - so mark it as not in flight, and not killing */
as->poke_state = 0u;
/* The poke associated with the atom has now finished. If this is
* also the last atom on the context, then we can guarentee no more
* pokes (and thus no more poking register accesses) will occur on
* the context until new atoms are run */
}
}
spin_unlock_irqrestore(&kbdev->js_data.runpool_irq.lock, flags);
katom->poking = 0;
}
| gpl-2.0 |
OpenELEC/linux | arch/hexagon/kernel/ptrace.c | 1794 | 5483 | /*
* Ptrace support for Hexagon
*
* Copyright (c) 2010-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <generated/compile.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/regset.h>
#include <linux/user.h>
#include <linux/elf.h>
#include <asm/user.h>
#if arch_has_single_step()
/* Both called from ptrace_resume */
void user_enable_single_step(struct task_struct *child)
{
pt_set_singlestep(task_pt_regs(child));
set_tsk_thread_flag(child, TIF_SINGLESTEP);
}
void user_disable_single_step(struct task_struct *child)
{
pt_clr_singlestep(task_pt_regs(child));
clear_tsk_thread_flag(child, TIF_SINGLESTEP);
}
#endif
static int genregs_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
unsigned int dummy;
struct pt_regs *regs = task_pt_regs(target);
if (!regs)
return -EIO;
/* The general idea here is that the copyout must happen in
* exactly the same order in which the userspace expects these
* regs. Now, the sequence in userspace does not match the
* sequence in the kernel, so everything past the 32 gprs
* happens one at a time.
*/
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
®s->r00, 0, 32*sizeof(unsigned long));
#define ONEXT(KPT_REG, USR_REG) \
if (!ret) \
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, \
KPT_REG, offsetof(struct user_regs_struct, USR_REG), \
offsetof(struct user_regs_struct, USR_REG) + \
sizeof(unsigned long));
/* Must be exactly same sequence as struct user_regs_struct */
ONEXT(®s->sa0, sa0);
ONEXT(®s->lc0, lc0);
ONEXT(®s->sa1, sa1);
ONEXT(®s->lc1, lc1);
ONEXT(®s->m0, m0);
ONEXT(®s->m1, m1);
ONEXT(®s->usr, usr);
ONEXT(®s->preds, p3_0);
ONEXT(®s->gp, gp);
ONEXT(®s->ugp, ugp);
ONEXT(&pt_elr(regs), pc);
dummy = pt_cause(regs);
ONEXT(&dummy, cause);
ONEXT(&pt_badva(regs), badva);
#if CONFIG_HEXAGON_ARCH_VERSION >=4
ONEXT(®s->cs0, cs0);
ONEXT(®s->cs1, cs1);
#endif
/* Pad the rest with zeros, if needed */
if (!ret)
ret = user_regset_copyout_zero(&pos, &count, &kbuf, &ubuf,
offsetof(struct user_regs_struct, pad1), -1);
return ret;
}
static int genregs_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
unsigned long bucket;
struct pt_regs *regs = task_pt_regs(target);
if (!regs)
return -EIO;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
®s->r00, 0, 32*sizeof(unsigned long));
#define INEXT(KPT_REG, USR_REG) \
if (!ret) \
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, \
KPT_REG, offsetof(struct user_regs_struct, USR_REG), \
offsetof(struct user_regs_struct, USR_REG) + \
sizeof(unsigned long));
/* Must be exactly same sequence as struct user_regs_struct */
INEXT(®s->sa0, sa0);
INEXT(®s->lc0, lc0);
INEXT(®s->sa1, sa1);
INEXT(®s->lc1, lc1);
INEXT(®s->m0, m0);
INEXT(®s->m1, m1);
INEXT(®s->usr, usr);
INEXT(®s->preds, p3_0);
INEXT(®s->gp, gp);
INEXT(®s->ugp, ugp);
INEXT(&pt_elr(regs), pc);
/* CAUSE and BADVA aren't writeable. */
INEXT(&bucket, cause);
INEXT(&bucket, badva);
#if CONFIG_HEXAGON_ARCH_VERSION >=4
INEXT(®s->cs0, cs0);
INEXT(®s->cs1, cs1);
#endif
/* Ignore the rest, if needed */
if (!ret)
ret = user_regset_copyin_ignore(&pos, &count, &kbuf, &ubuf,
offsetof(struct user_regs_struct, pad1), -1);
if (ret)
return ret;
/*
* This is special; SP is actually restored by the VM via the
* special event record which is set by the special trap.
*/
regs->hvmer.vmpsp = regs->r29;
return 0;
}
enum hexagon_regset {
REGSET_GENERAL,
};
static const struct user_regset hexagon_regsets[] = {
[REGSET_GENERAL] = {
.core_note_type = NT_PRSTATUS,
.n = ELF_NGREG,
.size = sizeof(unsigned long),
.align = sizeof(unsigned long),
.get = genregs_get,
.set = genregs_set,
},
};
static const struct user_regset_view hexagon_user_view = {
.name = UTS_MACHINE,
.e_machine = ELF_ARCH,
.ei_osabi = ELF_OSABI,
.regsets = hexagon_regsets,
.e_flags = ELF_CORE_EFLAGS,
.n = ARRAY_SIZE(hexagon_regsets)
};
const struct user_regset_view *task_user_regset_view(struct task_struct *task)
{
return &hexagon_user_view;
}
void ptrace_disable(struct task_struct *child)
{
/* Boilerplate - resolves to null inline if no HW single-step */
user_disable_single_step(child);
}
long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
return ptrace_request(child, request, addr, data);
}
| gpl-2.0 |
nitroglycerine33/kernel_samsung_tuna | arch/arm/mach-kirkwood/db88f6281-bp-setup.c | 2818 | 2424 | /*
* arch/arm/mach-kirkwood/db88f6281-bp-setup.c
*
* Marvell DB-88F6281-BP Development Board Setup
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mtd/partitions.h>
#include <linux/ata_platform.h>
#include <linux/mv643xx_eth.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/kirkwood.h>
#include <plat/mvsdio.h>
#include "common.h"
#include "mpp.h"
static struct mtd_partition db88f6281_nand_parts[] = {
{
.name = "u-boot",
.offset = 0,
.size = SZ_1M
}, {
.name = "uImage",
.offset = MTDPART_OFS_NXTBLK,
.size = SZ_4M
}, {
.name = "root",
.offset = MTDPART_OFS_NXTBLK,
.size = MTDPART_SIZ_FULL
},
};
static struct mv643xx_eth_platform_data db88f6281_ge00_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(8),
};
static struct mv_sata_platform_data db88f6281_sata_data = {
.n_ports = 2,
};
static struct mvsdio_platform_data db88f6281_mvsdio_data = {
.gpio_write_protect = 37,
.gpio_card_detect = 38,
};
static unsigned int db88f6281_mpp_config[] __initdata = {
MPP0_NF_IO2,
MPP1_NF_IO3,
MPP2_NF_IO4,
MPP3_NF_IO5,
MPP4_NF_IO6,
MPP5_NF_IO7,
MPP18_NF_IO0,
MPP19_NF_IO1,
MPP37_GPIO,
MPP38_GPIO,
0
};
static void __init db88f6281_init(void)
{
/*
* Basic setup. Needs to be called early.
*/
kirkwood_init();
kirkwood_mpp_conf(db88f6281_mpp_config);
kirkwood_nand_init(ARRAY_AND_SIZE(db88f6281_nand_parts), 25);
kirkwood_ehci_init();
kirkwood_ge00_init(&db88f6281_ge00_data);
kirkwood_sata_init(&db88f6281_sata_data);
kirkwood_uart0_init();
kirkwood_sdio_init(&db88f6281_mvsdio_data);
}
static int __init db88f6281_pci_init(void)
{
if (machine_is_db88f6281_bp()) {
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
if (dev == MV88F6282_DEV_ID)
kirkwood_pcie_init(KW_PCIE1 | KW_PCIE0);
else
kirkwood_pcie_init(KW_PCIE0);
}
return 0;
}
subsys_initcall(db88f6281_pci_init);
MACHINE_START(DB88F6281_BP, "Marvell DB-88F6281-BP Development Board")
/* Maintainer: Saeed Bishara <saeed@marvell.com> */
.boot_params = 0x00000100,
.init_machine = db88f6281_init,
.map_io = kirkwood_map_io,
.init_early = kirkwood_init_early,
.init_irq = kirkwood_init_irq,
.timer = &kirkwood_timer,
MACHINE_END
| gpl-2.0 |
akalongman/linux | drivers/scsi/sym53c8xx_2/sym_hipd.c | 4098 | 147483 | /*
* Device driver for the SYMBIOS/LSILOGIC 53C8XX and 53C1010 family
* of PCI-SCSI IO processors.
*
* Copyright (C) 1999-2001 Gerard Roudier <groudier@free.fr>
* Copyright (c) 2003-2005 Matthew Wilcox <matthew@wil.cx>
*
* This driver is derived from the Linux sym53c8xx driver.
* Copyright (C) 1998-2000 Gerard Roudier
*
* The sym53c8xx driver is derived from the ncr53c8xx driver that had been
* a port of the FreeBSD ncr driver to Linux-1.2.13.
*
* The original ncr driver has been written for 386bsd and FreeBSD by
* Wolfgang Stanglmeier <wolf@cologne.de>
* Stefan Esser <se@mi.Uni-Koeln.de>
* Copyright (C) 1994 Wolfgang Stanglmeier
*
* Other major contributions:
*
* NVRAM detection and reading.
* Copyright (C) 1997 Richard Waltham <dormouse@farsrobt.demon.co.uk>
*
*-----------------------------------------------------------------------------
*
* 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/slab.h>
#include <asm/param.h> /* for timeouts in units of HZ */
#include "sym_glue.h"
#include "sym_nvram.h"
#if 0
#define SYM_DEBUG_GENERIC_SUPPORT
#endif
/*
* Needed function prototypes.
*/
static void sym_int_ma (struct sym_hcb *np);
static void sym_int_sir(struct sym_hcb *);
static struct sym_ccb *sym_alloc_ccb(struct sym_hcb *np);
static struct sym_ccb *sym_ccb_from_dsa(struct sym_hcb *np, u32 dsa);
static void sym_alloc_lcb_tags (struct sym_hcb *np, u_char tn, u_char ln);
static void sym_complete_error (struct sym_hcb *np, struct sym_ccb *cp);
static void sym_complete_ok (struct sym_hcb *np, struct sym_ccb *cp);
static int sym_compute_residual(struct sym_hcb *np, struct sym_ccb *cp);
/*
* Print a buffer in hexadecimal format with a ".\n" at end.
*/
static void sym_printl_hex(u_char *p, int n)
{
while (n-- > 0)
printf (" %x", *p++);
printf (".\n");
}
static void sym_print_msg(struct sym_ccb *cp, char *label, u_char *msg)
{
sym_print_addr(cp->cmd, "%s: ", label);
spi_print_msg(msg);
printf("\n");
}
static void sym_print_nego_msg(struct sym_hcb *np, int target, char *label, u_char *msg)
{
struct sym_tcb *tp = &np->target[target];
dev_info(&tp->starget->dev, "%s: ", label);
spi_print_msg(msg);
printf("\n");
}
/*
* Print something that tells about extended errors.
*/
void sym_print_xerr(struct scsi_cmnd *cmd, int x_status)
{
if (x_status & XE_PARITY_ERR) {
sym_print_addr(cmd, "unrecovered SCSI parity error.\n");
}
if (x_status & XE_EXTRA_DATA) {
sym_print_addr(cmd, "extraneous data discarded.\n");
}
if (x_status & XE_BAD_PHASE) {
sym_print_addr(cmd, "illegal scsi phase (4/5).\n");
}
if (x_status & XE_SODL_UNRUN) {
sym_print_addr(cmd, "ODD transfer in DATA OUT phase.\n");
}
if (x_status & XE_SWIDE_OVRUN) {
sym_print_addr(cmd, "ODD transfer in DATA IN phase.\n");
}
}
/*
* Return a string for SCSI BUS mode.
*/
static char *sym_scsi_bus_mode(int mode)
{
switch(mode) {
case SMODE_HVD: return "HVD";
case SMODE_SE: return "SE";
case SMODE_LVD: return "LVD";
}
return "??";
}
/*
* Soft reset the chip.
*
* Raising SRST when the chip is running may cause
* problems on dual function chips (see below).
* On the other hand, LVD devices need some delay
* to settle and report actual BUS mode in STEST4.
*/
static void sym_chip_reset (struct sym_hcb *np)
{
OUTB(np, nc_istat, SRST);
INB(np, nc_mbox1);
udelay(10);
OUTB(np, nc_istat, 0);
INB(np, nc_mbox1);
udelay(2000); /* For BUS MODE to settle */
}
/*
* Really soft reset the chip.:)
*
* Some 896 and 876 chip revisions may hang-up if we set
* the SRST (soft reset) bit at the wrong time when SCRIPTS
* are running.
* So, we need to abort the current operation prior to
* soft resetting the chip.
*/
static void sym_soft_reset (struct sym_hcb *np)
{
u_char istat = 0;
int i;
if (!(np->features & FE_ISTAT1) || !(INB(np, nc_istat1) & SCRUN))
goto do_chip_reset;
OUTB(np, nc_istat, CABRT);
for (i = 100000 ; i ; --i) {
istat = INB(np, nc_istat);
if (istat & SIP) {
INW(np, nc_sist);
}
else if (istat & DIP) {
if (INB(np, nc_dstat) & ABRT)
break;
}
udelay(5);
}
OUTB(np, nc_istat, 0);
if (!i)
printf("%s: unable to abort current chip operation, "
"ISTAT=0x%02x.\n", sym_name(np), istat);
do_chip_reset:
sym_chip_reset(np);
}
/*
* Start reset process.
*
* The interrupt handler will reinitialize the chip.
*/
static void sym_start_reset(struct sym_hcb *np)
{
sym_reset_scsi_bus(np, 1);
}
int sym_reset_scsi_bus(struct sym_hcb *np, int enab_int)
{
u32 term;
int retv = 0;
sym_soft_reset(np); /* Soft reset the chip */
if (enab_int)
OUTW(np, nc_sien, RST);
/*
* Enable Tolerant, reset IRQD if present and
* properly set IRQ mode, prior to resetting the bus.
*/
OUTB(np, nc_stest3, TE);
OUTB(np, nc_dcntl, (np->rv_dcntl & IRQM));
OUTB(np, nc_scntl1, CRST);
INB(np, nc_mbox1);
udelay(200);
if (!SYM_SETUP_SCSI_BUS_CHECK)
goto out;
/*
* Check for no terminators or SCSI bus shorts to ground.
* Read SCSI data bus, data parity bits and control signals.
* We are expecting RESET to be TRUE and other signals to be
* FALSE.
*/
term = INB(np, nc_sstat0);
term = ((term & 2) << 7) + ((term & 1) << 17); /* rst sdp0 */
term |= ((INB(np, nc_sstat2) & 0x01) << 26) | /* sdp1 */
((INW(np, nc_sbdl) & 0xff) << 9) | /* d7-0 */
((INW(np, nc_sbdl) & 0xff00) << 10) | /* d15-8 */
INB(np, nc_sbcl); /* req ack bsy sel atn msg cd io */
if (!np->maxwide)
term &= 0x3ffff;
if (term != (2<<7)) {
printf("%s: suspicious SCSI data while resetting the BUS.\n",
sym_name(np));
printf("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
"0x%lx, expecting 0x%lx\n",
sym_name(np),
(np->features & FE_WIDE) ? "dp1,d15-8," : "",
(u_long)term, (u_long)(2<<7));
if (SYM_SETUP_SCSI_BUS_CHECK == 1)
retv = 1;
}
out:
OUTB(np, nc_scntl1, 0);
return retv;
}
/*
* Select SCSI clock frequency
*/
static void sym_selectclock(struct sym_hcb *np, u_char scntl3)
{
/*
* If multiplier not present or not selected, leave here.
*/
if (np->multiplier <= 1) {
OUTB(np, nc_scntl3, scntl3);
return;
}
if (sym_verbose >= 2)
printf ("%s: enabling clock multiplier\n", sym_name(np));
OUTB(np, nc_stest1, DBLEN); /* Enable clock multiplier */
/*
* Wait for the LCKFRQ bit to be set if supported by the chip.
* Otherwise wait 50 micro-seconds (at least).
*/
if (np->features & FE_LCKFRQ) {
int i = 20;
while (!(INB(np, nc_stest4) & LCKFRQ) && --i > 0)
udelay(20);
if (!i)
printf("%s: the chip cannot lock the frequency\n",
sym_name(np));
} else {
INB(np, nc_mbox1);
udelay(50+10);
}
OUTB(np, nc_stest3, HSC); /* Halt the scsi clock */
OUTB(np, nc_scntl3, scntl3);
OUTB(np, nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier */
OUTB(np, nc_stest3, 0x00); /* Restart scsi clock */
}
/*
* Determine the chip's clock frequency.
*
* This is essential for the negotiation of the synchronous
* transfer rate.
*
* Note: we have to return the correct value.
* THERE IS NO SAFE DEFAULT VALUE.
*
* Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
* 53C860 and 53C875 rev. 1 support fast20 transfers but
* do not have a clock doubler and so are provided with a
* 80 MHz clock. All other fast20 boards incorporate a doubler
* and so should be delivered with a 40 MHz clock.
* The recent fast40 chips (895/896/895A/1010) use a 40 Mhz base
* clock and provide a clock quadrupler (160 Mhz).
*/
/*
* calculate SCSI clock frequency (in KHz)
*/
static unsigned getfreq (struct sym_hcb *np, int gen)
{
unsigned int ms = 0;
unsigned int f;
/*
* Measure GEN timer delay in order
* to calculate SCSI clock frequency
*
* This code will never execute too
* many loop iterations (if DELAY is
* reasonably correct). It could get
* too low a delay (too high a freq.)
* if the CPU is slow executing the
* loop for some reason (an NMI, for
* example). For this reason we will
* if multiple measurements are to be
* performed trust the higher delay
* (lower frequency returned).
*/
OUTW(np, nc_sien, 0); /* mask all scsi interrupts */
INW(np, nc_sist); /* clear pending scsi interrupt */
OUTB(np, nc_dien, 0); /* mask all dma interrupts */
INW(np, nc_sist); /* another one, just to be sure :) */
/*
* The C1010-33 core does not report GEN in SIST,
* if this interrupt is masked in SIEN.
* I don't know yet if the C1010-66 behaves the same way.
*/
if (np->features & FE_C10) {
OUTW(np, nc_sien, GEN);
OUTB(np, nc_istat1, SIRQD);
}
OUTB(np, nc_scntl3, 4); /* set pre-scaler to divide by 3 */
OUTB(np, nc_stime1, 0); /* disable general purpose timer */
OUTB(np, nc_stime1, gen); /* set to nominal delay of 1<<gen * 125us */
while (!(INW(np, nc_sist) & GEN) && ms++ < 100000)
udelay(1000/4); /* count in 1/4 of ms */
OUTB(np, nc_stime1, 0); /* disable general purpose timer */
/*
* Undo C1010-33 specific settings.
*/
if (np->features & FE_C10) {
OUTW(np, nc_sien, 0);
OUTB(np, nc_istat1, 0);
}
/*
* set prescaler to divide by whatever 0 means
* 0 ought to choose divide by 2, but appears
* to set divide by 3.5 mode in my 53c810 ...
*/
OUTB(np, nc_scntl3, 0);
/*
* adjust for prescaler, and convert into KHz
*/
f = ms ? ((1 << gen) * (4340*4)) / ms : 0;
/*
* The C1010-33 result is biased by a factor
* of 2/3 compared to earlier chips.
*/
if (np->features & FE_C10)
f = (f * 2) / 3;
if (sym_verbose >= 2)
printf ("%s: Delay (GEN=%d): %u msec, %u KHz\n",
sym_name(np), gen, ms/4, f);
return f;
}
static unsigned sym_getfreq (struct sym_hcb *np)
{
u_int f1, f2;
int gen = 8;
getfreq (np, gen); /* throw away first result */
f1 = getfreq (np, gen);
f2 = getfreq (np, gen);
if (f1 > f2) f1 = f2; /* trust lower result */
return f1;
}
/*
* Get/probe chip SCSI clock frequency
*/
static void sym_getclock (struct sym_hcb *np, int mult)
{
unsigned char scntl3 = np->sv_scntl3;
unsigned char stest1 = np->sv_stest1;
unsigned f1;
np->multiplier = 1;
f1 = 40000;
/*
* True with 875/895/896/895A with clock multiplier selected
*/
if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
if (sym_verbose >= 2)
printf ("%s: clock multiplier found\n", sym_name(np));
np->multiplier = mult;
}
/*
* If multiplier not found or scntl3 not 7,5,3,
* reset chip and get frequency from general purpose timer.
* Otherwise trust scntl3 BIOS setting.
*/
if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
OUTB(np, nc_stest1, 0); /* make sure doubler is OFF */
f1 = sym_getfreq (np);
if (sym_verbose)
printf ("%s: chip clock is %uKHz\n", sym_name(np), f1);
if (f1 < 45000) f1 = 40000;
else if (f1 < 55000) f1 = 50000;
else f1 = 80000;
if (f1 < 80000 && mult > 1) {
if (sym_verbose >= 2)
printf ("%s: clock multiplier assumed\n",
sym_name(np));
np->multiplier = mult;
}
} else {
if ((scntl3 & 7) == 3) f1 = 40000;
else if ((scntl3 & 7) == 5) f1 = 80000;
else f1 = 160000;
f1 /= np->multiplier;
}
/*
* Compute controller synchronous parameters.
*/
f1 *= np->multiplier;
np->clock_khz = f1;
}
/*
* Get/probe PCI clock frequency
*/
static int sym_getpciclock (struct sym_hcb *np)
{
int f = 0;
/*
* For now, we only need to know about the actual
* PCI BUS clock frequency for C1010-66 chips.
*/
#if 1
if (np->features & FE_66MHZ) {
#else
if (1) {
#endif
OUTB(np, nc_stest1, SCLK); /* Use the PCI clock as SCSI clock */
f = sym_getfreq(np);
OUTB(np, nc_stest1, 0);
}
np->pciclk_khz = f;
return f;
}
/*
* SYMBIOS chip clock divisor table.
*
* Divisors are multiplied by 10,000,000 in order to make
* calculations more simple.
*/
#define _5M 5000000
static const u32 div_10M[] = {2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
/*
* Get clock factor and sync divisor for a given
* synchronous factor period.
*/
static int
sym_getsync(struct sym_hcb *np, u_char dt, u_char sfac, u_char *divp, u_char *fakp)
{
u32 clk = np->clock_khz; /* SCSI clock frequency in kHz */
int div = np->clock_divn; /* Number of divisors supported */
u32 fak; /* Sync factor in sxfer */
u32 per; /* Period in tenths of ns */
u32 kpc; /* (per * clk) */
int ret;
/*
* Compute the synchronous period in tenths of nano-seconds
*/
if (dt && sfac <= 9) per = 125;
else if (sfac <= 10) per = 250;
else if (sfac == 11) per = 303;
else if (sfac == 12) per = 500;
else per = 40 * sfac;
ret = per;
kpc = per * clk;
if (dt)
kpc <<= 1;
/*
* For earliest C10 revision 0, we cannot use extra
* clocks for the setting of the SCSI clocking.
* Note that this limits the lowest sync data transfer
* to 5 Mega-transfers per second and may result in
* using higher clock divisors.
*/
#if 1
if ((np->features & (FE_C10|FE_U3EN)) == FE_C10) {
/*
* Look for the lowest clock divisor that allows an
* output speed not faster than the period.
*/
while (div > 0) {
--div;
if (kpc > (div_10M[div] << 2)) {
++div;
break;
}
}
fak = 0; /* No extra clocks */
if (div == np->clock_divn) { /* Are we too fast ? */
ret = -1;
}
*divp = div;
*fakp = fak;
return ret;
}
#endif
/*
* Look for the greatest clock divisor that allows an
* input speed faster than the period.
*/
while (div-- > 0)
if (kpc >= (div_10M[div] << 2)) break;
/*
* Calculate the lowest clock factor that allows an output
* speed not faster than the period, and the max output speed.
* If fak >= 1 we will set both XCLKH_ST and XCLKH_DT.
* If fak >= 2 we will also set XCLKS_ST and XCLKS_DT.
*/
if (dt) {
fak = (kpc - 1) / (div_10M[div] << 1) + 1 - 2;
/* ret = ((2+fak)*div_10M[div])/np->clock_khz; */
} else {
fak = (kpc - 1) / div_10M[div] + 1 - 4;
/* ret = ((4+fak)*div_10M[div])/np->clock_khz; */
}
/*
* Check against our hardware limits, or bugs :).
*/
if (fak > 2) {
fak = 2;
ret = -1;
}
/*
* Compute and return sync parameters.
*/
*divp = div;
*fakp = fak;
return ret;
}
/*
* SYMBIOS chips allow burst lengths of 2, 4, 8, 16, 32, 64,
* 128 transfers. All chips support at least 16 transfers
* bursts. The 825A, 875 and 895 chips support bursts of up
* to 128 transfers and the 895A and 896 support bursts of up
* to 64 transfers. All other chips support up to 16
* transfers bursts.
*
* For PCI 32 bit data transfers each transfer is a DWORD.
* It is a QUADWORD (8 bytes) for PCI 64 bit data transfers.
*
* We use log base 2 (burst length) as internal code, with
* value 0 meaning "burst disabled".
*/
/*
* Burst length from burst code.
*/
#define burst_length(bc) (!(bc))? 0 : 1 << (bc)
/*
* Burst code from io register bits.
*/
#define burst_code(dmode, ctest4, ctest5) \
(ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
/*
* Set initial io register bits from burst code.
*/
static inline void sym_init_burst(struct sym_hcb *np, u_char bc)
{
np->rv_ctest4 &= ~0x80;
np->rv_dmode &= ~(0x3 << 6);
np->rv_ctest5 &= ~0x4;
if (!bc) {
np->rv_ctest4 |= 0x80;
}
else {
--bc;
np->rv_dmode |= ((bc & 0x3) << 6);
np->rv_ctest5 |= (bc & 0x4);
}
}
/*
* Save initial settings of some IO registers.
* Assumed to have been set by BIOS.
* We cannot reset the chip prior to reading the
* IO registers, since informations will be lost.
* Since the SCRIPTS processor may be running, this
* is not safe on paper, but it seems to work quite
* well. :)
*/
static void sym_save_initial_setting (struct sym_hcb *np)
{
np->sv_scntl0 = INB(np, nc_scntl0) & 0x0a;
np->sv_scntl3 = INB(np, nc_scntl3) & 0x07;
np->sv_dmode = INB(np, nc_dmode) & 0xce;
np->sv_dcntl = INB(np, nc_dcntl) & 0xa8;
np->sv_ctest3 = INB(np, nc_ctest3) & 0x01;
np->sv_ctest4 = INB(np, nc_ctest4) & 0x80;
np->sv_gpcntl = INB(np, nc_gpcntl);
np->sv_stest1 = INB(np, nc_stest1);
np->sv_stest2 = INB(np, nc_stest2) & 0x20;
np->sv_stest4 = INB(np, nc_stest4);
if (np->features & FE_C10) { /* Always large DMA fifo + ultra3 */
np->sv_scntl4 = INB(np, nc_scntl4);
np->sv_ctest5 = INB(np, nc_ctest5) & 0x04;
}
else
np->sv_ctest5 = INB(np, nc_ctest5) & 0x24;
}
/*
* Set SCSI BUS mode.
* - LVD capable chips (895/895A/896/1010) report the current BUS mode
* through the STEST4 IO register.
* - For previous generation chips (825/825A/875), the user has to tell us
* how to check against HVD, since a 100% safe algorithm is not possible.
*/
static void sym_set_bus_mode(struct sym_hcb *np, struct sym_nvram *nvram)
{
if (np->scsi_mode)
return;
np->scsi_mode = SMODE_SE;
if (np->features & (FE_ULTRA2|FE_ULTRA3))
np->scsi_mode = (np->sv_stest4 & SMODE);
else if (np->features & FE_DIFF) {
if (SYM_SETUP_SCSI_DIFF == 1) {
if (np->sv_scntl3) {
if (np->sv_stest2 & 0x20)
np->scsi_mode = SMODE_HVD;
} else if (nvram->type == SYM_SYMBIOS_NVRAM) {
if (!(INB(np, nc_gpreg) & 0x08))
np->scsi_mode = SMODE_HVD;
}
} else if (SYM_SETUP_SCSI_DIFF == 2)
np->scsi_mode = SMODE_HVD;
}
if (np->scsi_mode == SMODE_HVD)
np->rv_stest2 |= 0x20;
}
/*
* Prepare io register values used by sym_start_up()
* according to selected and supported features.
*/
static int sym_prepare_setting(struct Scsi_Host *shost, struct sym_hcb *np, struct sym_nvram *nvram)
{
struct sym_data *sym_data = shost_priv(shost);
struct pci_dev *pdev = sym_data->pdev;
u_char burst_max;
u32 period;
int i;
np->maxwide = (np->features & FE_WIDE) ? 1 : 0;
/*
* Guess the frequency of the chip's clock.
*/
if (np->features & (FE_ULTRA3 | FE_ULTRA2))
np->clock_khz = 160000;
else if (np->features & FE_ULTRA)
np->clock_khz = 80000;
else
np->clock_khz = 40000;
/*
* Get the clock multiplier factor.
*/
if (np->features & FE_QUAD)
np->multiplier = 4;
else if (np->features & FE_DBLR)
np->multiplier = 2;
else
np->multiplier = 1;
/*
* Measure SCSI clock frequency for chips
* it may vary from assumed one.
*/
if (np->features & FE_VARCLK)
sym_getclock(np, np->multiplier);
/*
* Divisor to be used for async (timer pre-scaler).
*/
i = np->clock_divn - 1;
while (--i >= 0) {
if (10ul * SYM_CONF_MIN_ASYNC * np->clock_khz > div_10M[i]) {
++i;
break;
}
}
np->rv_scntl3 = i+1;
/*
* The C1010 uses hardwired divisors for async.
* So, we just throw away, the async. divisor.:-)
*/
if (np->features & FE_C10)
np->rv_scntl3 = 0;
/*
* Minimum synchronous period factor supported by the chip.
* Btw, 'period' is in tenths of nanoseconds.
*/
period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
if (period <= 250) np->minsync = 10;
else if (period <= 303) np->minsync = 11;
else if (period <= 500) np->minsync = 12;
else np->minsync = (period + 40 - 1) / 40;
/*
* Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
*/
if (np->minsync < 25 &&
!(np->features & (FE_ULTRA|FE_ULTRA2|FE_ULTRA3)))
np->minsync = 25;
else if (np->minsync < 12 &&
!(np->features & (FE_ULTRA2|FE_ULTRA3)))
np->minsync = 12;
/*
* Maximum synchronous period factor supported by the chip.
*/
period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
np->maxsync = period > 2540 ? 254 : period / 10;
/*
* If chip is a C1010, guess the sync limits in DT mode.
*/
if ((np->features & (FE_C10|FE_ULTRA3)) == (FE_C10|FE_ULTRA3)) {
if (np->clock_khz == 160000) {
np->minsync_dt = 9;
np->maxsync_dt = 50;
np->maxoffs_dt = nvram->type ? 62 : 31;
}
}
/*
* 64 bit addressing (895A/896/1010) ?
*/
if (np->features & FE_DAC) {
if (!use_dac(np))
np->rv_ccntl1 |= (DDAC);
else if (SYM_CONF_DMA_ADDRESSING_MODE == 1)
np->rv_ccntl1 |= (XTIMOD | EXTIBMV);
else if (SYM_CONF_DMA_ADDRESSING_MODE == 2)
np->rv_ccntl1 |= (0 | EXTIBMV);
}
/*
* Phase mismatch handled by SCRIPTS (895A/896/1010) ?
*/
if (np->features & FE_NOPM)
np->rv_ccntl0 |= (ENPMJ);
/*
* C1010-33 Errata: Part Number:609-039638 (rev. 1) is fixed.
* In dual channel mode, contention occurs if internal cycles
* are used. Disable internal cycles.
*/
if (pdev->device == PCI_DEVICE_ID_LSI_53C1010_33 &&
pdev->revision < 0x1)
np->rv_ccntl0 |= DILS;
/*
* Select burst length (dwords)
*/
burst_max = SYM_SETUP_BURST_ORDER;
if (burst_max == 255)
burst_max = burst_code(np->sv_dmode, np->sv_ctest4,
np->sv_ctest5);
if (burst_max > 7)
burst_max = 7;
if (burst_max > np->maxburst)
burst_max = np->maxburst;
/*
* DEL 352 - 53C810 Rev x11 - Part Number 609-0392140 - ITEM 2.
* This chip and the 860 Rev 1 may wrongly use PCI cache line
* based transactions on LOAD/STORE instructions. So we have
* to prevent these chips from using such PCI transactions in
* this driver. The generic ncr driver that does not use
* LOAD/STORE instructions does not need this work-around.
*/
if ((pdev->device == PCI_DEVICE_ID_NCR_53C810 &&
pdev->revision >= 0x10 && pdev->revision <= 0x11) ||
(pdev->device == PCI_DEVICE_ID_NCR_53C860 &&
pdev->revision <= 0x1))
np->features &= ~(FE_WRIE|FE_ERL|FE_ERMP);
/*
* Select all supported special features.
* If we are using on-board RAM for scripts, prefetch (PFEN)
* does not help, but burst op fetch (BOF) does.
* Disabling PFEN makes sure BOF will be used.
*/
if (np->features & FE_ERL)
np->rv_dmode |= ERL; /* Enable Read Line */
if (np->features & FE_BOF)
np->rv_dmode |= BOF; /* Burst Opcode Fetch */
if (np->features & FE_ERMP)
np->rv_dmode |= ERMP; /* Enable Read Multiple */
#if 1
if ((np->features & FE_PFEN) && !np->ram_ba)
#else
if (np->features & FE_PFEN)
#endif
np->rv_dcntl |= PFEN; /* Prefetch Enable */
if (np->features & FE_CLSE)
np->rv_dcntl |= CLSE; /* Cache Line Size Enable */
if (np->features & FE_WRIE)
np->rv_ctest3 |= WRIE; /* Write and Invalidate */
if (np->features & FE_DFS)
np->rv_ctest5 |= DFS; /* Dma Fifo Size */
/*
* Select some other
*/
np->rv_ctest4 |= MPEE; /* Master parity checking */
np->rv_scntl0 |= 0x0a; /* full arb., ena parity, par->ATN */
/*
* Get parity checking, host ID and verbose mode from NVRAM
*/
np->myaddr = 255;
np->scsi_mode = 0;
sym_nvram_setup_host(shost, np, nvram);
/*
* Get SCSI addr of host adapter (set by bios?).
*/
if (np->myaddr == 255) {
np->myaddr = INB(np, nc_scid) & 0x07;
if (!np->myaddr)
np->myaddr = SYM_SETUP_HOST_ID;
}
/*
* Prepare initial io register bits for burst length
*/
sym_init_burst(np, burst_max);
sym_set_bus_mode(np, nvram);
/*
* Set LED support from SCRIPTS.
* Ignore this feature for boards known to use a
* specific GPIO wiring and for the 895A, 896
* and 1010 that drive the LED directly.
*/
if ((SYM_SETUP_SCSI_LED ||
(nvram->type == SYM_SYMBIOS_NVRAM ||
(nvram->type == SYM_TEKRAM_NVRAM &&
pdev->device == PCI_DEVICE_ID_NCR_53C895))) &&
!(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
np->features |= FE_LED0;
/*
* Set irq mode.
*/
switch(SYM_SETUP_IRQ_MODE & 3) {
case 2:
np->rv_dcntl |= IRQM;
break;
case 1:
np->rv_dcntl |= (np->sv_dcntl & IRQM);
break;
default:
break;
}
/*
* Configure targets according to driver setup.
* If NVRAM present get targets setup from NVRAM.
*/
for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
struct sym_tcb *tp = &np->target[i];
tp->usrflags |= (SYM_DISC_ENABLED | SYM_TAGS_ENABLED);
tp->usrtags = SYM_SETUP_MAX_TAG;
tp->usr_width = np->maxwide;
tp->usr_period = 9;
sym_nvram_setup_target(tp, i, nvram);
if (!tp->usrtags)
tp->usrflags &= ~SYM_TAGS_ENABLED;
}
/*
* Let user know about the settings.
*/
printf("%s: %s, ID %d, Fast-%d, %s, %s\n", sym_name(np),
sym_nvram_type(nvram), np->myaddr,
(np->features & FE_ULTRA3) ? 80 :
(np->features & FE_ULTRA2) ? 40 :
(np->features & FE_ULTRA) ? 20 : 10,
sym_scsi_bus_mode(np->scsi_mode),
(np->rv_scntl0 & 0xa) ? "parity checking" : "NO parity");
/*
* Tell him more on demand.
*/
if (sym_verbose) {
printf("%s: %s IRQ line driver%s\n",
sym_name(np),
np->rv_dcntl & IRQM ? "totem pole" : "open drain",
np->ram_ba ? ", using on-chip SRAM" : "");
printf("%s: using %s firmware.\n", sym_name(np), np->fw_name);
if (np->features & FE_NOPM)
printf("%s: handling phase mismatch from SCRIPTS.\n",
sym_name(np));
}
/*
* And still more.
*/
if (sym_verbose >= 2) {
printf ("%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
"(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
sym_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
printf ("%s: final SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
"(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
sym_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
}
return 0;
}
/*
* Test the pci bus snoop logic :-(
*
* Has to be called with interrupts disabled.
*/
#ifdef CONFIG_SCSI_SYM53C8XX_MMIO
static int sym_regtest(struct sym_hcb *np)
{
register volatile u32 data;
/*
* chip registers may NOT be cached.
* write 0xffffffff to a read only register area,
* and try to read it back.
*/
data = 0xffffffff;
OUTL(np, nc_dstat, data);
data = INL(np, nc_dstat);
#if 1
if (data == 0xffffffff) {
#else
if ((data & 0xe2f0fffd) != 0x02000080) {
#endif
printf ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
(unsigned) data);
return 0x10;
}
return 0;
}
#else
static inline int sym_regtest(struct sym_hcb *np)
{
return 0;
}
#endif
static int sym_snooptest(struct sym_hcb *np)
{
u32 sym_rd, sym_wr, sym_bk, host_rd, host_wr, pc, dstat;
int i, err;
err = sym_regtest(np);
if (err)
return err;
restart_test:
/*
* Enable Master Parity Checking as we intend
* to enable it for normal operations.
*/
OUTB(np, nc_ctest4, (np->rv_ctest4 & MPEE));
/*
* init
*/
pc = SCRIPTZ_BA(np, snooptest);
host_wr = 1;
sym_wr = 2;
/*
* Set memory and register.
*/
np->scratch = cpu_to_scr(host_wr);
OUTL(np, nc_temp, sym_wr);
/*
* Start script (exchange values)
*/
OUTL(np, nc_dsa, np->hcb_ba);
OUTL_DSP(np, pc);
/*
* Wait 'til done (with timeout)
*/
for (i=0; i<SYM_SNOOP_TIMEOUT; i++)
if (INB(np, nc_istat) & (INTF|SIP|DIP))
break;
if (i>=SYM_SNOOP_TIMEOUT) {
printf ("CACHE TEST FAILED: timeout.\n");
return (0x20);
}
/*
* Check for fatal DMA errors.
*/
dstat = INB(np, nc_dstat);
#if 1 /* Band aiding for broken hardwares that fail PCI parity */
if ((dstat & MDPE) && (np->rv_ctest4 & MPEE)) {
printf ("%s: PCI DATA PARITY ERROR DETECTED - "
"DISABLING MASTER DATA PARITY CHECKING.\n",
sym_name(np));
np->rv_ctest4 &= ~MPEE;
goto restart_test;
}
#endif
if (dstat & (MDPE|BF|IID)) {
printf ("CACHE TEST FAILED: DMA error (dstat=0x%02x).", dstat);
return (0x80);
}
/*
* Save termination position.
*/
pc = INL(np, nc_dsp);
/*
* Read memory and register.
*/
host_rd = scr_to_cpu(np->scratch);
sym_rd = INL(np, nc_scratcha);
sym_bk = INL(np, nc_temp);
/*
* Check termination position.
*/
if (pc != SCRIPTZ_BA(np, snoopend)+8) {
printf ("CACHE TEST FAILED: script execution failed.\n");
printf ("start=%08lx, pc=%08lx, end=%08lx\n",
(u_long) SCRIPTZ_BA(np, snooptest), (u_long) pc,
(u_long) SCRIPTZ_BA(np, snoopend) +8);
return (0x40);
}
/*
* Show results.
*/
if (host_wr != sym_rd) {
printf ("CACHE TEST FAILED: host wrote %d, chip read %d.\n",
(int) host_wr, (int) sym_rd);
err |= 1;
}
if (host_rd != sym_wr) {
printf ("CACHE TEST FAILED: chip wrote %d, host read %d.\n",
(int) sym_wr, (int) host_rd);
err |= 2;
}
if (sym_bk != sym_wr) {
printf ("CACHE TEST FAILED: chip wrote %d, read back %d.\n",
(int) sym_wr, (int) sym_bk);
err |= 4;
}
return err;
}
/*
* log message for real hard errors
*
* sym0 targ 0?: ERROR (ds:si) (so-si-sd) (sx/s3/s4) @ name (dsp:dbc).
* reg: r0 r1 r2 r3 r4 r5 r6 ..... rf.
*
* exception register:
* ds: dstat
* si: sist
*
* SCSI bus lines:
* so: control lines as driven by chip.
* si: control lines as seen by chip.
* sd: scsi data lines as seen by chip.
*
* wide/fastmode:
* sx: sxfer (see the manual)
* s3: scntl3 (see the manual)
* s4: scntl4 (see the manual)
*
* current script command:
* dsp: script address (relative to start of script).
* dbc: first word of script command.
*
* First 24 register of the chip:
* r0..rf
*/
static void sym_log_hard_error(struct Scsi_Host *shost, u_short sist, u_char dstat)
{
struct sym_hcb *np = sym_get_hcb(shost);
u32 dsp;
int script_ofs;
int script_size;
char *script_name;
u_char *script_base;
int i;
dsp = INL(np, nc_dsp);
if (dsp > np->scripta_ba &&
dsp <= np->scripta_ba + np->scripta_sz) {
script_ofs = dsp - np->scripta_ba;
script_size = np->scripta_sz;
script_base = (u_char *) np->scripta0;
script_name = "scripta";
}
else if (np->scriptb_ba < dsp &&
dsp <= np->scriptb_ba + np->scriptb_sz) {
script_ofs = dsp - np->scriptb_ba;
script_size = np->scriptb_sz;
script_base = (u_char *) np->scriptb0;
script_name = "scriptb";
} else {
script_ofs = dsp;
script_size = 0;
script_base = NULL;
script_name = "mem";
}
printf ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x/%x) @ (%s %x:%08x).\n",
sym_name(np), (unsigned)INB(np, nc_sdid)&0x0f, dstat, sist,
(unsigned)INB(np, nc_socl), (unsigned)INB(np, nc_sbcl),
(unsigned)INB(np, nc_sbdl), (unsigned)INB(np, nc_sxfer),
(unsigned)INB(np, nc_scntl3),
(np->features & FE_C10) ? (unsigned)INB(np, nc_scntl4) : 0,
script_name, script_ofs, (unsigned)INL(np, nc_dbc));
if (((script_ofs & 3) == 0) &&
(unsigned)script_ofs < script_size) {
printf ("%s: script cmd = %08x\n", sym_name(np),
scr_to_cpu((int) *(u32 *)(script_base + script_ofs)));
}
printf("%s: regdump:", sym_name(np));
for (i = 0; i < 24; i++)
printf(" %02x", (unsigned)INB_OFF(np, i));
printf(".\n");
/*
* PCI BUS error.
*/
if (dstat & (MDPE|BF))
sym_log_bus_error(shost);
}
void sym_dump_registers(struct Scsi_Host *shost)
{
struct sym_hcb *np = sym_get_hcb(shost);
u_short sist;
u_char dstat;
sist = INW(np, nc_sist);
dstat = INB(np, nc_dstat);
sym_log_hard_error(shost, sist, dstat);
}
static struct sym_chip sym_dev_table[] = {
{PCI_DEVICE_ID_NCR_53C810, 0x0f, "810", 4, 8, 4, 64,
FE_ERL}
,
#ifdef SYM_DEBUG_GENERIC_SUPPORT
{PCI_DEVICE_ID_NCR_53C810, 0xff, "810a", 4, 8, 4, 1,
FE_BOF}
,
#else
{PCI_DEVICE_ID_NCR_53C810, 0xff, "810a", 4, 8, 4, 1,
FE_CACHE_SET|FE_LDSTR|FE_PFEN|FE_BOF}
,
#endif
{PCI_DEVICE_ID_NCR_53C815, 0xff, "815", 4, 8, 4, 64,
FE_BOF|FE_ERL}
,
{PCI_DEVICE_ID_NCR_53C825, 0x0f, "825", 6, 8, 4, 64,
FE_WIDE|FE_BOF|FE_ERL|FE_DIFF}
,
{PCI_DEVICE_ID_NCR_53C825, 0xff, "825a", 6, 8, 4, 2,
FE_WIDE|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM|FE_DIFF}
,
{PCI_DEVICE_ID_NCR_53C860, 0xff, "860", 4, 8, 5, 1,
FE_ULTRA|FE_CACHE_SET|FE_BOF|FE_LDSTR|FE_PFEN}
,
{PCI_DEVICE_ID_NCR_53C875, 0x01, "875", 6, 16, 5, 2,
FE_WIDE|FE_ULTRA|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_DIFF|FE_VARCLK}
,
{PCI_DEVICE_ID_NCR_53C875, 0xff, "875", 6, 16, 5, 2,
FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_DIFF|FE_VARCLK}
,
{PCI_DEVICE_ID_NCR_53C875J, 0xff, "875J", 6, 16, 5, 2,
FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_DIFF|FE_VARCLK}
,
{PCI_DEVICE_ID_NCR_53C885, 0xff, "885", 6, 16, 5, 2,
FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_DIFF|FE_VARCLK}
,
#ifdef SYM_DEBUG_GENERIC_SUPPORT
{PCI_DEVICE_ID_NCR_53C895, 0xff, "895", 6, 31, 7, 2,
FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|
FE_RAM|FE_LCKFRQ}
,
#else
{PCI_DEVICE_ID_NCR_53C895, 0xff, "895", 6, 31, 7, 2,
FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_LCKFRQ}
,
#endif
{PCI_DEVICE_ID_NCR_53C896, 0xff, "896", 6, 31, 7, 4,
FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
,
{PCI_DEVICE_ID_LSI_53C895A, 0xff, "895a", 6, 31, 7, 4,
FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_RAM8K|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
,
{PCI_DEVICE_ID_LSI_53C875A, 0xff, "875a", 6, 31, 7, 4,
FE_WIDE|FE_ULTRA|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
,
{PCI_DEVICE_ID_LSI_53C1010_33, 0x00, "1010-33", 6, 31, 7, 8,
FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_CRC|
FE_C10}
,
{PCI_DEVICE_ID_LSI_53C1010_33, 0xff, "1010-33", 6, 31, 7, 8,
FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_CRC|
FE_C10|FE_U3EN}
,
{PCI_DEVICE_ID_LSI_53C1010_66, 0xff, "1010-66", 6, 31, 7, 8,
FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_66MHZ|FE_CRC|
FE_C10|FE_U3EN}
,
{PCI_DEVICE_ID_LSI_53C1510, 0xff, "1510d", 6, 31, 7, 4,
FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
FE_RAM|FE_IO256|FE_LEDC}
};
#define sym_num_devs (ARRAY_SIZE(sym_dev_table))
/*
* Look up the chip table.
*
* Return a pointer to the chip entry if found,
* zero otherwise.
*/
struct sym_chip *
sym_lookup_chip_table (u_short device_id, u_char revision)
{
struct sym_chip *chip;
int i;
for (i = 0; i < sym_num_devs; i++) {
chip = &sym_dev_table[i];
if (device_id != chip->device_id)
continue;
if (revision > chip->revision_id)
continue;
return chip;
}
return NULL;
}
#if SYM_CONF_DMA_ADDRESSING_MODE == 2
/*
* Lookup the 64 bit DMA segments map.
* This is only used if the direct mapping
* has been unsuccessful.
*/
int sym_lookup_dmap(struct sym_hcb *np, u32 h, int s)
{
int i;
if (!use_dac(np))
goto weird;
/* Look up existing mappings */
for (i = SYM_DMAP_SIZE-1; i > 0; i--) {
if (h == np->dmap_bah[i])
return i;
}
/* If direct mapping is free, get it */
if (!np->dmap_bah[s])
goto new;
/* Collision -> lookup free mappings */
for (s = SYM_DMAP_SIZE-1; s > 0; s--) {
if (!np->dmap_bah[s])
goto new;
}
weird:
panic("sym: ran out of 64 bit DMA segment registers");
return -1;
new:
np->dmap_bah[s] = h;
np->dmap_dirty = 1;
return s;
}
/*
* Update IO registers scratch C..R so they will be
* in sync. with queued CCB expectations.
*/
static void sym_update_dmap_regs(struct sym_hcb *np)
{
int o, i;
if (!np->dmap_dirty)
return;
o = offsetof(struct sym_reg, nc_scrx[0]);
for (i = 0; i < SYM_DMAP_SIZE; i++) {
OUTL_OFF(np, o, np->dmap_bah[i]);
o += 4;
}
np->dmap_dirty = 0;
}
#endif
/* Enforce all the fiddly SPI rules and the chip limitations */
static void sym_check_goals(struct sym_hcb *np, struct scsi_target *starget,
struct sym_trans *goal)
{
if (!spi_support_wide(starget))
goal->width = 0;
if (!spi_support_sync(starget)) {
goal->iu = 0;
goal->dt = 0;
goal->qas = 0;
goal->offset = 0;
return;
}
if (spi_support_dt(starget)) {
if (spi_support_dt_only(starget))
goal->dt = 1;
if (goal->offset == 0)
goal->dt = 0;
} else {
goal->dt = 0;
}
/* Some targets fail to properly negotiate DT in SE mode */
if ((np->scsi_mode != SMODE_LVD) || !(np->features & FE_U3EN))
goal->dt = 0;
if (goal->dt) {
/* all DT transfers must be wide */
goal->width = 1;
if (goal->offset > np->maxoffs_dt)
goal->offset = np->maxoffs_dt;
if (goal->period < np->minsync_dt)
goal->period = np->minsync_dt;
if (goal->period > np->maxsync_dt)
goal->period = np->maxsync_dt;
} else {
goal->iu = goal->qas = 0;
if (goal->offset > np->maxoffs)
goal->offset = np->maxoffs;
if (goal->period < np->minsync)
goal->period = np->minsync;
if (goal->period > np->maxsync)
goal->period = np->maxsync;
}
}
/*
* Prepare the next negotiation message if needed.
*
* Fill in the part of message buffer that contains the
* negotiation and the nego_status field of the CCB.
* Returns the size of the message in bytes.
*/
static int sym_prepare_nego(struct sym_hcb *np, struct sym_ccb *cp, u_char *msgptr)
{
struct sym_tcb *tp = &np->target[cp->target];
struct scsi_target *starget = tp->starget;
struct sym_trans *goal = &tp->tgoal;
int msglen = 0;
int nego;
sym_check_goals(np, starget, goal);
/*
* Many devices implement PPR in a buggy way, so only use it if we
* really want to.
*/
if (goal->renego == NS_PPR || (goal->offset &&
(goal->iu || goal->dt || goal->qas || (goal->period < 0xa)))) {
nego = NS_PPR;
} else if (goal->renego == NS_WIDE || goal->width) {
nego = NS_WIDE;
} else if (goal->renego == NS_SYNC || goal->offset) {
nego = NS_SYNC;
} else {
goal->check_nego = 0;
nego = 0;
}
switch (nego) {
case NS_SYNC:
msglen += spi_populate_sync_msg(msgptr + msglen, goal->period,
goal->offset);
break;
case NS_WIDE:
msglen += spi_populate_width_msg(msgptr + msglen, goal->width);
break;
case NS_PPR:
msglen += spi_populate_ppr_msg(msgptr + msglen, goal->period,
goal->offset, goal->width,
(goal->iu ? PPR_OPT_IU : 0) |
(goal->dt ? PPR_OPT_DT : 0) |
(goal->qas ? PPR_OPT_QAS : 0));
break;
}
cp->nego_status = nego;
if (nego) {
tp->nego_cp = cp; /* Keep track a nego will be performed */
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_nego_msg(np, cp->target,
nego == NS_SYNC ? "sync msgout" :
nego == NS_WIDE ? "wide msgout" :
"ppr msgout", msgptr);
}
}
return msglen;
}
/*
* Insert a job into the start queue.
*/
void sym_put_start_queue(struct sym_hcb *np, struct sym_ccb *cp)
{
u_short qidx;
#ifdef SYM_CONF_IARB_SUPPORT
/*
* If the previously queued CCB is not yet done,
* set the IARB hint. The SCRIPTS will go with IARB
* for this job when starting the previous one.
* We leave devices a chance to win arbitration by
* not using more than 'iarb_max' consecutive
* immediate arbitrations.
*/
if (np->last_cp && np->iarb_count < np->iarb_max) {
np->last_cp->host_flags |= HF_HINT_IARB;
++np->iarb_count;
}
else
np->iarb_count = 0;
np->last_cp = cp;
#endif
#if SYM_CONF_DMA_ADDRESSING_MODE == 2
/*
* Make SCRIPTS aware of the 64 bit DMA
* segment registers not being up-to-date.
*/
if (np->dmap_dirty)
cp->host_xflags |= HX_DMAP_DIRTY;
#endif
/*
* Insert first the idle task and then our job.
* The MBs should ensure proper ordering.
*/
qidx = np->squeueput + 2;
if (qidx >= MAX_QUEUE*2) qidx = 0;
np->squeue [qidx] = cpu_to_scr(np->idletask_ba);
MEMORY_WRITE_BARRIER();
np->squeue [np->squeueput] = cpu_to_scr(cp->ccb_ba);
np->squeueput = qidx;
if (DEBUG_FLAGS & DEBUG_QUEUE)
scmd_printk(KERN_DEBUG, cp->cmd, "queuepos=%d\n",
np->squeueput);
/*
* Script processor may be waiting for reselect.
* Wake it up.
*/
MEMORY_WRITE_BARRIER();
OUTB(np, nc_istat, SIGP|np->istat_sem);
}
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
/*
* Start next ready-to-start CCBs.
*/
void sym_start_next_ccbs(struct sym_hcb *np, struct sym_lcb *lp, int maxn)
{
SYM_QUEHEAD *qp;
struct sym_ccb *cp;
/*
* Paranoia, as usual. :-)
*/
assert(!lp->started_tags || !lp->started_no_tag);
/*
* Try to start as many commands as asked by caller.
* Prevent from having both tagged and untagged
* commands queued to the device at the same time.
*/
while (maxn--) {
qp = sym_remque_head(&lp->waiting_ccbq);
if (!qp)
break;
cp = sym_que_entry(qp, struct sym_ccb, link2_ccbq);
if (cp->tag != NO_TAG) {
if (lp->started_no_tag ||
lp->started_tags >= lp->started_max) {
sym_insque_head(qp, &lp->waiting_ccbq);
break;
}
lp->itlq_tbl[cp->tag] = cpu_to_scr(cp->ccb_ba);
lp->head.resel_sa =
cpu_to_scr(SCRIPTA_BA(np, resel_tag));
++lp->started_tags;
} else {
if (lp->started_no_tag || lp->started_tags) {
sym_insque_head(qp, &lp->waiting_ccbq);
break;
}
lp->head.itl_task_sa = cpu_to_scr(cp->ccb_ba);
lp->head.resel_sa =
cpu_to_scr(SCRIPTA_BA(np, resel_no_tag));
++lp->started_no_tag;
}
cp->started = 1;
sym_insque_tail(qp, &lp->started_ccbq);
sym_put_start_queue(np, cp);
}
}
#endif /* SYM_OPT_HANDLE_DEVICE_QUEUEING */
/*
* The chip may have completed jobs. Look at the DONE QUEUE.
*
* On paper, memory read barriers may be needed here to
* prevent out of order LOADs by the CPU from having
* prefetched stale data prior to DMA having occurred.
*/
static int sym_wakeup_done (struct sym_hcb *np)
{
struct sym_ccb *cp;
int i, n;
u32 dsa;
n = 0;
i = np->dqueueget;
/* MEMORY_READ_BARRIER(); */
while (1) {
dsa = scr_to_cpu(np->dqueue[i]);
if (!dsa)
break;
np->dqueue[i] = 0;
if ((i = i+2) >= MAX_QUEUE*2)
i = 0;
cp = sym_ccb_from_dsa(np, dsa);
if (cp) {
MEMORY_READ_BARRIER();
sym_complete_ok (np, cp);
++n;
}
else
printf ("%s: bad DSA (%x) in done queue.\n",
sym_name(np), (u_int) dsa);
}
np->dqueueget = i;
return n;
}
/*
* Complete all CCBs queued to the COMP queue.
*
* These CCBs are assumed:
* - Not to be referenced either by devices or
* SCRIPTS-related queues and datas.
* - To have to be completed with an error condition
* or requeued.
*
* The device queue freeze count is incremented
* for each CCB that does not prevent this.
* This function is called when all CCBs involved
* in error handling/recovery have been reaped.
*/
static void sym_flush_comp_queue(struct sym_hcb *np, int cam_status)
{
SYM_QUEHEAD *qp;
struct sym_ccb *cp;
while ((qp = sym_remque_head(&np->comp_ccbq)) != NULL) {
struct scsi_cmnd *cmd;
cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
/* Leave quiet CCBs waiting for resources */
if (cp->host_status == HS_WAIT)
continue;
cmd = cp->cmd;
if (cam_status)
sym_set_cam_status(cmd, cam_status);
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
if (sym_get_cam_status(cmd) == DID_SOFT_ERROR) {
struct sym_tcb *tp = &np->target[cp->target];
struct sym_lcb *lp = sym_lp(tp, cp->lun);
if (lp) {
sym_remque(&cp->link2_ccbq);
sym_insque_tail(&cp->link2_ccbq,
&lp->waiting_ccbq);
if (cp->started) {
if (cp->tag != NO_TAG)
--lp->started_tags;
else
--lp->started_no_tag;
}
}
cp->started = 0;
continue;
}
#endif
sym_free_ccb(np, cp);
sym_xpt_done(np, cmd);
}
}
/*
* Complete all active CCBs with error.
* Used on CHIP/SCSI RESET.
*/
static void sym_flush_busy_queue (struct sym_hcb *np, int cam_status)
{
/*
* Move all active CCBs to the COMP queue
* and flush this queue.
*/
sym_que_splice(&np->busy_ccbq, &np->comp_ccbq);
sym_que_init(&np->busy_ccbq);
sym_flush_comp_queue(np, cam_status);
}
/*
* Start chip.
*
* 'reason' means:
* 0: initialisation.
* 1: SCSI BUS RESET delivered or received.
* 2: SCSI BUS MODE changed.
*/
void sym_start_up(struct Scsi_Host *shost, int reason)
{
struct sym_data *sym_data = shost_priv(shost);
struct pci_dev *pdev = sym_data->pdev;
struct sym_hcb *np = sym_data->ncb;
int i;
u32 phys;
/*
* Reset chip if asked, otherwise just clear fifos.
*/
if (reason == 1)
sym_soft_reset(np);
else {
OUTB(np, nc_stest3, TE|CSF);
OUTONB(np, nc_ctest3, CLF);
}
/*
* Clear Start Queue
*/
phys = np->squeue_ba;
for (i = 0; i < MAX_QUEUE*2; i += 2) {
np->squeue[i] = cpu_to_scr(np->idletask_ba);
np->squeue[i+1] = cpu_to_scr(phys + (i+2)*4);
}
np->squeue[MAX_QUEUE*2-1] = cpu_to_scr(phys);
/*
* Start at first entry.
*/
np->squeueput = 0;
/*
* Clear Done Queue
*/
phys = np->dqueue_ba;
for (i = 0; i < MAX_QUEUE*2; i += 2) {
np->dqueue[i] = 0;
np->dqueue[i+1] = cpu_to_scr(phys + (i+2)*4);
}
np->dqueue[MAX_QUEUE*2-1] = cpu_to_scr(phys);
/*
* Start at first entry.
*/
np->dqueueget = 0;
/*
* Install patches in scripts.
* This also let point to first position the start
* and done queue pointers used from SCRIPTS.
*/
np->fw_patch(shost);
/*
* Wakeup all pending jobs.
*/
sym_flush_busy_queue(np, DID_RESET);
/*
* Init chip.
*/
OUTB(np, nc_istat, 0x00); /* Remove Reset, abort */
INB(np, nc_mbox1);
udelay(2000); /* The 895 needs time for the bus mode to settle */
OUTB(np, nc_scntl0, np->rv_scntl0 | 0xc0);
/* full arb., ena parity, par->ATN */
OUTB(np, nc_scntl1, 0x00); /* odd parity, and remove CRST!! */
sym_selectclock(np, np->rv_scntl3); /* Select SCSI clock */
OUTB(np, nc_scid , RRE|np->myaddr); /* Adapter SCSI address */
OUTW(np, nc_respid, 1ul<<np->myaddr); /* Id to respond to */
OUTB(np, nc_istat , SIGP ); /* Signal Process */
OUTB(np, nc_dmode , np->rv_dmode); /* Burst length, dma mode */
OUTB(np, nc_ctest5, np->rv_ctest5); /* Large fifo + large burst */
OUTB(np, nc_dcntl , NOCOM|np->rv_dcntl); /* Protect SFBR */
OUTB(np, nc_ctest3, np->rv_ctest3); /* Write and invalidate */
OUTB(np, nc_ctest4, np->rv_ctest4); /* Master parity checking */
/* Extended Sreq/Sack filtering not supported on the C10 */
if (np->features & FE_C10)
OUTB(np, nc_stest2, np->rv_stest2);
else
OUTB(np, nc_stest2, EXT|np->rv_stest2);
OUTB(np, nc_stest3, TE); /* TolerANT enable */
OUTB(np, nc_stime0, 0x0c); /* HTH disabled STO 0.25 sec */
/*
* For now, disable AIP generation on C1010-66.
*/
if (pdev->device == PCI_DEVICE_ID_LSI_53C1010_66)
OUTB(np, nc_aipcntl1, DISAIP);
/*
* C10101 rev. 0 errata.
* Errant SGE's when in narrow. Write bits 4 & 5 of
* STEST1 register to disable SGE. We probably should do
* that from SCRIPTS for each selection/reselection, but
* I just don't want. :)
*/
if (pdev->device == PCI_DEVICE_ID_LSI_53C1010_33 &&
pdev->revision < 1)
OUTB(np, nc_stest1, INB(np, nc_stest1) | 0x30);
/*
* DEL 441 - 53C876 Rev 5 - Part Number 609-0392787/2788 - ITEM 2.
* Disable overlapped arbitration for some dual function devices,
* regardless revision id (kind of post-chip-design feature. ;-))
*/
if (pdev->device == PCI_DEVICE_ID_NCR_53C875)
OUTB(np, nc_ctest0, (1<<5));
else if (pdev->device == PCI_DEVICE_ID_NCR_53C896)
np->rv_ccntl0 |= DPR;
/*
* Write CCNTL0/CCNTL1 for chips capable of 64 bit addressing
* and/or hardware phase mismatch, since only such chips
* seem to support those IO registers.
*/
if (np->features & (FE_DAC|FE_NOPM)) {
OUTB(np, nc_ccntl0, np->rv_ccntl0);
OUTB(np, nc_ccntl1, np->rv_ccntl1);
}
#if SYM_CONF_DMA_ADDRESSING_MODE == 2
/*
* Set up scratch C and DRS IO registers to map the 32 bit
* DMA address range our data structures are located in.
*/
if (use_dac(np)) {
np->dmap_bah[0] = 0; /* ??? */
OUTL(np, nc_scrx[0], np->dmap_bah[0]);
OUTL(np, nc_drs, np->dmap_bah[0]);
}
#endif
/*
* If phase mismatch handled by scripts (895A/896/1010),
* set PM jump addresses.
*/
if (np->features & FE_NOPM) {
OUTL(np, nc_pmjad1, SCRIPTB_BA(np, pm_handle));
OUTL(np, nc_pmjad2, SCRIPTB_BA(np, pm_handle));
}
/*
* Enable GPIO0 pin for writing if LED support from SCRIPTS.
* Also set GPIO5 and clear GPIO6 if hardware LED control.
*/
if (np->features & FE_LED0)
OUTB(np, nc_gpcntl, INB(np, nc_gpcntl) & ~0x01);
else if (np->features & FE_LEDC)
OUTB(np, nc_gpcntl, (INB(np, nc_gpcntl) & ~0x41) | 0x20);
/*
* enable ints
*/
OUTW(np, nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
OUTB(np, nc_dien , MDPE|BF|SSI|SIR|IID);
/*
* For 895/6 enable SBMC interrupt and save current SCSI bus mode.
* Try to eat the spurious SBMC interrupt that may occur when
* we reset the chip but not the SCSI BUS (at initialization).
*/
if (np->features & (FE_ULTRA2|FE_ULTRA3)) {
OUTONW(np, nc_sien, SBMC);
if (reason == 0) {
INB(np, nc_mbox1);
mdelay(100);
INW(np, nc_sist);
}
np->scsi_mode = INB(np, nc_stest4) & SMODE;
}
/*
* Fill in target structure.
* Reinitialize usrsync.
* Reinitialize usrwide.
* Prepare sync negotiation according to actual SCSI bus mode.
*/
for (i=0;i<SYM_CONF_MAX_TARGET;i++) {
struct sym_tcb *tp = &np->target[i];
tp->to_reset = 0;
tp->head.sval = 0;
tp->head.wval = np->rv_scntl3;
tp->head.uval = 0;
if (tp->lun0p)
tp->lun0p->to_clear = 0;
if (tp->lunmp) {
int ln;
for (ln = 1; ln < SYM_CONF_MAX_LUN; ln++)
if (tp->lunmp[ln])
tp->lunmp[ln]->to_clear = 0;
}
}
/*
* Download SCSI SCRIPTS to on-chip RAM if present,
* and start script processor.
* We do the download preferently from the CPU.
* For platforms that may not support PCI memory mapping,
* we use simple SCRIPTS that performs MEMORY MOVEs.
*/
phys = SCRIPTA_BA(np, init);
if (np->ram_ba) {
if (sym_verbose >= 2)
printf("%s: Downloading SCSI SCRIPTS.\n", sym_name(np));
memcpy_toio(np->s.ramaddr, np->scripta0, np->scripta_sz);
if (np->features & FE_RAM8K) {
memcpy_toio(np->s.ramaddr + 4096, np->scriptb0, np->scriptb_sz);
phys = scr_to_cpu(np->scr_ram_seg);
OUTL(np, nc_mmws, phys);
OUTL(np, nc_mmrs, phys);
OUTL(np, nc_sfs, phys);
phys = SCRIPTB_BA(np, start64);
}
}
np->istat_sem = 0;
OUTL(np, nc_dsa, np->hcb_ba);
OUTL_DSP(np, phys);
/*
* Notify the XPT about the RESET condition.
*/
if (reason != 0)
sym_xpt_async_bus_reset(np);
}
/*
* Switch trans mode for current job and its target.
*/
static void sym_settrans(struct sym_hcb *np, int target, u_char opts, u_char ofs,
u_char per, u_char wide, u_char div, u_char fak)
{
SYM_QUEHEAD *qp;
u_char sval, wval, uval;
struct sym_tcb *tp = &np->target[target];
assert(target == (INB(np, nc_sdid) & 0x0f));
sval = tp->head.sval;
wval = tp->head.wval;
uval = tp->head.uval;
#if 0
printf("XXXX sval=%x wval=%x uval=%x (%x)\n",
sval, wval, uval, np->rv_scntl3);
#endif
/*
* Set the offset.
*/
if (!(np->features & FE_C10))
sval = (sval & ~0x1f) | ofs;
else
sval = (sval & ~0x3f) | ofs;
/*
* Set the sync divisor and extra clock factor.
*/
if (ofs != 0) {
wval = (wval & ~0x70) | ((div+1) << 4);
if (!(np->features & FE_C10))
sval = (sval & ~0xe0) | (fak << 5);
else {
uval = uval & ~(XCLKH_ST|XCLKH_DT|XCLKS_ST|XCLKS_DT);
if (fak >= 1) uval |= (XCLKH_ST|XCLKH_DT);
if (fak >= 2) uval |= (XCLKS_ST|XCLKS_DT);
}
}
/*
* Set the bus width.
*/
wval = wval & ~EWS;
if (wide != 0)
wval |= EWS;
/*
* Set misc. ultra enable bits.
*/
if (np->features & FE_C10) {
uval = uval & ~(U3EN|AIPCKEN);
if (opts) {
assert(np->features & FE_U3EN);
uval |= U3EN;
}
} else {
wval = wval & ~ULTRA;
if (per <= 12) wval |= ULTRA;
}
/*
* Stop there if sync parameters are unchanged.
*/
if (tp->head.sval == sval &&
tp->head.wval == wval &&
tp->head.uval == uval)
return;
tp->head.sval = sval;
tp->head.wval = wval;
tp->head.uval = uval;
/*
* Disable extended Sreq/Sack filtering if per < 50.
* Not supported on the C1010.
*/
if (per < 50 && !(np->features & FE_C10))
OUTOFFB(np, nc_stest2, EXT);
/*
* set actual value and sync_status
*/
OUTB(np, nc_sxfer, tp->head.sval);
OUTB(np, nc_scntl3, tp->head.wval);
if (np->features & FE_C10) {
OUTB(np, nc_scntl4, tp->head.uval);
}
/*
* patch ALL busy ccbs of this target.
*/
FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
struct sym_ccb *cp;
cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
if (cp->target != target)
continue;
cp->phys.select.sel_scntl3 = tp->head.wval;
cp->phys.select.sel_sxfer = tp->head.sval;
if (np->features & FE_C10) {
cp->phys.select.sel_scntl4 = tp->head.uval;
}
}
}
static void sym_announce_transfer_rate(struct sym_tcb *tp)
{
struct scsi_target *starget = tp->starget;
if (tp->tprint.period != spi_period(starget) ||
tp->tprint.offset != spi_offset(starget) ||
tp->tprint.width != spi_width(starget) ||
tp->tprint.iu != spi_iu(starget) ||
tp->tprint.dt != spi_dt(starget) ||
tp->tprint.qas != spi_qas(starget) ||
!tp->tprint.check_nego) {
tp->tprint.period = spi_period(starget);
tp->tprint.offset = spi_offset(starget);
tp->tprint.width = spi_width(starget);
tp->tprint.iu = spi_iu(starget);
tp->tprint.dt = spi_dt(starget);
tp->tprint.qas = spi_qas(starget);
tp->tprint.check_nego = 1;
spi_display_xfer_agreement(starget);
}
}
/*
* We received a WDTR.
* Let everything be aware of the changes.
*/
static void sym_setwide(struct sym_hcb *np, int target, u_char wide)
{
struct sym_tcb *tp = &np->target[target];
struct scsi_target *starget = tp->starget;
sym_settrans(np, target, 0, 0, 0, wide, 0, 0);
if (wide)
tp->tgoal.renego = NS_WIDE;
else
tp->tgoal.renego = 0;
tp->tgoal.check_nego = 0;
tp->tgoal.width = wide;
spi_offset(starget) = 0;
spi_period(starget) = 0;
spi_width(starget) = wide;
spi_iu(starget) = 0;
spi_dt(starget) = 0;
spi_qas(starget) = 0;
if (sym_verbose >= 3)
sym_announce_transfer_rate(tp);
}
/*
* We received a SDTR.
* Let everything be aware of the changes.
*/
static void
sym_setsync(struct sym_hcb *np, int target,
u_char ofs, u_char per, u_char div, u_char fak)
{
struct sym_tcb *tp = &np->target[target];
struct scsi_target *starget = tp->starget;
u_char wide = (tp->head.wval & EWS) ? BUS_16_BIT : BUS_8_BIT;
sym_settrans(np, target, 0, ofs, per, wide, div, fak);
if (wide)
tp->tgoal.renego = NS_WIDE;
else if (ofs)
tp->tgoal.renego = NS_SYNC;
else
tp->tgoal.renego = 0;
spi_period(starget) = per;
spi_offset(starget) = ofs;
spi_iu(starget) = spi_dt(starget) = spi_qas(starget) = 0;
if (!tp->tgoal.dt && !tp->tgoal.iu && !tp->tgoal.qas) {
tp->tgoal.period = per;
tp->tgoal.offset = ofs;
tp->tgoal.check_nego = 0;
}
sym_announce_transfer_rate(tp);
}
/*
* We received a PPR.
* Let everything be aware of the changes.
*/
static void
sym_setpprot(struct sym_hcb *np, int target, u_char opts, u_char ofs,
u_char per, u_char wide, u_char div, u_char fak)
{
struct sym_tcb *tp = &np->target[target];
struct scsi_target *starget = tp->starget;
sym_settrans(np, target, opts, ofs, per, wide, div, fak);
if (wide || ofs)
tp->tgoal.renego = NS_PPR;
else
tp->tgoal.renego = 0;
spi_width(starget) = tp->tgoal.width = wide;
spi_period(starget) = tp->tgoal.period = per;
spi_offset(starget) = tp->tgoal.offset = ofs;
spi_iu(starget) = tp->tgoal.iu = !!(opts & PPR_OPT_IU);
spi_dt(starget) = tp->tgoal.dt = !!(opts & PPR_OPT_DT);
spi_qas(starget) = tp->tgoal.qas = !!(opts & PPR_OPT_QAS);
tp->tgoal.check_nego = 0;
sym_announce_transfer_rate(tp);
}
/*
* generic recovery from scsi interrupt
*
* The doc says that when the chip gets an SCSI interrupt,
* it tries to stop in an orderly fashion, by completing
* an instruction fetch that had started or by flushing
* the DMA fifo for a write to memory that was executing.
* Such a fashion is not enough to know if the instruction
* that was just before the current DSP value has been
* executed or not.
*
* There are some small SCRIPTS sections that deal with
* the start queue and the done queue that may break any
* assomption from the C code if we are interrupted
* inside, so we reset if this happens. Btw, since these
* SCRIPTS sections are executed while the SCRIPTS hasn't
* started SCSI operations, it is very unlikely to happen.
*
* All the driver data structures are supposed to be
* allocated from the same 4 GB memory window, so there
* is a 1 to 1 relationship between DSA and driver data
* structures. Since we are careful :) to invalidate the
* DSA when we complete a command or when the SCRIPTS
* pushes a DSA into a queue, we can trust it when it
* points to a CCB.
*/
static void sym_recover_scsi_int (struct sym_hcb *np, u_char hsts)
{
u32 dsp = INL(np, nc_dsp);
u32 dsa = INL(np, nc_dsa);
struct sym_ccb *cp = sym_ccb_from_dsa(np, dsa);
/*
* If we haven't been interrupted inside the SCRIPTS
* critical pathes, we can safely restart the SCRIPTS
* and trust the DSA value if it matches a CCB.
*/
if ((!(dsp > SCRIPTA_BA(np, getjob_begin) &&
dsp < SCRIPTA_BA(np, getjob_end) + 1)) &&
(!(dsp > SCRIPTA_BA(np, ungetjob) &&
dsp < SCRIPTA_BA(np, reselect) + 1)) &&
(!(dsp > SCRIPTB_BA(np, sel_for_abort) &&
dsp < SCRIPTB_BA(np, sel_for_abort_1) + 1)) &&
(!(dsp > SCRIPTA_BA(np, done) &&
dsp < SCRIPTA_BA(np, done_end) + 1))) {
OUTB(np, nc_ctest3, np->rv_ctest3 | CLF); /* clear dma fifo */
OUTB(np, nc_stest3, TE|CSF); /* clear scsi fifo */
/*
* If we have a CCB, let the SCRIPTS call us back for
* the handling of the error with SCRATCHA filled with
* STARTPOS. This way, we will be able to freeze the
* device queue and requeue awaiting IOs.
*/
if (cp) {
cp->host_status = hsts;
OUTL_DSP(np, SCRIPTA_BA(np, complete_error));
}
/*
* Otherwise just restart the SCRIPTS.
*/
else {
OUTL(np, nc_dsa, 0xffffff);
OUTL_DSP(np, SCRIPTA_BA(np, start));
}
}
else
goto reset_all;
return;
reset_all:
sym_start_reset(np);
}
/*
* chip exception handler for selection timeout
*/
static void sym_int_sto (struct sym_hcb *np)
{
u32 dsp = INL(np, nc_dsp);
if (DEBUG_FLAGS & DEBUG_TINY) printf ("T");
if (dsp == SCRIPTA_BA(np, wf_sel_done) + 8)
sym_recover_scsi_int(np, HS_SEL_TIMEOUT);
else
sym_start_reset(np);
}
/*
* chip exception handler for unexpected disconnect
*/
static void sym_int_udc (struct sym_hcb *np)
{
printf ("%s: unexpected disconnect\n", sym_name(np));
sym_recover_scsi_int(np, HS_UNEXPECTED);
}
/*
* chip exception handler for SCSI bus mode change
*
* spi2-r12 11.2.3 says a transceiver mode change must
* generate a reset event and a device that detects a reset
* event shall initiate a hard reset. It says also that a
* device that detects a mode change shall set data transfer
* mode to eight bit asynchronous, etc...
* So, just reinitializing all except chip should be enough.
*/
static void sym_int_sbmc(struct Scsi_Host *shost)
{
struct sym_hcb *np = sym_get_hcb(shost);
u_char scsi_mode = INB(np, nc_stest4) & SMODE;
/*
* Notify user.
*/
printf("%s: SCSI BUS mode change from %s to %s.\n", sym_name(np),
sym_scsi_bus_mode(np->scsi_mode), sym_scsi_bus_mode(scsi_mode));
/*
* Should suspend command processing for a few seconds and
* reinitialize all except the chip.
*/
sym_start_up(shost, 2);
}
/*
* chip exception handler for SCSI parity error.
*
* When the chip detects a SCSI parity error and is
* currently executing a (CH)MOV instruction, it does
* not interrupt immediately, but tries to finish the
* transfer of the current scatter entry before
* interrupting. The following situations may occur:
*
* - The complete scatter entry has been transferred
* without the device having changed phase.
* The chip will then interrupt with the DSP pointing
* to the instruction that follows the MOV.
*
* - A phase mismatch occurs before the MOV finished
* and phase errors are to be handled by the C code.
* The chip will then interrupt with both PAR and MA
* conditions set.
*
* - A phase mismatch occurs before the MOV finished and
* phase errors are to be handled by SCRIPTS.
* The chip will load the DSP with the phase mismatch
* JUMP address and interrupt the host processor.
*/
static void sym_int_par (struct sym_hcb *np, u_short sist)
{
u_char hsts = INB(np, HS_PRT);
u32 dsp = INL(np, nc_dsp);
u32 dbc = INL(np, nc_dbc);
u32 dsa = INL(np, nc_dsa);
u_char sbcl = INB(np, nc_sbcl);
u_char cmd = dbc >> 24;
int phase = cmd & 7;
struct sym_ccb *cp = sym_ccb_from_dsa(np, dsa);
if (printk_ratelimit())
printf("%s: SCSI parity error detected: SCR1=%d DBC=%x SBCL=%x\n",
sym_name(np), hsts, dbc, sbcl);
/*
* Check that the chip is connected to the SCSI BUS.
*/
if (!(INB(np, nc_scntl1) & ISCON)) {
sym_recover_scsi_int(np, HS_UNEXPECTED);
return;
}
/*
* If the nexus is not clearly identified, reset the bus.
* We will try to do better later.
*/
if (!cp)
goto reset_all;
/*
* Check instruction was a MOV, direction was INPUT and
* ATN is asserted.
*/
if ((cmd & 0xc0) || !(phase & 1) || !(sbcl & 0x8))
goto reset_all;
/*
* Keep track of the parity error.
*/
OUTONB(np, HF_PRT, HF_EXT_ERR);
cp->xerr_status |= XE_PARITY_ERR;
/*
* Prepare the message to send to the device.
*/
np->msgout[0] = (phase == 7) ? M_PARITY : M_ID_ERROR;
/*
* If the old phase was DATA IN phase, we have to deal with
* the 3 situations described above.
* For other input phases (MSG IN and STATUS), the device
* must resend the whole thing that failed parity checking
* or signal error. So, jumping to dispatcher should be OK.
*/
if (phase == 1 || phase == 5) {
/* Phase mismatch handled by SCRIPTS */
if (dsp == SCRIPTB_BA(np, pm_handle))
OUTL_DSP(np, dsp);
/* Phase mismatch handled by the C code */
else if (sist & MA)
sym_int_ma (np);
/* No phase mismatch occurred */
else {
sym_set_script_dp (np, cp, dsp);
OUTL_DSP(np, SCRIPTA_BA(np, dispatch));
}
}
else if (phase == 7) /* We definitely cannot handle parity errors */
#if 1 /* in message-in phase due to the relection */
goto reset_all; /* path and various message anticipations. */
#else
OUTL_DSP(np, SCRIPTA_BA(np, clrack));
#endif
else
OUTL_DSP(np, SCRIPTA_BA(np, dispatch));
return;
reset_all:
sym_start_reset(np);
return;
}
/*
* chip exception handler for phase errors.
*
* We have to construct a new transfer descriptor,
* to transfer the rest of the current block.
*/
static void sym_int_ma (struct sym_hcb *np)
{
u32 dbc;
u32 rest;
u32 dsp;
u32 dsa;
u32 nxtdsp;
u32 *vdsp;
u32 oadr, olen;
u32 *tblp;
u32 newcmd;
u_int delta;
u_char cmd;
u_char hflags, hflags0;
struct sym_pmc *pm;
struct sym_ccb *cp;
dsp = INL(np, nc_dsp);
dbc = INL(np, nc_dbc);
dsa = INL(np, nc_dsa);
cmd = dbc >> 24;
rest = dbc & 0xffffff;
delta = 0;
/*
* locate matching cp if any.
*/
cp = sym_ccb_from_dsa(np, dsa);
/*
* Donnot take into account dma fifo and various buffers in
* INPUT phase since the chip flushes everything before
* raising the MA interrupt for interrupted INPUT phases.
* For DATA IN phase, we will check for the SWIDE later.
*/
if ((cmd & 7) != 1 && (cmd & 7) != 5) {
u_char ss0, ss2;
if (np->features & FE_DFBC)
delta = INW(np, nc_dfbc);
else {
u32 dfifo;
/*
* Read DFIFO, CTEST[4-6] using 1 PCI bus ownership.
*/
dfifo = INL(np, nc_dfifo);
/*
* Calculate remaining bytes in DMA fifo.
* (CTEST5 = dfifo >> 16)
*/
if (dfifo & (DFS << 16))
delta = ((((dfifo >> 8) & 0x300) |
(dfifo & 0xff)) - rest) & 0x3ff;
else
delta = ((dfifo & 0xff) - rest) & 0x7f;
}
/*
* The data in the dma fifo has not been transferred to
* the target -> add the amount to the rest
* and clear the data.
* Check the sstat2 register in case of wide transfer.
*/
rest += delta;
ss0 = INB(np, nc_sstat0);
if (ss0 & OLF) rest++;
if (!(np->features & FE_C10))
if (ss0 & ORF) rest++;
if (cp && (cp->phys.select.sel_scntl3 & EWS)) {
ss2 = INB(np, nc_sstat2);
if (ss2 & OLF1) rest++;
if (!(np->features & FE_C10))
if (ss2 & ORF1) rest++;
}
/*
* Clear fifos.
*/
OUTB(np, nc_ctest3, np->rv_ctest3 | CLF); /* dma fifo */
OUTB(np, nc_stest3, TE|CSF); /* scsi fifo */
}
/*
* log the information
*/
if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
printf ("P%x%x RL=%d D=%d ", cmd&7, INB(np, nc_sbcl)&7,
(unsigned) rest, (unsigned) delta);
/*
* try to find the interrupted script command,
* and the address at which to continue.
*/
vdsp = NULL;
nxtdsp = 0;
if (dsp > np->scripta_ba &&
dsp <= np->scripta_ba + np->scripta_sz) {
vdsp = (u32 *)((char*)np->scripta0 + (dsp-np->scripta_ba-8));
nxtdsp = dsp;
}
else if (dsp > np->scriptb_ba &&
dsp <= np->scriptb_ba + np->scriptb_sz) {
vdsp = (u32 *)((char*)np->scriptb0 + (dsp-np->scriptb_ba-8));
nxtdsp = dsp;
}
/*
* log the information
*/
if (DEBUG_FLAGS & DEBUG_PHASE) {
printf ("\nCP=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
cp, (unsigned)dsp, (unsigned)nxtdsp, vdsp, cmd);
}
if (!vdsp) {
printf ("%s: interrupted SCRIPT address not found.\n",
sym_name (np));
goto reset_all;
}
if (!cp) {
printf ("%s: SCSI phase error fixup: CCB already dequeued.\n",
sym_name (np));
goto reset_all;
}
/*
* get old startaddress and old length.
*/
oadr = scr_to_cpu(vdsp[1]);
if (cmd & 0x10) { /* Table indirect */
tblp = (u32 *) ((char*) &cp->phys + oadr);
olen = scr_to_cpu(tblp[0]);
oadr = scr_to_cpu(tblp[1]);
} else {
tblp = (u32 *) 0;
olen = scr_to_cpu(vdsp[0]) & 0xffffff;
}
if (DEBUG_FLAGS & DEBUG_PHASE) {
printf ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
(unsigned) (scr_to_cpu(vdsp[0]) >> 24),
tblp,
(unsigned) olen,
(unsigned) oadr);
}
/*
* check cmd against assumed interrupted script command.
* If dt data phase, the MOVE instruction hasn't bit 4 of
* the phase.
*/
if (((cmd & 2) ? cmd : (cmd & ~4)) != (scr_to_cpu(vdsp[0]) >> 24)) {
sym_print_addr(cp->cmd,
"internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
cmd, scr_to_cpu(vdsp[0]) >> 24);
goto reset_all;
}
/*
* if old phase not dataphase, leave here.
*/
if (cmd & 2) {
sym_print_addr(cp->cmd,
"phase change %x-%x %d@%08x resid=%d.\n",
cmd&7, INB(np, nc_sbcl)&7, (unsigned)olen,
(unsigned)oadr, (unsigned)rest);
goto unexpected_phase;
}
/*
* Choose the correct PM save area.
*
* Look at the PM_SAVE SCRIPT if you want to understand
* this stuff. The equivalent code is implemented in
* SCRIPTS for the 895A, 896 and 1010 that are able to
* handle PM from the SCRIPTS processor.
*/
hflags0 = INB(np, HF_PRT);
hflags = hflags0;
if (hflags & (HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED)) {
if (hflags & HF_IN_PM0)
nxtdsp = scr_to_cpu(cp->phys.pm0.ret);
else if (hflags & HF_IN_PM1)
nxtdsp = scr_to_cpu(cp->phys.pm1.ret);
if (hflags & HF_DP_SAVED)
hflags ^= HF_ACT_PM;
}
if (!(hflags & HF_ACT_PM)) {
pm = &cp->phys.pm0;
newcmd = SCRIPTA_BA(np, pm0_data);
}
else {
pm = &cp->phys.pm1;
newcmd = SCRIPTA_BA(np, pm1_data);
}
hflags &= ~(HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED);
if (hflags != hflags0)
OUTB(np, HF_PRT, hflags);
/*
* fillin the phase mismatch context
*/
pm->sg.addr = cpu_to_scr(oadr + olen - rest);
pm->sg.size = cpu_to_scr(rest);
pm->ret = cpu_to_scr(nxtdsp);
/*
* If we have a SWIDE,
* - prepare the address to write the SWIDE from SCRIPTS,
* - compute the SCRIPTS address to restart from,
* - move current data pointer context by one byte.
*/
nxtdsp = SCRIPTA_BA(np, dispatch);
if ((cmd & 7) == 1 && cp && (cp->phys.select.sel_scntl3 & EWS) &&
(INB(np, nc_scntl2) & WSR)) {
u32 tmp;
/*
* Set up the table indirect for the MOVE
* of the residual byte and adjust the data
* pointer context.
*/
tmp = scr_to_cpu(pm->sg.addr);
cp->phys.wresid.addr = cpu_to_scr(tmp);
pm->sg.addr = cpu_to_scr(tmp + 1);
tmp = scr_to_cpu(pm->sg.size);
cp->phys.wresid.size = cpu_to_scr((tmp&0xff000000) | 1);
pm->sg.size = cpu_to_scr(tmp - 1);
/*
* If only the residual byte is to be moved,
* no PM context is needed.
*/
if ((tmp&0xffffff) == 1)
newcmd = pm->ret;
/*
* Prepare the address of SCRIPTS that will
* move the residual byte to memory.
*/
nxtdsp = SCRIPTB_BA(np, wsr_ma_helper);
}
if (DEBUG_FLAGS & DEBUG_PHASE) {
sym_print_addr(cp->cmd, "PM %x %x %x / %x %x %x.\n",
hflags0, hflags, newcmd,
(unsigned)scr_to_cpu(pm->sg.addr),
(unsigned)scr_to_cpu(pm->sg.size),
(unsigned)scr_to_cpu(pm->ret));
}
/*
* Restart the SCRIPTS processor.
*/
sym_set_script_dp (np, cp, newcmd);
OUTL_DSP(np, nxtdsp);
return;
/*
* Unexpected phase changes that occurs when the current phase
* is not a DATA IN or DATA OUT phase are due to error conditions.
* Such event may only happen when the SCRIPTS is using a
* multibyte SCSI MOVE.
*
* Phase change Some possible cause
*
* COMMAND --> MSG IN SCSI parity error detected by target.
* COMMAND --> STATUS Bad command or refused by target.
* MSG OUT --> MSG IN Message rejected by target.
* MSG OUT --> COMMAND Bogus target that discards extended
* negotiation messages.
*
* The code below does not care of the new phase and so
* trusts the target. Why to annoy it ?
* If the interrupted phase is COMMAND phase, we restart at
* dispatcher.
* If a target does not get all the messages after selection,
* the code assumes blindly that the target discards extended
* messages and clears the negotiation status.
* If the target does not want all our response to negotiation,
* we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids
* bloat for such a should_not_happen situation).
* In all other situation, we reset the BUS.
* Are these assumptions reasonable ? (Wait and see ...)
*/
unexpected_phase:
dsp -= 8;
nxtdsp = 0;
switch (cmd & 7) {
case 2: /* COMMAND phase */
nxtdsp = SCRIPTA_BA(np, dispatch);
break;
#if 0
case 3: /* STATUS phase */
nxtdsp = SCRIPTA_BA(np, dispatch);
break;
#endif
case 6: /* MSG OUT phase */
/*
* If the device may want to use untagged when we want
* tagged, we prepare an IDENTIFY without disc. granted,
* since we will not be able to handle reselect.
* Otherwise, we just don't care.
*/
if (dsp == SCRIPTA_BA(np, send_ident)) {
if (cp->tag != NO_TAG && olen - rest <= 3) {
cp->host_status = HS_BUSY;
np->msgout[0] = IDENTIFY(0, cp->lun);
nxtdsp = SCRIPTB_BA(np, ident_break_atn);
}
else
nxtdsp = SCRIPTB_BA(np, ident_break);
}
else if (dsp == SCRIPTB_BA(np, send_wdtr) ||
dsp == SCRIPTB_BA(np, send_sdtr) ||
dsp == SCRIPTB_BA(np, send_ppr)) {
nxtdsp = SCRIPTB_BA(np, nego_bad_phase);
if (dsp == SCRIPTB_BA(np, send_ppr)) {
struct scsi_device *dev = cp->cmd->device;
dev->ppr = 0;
}
}
break;
#if 0
case 7: /* MSG IN phase */
nxtdsp = SCRIPTA_BA(np, clrack);
break;
#endif
}
if (nxtdsp) {
OUTL_DSP(np, nxtdsp);
return;
}
reset_all:
sym_start_reset(np);
}
/*
* chip interrupt handler
*
* In normal situations, interrupt conditions occur one at
* a time. But when something bad happens on the SCSI BUS,
* the chip may raise several interrupt flags before
* stopping and interrupting the CPU. The additionnal
* interrupt flags are stacked in some extra registers
* after the SIP and/or DIP flag has been raised in the
* ISTAT. After the CPU has read the interrupt condition
* flag from SIST or DSTAT, the chip unstacks the other
* interrupt flags and sets the corresponding bits in
* SIST or DSTAT. Since the chip starts stacking once the
* SIP or DIP flag is set, there is a small window of time
* where the stacking does not occur.
*
* Typically, multiple interrupt conditions may happen in
* the following situations:
*
* - SCSI parity error + Phase mismatch (PAR|MA)
* When an parity error is detected in input phase
* and the device switches to msg-in phase inside a
* block MOV.
* - SCSI parity error + Unexpected disconnect (PAR|UDC)
* When a stupid device does not want to handle the
* recovery of an SCSI parity error.
* - Some combinations of STO, PAR, UDC, ...
* When using non compliant SCSI stuff, when user is
* doing non compliant hot tampering on the BUS, when
* something really bad happens to a device, etc ...
*
* The heuristic suggested by SYMBIOS to handle
* multiple interrupts is to try unstacking all
* interrupts conditions and to handle them on some
* priority based on error severity.
* This will work when the unstacking has been
* successful, but we cannot be 100 % sure of that,
* since the CPU may have been faster to unstack than
* the chip is able to stack. Hmmm ... But it seems that
* such a situation is very unlikely to happen.
*
* If this happen, for example STO caught by the CPU
* then UDC happenning before the CPU have restarted
* the SCRIPTS, the driver may wrongly complete the
* same command on UDC, since the SCRIPTS didn't restart
* and the DSA still points to the same command.
* We avoid this situation by setting the DSA to an
* invalid value when the CCB is completed and before
* restarting the SCRIPTS.
*
* Another issue is that we need some section of our
* recovery procedures to be somehow uninterruptible but
* the SCRIPTS processor does not provides such a
* feature. For this reason, we handle recovery preferently
* from the C code and check against some SCRIPTS critical
* sections from the C code.
*
* Hopefully, the interrupt handling of the driver is now
* able to resist to weird BUS error conditions, but donnot
* ask me for any guarantee that it will never fail. :-)
* Use at your own decision and risk.
*/
irqreturn_t sym_interrupt(struct Scsi_Host *shost)
{
struct sym_data *sym_data = shost_priv(shost);
struct sym_hcb *np = sym_data->ncb;
struct pci_dev *pdev = sym_data->pdev;
u_char istat, istatc;
u_char dstat;
u_short sist;
/*
* interrupt on the fly ?
* (SCRIPTS may still be running)
*
* A `dummy read' is needed to ensure that the
* clear of the INTF flag reaches the device
* and that posted writes are flushed to memory
* before the scanning of the DONE queue.
* Note that SCRIPTS also (dummy) read to memory
* prior to deliver the INTF interrupt condition.
*/
istat = INB(np, nc_istat);
if (istat & INTF) {
OUTB(np, nc_istat, (istat & SIGP) | INTF | np->istat_sem);
istat |= INB(np, nc_istat); /* DUMMY READ */
if (DEBUG_FLAGS & DEBUG_TINY) printf ("F ");
sym_wakeup_done(np);
}
if (!(istat & (SIP|DIP)))
return (istat & INTF) ? IRQ_HANDLED : IRQ_NONE;
#if 0 /* We should never get this one */
if (istat & CABRT)
OUTB(np, nc_istat, CABRT);
#endif
/*
* PAR and MA interrupts may occur at the same time,
* and we need to know of both in order to handle
* this situation properly. We try to unstack SCSI
* interrupts for that reason. BTW, I dislike a LOT
* such a loop inside the interrupt routine.
* Even if DMA interrupt stacking is very unlikely to
* happen, we also try unstacking these ones, since
* this has no performance impact.
*/
sist = 0;
dstat = 0;
istatc = istat;
do {
if (istatc & SIP)
sist |= INW(np, nc_sist);
if (istatc & DIP)
dstat |= INB(np, nc_dstat);
istatc = INB(np, nc_istat);
istat |= istatc;
/* Prevent deadlock waiting on a condition that may
* never clear. */
if (unlikely(sist == 0xffff && dstat == 0xff)) {
if (pci_channel_offline(pdev))
return IRQ_NONE;
}
} while (istatc & (SIP|DIP));
if (DEBUG_FLAGS & DEBUG_TINY)
printf ("<%d|%x:%x|%x:%x>",
(int)INB(np, nc_scr0),
dstat,sist,
(unsigned)INL(np, nc_dsp),
(unsigned)INL(np, nc_dbc));
/*
* On paper, a memory read barrier may be needed here to
* prevent out of order LOADs by the CPU from having
* prefetched stale data prior to DMA having occurred.
* And since we are paranoid ... :)
*/
MEMORY_READ_BARRIER();
/*
* First, interrupts we want to service cleanly.
*
* Phase mismatch (MA) is the most frequent interrupt
* for chip earlier than the 896 and so we have to service
* it as quickly as possible.
* A SCSI parity error (PAR) may be combined with a phase
* mismatch condition (MA).
* Programmed interrupts (SIR) are used to call the C code
* from SCRIPTS.
* The single step interrupt (SSI) is not used in this
* driver.
*/
if (!(sist & (STO|GEN|HTH|SGE|UDC|SBMC|RST)) &&
!(dstat & (MDPE|BF|ABRT|IID))) {
if (sist & PAR) sym_int_par (np, sist);
else if (sist & MA) sym_int_ma (np);
else if (dstat & SIR) sym_int_sir(np);
else if (dstat & SSI) OUTONB_STD();
else goto unknown_int;
return IRQ_HANDLED;
}
/*
* Now, interrupts that donnot happen in normal
* situations and that we may need to recover from.
*
* On SCSI RESET (RST), we reset everything.
* On SCSI BUS MODE CHANGE (SBMC), we complete all
* active CCBs with RESET status, prepare all devices
* for negotiating again and restart the SCRIPTS.
* On STO and UDC, we complete the CCB with the corres-
* ponding status and restart the SCRIPTS.
*/
if (sist & RST) {
printf("%s: SCSI BUS reset detected.\n", sym_name(np));
sym_start_up(shost, 1);
return IRQ_HANDLED;
}
OUTB(np, nc_ctest3, np->rv_ctest3 | CLF); /* clear dma fifo */
OUTB(np, nc_stest3, TE|CSF); /* clear scsi fifo */
if (!(sist & (GEN|HTH|SGE)) &&
!(dstat & (MDPE|BF|ABRT|IID))) {
if (sist & SBMC) sym_int_sbmc(shost);
else if (sist & STO) sym_int_sto (np);
else if (sist & UDC) sym_int_udc (np);
else goto unknown_int;
return IRQ_HANDLED;
}
/*
* Now, interrupts we are not able to recover cleanly.
*
* Log message for hard errors.
* Reset everything.
*/
sym_log_hard_error(shost, sist, dstat);
if ((sist & (GEN|HTH|SGE)) ||
(dstat & (MDPE|BF|ABRT|IID))) {
sym_start_reset(np);
return IRQ_HANDLED;
}
unknown_int:
/*
* We just miss the cause of the interrupt. :(
* Print a message. The timeout will do the real work.
*/
printf( "%s: unknown interrupt(s) ignored, "
"ISTAT=0x%x DSTAT=0x%x SIST=0x%x\n",
sym_name(np), istat, dstat, sist);
return IRQ_NONE;
}
/*
* Dequeue from the START queue all CCBs that match
* a given target/lun/task condition (-1 means all),
* and move them from the BUSY queue to the COMP queue
* with DID_SOFT_ERROR status condition.
* This function is used during error handling/recovery.
* It is called with SCRIPTS not running.
*/
static int
sym_dequeue_from_squeue(struct sym_hcb *np, int i, int target, int lun, int task)
{
int j;
struct sym_ccb *cp;
/*
* Make sure the starting index is within range.
*/
assert((i >= 0) && (i < 2*MAX_QUEUE));
/*
* Walk until end of START queue and dequeue every job
* that matches the target/lun/task condition.
*/
j = i;
while (i != np->squeueput) {
cp = sym_ccb_from_dsa(np, scr_to_cpu(np->squeue[i]));
assert(cp);
#ifdef SYM_CONF_IARB_SUPPORT
/* Forget hints for IARB, they may be no longer relevant */
cp->host_flags &= ~HF_HINT_IARB;
#endif
if ((target == -1 || cp->target == target) &&
(lun == -1 || cp->lun == lun) &&
(task == -1 || cp->tag == task)) {
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
sym_set_cam_status(cp->cmd, DID_SOFT_ERROR);
#else
sym_set_cam_status(cp->cmd, DID_REQUEUE);
#endif
sym_remque(&cp->link_ccbq);
sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
}
else {
if (i != j)
np->squeue[j] = np->squeue[i];
if ((j += 2) >= MAX_QUEUE*2) j = 0;
}
if ((i += 2) >= MAX_QUEUE*2) i = 0;
}
if (i != j) /* Copy back the idle task if needed */
np->squeue[j] = np->squeue[i];
np->squeueput = j; /* Update our current start queue pointer */
return (i - j) / 2;
}
/*
* chip handler for bad SCSI status condition
*
* In case of bad SCSI status, we unqueue all the tasks
* currently queued to the controller but not yet started
* and then restart the SCRIPTS processor immediately.
*
* QUEUE FULL and BUSY conditions are handled the same way.
* Basically all the not yet started tasks are requeued in
* device queue and the queue is frozen until a completion.
*
* For CHECK CONDITION and COMMAND TERMINATED status, we use
* the CCB of the failed command to prepare a REQUEST SENSE
* SCSI command and queue it to the controller queue.
*
* SCRATCHA is assumed to have been loaded with STARTPOS
* before the SCRIPTS called the C code.
*/
static void sym_sir_bad_scsi_status(struct sym_hcb *np, int num, struct sym_ccb *cp)
{
u32 startp;
u_char s_status = cp->ssss_status;
u_char h_flags = cp->host_flags;
int msglen;
int i;
/*
* Compute the index of the next job to start from SCRIPTS.
*/
i = (INL(np, nc_scratcha) - np->squeue_ba) / 4;
/*
* The last CCB queued used for IARB hint may be
* no longer relevant. Forget it.
*/
#ifdef SYM_CONF_IARB_SUPPORT
if (np->last_cp)
np->last_cp = 0;
#endif
/*
* Now deal with the SCSI status.
*/
switch(s_status) {
case S_BUSY:
case S_QUEUE_FULL:
if (sym_verbose >= 2) {
sym_print_addr(cp->cmd, "%s\n",
s_status == S_BUSY ? "BUSY" : "QUEUE FULL\n");
}
default: /* S_INT, S_INT_COND_MET, S_CONFLICT */
sym_complete_error (np, cp);
break;
case S_TERMINATED:
case S_CHECK_COND:
/*
* If we get an SCSI error when requesting sense, give up.
*/
if (h_flags & HF_SENSE) {
sym_complete_error (np, cp);
break;
}
/*
* Dequeue all queued CCBs for that device not yet started,
* and restart the SCRIPTS processor immediately.
*/
sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
OUTL_DSP(np, SCRIPTA_BA(np, start));
/*
* Save some info of the actual IO.
* Compute the data residual.
*/
cp->sv_scsi_status = cp->ssss_status;
cp->sv_xerr_status = cp->xerr_status;
cp->sv_resid = sym_compute_residual(np, cp);
/*
* Prepare all needed data structures for
* requesting sense data.
*/
cp->scsi_smsg2[0] = IDENTIFY(0, cp->lun);
msglen = 1;
/*
* If we are currently using anything different from
* async. 8 bit data transfers with that target,
* start a negotiation, since the device may want
* to report us a UNIT ATTENTION condition due to
* a cause we currently ignore, and we donnot want
* to be stuck with WIDE and/or SYNC data transfer.
*
* cp->nego_status is filled by sym_prepare_nego().
*/
cp->nego_status = 0;
msglen += sym_prepare_nego(np, cp, &cp->scsi_smsg2[msglen]);
/*
* Message table indirect structure.
*/
cp->phys.smsg.addr = CCB_BA(cp, scsi_smsg2);
cp->phys.smsg.size = cpu_to_scr(msglen);
/*
* sense command
*/
cp->phys.cmd.addr = CCB_BA(cp, sensecmd);
cp->phys.cmd.size = cpu_to_scr(6);
/*
* patch requested size into sense command
*/
cp->sensecmd[0] = REQUEST_SENSE;
cp->sensecmd[1] = 0;
if (cp->cmd->device->scsi_level <= SCSI_2 && cp->lun <= 7)
cp->sensecmd[1] = cp->lun << 5;
cp->sensecmd[4] = SYM_SNS_BBUF_LEN;
cp->data_len = SYM_SNS_BBUF_LEN;
/*
* sense data
*/
memset(cp->sns_bbuf, 0, SYM_SNS_BBUF_LEN);
cp->phys.sense.addr = CCB_BA(cp, sns_bbuf);
cp->phys.sense.size = cpu_to_scr(SYM_SNS_BBUF_LEN);
/*
* requeue the command.
*/
startp = SCRIPTB_BA(np, sdata_in);
cp->phys.head.savep = cpu_to_scr(startp);
cp->phys.head.lastp = cpu_to_scr(startp);
cp->startp = cpu_to_scr(startp);
cp->goalp = cpu_to_scr(startp + 16);
cp->host_xflags = 0;
cp->host_status = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
cp->ssss_status = S_ILLEGAL;
cp->host_flags = (HF_SENSE|HF_DATA_IN);
cp->xerr_status = 0;
cp->extra_bytes = 0;
cp->phys.head.go.start = cpu_to_scr(SCRIPTA_BA(np, select));
/*
* Requeue the command.
*/
sym_put_start_queue(np, cp);
/*
* Give back to upper layer everything we have dequeued.
*/
sym_flush_comp_queue(np, 0);
break;
}
}
/*
* After a device has accepted some management message
* as BUS DEVICE RESET, ABORT TASK, etc ..., or when
* a device signals a UNIT ATTENTION condition, some
* tasks are thrown away by the device. We are required
* to reflect that on our tasks list since the device
* will never complete these tasks.
*
* This function move from the BUSY queue to the COMP
* queue all disconnected CCBs for a given target that
* match the following criteria:
* - lun=-1 means any logical UNIT otherwise a given one.
* - task=-1 means any task, otherwise a given one.
*/
int sym_clear_tasks(struct sym_hcb *np, int cam_status, int target, int lun, int task)
{
SYM_QUEHEAD qtmp, *qp;
int i = 0;
struct sym_ccb *cp;
/*
* Move the entire BUSY queue to our temporary queue.
*/
sym_que_init(&qtmp);
sym_que_splice(&np->busy_ccbq, &qtmp);
sym_que_init(&np->busy_ccbq);
/*
* Put all CCBs that matches our criteria into
* the COMP queue and put back other ones into
* the BUSY queue.
*/
while ((qp = sym_remque_head(&qtmp)) != NULL) {
struct scsi_cmnd *cmd;
cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
cmd = cp->cmd;
if (cp->host_status != HS_DISCONNECT ||
cp->target != target ||
(lun != -1 && cp->lun != lun) ||
(task != -1 &&
(cp->tag != NO_TAG && cp->scsi_smsg[2] != task))) {
sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
continue;
}
sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
/* Preserve the software timeout condition */
if (sym_get_cam_status(cmd) != DID_TIME_OUT)
sym_set_cam_status(cmd, cam_status);
++i;
#if 0
printf("XXXX TASK @%p CLEARED\n", cp);
#endif
}
return i;
}
/*
* chip handler for TASKS recovery
*
* We cannot safely abort a command, while the SCRIPTS
* processor is running, since we just would be in race
* with it.
*
* As long as we have tasks to abort, we keep the SEM
* bit set in the ISTAT. When this bit is set, the
* SCRIPTS processor interrupts (SIR_SCRIPT_STOPPED)
* each time it enters the scheduler.
*
* If we have to reset a target, clear tasks of a unit,
* or to perform the abort of a disconnected job, we
* restart the SCRIPTS for selecting the target. Once
* selected, the SCRIPTS interrupts (SIR_TARGET_SELECTED).
* If it loses arbitration, the SCRIPTS will interrupt again
* the next time it will enter its scheduler, and so on ...
*
* On SIR_TARGET_SELECTED, we scan for the more
* appropriate thing to do:
*
* - If nothing, we just sent a M_ABORT message to the
* target to get rid of the useless SCSI bus ownership.
* According to the specs, no tasks shall be affected.
* - If the target is to be reset, we send it a M_RESET
* message.
* - If a logical UNIT is to be cleared , we send the
* IDENTIFY(lun) + M_ABORT.
* - If an untagged task is to be aborted, we send the
* IDENTIFY(lun) + M_ABORT.
* - If a tagged task is to be aborted, we send the
* IDENTIFY(lun) + task attributes + M_ABORT_TAG.
*
* Once our 'kiss of death' :) message has been accepted
* by the target, the SCRIPTS interrupts again
* (SIR_ABORT_SENT). On this interrupt, we complete
* all the CCBs that should have been aborted by the
* target according to our message.
*/
static void sym_sir_task_recovery(struct sym_hcb *np, int num)
{
SYM_QUEHEAD *qp;
struct sym_ccb *cp;
struct sym_tcb *tp = NULL; /* gcc isn't quite smart enough yet */
struct scsi_target *starget;
int target=-1, lun=-1, task;
int i, k;
switch(num) {
/*
* The SCRIPTS processor stopped before starting
* the next command in order to allow us to perform
* some task recovery.
*/
case SIR_SCRIPT_STOPPED:
/*
* Do we have any target to reset or unit to clear ?
*/
for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
tp = &np->target[i];
if (tp->to_reset ||
(tp->lun0p && tp->lun0p->to_clear)) {
target = i;
break;
}
if (!tp->lunmp)
continue;
for (k = 1 ; k < SYM_CONF_MAX_LUN ; k++) {
if (tp->lunmp[k] && tp->lunmp[k]->to_clear) {
target = i;
break;
}
}
if (target != -1)
break;
}
/*
* If not, walk the busy queue for any
* disconnected CCB to be aborted.
*/
if (target == -1) {
FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
cp = sym_que_entry(qp,struct sym_ccb,link_ccbq);
if (cp->host_status != HS_DISCONNECT)
continue;
if (cp->to_abort) {
target = cp->target;
break;
}
}
}
/*
* If some target is to be selected,
* prepare and start the selection.
*/
if (target != -1) {
tp = &np->target[target];
np->abrt_sel.sel_id = target;
np->abrt_sel.sel_scntl3 = tp->head.wval;
np->abrt_sel.sel_sxfer = tp->head.sval;
OUTL(np, nc_dsa, np->hcb_ba);
OUTL_DSP(np, SCRIPTB_BA(np, sel_for_abort));
return;
}
/*
* Now look for a CCB to abort that haven't started yet.
* Btw, the SCRIPTS processor is still stopped, so
* we are not in race.
*/
i = 0;
cp = NULL;
FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
if (cp->host_status != HS_BUSY &&
cp->host_status != HS_NEGOTIATE)
continue;
if (!cp->to_abort)
continue;
#ifdef SYM_CONF_IARB_SUPPORT
/*
* If we are using IMMEDIATE ARBITRATION, we donnot
* want to cancel the last queued CCB, since the
* SCRIPTS may have anticipated the selection.
*/
if (cp == np->last_cp) {
cp->to_abort = 0;
continue;
}
#endif
i = 1; /* Means we have found some */
break;
}
if (!i) {
/*
* We are done, so we donnot need
* to synchronize with the SCRIPTS anylonger.
* Remove the SEM flag from the ISTAT.
*/
np->istat_sem = 0;
OUTB(np, nc_istat, SIGP);
break;
}
/*
* Compute index of next position in the start
* queue the SCRIPTS intends to start and dequeue
* all CCBs for that device that haven't been started.
*/
i = (INL(np, nc_scratcha) - np->squeue_ba) / 4;
i = sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
/*
* Make sure at least our IO to abort has been dequeued.
*/
#ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
assert(i && sym_get_cam_status(cp->cmd) == DID_SOFT_ERROR);
#else
sym_remque(&cp->link_ccbq);
sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
#endif
/*
* Keep track in cam status of the reason of the abort.
*/
if (cp->to_abort == 2)
sym_set_cam_status(cp->cmd, DID_TIME_OUT);
else
sym_set_cam_status(cp->cmd, DID_ABORT);
/*
* Complete with error everything that we have dequeued.
*/
sym_flush_comp_queue(np, 0);
break;
/*
* The SCRIPTS processor has selected a target
* we may have some manual recovery to perform for.
*/
case SIR_TARGET_SELECTED:
target = INB(np, nc_sdid) & 0xf;
tp = &np->target[target];
np->abrt_tbl.addr = cpu_to_scr(vtobus(np->abrt_msg));
/*
* If the target is to be reset, prepare a
* M_RESET message and clear the to_reset flag
* since we donnot expect this operation to fail.
*/
if (tp->to_reset) {
np->abrt_msg[0] = M_RESET;
np->abrt_tbl.size = 1;
tp->to_reset = 0;
break;
}
/*
* Otherwise, look for some logical unit to be cleared.
*/
if (tp->lun0p && tp->lun0p->to_clear)
lun = 0;
else if (tp->lunmp) {
for (k = 1 ; k < SYM_CONF_MAX_LUN ; k++) {
if (tp->lunmp[k] && tp->lunmp[k]->to_clear) {
lun = k;
break;
}
}
}
/*
* If a logical unit is to be cleared, prepare
* an IDENTIFY(lun) + ABORT MESSAGE.
*/
if (lun != -1) {
struct sym_lcb *lp = sym_lp(tp, lun);
lp->to_clear = 0; /* We don't expect to fail here */
np->abrt_msg[0] = IDENTIFY(0, lun);
np->abrt_msg[1] = M_ABORT;
np->abrt_tbl.size = 2;
break;
}
/*
* Otherwise, look for some disconnected job to
* abort for this target.
*/
i = 0;
cp = NULL;
FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
if (cp->host_status != HS_DISCONNECT)
continue;
if (cp->target != target)
continue;
if (!cp->to_abort)
continue;
i = 1; /* Means we have some */
break;
}
/*
* If we have none, probably since the device has
* completed the command before we won abitration,
* send a M_ABORT message without IDENTIFY.
* According to the specs, the device must just
* disconnect the BUS and not abort any task.
*/
if (!i) {
np->abrt_msg[0] = M_ABORT;
np->abrt_tbl.size = 1;
break;
}
/*
* We have some task to abort.
* Set the IDENTIFY(lun)
*/
np->abrt_msg[0] = IDENTIFY(0, cp->lun);
/*
* If we want to abort an untagged command, we
* will send a IDENTIFY + M_ABORT.
* Otherwise (tagged command), we will send
* a IDENTITFY + task attributes + ABORT TAG.
*/
if (cp->tag == NO_TAG) {
np->abrt_msg[1] = M_ABORT;
np->abrt_tbl.size = 2;
} else {
np->abrt_msg[1] = cp->scsi_smsg[1];
np->abrt_msg[2] = cp->scsi_smsg[2];
np->abrt_msg[3] = M_ABORT_TAG;
np->abrt_tbl.size = 4;
}
/*
* Keep track of software timeout condition, since the
* peripheral driver may not count retries on abort
* conditions not due to timeout.
*/
if (cp->to_abort == 2)
sym_set_cam_status(cp->cmd, DID_TIME_OUT);
cp->to_abort = 0; /* We donnot expect to fail here */
break;
/*
* The target has accepted our message and switched
* to BUS FREE phase as we expected.
*/
case SIR_ABORT_SENT:
target = INB(np, nc_sdid) & 0xf;
tp = &np->target[target];
starget = tp->starget;
/*
** If we didn't abort anything, leave here.
*/
if (np->abrt_msg[0] == M_ABORT)
break;
/*
* If we sent a M_RESET, then a hardware reset has
* been performed by the target.
* - Reset everything to async 8 bit
* - Tell ourself to negotiate next time :-)
* - Prepare to clear all disconnected CCBs for
* this target from our task list (lun=task=-1)
*/
lun = -1;
task = -1;
if (np->abrt_msg[0] == M_RESET) {
tp->head.sval = 0;
tp->head.wval = np->rv_scntl3;
tp->head.uval = 0;
spi_period(starget) = 0;
spi_offset(starget) = 0;
spi_width(starget) = 0;
spi_iu(starget) = 0;
spi_dt(starget) = 0;
spi_qas(starget) = 0;
tp->tgoal.check_nego = 1;
tp->tgoal.renego = 0;
}
/*
* Otherwise, check for the LUN and TASK(s)
* concerned by the cancelation.
* If it is not ABORT_TAG then it is CLEAR_QUEUE
* or an ABORT message :-)
*/
else {
lun = np->abrt_msg[0] & 0x3f;
if (np->abrt_msg[1] == M_ABORT_TAG)
task = np->abrt_msg[2];
}
/*
* Complete all the CCBs the device should have
* aborted due to our 'kiss of death' message.
*/
i = (INL(np, nc_scratcha) - np->squeue_ba) / 4;
sym_dequeue_from_squeue(np, i, target, lun, -1);
sym_clear_tasks(np, DID_ABORT, target, lun, task);
sym_flush_comp_queue(np, 0);
/*
* If we sent a BDR, make upper layer aware of that.
*/
if (np->abrt_msg[0] == M_RESET)
starget_printk(KERN_NOTICE, starget,
"has been reset\n");
break;
}
/*
* Print to the log the message we intend to send.
*/
if (num == SIR_TARGET_SELECTED) {
dev_info(&tp->starget->dev, "control msgout:");
sym_printl_hex(np->abrt_msg, np->abrt_tbl.size);
np->abrt_tbl.size = cpu_to_scr(np->abrt_tbl.size);
}
/*
* Let the SCRIPTS processor continue.
*/
OUTONB_STD();
}
/*
* Gerard's alchemy:) that deals with with the data
* pointer for both MDP and the residual calculation.
*
* I didn't want to bloat the code by more than 200
* lines for the handling of both MDP and the residual.
* This has been achieved by using a data pointer
* representation consisting in an index in the data
* array (dp_sg) and a negative offset (dp_ofs) that
* have the following meaning:
*
* - dp_sg = SYM_CONF_MAX_SG
* we are at the end of the data script.
* - dp_sg < SYM_CONF_MAX_SG
* dp_sg points to the next entry of the scatter array
* we want to transfer.
* - dp_ofs < 0
* dp_ofs represents the residual of bytes of the
* previous entry scatter entry we will send first.
* - dp_ofs = 0
* no residual to send first.
*
* The function sym_evaluate_dp() accepts an arbitray
* offset (basically from the MDP message) and returns
* the corresponding values of dp_sg and dp_ofs.
*/
static int sym_evaluate_dp(struct sym_hcb *np, struct sym_ccb *cp, u32 scr, int *ofs)
{
u32 dp_scr;
int dp_ofs, dp_sg, dp_sgmin;
int tmp;
struct sym_pmc *pm;
/*
* Compute the resulted data pointer in term of a script
* address within some DATA script and a signed byte offset.
*/
dp_scr = scr;
dp_ofs = *ofs;
if (dp_scr == SCRIPTA_BA(np, pm0_data))
pm = &cp->phys.pm0;
else if (dp_scr == SCRIPTA_BA(np, pm1_data))
pm = &cp->phys.pm1;
else
pm = NULL;
if (pm) {
dp_scr = scr_to_cpu(pm->ret);
dp_ofs -= scr_to_cpu(pm->sg.size) & 0x00ffffff;
}
/*
* If we are auto-sensing, then we are done.
*/
if (cp->host_flags & HF_SENSE) {
*ofs = dp_ofs;
return 0;
}
/*
* Deduce the index of the sg entry.
* Keep track of the index of the first valid entry.
* If result is dp_sg = SYM_CONF_MAX_SG, then we are at the
* end of the data.
*/
tmp = scr_to_cpu(cp->goalp);
dp_sg = SYM_CONF_MAX_SG;
if (dp_scr != tmp)
dp_sg -= (tmp - 8 - (int)dp_scr) / (2*4);
dp_sgmin = SYM_CONF_MAX_SG - cp->segments;
/*
* Move to the sg entry the data pointer belongs to.
*
* If we are inside the data area, we expect result to be:
*
* Either,
* dp_ofs = 0 and dp_sg is the index of the sg entry
* the data pointer belongs to (or the end of the data)
* Or,
* dp_ofs < 0 and dp_sg is the index of the sg entry
* the data pointer belongs to + 1.
*/
if (dp_ofs < 0) {
int n;
while (dp_sg > dp_sgmin) {
--dp_sg;
tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
n = dp_ofs + (tmp & 0xffffff);
if (n > 0) {
++dp_sg;
break;
}
dp_ofs = n;
}
}
else if (dp_ofs > 0) {
while (dp_sg < SYM_CONF_MAX_SG) {
tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
dp_ofs -= (tmp & 0xffffff);
++dp_sg;
if (dp_ofs <= 0)
break;
}
}
/*
* Make sure the data pointer is inside the data area.
* If not, return some error.
*/
if (dp_sg < dp_sgmin || (dp_sg == dp_sgmin && dp_ofs < 0))
goto out_err;
else if (dp_sg > SYM_CONF_MAX_SG ||
(dp_sg == SYM_CONF_MAX_SG && dp_ofs > 0))
goto out_err;
/*
* Save the extreme pointer if needed.
*/
if (dp_sg > cp->ext_sg ||
(dp_sg == cp->ext_sg && dp_ofs > cp->ext_ofs)) {
cp->ext_sg = dp_sg;
cp->ext_ofs = dp_ofs;
}
/*
* Return data.
*/
*ofs = dp_ofs;
return dp_sg;
out_err:
return -1;
}
/*
* chip handler for MODIFY DATA POINTER MESSAGE
*
* We also call this function on IGNORE WIDE RESIDUE
* messages that do not match a SWIDE full condition.
* Btw, we assume in that situation that such a message
* is equivalent to a MODIFY DATA POINTER (offset=-1).
*/
static void sym_modify_dp(struct sym_hcb *np, struct sym_tcb *tp, struct sym_ccb *cp, int ofs)
{
int dp_ofs = ofs;
u32 dp_scr = sym_get_script_dp (np, cp);
u32 dp_ret;
u32 tmp;
u_char hflags;
int dp_sg;
struct sym_pmc *pm;
/*
* Not supported for auto-sense.
*/
if (cp->host_flags & HF_SENSE)
goto out_reject;
/*
* Apply our alchemy:) (see comments in sym_evaluate_dp()),
* to the resulted data pointer.
*/
dp_sg = sym_evaluate_dp(np, cp, dp_scr, &dp_ofs);
if (dp_sg < 0)
goto out_reject;
/*
* And our alchemy:) allows to easily calculate the data
* script address we want to return for the next data phase.
*/
dp_ret = cpu_to_scr(cp->goalp);
dp_ret = dp_ret - 8 - (SYM_CONF_MAX_SG - dp_sg) * (2*4);
/*
* If offset / scatter entry is zero we donnot need
* a context for the new current data pointer.
*/
if (dp_ofs == 0) {
dp_scr = dp_ret;
goto out_ok;
}
/*
* Get a context for the new current data pointer.
*/
hflags = INB(np, HF_PRT);
if (hflags & HF_DP_SAVED)
hflags ^= HF_ACT_PM;
if (!(hflags & HF_ACT_PM)) {
pm = &cp->phys.pm0;
dp_scr = SCRIPTA_BA(np, pm0_data);
}
else {
pm = &cp->phys.pm1;
dp_scr = SCRIPTA_BA(np, pm1_data);
}
hflags &= ~(HF_DP_SAVED);
OUTB(np, HF_PRT, hflags);
/*
* Set up the new current data pointer.
* ofs < 0 there, and for the next data phase, we
* want to transfer part of the data of the sg entry
* corresponding to index dp_sg-1 prior to returning
* to the main data script.
*/
pm->ret = cpu_to_scr(dp_ret);
tmp = scr_to_cpu(cp->phys.data[dp_sg-1].addr);
tmp += scr_to_cpu(cp->phys.data[dp_sg-1].size) + dp_ofs;
pm->sg.addr = cpu_to_scr(tmp);
pm->sg.size = cpu_to_scr(-dp_ofs);
out_ok:
sym_set_script_dp (np, cp, dp_scr);
OUTL_DSP(np, SCRIPTA_BA(np, clrack));
return;
out_reject:
OUTL_DSP(np, SCRIPTB_BA(np, msg_bad));
}
/*
* chip calculation of the data residual.
*
* As I used to say, the requirement of data residual
* in SCSI is broken, useless and cannot be achieved
* without huge complexity.
* But most OSes and even the official CAM require it.
* When stupidity happens to be so widely spread inside
* a community, it gets hard to convince.
*
* Anyway, I don't care, since I am not going to use
* any software that considers this data residual as
* a relevant information. :)
*/
int sym_compute_residual(struct sym_hcb *np, struct sym_ccb *cp)
{
int dp_sg, dp_sgmin, resid = 0;
int dp_ofs = 0;
/*
* Check for some data lost or just thrown away.
* We are not required to be quite accurate in this
* situation. Btw, if we are odd for output and the
* device claims some more data, it may well happen
* than our residual be zero. :-)
*/
if (cp->xerr_status & (XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN)) {
if (cp->xerr_status & XE_EXTRA_DATA)
resid -= cp->extra_bytes;
if (cp->xerr_status & XE_SODL_UNRUN)
++resid;
if (cp->xerr_status & XE_SWIDE_OVRUN)
--resid;
}
/*
* If all data has been transferred,
* there is no residual.
*/
if (cp->phys.head.lastp == cp->goalp)
return resid;
/*
* If no data transfer occurs, or if the data
* pointer is weird, return full residual.
*/
if (cp->startp == cp->phys.head.lastp ||
sym_evaluate_dp(np, cp, scr_to_cpu(cp->phys.head.lastp),
&dp_ofs) < 0) {
return cp->data_len - cp->odd_byte_adjustment;
}
/*
* If we were auto-sensing, then we are done.
*/
if (cp->host_flags & HF_SENSE) {
return -dp_ofs;
}
/*
* We are now full comfortable in the computation
* of the data residual (2's complement).
*/
dp_sgmin = SYM_CONF_MAX_SG - cp->segments;
resid = -cp->ext_ofs;
for (dp_sg = cp->ext_sg; dp_sg < SYM_CONF_MAX_SG; ++dp_sg) {
u_int tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
resid += (tmp & 0xffffff);
}
resid -= cp->odd_byte_adjustment;
/*
* Hopefully, the result is not too wrong.
*/
return resid;
}
/*
* Negotiation for WIDE and SYNCHRONOUS DATA TRANSFER.
*
* When we try to negotiate, we append the negotiation message
* to the identify and (maybe) simple tag message.
* The host status field is set to HS_NEGOTIATE to mark this
* situation.
*
* If the target doesn't answer this message immediately
* (as required by the standard), the SIR_NEGO_FAILED interrupt
* will be raised eventually.
* The handler removes the HS_NEGOTIATE status, and sets the
* negotiated value to the default (async / nowide).
*
* If we receive a matching answer immediately, we check it
* for validity, and set the values.
*
* If we receive a Reject message immediately, we assume the
* negotiation has failed, and fall back to standard values.
*
* If we receive a negotiation message while not in HS_NEGOTIATE
* state, it's a target initiated negotiation. We prepare a
* (hopefully) valid answer, set our parameters, and send back
* this answer to the target.
*
* If the target doesn't fetch the answer (no message out phase),
* we assume the negotiation has failed, and fall back to default
* settings (SIR_NEGO_PROTO interrupt).
*
* When we set the values, we adjust them in all ccbs belonging
* to this target, in the controller's register, and in the "phys"
* field of the controller's struct sym_hcb.
*/
/*
* chip handler for SYNCHRONOUS DATA TRANSFER REQUEST (SDTR) message.
*/
static int
sym_sync_nego_check(struct sym_hcb *np, int req, struct sym_ccb *cp)
{
int target = cp->target;
u_char chg, ofs, per, fak, div;
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_nego_msg(np, target, "sync msgin", np->msgin);
}
/*
* Get requested values.
*/
chg = 0;
per = np->msgin[3];
ofs = np->msgin[4];
/*
* Check values against our limits.
*/
if (ofs) {
if (ofs > np->maxoffs)
{chg = 1; ofs = np->maxoffs;}
}
if (ofs) {
if (per < np->minsync)
{chg = 1; per = np->minsync;}
}
/*
* Get new chip synchronous parameters value.
*/
div = fak = 0;
if (ofs && sym_getsync(np, 0, per, &div, &fak) < 0)
goto reject_it;
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_addr(cp->cmd,
"sdtr: ofs=%d per=%d div=%d fak=%d chg=%d.\n",
ofs, per, div, fak, chg);
}
/*
* If it was an answer we want to change,
* then it isn't acceptable. Reject it.
*/
if (!req && chg)
goto reject_it;
/*
* Apply new values.
*/
sym_setsync (np, target, ofs, per, div, fak);
/*
* It was an answer. We are done.
*/
if (!req)
return 0;
/*
* It was a request. Prepare an answer message.
*/
spi_populate_sync_msg(np->msgout, per, ofs);
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_nego_msg(np, target, "sync msgout", np->msgout);
}
np->msgin [0] = M_NOOP;
return 0;
reject_it:
sym_setsync (np, target, 0, 0, 0, 0);
return -1;
}
static void sym_sync_nego(struct sym_hcb *np, struct sym_tcb *tp, struct sym_ccb *cp)
{
int req = 1;
int result;
/*
* Request or answer ?
*/
if (INB(np, HS_PRT) == HS_NEGOTIATE) {
OUTB(np, HS_PRT, HS_BUSY);
if (cp->nego_status && cp->nego_status != NS_SYNC)
goto reject_it;
req = 0;
}
/*
* Check and apply new values.
*/
result = sym_sync_nego_check(np, req, cp);
if (result) /* Not acceptable, reject it */
goto reject_it;
if (req) { /* Was a request, send response. */
cp->nego_status = NS_SYNC;
OUTL_DSP(np, SCRIPTB_BA(np, sdtr_resp));
}
else /* Was a response, we are done. */
OUTL_DSP(np, SCRIPTA_BA(np, clrack));
return;
reject_it:
OUTL_DSP(np, SCRIPTB_BA(np, msg_bad));
}
/*
* chip handler for PARALLEL PROTOCOL REQUEST (PPR) message.
*/
static int
sym_ppr_nego_check(struct sym_hcb *np, int req, int target)
{
struct sym_tcb *tp = &np->target[target];
unsigned char fak, div;
int dt, chg = 0;
unsigned char per = np->msgin[3];
unsigned char ofs = np->msgin[5];
unsigned char wide = np->msgin[6];
unsigned char opts = np->msgin[7] & PPR_OPT_MASK;
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_nego_msg(np, target, "ppr msgin", np->msgin);
}
/*
* Check values against our limits.
*/
if (wide > np->maxwide) {
chg = 1;
wide = np->maxwide;
}
if (!wide || !(np->features & FE_U3EN))
opts = 0;
if (opts != (np->msgin[7] & PPR_OPT_MASK))
chg = 1;
dt = opts & PPR_OPT_DT;
if (ofs) {
unsigned char maxoffs = dt ? np->maxoffs_dt : np->maxoffs;
if (ofs > maxoffs) {
chg = 1;
ofs = maxoffs;
}
}
if (ofs) {
unsigned char minsync = dt ? np->minsync_dt : np->minsync;
if (per < minsync) {
chg = 1;
per = minsync;
}
}
/*
* Get new chip synchronous parameters value.
*/
div = fak = 0;
if (ofs && sym_getsync(np, dt, per, &div, &fak) < 0)
goto reject_it;
/*
* If it was an answer we want to change,
* then it isn't acceptable. Reject it.
*/
if (!req && chg)
goto reject_it;
/*
* Apply new values.
*/
sym_setpprot(np, target, opts, ofs, per, wide, div, fak);
/*
* It was an answer. We are done.
*/
if (!req)
return 0;
/*
* It was a request. Prepare an answer message.
*/
spi_populate_ppr_msg(np->msgout, per, ofs, wide, opts);
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_nego_msg(np, target, "ppr msgout", np->msgout);
}
np->msgin [0] = M_NOOP;
return 0;
reject_it:
sym_setpprot (np, target, 0, 0, 0, 0, 0, 0);
/*
* If it is a device response that should result in
* ST, we may want to try a legacy negotiation later.
*/
if (!req && !opts) {
tp->tgoal.period = per;
tp->tgoal.offset = ofs;
tp->tgoal.width = wide;
tp->tgoal.iu = tp->tgoal.dt = tp->tgoal.qas = 0;
tp->tgoal.check_nego = 1;
}
return -1;
}
static void sym_ppr_nego(struct sym_hcb *np, struct sym_tcb *tp, struct sym_ccb *cp)
{
int req = 1;
int result;
/*
* Request or answer ?
*/
if (INB(np, HS_PRT) == HS_NEGOTIATE) {
OUTB(np, HS_PRT, HS_BUSY);
if (cp->nego_status && cp->nego_status != NS_PPR)
goto reject_it;
req = 0;
}
/*
* Check and apply new values.
*/
result = sym_ppr_nego_check(np, req, cp->target);
if (result) /* Not acceptable, reject it */
goto reject_it;
if (req) { /* Was a request, send response. */
cp->nego_status = NS_PPR;
OUTL_DSP(np, SCRIPTB_BA(np, ppr_resp));
}
else /* Was a response, we are done. */
OUTL_DSP(np, SCRIPTA_BA(np, clrack));
return;
reject_it:
OUTL_DSP(np, SCRIPTB_BA(np, msg_bad));
}
/*
* chip handler for WIDE DATA TRANSFER REQUEST (WDTR) message.
*/
static int
sym_wide_nego_check(struct sym_hcb *np, int req, struct sym_ccb *cp)
{
int target = cp->target;
u_char chg, wide;
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_nego_msg(np, target, "wide msgin", np->msgin);
}
/*
* Get requested values.
*/
chg = 0;
wide = np->msgin[3];
/*
* Check values against our limits.
*/
if (wide > np->maxwide) {
chg = 1;
wide = np->maxwide;
}
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_addr(cp->cmd, "wdtr: wide=%d chg=%d.\n",
wide, chg);
}
/*
* If it was an answer we want to change,
* then it isn't acceptable. Reject it.
*/
if (!req && chg)
goto reject_it;
/*
* Apply new values.
*/
sym_setwide (np, target, wide);
/*
* It was an answer. We are done.
*/
if (!req)
return 0;
/*
* It was a request. Prepare an answer message.
*/
spi_populate_width_msg(np->msgout, wide);
np->msgin [0] = M_NOOP;
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_nego_msg(np, target, "wide msgout", np->msgout);
}
return 0;
reject_it:
return -1;
}
static void sym_wide_nego(struct sym_hcb *np, struct sym_tcb *tp, struct sym_ccb *cp)
{
int req = 1;
int result;
/*
* Request or answer ?
*/
if (INB(np, HS_PRT) == HS_NEGOTIATE) {
OUTB(np, HS_PRT, HS_BUSY);
if (cp->nego_status && cp->nego_status != NS_WIDE)
goto reject_it;
req = 0;
}
/*
* Check and apply new values.
*/
result = sym_wide_nego_check(np, req, cp);
if (result) /* Not acceptable, reject it */
goto reject_it;
if (req) { /* Was a request, send response. */
cp->nego_status = NS_WIDE;
OUTL_DSP(np, SCRIPTB_BA(np, wdtr_resp));
} else { /* Was a response. */
/*
* Negotiate for SYNC immediately after WIDE response.
* This allows to negotiate for both WIDE and SYNC on
* a single SCSI command (Suggested by Justin Gibbs).
*/
if (tp->tgoal.offset) {
spi_populate_sync_msg(np->msgout, tp->tgoal.period,
tp->tgoal.offset);
if (DEBUG_FLAGS & DEBUG_NEGO) {
sym_print_nego_msg(np, cp->target,
"sync msgout", np->msgout);
}
cp->nego_status = NS_SYNC;
OUTB(np, HS_PRT, HS_NEGOTIATE);
OUTL_DSP(np, SCRIPTB_BA(np, sdtr_resp));
return;
} else
OUTL_DSP(np, SCRIPTA_BA(np, clrack));
}
return;
reject_it:
OUTL_DSP(np, SCRIPTB_BA(np, msg_bad));
}
/*
* Reset DT, SYNC or WIDE to default settings.
*
* Called when a negotiation does not succeed either
* on rejection or on protocol error.
*
* A target that understands a PPR message should never
* reject it, and messing with it is very unlikely.
* So, if a PPR makes problems, we may just want to
* try a legacy negotiation later.
*/
static void sym_nego_default(struct sym_hcb *np, struct sym_tcb *tp, struct sym_ccb *cp)
{
switch (cp->nego_status) {
case NS_PPR:
#if 0
sym_setpprot (np, cp->target, 0, 0, 0, 0, 0, 0);
#else
if (tp->tgoal.period < np->minsync)
tp->tgoal.period = np->minsync;
if (tp->tgoal.offset > np->maxoffs)
tp->tgoal.offset = np->maxoffs;
tp->tgoal.iu = tp->tgoal.dt = tp->tgoal.qas = 0;
tp->tgoal.check_nego = 1;
#endif
break;
case NS_SYNC:
sym_setsync (np, cp->target, 0, 0, 0, 0);
break;
case NS_WIDE:
sym_setwide (np, cp->target, 0);
break;
}
np->msgin [0] = M_NOOP;
np->msgout[0] = M_NOOP;
cp->nego_status = 0;
}
/*
* chip handler for MESSAGE REJECT received in response to
* PPR, WIDE or SYNCHRONOUS negotiation.
*/
static void sym_nego_rejected(struct sym_hcb *np, struct sym_tcb *tp, struct sym_ccb *cp)
{
sym_nego_default(np, tp, cp);
OUTB(np, HS_PRT, HS_BUSY);
}
/*
* chip exception handler for programmed interrupts.
*/
static void sym_int_sir(struct sym_hcb *np)
{
u_char num = INB(np, nc_dsps);
u32 dsa = INL(np, nc_dsa);
struct sym_ccb *cp = sym_ccb_from_dsa(np, dsa);
u_char target = INB(np, nc_sdid) & 0x0f;
struct sym_tcb *tp = &np->target[target];
int tmp;
if (DEBUG_FLAGS & DEBUG_TINY) printf ("I#%d", num);
switch (num) {
#if SYM_CONF_DMA_ADDRESSING_MODE == 2
/*
* SCRIPTS tell us that we may have to update
* 64 bit DMA segment registers.
*/
case SIR_DMAP_DIRTY:
sym_update_dmap_regs(np);
goto out;
#endif
/*
* Command has been completed with error condition
* or has been auto-sensed.
*/
case SIR_COMPLETE_ERROR:
sym_complete_error(np, cp);
return;
/*
* The C code is currently trying to recover from something.
* Typically, user want to abort some command.
*/
case SIR_SCRIPT_STOPPED:
case SIR_TARGET_SELECTED:
case SIR_ABORT_SENT:
sym_sir_task_recovery(np, num);
return;
/*
* The device didn't go to MSG OUT phase after having
* been selected with ATN. We do not want to handle that.
*/
case SIR_SEL_ATN_NO_MSG_OUT:
scmd_printk(KERN_WARNING, cp->cmd,
"No MSG OUT phase after selection with ATN\n");
goto out_stuck;
/*
* The device didn't switch to MSG IN phase after
* having reselected the initiator.
*/
case SIR_RESEL_NO_MSG_IN:
scmd_printk(KERN_WARNING, cp->cmd,
"No MSG IN phase after reselection\n");
goto out_stuck;
/*
* After reselection, the device sent a message that wasn't
* an IDENTIFY.
*/
case SIR_RESEL_NO_IDENTIFY:
scmd_printk(KERN_WARNING, cp->cmd,
"No IDENTIFY after reselection\n");
goto out_stuck;
/*
* The device reselected a LUN we do not know about.
*/
case SIR_RESEL_BAD_LUN:
np->msgout[0] = M_RESET;
goto out;
/*
* The device reselected for an untagged nexus and we
* haven't any.
*/
case SIR_RESEL_BAD_I_T_L:
np->msgout[0] = M_ABORT;
goto out;
/*
* The device reselected for a tagged nexus that we do not have.
*/
case SIR_RESEL_BAD_I_T_L_Q:
np->msgout[0] = M_ABORT_TAG;
goto out;
/*
* The SCRIPTS let us know that the device has grabbed
* our message and will abort the job.
*/
case SIR_RESEL_ABORTED:
np->lastmsg = np->msgout[0];
np->msgout[0] = M_NOOP;
scmd_printk(KERN_WARNING, cp->cmd,
"message %x sent on bad reselection\n", np->lastmsg);
goto out;
/*
* The SCRIPTS let us know that a message has been
* successfully sent to the device.
*/
case SIR_MSG_OUT_DONE:
np->lastmsg = np->msgout[0];
np->msgout[0] = M_NOOP;
/* Should we really care of that */
if (np->lastmsg == M_PARITY || np->lastmsg == M_ID_ERROR) {
if (cp) {
cp->xerr_status &= ~XE_PARITY_ERR;
if (!cp->xerr_status)
OUTOFFB(np, HF_PRT, HF_EXT_ERR);
}
}
goto out;
/*
* The device didn't send a GOOD SCSI status.
* We may have some work to do prior to allow
* the SCRIPTS processor to continue.
*/
case SIR_BAD_SCSI_STATUS:
if (!cp)
goto out;
sym_sir_bad_scsi_status(np, num, cp);
return;
/*
* We are asked by the SCRIPTS to prepare a
* REJECT message.
*/
case SIR_REJECT_TO_SEND:
sym_print_msg(cp, "M_REJECT to send for ", np->msgin);
np->msgout[0] = M_REJECT;
goto out;
/*
* We have been ODD at the end of a DATA IN
* transfer and the device didn't send a
* IGNORE WIDE RESIDUE message.
* It is a data overrun condition.
*/
case SIR_SWIDE_OVERRUN:
if (cp) {
OUTONB(np, HF_PRT, HF_EXT_ERR);
cp->xerr_status |= XE_SWIDE_OVRUN;
}
goto out;
/*
* We have been ODD at the end of a DATA OUT
* transfer.
* It is a data underrun condition.
*/
case SIR_SODL_UNDERRUN:
if (cp) {
OUTONB(np, HF_PRT, HF_EXT_ERR);
cp->xerr_status |= XE_SODL_UNRUN;
}
goto out;
/*
* The device wants us to tranfer more data than
* expected or in the wrong direction.
* The number of extra bytes is in scratcha.
* It is a data overrun condition.
*/
case SIR_DATA_OVERRUN:
if (cp) {
OUTONB(np, HF_PRT, HF_EXT_ERR);
cp->xerr_status |= XE_EXTRA_DATA;
cp->extra_bytes += INL(np, nc_scratcha);
}
goto out;
/*
* The device switched to an illegal phase (4/5).
*/
case SIR_BAD_PHASE:
if (cp) {
OUTONB(np, HF_PRT, HF_EXT_ERR);
cp->xerr_status |= XE_BAD_PHASE;
}
goto out;
/*
* We received a message.
*/
case SIR_MSG_RECEIVED:
if (!cp)
goto out_stuck;
switch (np->msgin [0]) {
/*
* We received an extended message.
* We handle MODIFY DATA POINTER, SDTR, WDTR
* and reject all other extended messages.
*/
case M_EXTENDED:
switch (np->msgin [2]) {
case M_X_MODIFY_DP:
if (DEBUG_FLAGS & DEBUG_POINTER)
sym_print_msg(cp, "extended msg ",
np->msgin);
tmp = (np->msgin[3]<<24) + (np->msgin[4]<<16) +
(np->msgin[5]<<8) + (np->msgin[6]);
sym_modify_dp(np, tp, cp, tmp);
return;
case M_X_SYNC_REQ:
sym_sync_nego(np, tp, cp);
return;
case M_X_PPR_REQ:
sym_ppr_nego(np, tp, cp);
return;
case M_X_WIDE_REQ:
sym_wide_nego(np, tp, cp);
return;
default:
goto out_reject;
}
break;
/*
* We received a 1/2 byte message not handled from SCRIPTS.
* We are only expecting MESSAGE REJECT and IGNORE WIDE
* RESIDUE messages that haven't been anticipated by
* SCRIPTS on SWIDE full condition. Unanticipated IGNORE
* WIDE RESIDUE messages are aliased as MODIFY DP (-1).
*/
case M_IGN_RESIDUE:
if (DEBUG_FLAGS & DEBUG_POINTER)
sym_print_msg(cp, "1 or 2 byte ", np->msgin);
if (cp->host_flags & HF_SENSE)
OUTL_DSP(np, SCRIPTA_BA(np, clrack));
else
sym_modify_dp(np, tp, cp, -1);
return;
case M_REJECT:
if (INB(np, HS_PRT) == HS_NEGOTIATE)
sym_nego_rejected(np, tp, cp);
else {
sym_print_addr(cp->cmd,
"M_REJECT received (%x:%x).\n",
scr_to_cpu(np->lastmsg), np->msgout[0]);
}
goto out_clrack;
break;
default:
goto out_reject;
}
break;
/*
* We received an unknown message.
* Ignore all MSG IN phases and reject it.
*/
case SIR_MSG_WEIRD:
sym_print_msg(cp, "WEIRD message received", np->msgin);
OUTL_DSP(np, SCRIPTB_BA(np, msg_weird));
return;
/*
* Negotiation failed.
* Target does not send us the reply.
* Remove the HS_NEGOTIATE status.
*/
case SIR_NEGO_FAILED:
OUTB(np, HS_PRT, HS_BUSY);
/*
* Negotiation failed.
* Target does not want answer message.
*/
case SIR_NEGO_PROTO:
sym_nego_default(np, tp, cp);
goto out;
}
out:
OUTONB_STD();
return;
out_reject:
OUTL_DSP(np, SCRIPTB_BA(np, msg_bad));
return;
out_clrack:
OUTL_DSP(np, SCRIPTA_BA(np, clrack));
return;
out_stuck:
return;
}
/*
* Acquire a control block
*/
struct sym_ccb *sym_get_ccb (struct sym_hcb *np, struct scsi_cmnd *cmd, u_char tag_order)
{
u_char tn = cmd->device->id;
u_char ln = cmd->device->lun;
struct sym_tcb *tp = &np->target[tn];
struct sym_lcb *lp = sym_lp(tp, ln);
u_short tag = NO_TAG;
SYM_QUEHEAD *qp;
struct sym_ccb *cp = NULL;
/*
* Look for a free CCB
*/
if (sym_que_empty(&np->free_ccbq))
sym_alloc_ccb(np);
qp = sym_remque_head(&np->free_ccbq);
if (!qp)
goto out;
cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
{
/*
* If we have been asked for a tagged command.
*/
if (tag_order) {
/*
* Debugging purpose.
*/
#ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
if (lp->busy_itl != 0)
goto out_free;
#endif
/*
* Allocate resources for tags if not yet.
*/
if (!lp->cb_tags) {
sym_alloc_lcb_tags(np, tn, ln);
if (!lp->cb_tags)
goto out_free;
}
/*
* Get a tag for this SCSI IO and set up
* the CCB bus address for reselection,
* and count it for this LUN.
* Toggle reselect path to tagged.
*/
if (lp->busy_itlq < SYM_CONF_MAX_TASK) {
tag = lp->cb_tags[lp->ia_tag];
if (++lp->ia_tag == SYM_CONF_MAX_TASK)
lp->ia_tag = 0;
++lp->busy_itlq;
#ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
lp->itlq_tbl[tag] = cpu_to_scr(cp->ccb_ba);
lp->head.resel_sa =
cpu_to_scr(SCRIPTA_BA(np, resel_tag));
#endif
#ifdef SYM_OPT_LIMIT_COMMAND_REORDERING
cp->tags_si = lp->tags_si;
++lp->tags_sum[cp->tags_si];
++lp->tags_since;
#endif
}
else
goto out_free;
}
/*
* This command will not be tagged.
* If we already have either a tagged or untagged
* one, refuse to overlap this untagged one.
*/
else {
/*
* Debugging purpose.
*/
#ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
if (lp->busy_itl != 0 || lp->busy_itlq != 0)
goto out_free;
#endif
/*
* Count this nexus for this LUN.
* Set up the CCB bus address for reselection.
* Toggle reselect path to untagged.
*/
++lp->busy_itl;
#ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
if (lp->busy_itl == 1) {
lp->head.itl_task_sa = cpu_to_scr(cp->ccb_ba);
lp->head.resel_sa =
cpu_to_scr(SCRIPTA_BA(np, resel_no_tag));
}
else
goto out_free;
#endif
}
}
/*
* Put the CCB into the busy queue.
*/
sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
if (lp) {
sym_remque(&cp->link2_ccbq);
sym_insque_tail(&cp->link2_ccbq, &lp->waiting_ccbq);
}
#endif
cp->to_abort = 0;
cp->odd_byte_adjustment = 0;
cp->tag = tag;
cp->order = tag_order;
cp->target = tn;
cp->lun = ln;
if (DEBUG_FLAGS & DEBUG_TAGS) {
sym_print_addr(cmd, "ccb @%p using tag %d.\n", cp, tag);
}
out:
return cp;
out_free:
sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
return NULL;
}
/*
* Release one control block
*/
void sym_free_ccb (struct sym_hcb *np, struct sym_ccb *cp)
{
struct sym_tcb *tp = &np->target[cp->target];
struct sym_lcb *lp = sym_lp(tp, cp->lun);
if (DEBUG_FLAGS & DEBUG_TAGS) {
sym_print_addr(cp->cmd, "ccb @%p freeing tag %d.\n",
cp, cp->tag);
}
/*
* If LCB available,
*/
if (lp) {
/*
* If tagged, release the tag, set the relect path
*/
if (cp->tag != NO_TAG) {
#ifdef SYM_OPT_LIMIT_COMMAND_REORDERING
--lp->tags_sum[cp->tags_si];
#endif
/*
* Free the tag value.
*/
lp->cb_tags[lp->if_tag] = cp->tag;
if (++lp->if_tag == SYM_CONF_MAX_TASK)
lp->if_tag = 0;
/*
* Make the reselect path invalid,
* and uncount this CCB.
*/
lp->itlq_tbl[cp->tag] = cpu_to_scr(np->bad_itlq_ba);
--lp->busy_itlq;
} else { /* Untagged */
/*
* Make the reselect path invalid,
* and uncount this CCB.
*/
lp->head.itl_task_sa = cpu_to_scr(np->bad_itl_ba);
--lp->busy_itl;
}
/*
* If no JOB active, make the LUN reselect path invalid.
*/
if (lp->busy_itlq == 0 && lp->busy_itl == 0)
lp->head.resel_sa =
cpu_to_scr(SCRIPTB_BA(np, resel_bad_lun));
}
/*
* We donnot queue more than 1 ccb per target
* with negotiation at any time. If this ccb was
* used for negotiation, clear this info in the tcb.
*/
if (cp == tp->nego_cp)
tp->nego_cp = NULL;
#ifdef SYM_CONF_IARB_SUPPORT
/*
* If we just complete the last queued CCB,
* clear this info that is no longer relevant.
*/
if (cp == np->last_cp)
np->last_cp = 0;
#endif
/*
* Make this CCB available.
*/
cp->cmd = NULL;
cp->host_status = HS_IDLE;
sym_remque(&cp->link_ccbq);
sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
if (lp) {
sym_remque(&cp->link2_ccbq);
sym_insque_tail(&cp->link2_ccbq, &np->dummy_ccbq);
if (cp->started) {
if (cp->tag != NO_TAG)
--lp->started_tags;
else
--lp->started_no_tag;
}
}
cp->started = 0;
#endif
}
/*
* Allocate a CCB from memory and initialize its fixed part.
*/
static struct sym_ccb *sym_alloc_ccb(struct sym_hcb *np)
{
struct sym_ccb *cp = NULL;
int hcode;
/*
* Prevent from allocating more CCBs than we can
* queue to the controller.
*/
if (np->actccbs >= SYM_CONF_MAX_START)
return NULL;
/*
* Allocate memory for this CCB.
*/
cp = sym_calloc_dma(sizeof(struct sym_ccb), "CCB");
if (!cp)
goto out_free;
/*
* Count it.
*/
np->actccbs++;
/*
* Compute the bus address of this ccb.
*/
cp->ccb_ba = vtobus(cp);
/*
* Insert this ccb into the hashed list.
*/
hcode = CCB_HASH_CODE(cp->ccb_ba);
cp->link_ccbh = np->ccbh[hcode];
np->ccbh[hcode] = cp;
/*
* Initialyze the start and restart actions.
*/
cp->phys.head.go.start = cpu_to_scr(SCRIPTA_BA(np, idle));
cp->phys.head.go.restart = cpu_to_scr(SCRIPTB_BA(np, bad_i_t_l));
/*
* Initilialyze some other fields.
*/
cp->phys.smsg_ext.addr = cpu_to_scr(HCB_BA(np, msgin[2]));
/*
* Chain into free ccb queue.
*/
sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
/*
* Chain into optionnal lists.
*/
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
sym_insque_head(&cp->link2_ccbq, &np->dummy_ccbq);
#endif
return cp;
out_free:
if (cp)
sym_mfree_dma(cp, sizeof(*cp), "CCB");
return NULL;
}
/*
* Look up a CCB from a DSA value.
*/
static struct sym_ccb *sym_ccb_from_dsa(struct sym_hcb *np, u32 dsa)
{
int hcode;
struct sym_ccb *cp;
hcode = CCB_HASH_CODE(dsa);
cp = np->ccbh[hcode];
while (cp) {
if (cp->ccb_ba == dsa)
break;
cp = cp->link_ccbh;
}
return cp;
}
/*
* Target control block initialisation.
* Nothing important to do at the moment.
*/
static void sym_init_tcb (struct sym_hcb *np, u_char tn)
{
#if 0 /* Hmmm... this checking looks paranoid. */
/*
* Check some alignments required by the chip.
*/
assert (((offsetof(struct sym_reg, nc_sxfer) ^
offsetof(struct sym_tcb, head.sval)) &3) == 0);
assert (((offsetof(struct sym_reg, nc_scntl3) ^
offsetof(struct sym_tcb, head.wval)) &3) == 0);
#endif
}
/*
* Lun control block allocation and initialization.
*/
struct sym_lcb *sym_alloc_lcb (struct sym_hcb *np, u_char tn, u_char ln)
{
struct sym_tcb *tp = &np->target[tn];
struct sym_lcb *lp = NULL;
/*
* Initialize the target control block if not yet.
*/
sym_init_tcb (np, tn);
/*
* Allocate the LCB bus address array.
* Compute the bus address of this table.
*/
if (ln && !tp->luntbl) {
int i;
tp->luntbl = sym_calloc_dma(256, "LUNTBL");
if (!tp->luntbl)
goto fail;
for (i = 0 ; i < 64 ; i++)
tp->luntbl[i] = cpu_to_scr(vtobus(&np->badlun_sa));
tp->head.luntbl_sa = cpu_to_scr(vtobus(tp->luntbl));
}
/*
* Allocate the table of pointers for LUN(s) > 0, if needed.
*/
if (ln && !tp->lunmp) {
tp->lunmp = kcalloc(SYM_CONF_MAX_LUN, sizeof(struct sym_lcb *),
GFP_ATOMIC);
if (!tp->lunmp)
goto fail;
}
/*
* Allocate the lcb.
* Make it available to the chip.
*/
lp = sym_calloc_dma(sizeof(struct sym_lcb), "LCB");
if (!lp)
goto fail;
if (ln) {
tp->lunmp[ln] = lp;
tp->luntbl[ln] = cpu_to_scr(vtobus(lp));
}
else {
tp->lun0p = lp;
tp->head.lun0_sa = cpu_to_scr(vtobus(lp));
}
tp->nlcb++;
/*
* Let the itl task point to error handling.
*/
lp->head.itl_task_sa = cpu_to_scr(np->bad_itl_ba);
/*
* Set the reselect pattern to our default. :)
*/
lp->head.resel_sa = cpu_to_scr(SCRIPTB_BA(np, resel_bad_lun));
/*
* Set user capabilities.
*/
lp->user_flags = tp->usrflags & (SYM_DISC_ENABLED | SYM_TAGS_ENABLED);
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
/*
* Initialize device queueing.
*/
sym_que_init(&lp->waiting_ccbq);
sym_que_init(&lp->started_ccbq);
lp->started_max = SYM_CONF_MAX_TASK;
lp->started_limit = SYM_CONF_MAX_TASK;
#endif
fail:
return lp;
}
/*
* Allocate LCB resources for tagged command queuing.
*/
static void sym_alloc_lcb_tags (struct sym_hcb *np, u_char tn, u_char ln)
{
struct sym_tcb *tp = &np->target[tn];
struct sym_lcb *lp = sym_lp(tp, ln);
int i;
/*
* Allocate the task table and and the tag allocation
* circular buffer. We want both or none.
*/
lp->itlq_tbl = sym_calloc_dma(SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
if (!lp->itlq_tbl)
goto fail;
lp->cb_tags = kcalloc(SYM_CONF_MAX_TASK, 1, GFP_ATOMIC);
if (!lp->cb_tags) {
sym_mfree_dma(lp->itlq_tbl, SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
lp->itlq_tbl = NULL;
goto fail;
}
/*
* Initialize the task table with invalid entries.
*/
for (i = 0 ; i < SYM_CONF_MAX_TASK ; i++)
lp->itlq_tbl[i] = cpu_to_scr(np->notask_ba);
/*
* Fill up the tag buffer with tag numbers.
*/
for (i = 0 ; i < SYM_CONF_MAX_TASK ; i++)
lp->cb_tags[i] = i;
/*
* Make the task table available to SCRIPTS,
* And accept tagged commands now.
*/
lp->head.itlq_tbl_sa = cpu_to_scr(vtobus(lp->itlq_tbl));
return;
fail:
return;
}
/*
* Lun control block deallocation. Returns the number of valid remaining LCBs
* for the target.
*/
int sym_free_lcb(struct sym_hcb *np, u_char tn, u_char ln)
{
struct sym_tcb *tp = &np->target[tn];
struct sym_lcb *lp = sym_lp(tp, ln);
tp->nlcb--;
if (ln) {
if (!tp->nlcb) {
kfree(tp->lunmp);
sym_mfree_dma(tp->luntbl, 256, "LUNTBL");
tp->lunmp = NULL;
tp->luntbl = NULL;
tp->head.luntbl_sa = cpu_to_scr(vtobus(np->badluntbl));
} else {
tp->luntbl[ln] = cpu_to_scr(vtobus(&np->badlun_sa));
tp->lunmp[ln] = NULL;
}
} else {
tp->lun0p = NULL;
tp->head.lun0_sa = cpu_to_scr(vtobus(&np->badlun_sa));
}
if (lp->itlq_tbl) {
sym_mfree_dma(lp->itlq_tbl, SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
kfree(lp->cb_tags);
}
sym_mfree_dma(lp, sizeof(*lp), "LCB");
return tp->nlcb;
}
/*
* Queue a SCSI IO to the controller.
*/
int sym_queue_scsiio(struct sym_hcb *np, struct scsi_cmnd *cmd, struct sym_ccb *cp)
{
struct scsi_device *sdev = cmd->device;
struct sym_tcb *tp;
struct sym_lcb *lp;
u_char *msgptr;
u_int msglen;
int can_disconnect;
/*
* Keep track of the IO in our CCB.
*/
cp->cmd = cmd;
/*
* Retrieve the target descriptor.
*/
tp = &np->target[cp->target];
/*
* Retrieve the lun descriptor.
*/
lp = sym_lp(tp, sdev->lun);
can_disconnect = (cp->tag != NO_TAG) ||
(lp && (lp->curr_flags & SYM_DISC_ENABLED));
msgptr = cp->scsi_smsg;
msglen = 0;
msgptr[msglen++] = IDENTIFY(can_disconnect, sdev->lun);
/*
* Build the tag message if present.
*/
if (cp->tag != NO_TAG) {
u_char order = cp->order;
switch(order) {
case M_ORDERED_TAG:
break;
case M_HEAD_TAG:
break;
default:
order = M_SIMPLE_TAG;
}
#ifdef SYM_OPT_LIMIT_COMMAND_REORDERING
/*
* Avoid too much reordering of SCSI commands.
* The algorithm tries to prevent completion of any
* tagged command from being delayed against more
* than 3 times the max number of queued commands.
*/
if (lp && lp->tags_since > 3*SYM_CONF_MAX_TAG) {
lp->tags_si = !(lp->tags_si);
if (lp->tags_sum[lp->tags_si]) {
order = M_ORDERED_TAG;
if ((DEBUG_FLAGS & DEBUG_TAGS)||sym_verbose>1) {
sym_print_addr(cmd,
"ordered tag forced.\n");
}
}
lp->tags_since = 0;
}
#endif
msgptr[msglen++] = order;
/*
* For less than 128 tags, actual tags are numbered
* 1,3,5,..2*MAXTAGS+1,since we may have to deal
* with devices that have problems with #TAG 0 or too
* great #TAG numbers. For more tags (up to 256),
* we use directly our tag number.
*/
#if SYM_CONF_MAX_TASK > (512/4)
msgptr[msglen++] = cp->tag;
#else
msgptr[msglen++] = (cp->tag << 1) + 1;
#endif
}
/*
* Build a negotiation message if needed.
* (nego_status is filled by sym_prepare_nego())
*
* Always negotiate on INQUIRY and REQUEST SENSE.
*
*/
cp->nego_status = 0;
if ((tp->tgoal.check_nego ||
cmd->cmnd[0] == INQUIRY || cmd->cmnd[0] == REQUEST_SENSE) &&
!tp->nego_cp && lp) {
msglen += sym_prepare_nego(np, cp, msgptr + msglen);
}
/*
* Startqueue
*/
cp->phys.head.go.start = cpu_to_scr(SCRIPTA_BA(np, select));
cp->phys.head.go.restart = cpu_to_scr(SCRIPTA_BA(np, resel_dsa));
/*
* select
*/
cp->phys.select.sel_id = cp->target;
cp->phys.select.sel_scntl3 = tp->head.wval;
cp->phys.select.sel_sxfer = tp->head.sval;
cp->phys.select.sel_scntl4 = tp->head.uval;
/*
* message
*/
cp->phys.smsg.addr = CCB_BA(cp, scsi_smsg);
cp->phys.smsg.size = cpu_to_scr(msglen);
/*
* status
*/
cp->host_xflags = 0;
cp->host_status = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
cp->ssss_status = S_ILLEGAL;
cp->xerr_status = 0;
cp->host_flags = 0;
cp->extra_bytes = 0;
/*
* extreme data pointer.
* shall be positive, so -1 is lower than lowest.:)
*/
cp->ext_sg = -1;
cp->ext_ofs = 0;
/*
* Build the CDB and DATA descriptor block
* and start the IO.
*/
return sym_setup_data_and_start(np, cmd, cp);
}
/*
* Reset a SCSI target (all LUNs of this target).
*/
int sym_reset_scsi_target(struct sym_hcb *np, int target)
{
struct sym_tcb *tp;
if (target == np->myaddr || (u_int)target >= SYM_CONF_MAX_TARGET)
return -1;
tp = &np->target[target];
tp->to_reset = 1;
np->istat_sem = SEM;
OUTB(np, nc_istat, SIGP|SEM);
return 0;
}
/*
* Abort a SCSI IO.
*/
static int sym_abort_ccb(struct sym_hcb *np, struct sym_ccb *cp, int timed_out)
{
/*
* Check that the IO is active.
*/
if (!cp || !cp->host_status || cp->host_status == HS_WAIT)
return -1;
/*
* If a previous abort didn't succeed in time,
* perform a BUS reset.
*/
if (cp->to_abort) {
sym_reset_scsi_bus(np, 1);
return 0;
}
/*
* Mark the CCB for abort and allow time for.
*/
cp->to_abort = timed_out ? 2 : 1;
/*
* Tell the SCRIPTS processor to stop and synchronize with us.
*/
np->istat_sem = SEM;
OUTB(np, nc_istat, SIGP|SEM);
return 0;
}
int sym_abort_scsiio(struct sym_hcb *np, struct scsi_cmnd *cmd, int timed_out)
{
struct sym_ccb *cp;
SYM_QUEHEAD *qp;
/*
* Look up our CCB control block.
*/
cp = NULL;
FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
struct sym_ccb *cp2 = sym_que_entry(qp, struct sym_ccb, link_ccbq);
if (cp2->cmd == cmd) {
cp = cp2;
break;
}
}
return sym_abort_ccb(np, cp, timed_out);
}
/*
* Complete execution of a SCSI command with extended
* error, SCSI status error, or having been auto-sensed.
*
* The SCRIPTS processor is not running there, so we
* can safely access IO registers and remove JOBs from
* the START queue.
* SCRATCHA is assumed to have been loaded with STARTPOS
* before the SCRIPTS called the C code.
*/
void sym_complete_error(struct sym_hcb *np, struct sym_ccb *cp)
{
struct scsi_device *sdev;
struct scsi_cmnd *cmd;
struct sym_tcb *tp;
struct sym_lcb *lp;
int resid;
int i;
/*
* Paranoid check. :)
*/
if (!cp || !cp->cmd)
return;
cmd = cp->cmd;
sdev = cmd->device;
if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_RESULT)) {
dev_info(&sdev->sdev_gendev, "CCB=%p STAT=%x/%x/%x\n", cp,
cp->host_status, cp->ssss_status, cp->host_flags);
}
/*
* Get target and lun pointers.
*/
tp = &np->target[cp->target];
lp = sym_lp(tp, sdev->lun);
/*
* Check for extended errors.
*/
if (cp->xerr_status) {
if (sym_verbose)
sym_print_xerr(cmd, cp->xerr_status);
if (cp->host_status == HS_COMPLETE)
cp->host_status = HS_COMP_ERR;
}
/*
* Calculate the residual.
*/
resid = sym_compute_residual(np, cp);
if (!SYM_SETUP_RESIDUAL_SUPPORT) {/* If user does not want residuals */
resid = 0; /* throw them away. :) */
cp->sv_resid = 0;
}
#ifdef DEBUG_2_0_X
if (resid)
printf("XXXX RESID= %d - 0x%x\n", resid, resid);
#endif
/*
* Dequeue all queued CCBs for that device
* not yet started by SCRIPTS.
*/
i = (INL(np, nc_scratcha) - np->squeue_ba) / 4;
i = sym_dequeue_from_squeue(np, i, cp->target, sdev->lun, -1);
/*
* Restart the SCRIPTS processor.
*/
OUTL_DSP(np, SCRIPTA_BA(np, start));
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
if (cp->host_status == HS_COMPLETE &&
cp->ssss_status == S_QUEUE_FULL) {
if (!lp || lp->started_tags - i < 2)
goto weirdness;
/*
* Decrease queue depth as needed.
*/
lp->started_max = lp->started_tags - i - 1;
lp->num_sgood = 0;
if (sym_verbose >= 2) {
sym_print_addr(cmd, " queue depth is now %d\n",
lp->started_max);
}
/*
* Repair the CCB.
*/
cp->host_status = HS_BUSY;
cp->ssss_status = S_ILLEGAL;
/*
* Let's requeue it to device.
*/
sym_set_cam_status(cmd, DID_SOFT_ERROR);
goto finish;
}
weirdness:
#endif
/*
* Build result in CAM ccb.
*/
sym_set_cam_result_error(np, cp, resid);
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
finish:
#endif
/*
* Add this one to the COMP queue.
*/
sym_remque(&cp->link_ccbq);
sym_insque_head(&cp->link_ccbq, &np->comp_ccbq);
/*
* Complete all those commands with either error
* or requeue condition.
*/
sym_flush_comp_queue(np, 0);
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
/*
* Donnot start more than 1 command after an error.
*/
sym_start_next_ccbs(np, lp, 1);
#endif
}
/*
* Complete execution of a successful SCSI command.
*
* Only successful commands go to the DONE queue,
* since we need to have the SCRIPTS processor
* stopped on any error condition.
* The SCRIPTS processor is running while we are
* completing successful commands.
*/
void sym_complete_ok (struct sym_hcb *np, struct sym_ccb *cp)
{
struct sym_tcb *tp;
struct sym_lcb *lp;
struct scsi_cmnd *cmd;
int resid;
/*
* Paranoid check. :)
*/
if (!cp || !cp->cmd)
return;
assert (cp->host_status == HS_COMPLETE);
/*
* Get user command.
*/
cmd = cp->cmd;
/*
* Get target and lun pointers.
*/
tp = &np->target[cp->target];
lp = sym_lp(tp, cp->lun);
/*
* If all data have been transferred, given than no
* extended error did occur, there is no residual.
*/
resid = 0;
if (cp->phys.head.lastp != cp->goalp)
resid = sym_compute_residual(np, cp);
/*
* Wrong transfer residuals may be worse than just always
* returning zero. User can disable this feature in
* sym53c8xx.h. Residual support is enabled by default.
*/
if (!SYM_SETUP_RESIDUAL_SUPPORT)
resid = 0;
#ifdef DEBUG_2_0_X
if (resid)
printf("XXXX RESID= %d - 0x%x\n", resid, resid);
#endif
/*
* Build result in CAM ccb.
*/
sym_set_cam_result_ok(cp, cmd, resid);
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
/*
* If max number of started ccbs had been reduced,
* increase it if 200 good status received.
*/
if (lp && lp->started_max < lp->started_limit) {
++lp->num_sgood;
if (lp->num_sgood >= 200) {
lp->num_sgood = 0;
++lp->started_max;
if (sym_verbose >= 2) {
sym_print_addr(cmd, " queue depth is now %d\n",
lp->started_max);
}
}
}
#endif
/*
* Free our CCB.
*/
sym_free_ccb (np, cp);
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
/*
* Requeue a couple of awaiting scsi commands.
*/
if (!sym_que_empty(&lp->waiting_ccbq))
sym_start_next_ccbs(np, lp, 2);
#endif
/*
* Complete the command.
*/
sym_xpt_done(np, cmd);
}
/*
* Soft-attach the controller.
*/
int sym_hcb_attach(struct Scsi_Host *shost, struct sym_fw *fw, struct sym_nvram *nvram)
{
struct sym_hcb *np = sym_get_hcb(shost);
int i;
/*
* Get some info about the firmware.
*/
np->scripta_sz = fw->a_size;
np->scriptb_sz = fw->b_size;
np->scriptz_sz = fw->z_size;
np->fw_setup = fw->setup;
np->fw_patch = fw->patch;
np->fw_name = fw->name;
/*
* Save setting of some IO registers, so we will
* be able to probe specific implementations.
*/
sym_save_initial_setting (np);
/*
* Reset the chip now, since it has been reported
* that SCSI clock calibration may not work properly
* if the chip is currently active.
*/
sym_chip_reset(np);
/*
* Prepare controller and devices settings, according
* to chip features, user set-up and driver set-up.
*/
sym_prepare_setting(shost, np, nvram);
/*
* Check the PCI clock frequency.
* Must be performed after prepare_setting since it destroys
* STEST1 that is used to probe for the clock doubler.
*/
i = sym_getpciclock(np);
if (i > 37000 && !(np->features & FE_66MHZ))
printf("%s: PCI BUS clock seems too high: %u KHz.\n",
sym_name(np), i);
/*
* Allocate the start queue.
*/
np->squeue = sym_calloc_dma(sizeof(u32)*(MAX_QUEUE*2),"SQUEUE");
if (!np->squeue)
goto attach_failed;
np->squeue_ba = vtobus(np->squeue);
/*
* Allocate the done queue.
*/
np->dqueue = sym_calloc_dma(sizeof(u32)*(MAX_QUEUE*2),"DQUEUE");
if (!np->dqueue)
goto attach_failed;
np->dqueue_ba = vtobus(np->dqueue);
/*
* Allocate the target bus address array.
*/
np->targtbl = sym_calloc_dma(256, "TARGTBL");
if (!np->targtbl)
goto attach_failed;
np->targtbl_ba = vtobus(np->targtbl);
/*
* Allocate SCRIPTS areas.
*/
np->scripta0 = sym_calloc_dma(np->scripta_sz, "SCRIPTA0");
np->scriptb0 = sym_calloc_dma(np->scriptb_sz, "SCRIPTB0");
np->scriptz0 = sym_calloc_dma(np->scriptz_sz, "SCRIPTZ0");
if (!np->scripta0 || !np->scriptb0 || !np->scriptz0)
goto attach_failed;
/*
* Allocate the array of lists of CCBs hashed by DSA.
*/
np->ccbh = kcalloc(CCB_HASH_SIZE, sizeof(struct sym_ccb **), GFP_KERNEL);
if (!np->ccbh)
goto attach_failed;
/*
* Initialyze the CCB free and busy queues.
*/
sym_que_init(&np->free_ccbq);
sym_que_init(&np->busy_ccbq);
sym_que_init(&np->comp_ccbq);
/*
* Initialization for optional handling
* of device queueing.
*/
#ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
sym_que_init(&np->dummy_ccbq);
#endif
/*
* Allocate some CCB. We need at least ONE.
*/
if (!sym_alloc_ccb(np))
goto attach_failed;
/*
* Calculate BUS addresses where we are going
* to load the SCRIPTS.
*/
np->scripta_ba = vtobus(np->scripta0);
np->scriptb_ba = vtobus(np->scriptb0);
np->scriptz_ba = vtobus(np->scriptz0);
if (np->ram_ba) {
np->scripta_ba = np->ram_ba;
if (np->features & FE_RAM8K) {
np->scriptb_ba = np->scripta_ba + 4096;
#if 0 /* May get useful for 64 BIT PCI addressing */
np->scr_ram_seg = cpu_to_scr(np->scripta_ba >> 32);
#endif
}
}
/*
* Copy scripts to controller instance.
*/
memcpy(np->scripta0, fw->a_base, np->scripta_sz);
memcpy(np->scriptb0, fw->b_base, np->scriptb_sz);
memcpy(np->scriptz0, fw->z_base, np->scriptz_sz);
/*
* Setup variable parts in scripts and compute
* scripts bus addresses used from the C code.
*/
np->fw_setup(np, fw);
/*
* Bind SCRIPTS with physical addresses usable by the
* SCRIPTS processor (as seen from the BUS = BUS addresses).
*/
sym_fw_bind_script(np, (u32 *) np->scripta0, np->scripta_sz);
sym_fw_bind_script(np, (u32 *) np->scriptb0, np->scriptb_sz);
sym_fw_bind_script(np, (u32 *) np->scriptz0, np->scriptz_sz);
#ifdef SYM_CONF_IARB_SUPPORT
/*
* If user wants IARB to be set when we win arbitration
* and have other jobs, compute the max number of consecutive
* settings of IARB hints before we leave devices a chance to
* arbitrate for reselection.
*/
#ifdef SYM_SETUP_IARB_MAX
np->iarb_max = SYM_SETUP_IARB_MAX;
#else
np->iarb_max = 4;
#endif
#endif
/*
* Prepare the idle and invalid task actions.
*/
np->idletask.start = cpu_to_scr(SCRIPTA_BA(np, idle));
np->idletask.restart = cpu_to_scr(SCRIPTB_BA(np, bad_i_t_l));
np->idletask_ba = vtobus(&np->idletask);
np->notask.start = cpu_to_scr(SCRIPTA_BA(np, idle));
np->notask.restart = cpu_to_scr(SCRIPTB_BA(np, bad_i_t_l));
np->notask_ba = vtobus(&np->notask);
np->bad_itl.start = cpu_to_scr(SCRIPTA_BA(np, idle));
np->bad_itl.restart = cpu_to_scr(SCRIPTB_BA(np, bad_i_t_l));
np->bad_itl_ba = vtobus(&np->bad_itl);
np->bad_itlq.start = cpu_to_scr(SCRIPTA_BA(np, idle));
np->bad_itlq.restart = cpu_to_scr(SCRIPTB_BA(np,bad_i_t_l_q));
np->bad_itlq_ba = vtobus(&np->bad_itlq);
/*
* Allocate and prepare the lun JUMP table that is used
* for a target prior the probing of devices (bad lun table).
* A private table will be allocated for the target on the
* first INQUIRY response received.
*/
np->badluntbl = sym_calloc_dma(256, "BADLUNTBL");
if (!np->badluntbl)
goto attach_failed;
np->badlun_sa = cpu_to_scr(SCRIPTB_BA(np, resel_bad_lun));
for (i = 0 ; i < 64 ; i++) /* 64 luns/target, no less */
np->badluntbl[i] = cpu_to_scr(vtobus(&np->badlun_sa));
/*
* Prepare the bus address array that contains the bus
* address of each target control block.
* For now, assume all logical units are wrong. :)
*/
for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
np->targtbl[i] = cpu_to_scr(vtobus(&np->target[i]));
np->target[i].head.luntbl_sa =
cpu_to_scr(vtobus(np->badluntbl));
np->target[i].head.lun0_sa =
cpu_to_scr(vtobus(&np->badlun_sa));
}
/*
* Now check the cache handling of the pci chipset.
*/
if (sym_snooptest (np)) {
printf("%s: CACHE INCORRECTLY CONFIGURED.\n", sym_name(np));
goto attach_failed;
}
/*
* Sigh! we are done.
*/
return 0;
attach_failed:
return -ENXIO;
}
/*
* Free everything that has been allocated for this device.
*/
void sym_hcb_free(struct sym_hcb *np)
{
SYM_QUEHEAD *qp;
struct sym_ccb *cp;
struct sym_tcb *tp;
int target;
if (np->scriptz0)
sym_mfree_dma(np->scriptz0, np->scriptz_sz, "SCRIPTZ0");
if (np->scriptb0)
sym_mfree_dma(np->scriptb0, np->scriptb_sz, "SCRIPTB0");
if (np->scripta0)
sym_mfree_dma(np->scripta0, np->scripta_sz, "SCRIPTA0");
if (np->squeue)
sym_mfree_dma(np->squeue, sizeof(u32)*(MAX_QUEUE*2), "SQUEUE");
if (np->dqueue)
sym_mfree_dma(np->dqueue, sizeof(u32)*(MAX_QUEUE*2), "DQUEUE");
if (np->actccbs) {
while ((qp = sym_remque_head(&np->free_ccbq)) != NULL) {
cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
sym_mfree_dma(cp, sizeof(*cp), "CCB");
}
}
kfree(np->ccbh);
if (np->badluntbl)
sym_mfree_dma(np->badluntbl, 256,"BADLUNTBL");
for (target = 0; target < SYM_CONF_MAX_TARGET ; target++) {
tp = &np->target[target];
if (tp->luntbl)
sym_mfree_dma(tp->luntbl, 256, "LUNTBL");
#if SYM_CONF_MAX_LUN > 1
kfree(tp->lunmp);
#endif
}
if (np->targtbl)
sym_mfree_dma(np->targtbl, 256, "TARGTBL");
}
| gpl-2.0 |
5victor/linux-tiny210v2 | drivers/video/omap/lcd_omap3evm.c | 4098 | 5012 | /*
* LCD panel support for the TI OMAP3 EVM board
*
* Author: Steve Sakoman <steve@sakoman.com>
*
* Derived from drivers/video/omap/lcd-apollon.c
*
* 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/module.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/i2c/twl.h>
#include <plat/mux.h>
#include <asm/mach-types.h>
#include "omapfb.h"
#define LCD_PANEL_ENABLE_GPIO 153
#define LCD_PANEL_LR 2
#define LCD_PANEL_UD 3
#define LCD_PANEL_INI 152
#define LCD_PANEL_QVGA 154
#define LCD_PANEL_RESB 155
#define ENABLE_VDAC_DEDICATED 0x03
#define ENABLE_VDAC_DEV_GRP 0x20
#define ENABLE_VPLL2_DEDICATED 0x05
#define ENABLE_VPLL2_DEV_GRP 0xE0
#define TWL_LED_LEDEN 0x00
#define TWL_PWMA_PWMAON 0x00
#define TWL_PWMA_PWMAOFF 0x01
static unsigned int bklight_level;
static int omap3evm_panel_init(struct lcd_panel *panel,
struct omapfb_device *fbdev)
{
gpio_request(LCD_PANEL_LR, "LCD lr");
gpio_request(LCD_PANEL_UD, "LCD ud");
gpio_request(LCD_PANEL_INI, "LCD ini");
gpio_request(LCD_PANEL_RESB, "LCD resb");
gpio_request(LCD_PANEL_QVGA, "LCD qvga");
gpio_direction_output(LCD_PANEL_RESB, 1);
gpio_direction_output(LCD_PANEL_INI, 1);
gpio_direction_output(LCD_PANEL_QVGA, 0);
gpio_direction_output(LCD_PANEL_LR, 1);
gpio_direction_output(LCD_PANEL_UD, 1);
twl_i2c_write_u8(TWL4030_MODULE_LED, 0x11, TWL_LED_LEDEN);
twl_i2c_write_u8(TWL4030_MODULE_PWMA, 0x01, TWL_PWMA_PWMAON);
twl_i2c_write_u8(TWL4030_MODULE_PWMA, 0x02, TWL_PWMA_PWMAOFF);
bklight_level = 100;
return 0;
}
static void omap3evm_panel_cleanup(struct lcd_panel *panel)
{
gpio_free(LCD_PANEL_QVGA);
gpio_free(LCD_PANEL_RESB);
gpio_free(LCD_PANEL_INI);
gpio_free(LCD_PANEL_UD);
gpio_free(LCD_PANEL_LR);
}
static int omap3evm_panel_enable(struct lcd_panel *panel)
{
gpio_set_value(LCD_PANEL_ENABLE_GPIO, 0);
return 0;
}
static void omap3evm_panel_disable(struct lcd_panel *panel)
{
gpio_set_value(LCD_PANEL_ENABLE_GPIO, 1);
}
static unsigned long omap3evm_panel_get_caps(struct lcd_panel *panel)
{
return 0;
}
static int omap3evm_bklight_setlevel(struct lcd_panel *panel,
unsigned int level)
{
u8 c;
if ((level >= 0) && (level <= 100)) {
c = (125 * (100 - level)) / 100 + 2;
twl_i2c_write_u8(TWL4030_MODULE_PWMA, c, TWL_PWMA_PWMAOFF);
bklight_level = level;
}
return 0;
}
static unsigned int omap3evm_bklight_getlevel(struct lcd_panel *panel)
{
return bklight_level;
}
static unsigned int omap3evm_bklight_getmaxlevel(struct lcd_panel *panel)
{
return 100;
}
struct lcd_panel omap3evm_panel = {
.name = "omap3evm",
.config = OMAP_LCDC_PANEL_TFT | OMAP_LCDC_INV_VSYNC |
OMAP_LCDC_INV_HSYNC,
.bpp = 16,
.data_lines = 18,
.x_res = 480,
.y_res = 640,
.hsw = 3, /* hsync_len (4) - 1 */
.hfp = 3, /* right_margin (4) - 1 */
.hbp = 39, /* left_margin (40) - 1 */
.vsw = 1, /* vsync_len (2) - 1 */
.vfp = 2, /* lower_margin */
.vbp = 7, /* upper_margin (8) - 1 */
.pixel_clock = 26000,
.init = omap3evm_panel_init,
.cleanup = omap3evm_panel_cleanup,
.enable = omap3evm_panel_enable,
.disable = omap3evm_panel_disable,
.get_caps = omap3evm_panel_get_caps,
.set_bklight_level = omap3evm_bklight_setlevel,
.get_bklight_level = omap3evm_bklight_getlevel,
.get_bklight_max = omap3evm_bklight_getmaxlevel,
};
static int omap3evm_panel_probe(struct platform_device *pdev)
{
omapfb_register_panel(&omap3evm_panel);
return 0;
}
static int omap3evm_panel_remove(struct platform_device *pdev)
{
return 0;
}
static int omap3evm_panel_suspend(struct platform_device *pdev,
pm_message_t mesg)
{
return 0;
}
static int omap3evm_panel_resume(struct platform_device *pdev)
{
return 0;
}
struct platform_driver omap3evm_panel_driver = {
.probe = omap3evm_panel_probe,
.remove = omap3evm_panel_remove,
.suspend = omap3evm_panel_suspend,
.resume = omap3evm_panel_resume,
.driver = {
.name = "omap3evm_lcd",
.owner = THIS_MODULE,
},
};
static int __init omap3evm_panel_drv_init(void)
{
return platform_driver_register(&omap3evm_panel_driver);
}
static void __exit omap3evm_panel_drv_exit(void)
{
platform_driver_unregister(&omap3evm_panel_driver);
}
module_init(omap3evm_panel_drv_init);
module_exit(omap3evm_panel_drv_exit);
| gpl-2.0 |
wangsai008/NewWorld-F160-JB-Kernel | drivers/input/misc/gpio_input.c | 4866 | 11119 | /* drivers/input/misc/gpio_input.c
*
* Copyright (C) 2007 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/gpio_event.h>
#include <linux/hrtimer.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/wakelock.h>
enum {
DEBOUNCE_UNSTABLE = BIT(0), /* Got irq, while debouncing */
DEBOUNCE_PRESSED = BIT(1),
DEBOUNCE_NOTPRESSED = BIT(2),
DEBOUNCE_WAIT_IRQ = BIT(3), /* Stable irq state */
DEBOUNCE_POLL = BIT(4), /* Stable polling state */
DEBOUNCE_UNKNOWN =
DEBOUNCE_PRESSED | DEBOUNCE_NOTPRESSED,
};
struct gpio_key_state {
struct gpio_input_state *ds;
uint8_t debounce;
};
struct gpio_input_state {
struct gpio_event_input_devs *input_devs;
const struct gpio_event_input_info *info;
struct hrtimer timer;
int use_irq;
int debounce_count;
spinlock_t irq_lock;
struct wake_lock wake_lock;
struct gpio_key_state key_state[0];
};
static enum hrtimer_restart gpio_event_input_timer_func(struct hrtimer *timer)
{
int i;
int pressed;
struct gpio_input_state *ds =
container_of(timer, struct gpio_input_state, timer);
unsigned gpio_flags = ds->info->flags;
unsigned npolarity;
int nkeys = ds->info->keymap_size;
const struct gpio_event_direct_entry *key_entry;
struct gpio_key_state *key_state;
unsigned long irqflags;
uint8_t debounce;
bool sync_needed;
#if 0
key_entry = kp->keys_info->keymap;
key_state = kp->key_state;
for (i = 0; i < nkeys; i++, key_entry++, key_state++)
pr_info("gpio_read_detect_status %d %d\n", key_entry->gpio,
gpio_read_detect_status(key_entry->gpio));
#endif
key_entry = ds->info->keymap;
key_state = ds->key_state;
sync_needed = false;
spin_lock_irqsave(&ds->irq_lock, irqflags);
for (i = 0; i < nkeys; i++, key_entry++, key_state++) {
debounce = key_state->debounce;
if (debounce & DEBOUNCE_WAIT_IRQ)
continue;
if (key_state->debounce & DEBOUNCE_UNSTABLE) {
debounce = key_state->debounce = DEBOUNCE_UNKNOWN;
enable_irq(gpio_to_irq(key_entry->gpio));
if (gpio_flags & GPIOEDF_PRINT_KEY_UNSTABLE)
pr_info("gpio_keys_scan_keys: key %x-%x, %d "
"(%d) continue debounce\n",
ds->info->type, key_entry->code,
i, key_entry->gpio);
}
npolarity = !(gpio_flags & GPIOEDF_ACTIVE_HIGH);
pressed = gpio_get_value(key_entry->gpio) ^ npolarity;
if (debounce & DEBOUNCE_POLL) {
if (pressed == !(debounce & DEBOUNCE_PRESSED)) {
ds->debounce_count++;
key_state->debounce = DEBOUNCE_UNKNOWN;
if (gpio_flags & GPIOEDF_PRINT_KEY_DEBOUNCE)
pr_info("gpio_keys_scan_keys: key %x-"
"%x, %d (%d) start debounce\n",
ds->info->type, key_entry->code,
i, key_entry->gpio);
}
continue;
}
if (pressed && (debounce & DEBOUNCE_NOTPRESSED)) {
if (gpio_flags & GPIOEDF_PRINT_KEY_DEBOUNCE)
pr_info("gpio_keys_scan_keys: key %x-%x, %d "
"(%d) debounce pressed 1\n",
ds->info->type, key_entry->code,
i, key_entry->gpio);
key_state->debounce = DEBOUNCE_PRESSED;
continue;
}
if (!pressed && (debounce & DEBOUNCE_PRESSED)) {
if (gpio_flags & GPIOEDF_PRINT_KEY_DEBOUNCE)
pr_info("gpio_keys_scan_keys: key %x-%x, %d "
"(%d) debounce pressed 0\n",
ds->info->type, key_entry->code,
i, key_entry->gpio);
key_state->debounce = DEBOUNCE_NOTPRESSED;
continue;
}
/* key is stable */
ds->debounce_count--;
if (ds->use_irq)
key_state->debounce |= DEBOUNCE_WAIT_IRQ;
else
key_state->debounce |= DEBOUNCE_POLL;
if (gpio_flags & GPIOEDF_PRINT_KEYS)
pr_info("gpio_keys_scan_keys: key %x-%x, %d (%d) "
"changed to %d\n", ds->info->type,
key_entry->code, i, key_entry->gpio, pressed);
input_event(ds->input_devs->dev[key_entry->dev], ds->info->type,
key_entry->code, pressed);
sync_needed = true;
}
if (sync_needed) {
for (i = 0; i < ds->input_devs->count; i++)
input_sync(ds->input_devs->dev[i]);
}
#if 0
key_entry = kp->keys_info->keymap;
key_state = kp->key_state;
for (i = 0; i < nkeys; i++, key_entry++, key_state++) {
pr_info("gpio_read_detect_status %d %d\n", key_entry->gpio,
gpio_read_detect_status(key_entry->gpio));
}
#endif
if (ds->debounce_count)
hrtimer_start(timer, ds->info->debounce_time, HRTIMER_MODE_REL);
else if (!ds->use_irq)
hrtimer_start(timer, ds->info->poll_time, HRTIMER_MODE_REL);
else
wake_unlock(&ds->wake_lock);
spin_unlock_irqrestore(&ds->irq_lock, irqflags);
return HRTIMER_NORESTART;
}
static irqreturn_t gpio_event_input_irq_handler(int irq, void *dev_id)
{
struct gpio_key_state *ks = dev_id;
struct gpio_input_state *ds = ks->ds;
int keymap_index = ks - ds->key_state;
const struct gpio_event_direct_entry *key_entry;
unsigned long irqflags;
int pressed;
if (!ds->use_irq)
return IRQ_HANDLED;
key_entry = &ds->info->keymap[keymap_index];
if (ds->info->debounce_time.tv64) {
spin_lock_irqsave(&ds->irq_lock, irqflags);
if (ks->debounce & DEBOUNCE_WAIT_IRQ) {
ks->debounce = DEBOUNCE_UNKNOWN;
if (ds->debounce_count++ == 0) {
wake_lock(&ds->wake_lock);
hrtimer_start(
&ds->timer, ds->info->debounce_time,
HRTIMER_MODE_REL);
}
if (ds->info->flags & GPIOEDF_PRINT_KEY_DEBOUNCE)
pr_info("gpio_event_input_irq_handler: "
"key %x-%x, %d (%d) start debounce\n",
ds->info->type, key_entry->code,
keymap_index, key_entry->gpio);
} else {
disable_irq_nosync(irq);
ks->debounce = DEBOUNCE_UNSTABLE;
}
spin_unlock_irqrestore(&ds->irq_lock, irqflags);
} else {
pressed = gpio_get_value(key_entry->gpio) ^
!(ds->info->flags & GPIOEDF_ACTIVE_HIGH);
if (ds->info->flags & GPIOEDF_PRINT_KEYS)
pr_info("gpio_event_input_irq_handler: key %x-%x, %d "
"(%d) changed to %d\n",
ds->info->type, key_entry->code, keymap_index,
key_entry->gpio, pressed);
input_event(ds->input_devs->dev[key_entry->dev], ds->info->type,
key_entry->code, pressed);
input_sync(ds->input_devs->dev[key_entry->dev]);
}
return IRQ_HANDLED;
}
static int gpio_event_input_request_irqs(struct gpio_input_state *ds)
{
int i;
int err;
unsigned int irq;
unsigned long req_flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
for (i = 0; i < ds->info->keymap_size; i++) {
err = irq = gpio_to_irq(ds->info->keymap[i].gpio);
if (err < 0)
goto err_gpio_get_irq_num_failed;
err = request_irq(irq, gpio_event_input_irq_handler,
req_flags, "gpio_keys", &ds->key_state[i]);
if (err) {
pr_err("gpio_event_input_request_irqs: request_irq "
"failed for input %d, irq %d\n",
ds->info->keymap[i].gpio, irq);
goto err_request_irq_failed;
}
if (ds->info->info.no_suspend) {
err = enable_irq_wake(irq);
if (err) {
pr_err("gpio_event_input_request_irqs: "
"enable_irq_wake failed for input %d, "
"irq %d\n",
ds->info->keymap[i].gpio, irq);
goto err_enable_irq_wake_failed;
}
}
}
return 0;
for (i = ds->info->keymap_size - 1; i >= 0; i--) {
irq = gpio_to_irq(ds->info->keymap[i].gpio);
if (ds->info->info.no_suspend)
disable_irq_wake(irq);
err_enable_irq_wake_failed:
free_irq(irq, &ds->key_state[i]);
err_request_irq_failed:
err_gpio_get_irq_num_failed:
;
}
return err;
}
int gpio_event_input_func(struct gpio_event_input_devs *input_devs,
struct gpio_event_info *info, void **data, int func)
{
int ret;
int i;
unsigned long irqflags;
struct gpio_event_input_info *di;
struct gpio_input_state *ds = *data;
di = container_of(info, struct gpio_event_input_info, info);
if (func == GPIO_EVENT_FUNC_SUSPEND) {
if (ds->use_irq)
for (i = 0; i < di->keymap_size; i++)
disable_irq(gpio_to_irq(di->keymap[i].gpio));
hrtimer_cancel(&ds->timer);
return 0;
}
if (func == GPIO_EVENT_FUNC_RESUME) {
spin_lock_irqsave(&ds->irq_lock, irqflags);
if (ds->use_irq)
for (i = 0; i < di->keymap_size; i++)
enable_irq(gpio_to_irq(di->keymap[i].gpio));
hrtimer_start(&ds->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
spin_unlock_irqrestore(&ds->irq_lock, irqflags);
return 0;
}
if (func == GPIO_EVENT_FUNC_INIT) {
if (ktime_to_ns(di->poll_time) <= 0)
di->poll_time = ktime_set(0, 20 * NSEC_PER_MSEC);
*data = ds = kzalloc(sizeof(*ds) + sizeof(ds->key_state[0]) *
di->keymap_size, GFP_KERNEL);
if (ds == NULL) {
ret = -ENOMEM;
pr_err("gpio_event_input_func: "
"Failed to allocate private data\n");
goto err_ds_alloc_failed;
}
ds->debounce_count = di->keymap_size;
ds->input_devs = input_devs;
ds->info = di;
wake_lock_init(&ds->wake_lock, WAKE_LOCK_SUSPEND, "gpio_input");
spin_lock_init(&ds->irq_lock);
for (i = 0; i < di->keymap_size; i++) {
int dev = di->keymap[i].dev;
if (dev >= input_devs->count) {
pr_err("gpio_event_input_func: bad device "
"index %d >= %d for key code %d\n",
dev, input_devs->count,
di->keymap[i].code);
ret = -EINVAL;
goto err_bad_keymap;
}
input_set_capability(input_devs->dev[dev], di->type,
di->keymap[i].code);
ds->key_state[i].ds = ds;
ds->key_state[i].debounce = DEBOUNCE_UNKNOWN;
}
for (i = 0; i < di->keymap_size; i++) {
ret = gpio_request(di->keymap[i].gpio, "gpio_kp_in");
if (ret) {
pr_err("gpio_event_input_func: gpio_request "
"failed for %d\n", di->keymap[i].gpio);
goto err_gpio_request_failed;
}
ret = gpio_direction_input(di->keymap[i].gpio);
if (ret) {
pr_err("gpio_event_input_func: "
"gpio_direction_input failed for %d\n",
di->keymap[i].gpio);
goto err_gpio_configure_failed;
}
}
ret = gpio_event_input_request_irqs(ds);
spin_lock_irqsave(&ds->irq_lock, irqflags);
ds->use_irq = ret == 0;
pr_info("GPIO Input Driver: Start gpio inputs for %s%s in %s "
"mode\n", input_devs->dev[0]->name,
(input_devs->count > 1) ? "..." : "",
ret == 0 ? "interrupt" : "polling");
hrtimer_init(&ds->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
ds->timer.function = gpio_event_input_timer_func;
hrtimer_start(&ds->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
spin_unlock_irqrestore(&ds->irq_lock, irqflags);
return 0;
}
ret = 0;
spin_lock_irqsave(&ds->irq_lock, irqflags);
hrtimer_cancel(&ds->timer);
if (ds->use_irq) {
for (i = di->keymap_size - 1; i >= 0; i--) {
int irq = gpio_to_irq(di->keymap[i].gpio);
if (ds->info->info.no_suspend)
disable_irq_wake(irq);
free_irq(irq, &ds->key_state[i]);
}
}
spin_unlock_irqrestore(&ds->irq_lock, irqflags);
for (i = di->keymap_size - 1; i >= 0; i--) {
err_gpio_configure_failed:
gpio_free(di->keymap[i].gpio);
err_gpio_request_failed:
;
}
err_bad_keymap:
wake_lock_destroy(&ds->wake_lock);
kfree(ds);
err_ds_alloc_failed:
return ret;
}
| gpl-2.0 |
jackie099/android_kernel_sony_msm8974 | fs/nilfs2/ifile.c | 4866 | 5318 | /*
* ifile.c - NILFS inode file
*
* Copyright (C) 2006-2008 Nippon Telegraph and Telephone Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by Amagai Yoshiji <amagai@osrg.net>.
* Revised by Ryusuke Konishi <ryusuke@osrg.net>.
*
*/
#include <linux/types.h>
#include <linux/buffer_head.h>
#include "nilfs.h"
#include "mdt.h"
#include "alloc.h"
#include "ifile.h"
struct nilfs_ifile_info {
struct nilfs_mdt_info mi;
struct nilfs_palloc_cache palloc_cache;
};
static inline struct nilfs_ifile_info *NILFS_IFILE_I(struct inode *ifile)
{
return (struct nilfs_ifile_info *)NILFS_MDT(ifile);
}
/**
* nilfs_ifile_create_inode - create a new disk inode
* @ifile: ifile inode
* @out_ino: pointer to a variable to store inode number
* @out_bh: buffer_head contains newly allocated disk inode
*
* Return Value: On success, 0 is returned and the newly allocated inode
* number is stored in the place pointed by @ino, and buffer_head pointer
* that contains newly allocated disk inode structure is stored in the
* place pointed by @out_bh
* On error, one of the following negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-ENOSPC - No inode left.
*/
int nilfs_ifile_create_inode(struct inode *ifile, ino_t *out_ino,
struct buffer_head **out_bh)
{
struct nilfs_palloc_req req;
int ret;
req.pr_entry_nr = 0; /* 0 says find free inode from beginning of
a group. dull code!! */
req.pr_entry_bh = NULL;
ret = nilfs_palloc_prepare_alloc_entry(ifile, &req);
if (!ret) {
ret = nilfs_palloc_get_entry_block(ifile, req.pr_entry_nr, 1,
&req.pr_entry_bh);
if (ret < 0)
nilfs_palloc_abort_alloc_entry(ifile, &req);
}
if (ret < 0) {
brelse(req.pr_entry_bh);
return ret;
}
nilfs_palloc_commit_alloc_entry(ifile, &req);
mark_buffer_dirty(req.pr_entry_bh);
nilfs_mdt_mark_dirty(ifile);
*out_ino = (ino_t)req.pr_entry_nr;
*out_bh = req.pr_entry_bh;
return 0;
}
/**
* nilfs_ifile_delete_inode - delete a disk inode
* @ifile: ifile inode
* @ino: inode number
*
* Return Value: On success, 0 is returned. On error, one of the following
* negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-ENOENT - The inode number @ino have not been allocated.
*/
int nilfs_ifile_delete_inode(struct inode *ifile, ino_t ino)
{
struct nilfs_palloc_req req = {
.pr_entry_nr = ino, .pr_entry_bh = NULL
};
struct nilfs_inode *raw_inode;
void *kaddr;
int ret;
ret = nilfs_palloc_prepare_free_entry(ifile, &req);
if (!ret) {
ret = nilfs_palloc_get_entry_block(ifile, req.pr_entry_nr, 0,
&req.pr_entry_bh);
if (ret < 0)
nilfs_palloc_abort_free_entry(ifile, &req);
}
if (ret < 0) {
brelse(req.pr_entry_bh);
return ret;
}
kaddr = kmap_atomic(req.pr_entry_bh->b_page);
raw_inode = nilfs_palloc_block_get_entry(ifile, req.pr_entry_nr,
req.pr_entry_bh, kaddr);
raw_inode->i_flags = 0;
kunmap_atomic(kaddr);
mark_buffer_dirty(req.pr_entry_bh);
brelse(req.pr_entry_bh);
nilfs_palloc_commit_free_entry(ifile, &req);
return 0;
}
int nilfs_ifile_get_inode_block(struct inode *ifile, ino_t ino,
struct buffer_head **out_bh)
{
struct super_block *sb = ifile->i_sb;
int err;
if (unlikely(!NILFS_VALID_INODE(sb, ino))) {
nilfs_error(sb, __func__, "bad inode number: %lu",
(unsigned long) ino);
return -EINVAL;
}
err = nilfs_palloc_get_entry_block(ifile, ino, 0, out_bh);
if (unlikely(err))
nilfs_warning(sb, __func__, "unable to read inode: %lu",
(unsigned long) ino);
return err;
}
/**
* nilfs_ifile_read - read or get ifile inode
* @sb: super block instance
* @root: root object
* @inode_size: size of an inode
* @raw_inode: on-disk ifile inode
* @inodep: buffer to store the inode
*/
int nilfs_ifile_read(struct super_block *sb, struct nilfs_root *root,
size_t inode_size, struct nilfs_inode *raw_inode,
struct inode **inodep)
{
struct inode *ifile;
int err;
ifile = nilfs_iget_locked(sb, root, NILFS_IFILE_INO);
if (unlikely(!ifile))
return -ENOMEM;
if (!(ifile->i_state & I_NEW))
goto out;
err = nilfs_mdt_init(ifile, NILFS_MDT_GFP,
sizeof(struct nilfs_ifile_info));
if (err)
goto failed;
err = nilfs_palloc_init_blockgroup(ifile, inode_size);
if (err)
goto failed;
nilfs_palloc_setup_cache(ifile, &NILFS_IFILE_I(ifile)->palloc_cache);
err = nilfs_read_inode_common(ifile, raw_inode);
if (err)
goto failed;
unlock_new_inode(ifile);
out:
*inodep = ifile;
return 0;
failed:
iget_failed(ifile);
return err;
}
| gpl-2.0 |
vwmofo/android_kernel_htc_liberty-villec2 | arch/arm/mach-omap2/sdrc2xxx.c | 4866 | 4427 | /*
* linux/arch/arm/mach-omap2/sdrc2xxx.c
*
* SDRAM timing related functions for OMAP2xxx
*
* Copyright (C) 2005, 2008 Texas Instruments Inc.
* Copyright (C) 2005, 2008 Nokia Corporation
*
* Tony Lindgren <tony@atomide.com>
* Paul Walmsley
* Richard Woodruff <r-woodruff2@ti.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 <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/list.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/hardware.h>
#include <plat/clock.h>
#include <plat/sram.h>
#include <plat/sdrc.h>
#include "iomap.h"
#include "common.h"
#include "prm2xxx_3xxx.h"
#include "clock.h"
#include "sdrc.h"
/* Memory timing, DLL mode flags */
#define M_DDR 1
#define M_LOCK_CTRL (1 << 2)
#define M_UNLOCK 0
#define M_LOCK 1
static struct memory_timings mem_timings;
static u32 curr_perf_level = CORE_CLK_SRC_DPLL_X2;
static u32 omap2xxx_sdrc_get_slow_dll_ctrl(void)
{
return mem_timings.slow_dll_ctrl;
}
static u32 omap2xxx_sdrc_get_fast_dll_ctrl(void)
{
return mem_timings.fast_dll_ctrl;
}
static u32 omap2xxx_sdrc_get_type(void)
{
return mem_timings.m_type;
}
/*
* Check the DLL lock state, and return tue if running in unlock mode.
* This is needed to compensate for the shifted DLL value in unlock mode.
*/
u32 omap2xxx_sdrc_dll_is_unlocked(void)
{
/* dlla and dllb are a set */
u32 dll_state = sdrc_read_reg(SDRC_DLLA_CTRL);
if ((dll_state & (1 << 2)) == (1 << 2))
return 1;
else
return 0;
}
/*
* 'level' is the value to store to CM_CLKSEL2_PLL.CORE_CLK_SRC.
* Practical values are CORE_CLK_SRC_DPLL (for CORE_CLK = DPLL_CLK) or
* CORE_CLK_SRC_DPLL_X2 (for CORE_CLK = * DPLL_CLK * 2)
*
* Used by the clock framework during CORE DPLL changes
*/
u32 omap2xxx_sdrc_reprogram(u32 level, u32 force)
{
u32 dll_ctrl, m_type;
u32 prev = curr_perf_level;
unsigned long flags;
if ((curr_perf_level == level) && !force)
return prev;
if (level == CORE_CLK_SRC_DPLL)
dll_ctrl = omap2xxx_sdrc_get_slow_dll_ctrl();
else if (level == CORE_CLK_SRC_DPLL_X2)
dll_ctrl = omap2xxx_sdrc_get_fast_dll_ctrl();
else
return prev;
m_type = omap2xxx_sdrc_get_type();
local_irq_save(flags);
/*
* XXX These calls should be abstracted out through a
* prm2xxx.c function
*/
if (cpu_is_omap2420())
__raw_writel(0xffff, OMAP2420_PRCM_VOLTSETUP);
else
__raw_writel(0xffff, OMAP2430_PRCM_VOLTSETUP);
omap2_sram_reprogram_sdrc(level, dll_ctrl, m_type);
curr_perf_level = level;
local_irq_restore(flags);
return prev;
}
/* Used by the clock framework during CORE DPLL changes */
void omap2xxx_sdrc_init_params(u32 force_lock_to_unlock_mode)
{
unsigned long dll_cnt;
u32 fast_dll = 0;
/* DDR = 1, SDR = 0 */
mem_timings.m_type = !((sdrc_read_reg(SDRC_MR_0) & 0x3) == 0x1);
/* 2422 es2.05 and beyond has a single SIP DDR instead of 2 like others.
* In the case of 2422, its ok to use CS1 instead of CS0.
*/
if (cpu_is_omap2422())
mem_timings.base_cs = 1;
else
mem_timings.base_cs = 0;
if (mem_timings.m_type != M_DDR)
return;
/* With DDR we need to determine the low frequency DLL value */
if (((mem_timings.fast_dll_ctrl & (1 << 2)) == M_LOCK_CTRL))
mem_timings.dll_mode = M_UNLOCK;
else
mem_timings.dll_mode = M_LOCK;
if (mem_timings.base_cs == 0) {
fast_dll = sdrc_read_reg(SDRC_DLLA_CTRL);
dll_cnt = sdrc_read_reg(SDRC_DLLA_STATUS) & 0xff00;
} else {
fast_dll = sdrc_read_reg(SDRC_DLLB_CTRL);
dll_cnt = sdrc_read_reg(SDRC_DLLB_STATUS) & 0xff00;
}
if (force_lock_to_unlock_mode) {
fast_dll &= ~0xff00;
fast_dll |= dll_cnt; /* Current lock mode */
}
/* set fast timings with DLL filter disabled */
mem_timings.fast_dll_ctrl = (fast_dll | (3 << 8));
/* No disruptions, DDR will be offline & C-ABI not followed */
omap2_sram_ddr_init(&mem_timings.slow_dll_ctrl,
mem_timings.fast_dll_ctrl,
mem_timings.base_cs,
force_lock_to_unlock_mode);
mem_timings.slow_dll_ctrl &= 0xff00; /* Keep lock value */
/* Turn status into unlock ctrl */
mem_timings.slow_dll_ctrl |=
((mem_timings.fast_dll_ctrl & 0xF) | (1 << 2));
/* 90 degree phase for anything below 133Mhz + disable DLL filter */
mem_timings.slow_dll_ctrl |= ((1 << 1) | (3 << 8));
}
| gpl-2.0 |
armStrapTools/linux-sunxi-ap6210 | drivers/ide/opti621.c | 9218 | 4592 | /*
* Copyright (C) 1996-1998 Linus Torvalds & authors (see below)
*/
/*
* Authors:
* Jaromir Koutek <miri@punknet.cz>,
* Jan Harkes <jaharkes@cwi.nl>,
* Mark Lord <mlord@pobox.com>
* Some parts of code are from ali14xx.c and from rz1000.c.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/ide.h>
#include <asm/io.h>
#define DRV_NAME "opti621"
#define READ_REG 0 /* index of Read cycle timing register */
#define WRITE_REG 1 /* index of Write cycle timing register */
#define CNTRL_REG 3 /* index of Control register */
#define STRAP_REG 5 /* index of Strap register */
#define MISC_REG 6 /* index of Miscellaneous register */
static int reg_base;
static DEFINE_SPINLOCK(opti621_lock);
/* Write value to register reg, base of register
* is at reg_base (0x1f0 primary, 0x170 secondary,
* if not changed by PCI configuration).
* This is from setupvic.exe program.
*/
static void write_reg(u8 value, int reg)
{
inw(reg_base + 1);
inw(reg_base + 1);
outb(3, reg_base + 2);
outb(value, reg_base + reg);
outb(0x83, reg_base + 2);
}
/* Read value from register reg, base of register
* is at reg_base (0x1f0 primary, 0x170 secondary,
* if not changed by PCI configuration).
* This is from setupvic.exe program.
*/
static u8 read_reg(int reg)
{
u8 ret = 0;
inw(reg_base + 1);
inw(reg_base + 1);
outb(3, reg_base + 2);
ret = inb(reg_base + reg);
outb(0x83, reg_base + 2);
return ret;
}
static void opti621_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
ide_drive_t *pair = ide_get_pair_dev(drive);
unsigned long flags;
unsigned long mode = drive->pio_mode, pair_mode;
const u8 pio = mode - XFER_PIO_0;
u8 tim, misc, addr_pio = pio, clk;
/* DRDY is default 2 (by OPTi Databook) */
static const u8 addr_timings[2][5] = {
{ 0x20, 0x10, 0x00, 0x00, 0x00 }, /* 33 MHz */
{ 0x10, 0x10, 0x00, 0x00, 0x00 }, /* 25 MHz */
};
static const u8 data_rec_timings[2][5] = {
{ 0x5b, 0x45, 0x32, 0x21, 0x20 }, /* 33 MHz */
{ 0x48, 0x34, 0x21, 0x10, 0x10 } /* 25 MHz */
};
ide_set_drivedata(drive, (void *)mode);
if (pair) {
pair_mode = (unsigned long)ide_get_drivedata(pair);
if (pair_mode && pair_mode < mode)
addr_pio = pair_mode - XFER_PIO_0;
}
spin_lock_irqsave(&opti621_lock, flags);
reg_base = hwif->io_ports.data_addr;
/* allow Register-B */
outb(0xc0, reg_base + CNTRL_REG);
/* hmm, setupvic.exe does this ;-) */
outb(0xff, reg_base + 5);
/* if reads 0xff, adapter not exist? */
(void)inb(reg_base + CNTRL_REG);
/* if reads 0xc0, no interface exist? */
read_reg(CNTRL_REG);
/* check CLK speed */
clk = read_reg(STRAP_REG) & 1;
printk(KERN_INFO "%s: CLK = %d MHz\n", hwif->name, clk ? 25 : 33);
tim = data_rec_timings[clk][pio];
misc = addr_timings[clk][addr_pio];
/* select Index-0/1 for Register-A/B */
write_reg(drive->dn & 1, MISC_REG);
/* set read cycle timings */
write_reg(tim, READ_REG);
/* set write cycle timings */
write_reg(tim, WRITE_REG);
/* use Register-A for drive 0 */
/* use Register-B for drive 1 */
write_reg(0x85, CNTRL_REG);
/* set address setup, DRDY timings, */
/* and read prefetch for both drives */
write_reg(misc, MISC_REG);
spin_unlock_irqrestore(&opti621_lock, flags);
}
static const struct ide_port_ops opti621_port_ops = {
.set_pio_mode = opti621_set_pio_mode,
};
static const struct ide_port_info opti621_chipset __devinitdata = {
.name = DRV_NAME,
.enablebits = { {0x45, 0x80, 0x00}, {0x40, 0x08, 0x00} },
.port_ops = &opti621_port_ops,
.host_flags = IDE_HFLAG_NO_DMA,
.pio_mask = ATA_PIO4,
};
static int __devinit opti621_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
return ide_pci_init_one(dev, &opti621_chipset, NULL);
}
static const struct pci_device_id opti621_pci_tbl[] = {
{ PCI_VDEVICE(OPTI, PCI_DEVICE_ID_OPTI_82C621), 0 },
{ PCI_VDEVICE(OPTI, PCI_DEVICE_ID_OPTI_82C825), 0 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, opti621_pci_tbl);
static struct pci_driver opti621_pci_driver = {
.name = "Opti621_IDE",
.id_table = opti621_pci_tbl,
.probe = opti621_init_one,
.remove = ide_pci_remove,
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init opti621_ide_init(void)
{
return ide_pci_register_driver(&opti621_pci_driver);
}
static void __exit opti621_ide_exit(void)
{
pci_unregister_driver(&opti621_pci_driver);
}
module_init(opti621_ide_init);
module_exit(opti621_ide_exit);
MODULE_AUTHOR("Jaromir Koutek, Jan Harkes, Mark Lord");
MODULE_DESCRIPTION("PCI driver module for Opti621 IDE");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ShikharArvind/android_kernel_xolo_q1100 | drivers/clocksource/scx200_hrt.c | 9474 | 2816 | /*
* Copyright (C) 2006 Jim Cromie
*
* This is a clocksource driver for the Geode SCx200's 1 or 27 MHz
* high-resolution timer. The Geode SC-1100 (at least) has a buggy
* time stamp counter (TSC), which loses time unless 'idle=poll' is
* given as a boot-arg. In its absence, the Generic Timekeeping code
* will detect and de-rate the bad TSC, allowing this timer to take
* over timekeeping duties.
*
* Based on work by John Stultz, and Ted Phelps (in a 2.6.12-rc6 patch)
*
* 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 <linux/clocksource.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/scx200.h>
#define NAME "scx200_hrt"
static int mhz27;
module_param(mhz27, int, 0); /* load time only */
MODULE_PARM_DESC(mhz27, "count at 27.0 MHz (default is 1.0 MHz)");
static int ppm;
module_param(ppm, int, 0); /* load time only */
MODULE_PARM_DESC(ppm, "+-adjust to actual XO freq (ppm)");
/* HiRes Timer configuration register address */
#define SCx200_TMCNFG_OFFSET (SCx200_TIMER_OFFSET + 5)
/* and config settings */
#define HR_TMEN (1 << 0) /* timer interrupt enable */
#define HR_TMCLKSEL (1 << 1) /* 1|0 counts at 27|1 MHz */
#define HR_TM27MPD (1 << 2) /* 1 turns off input clock (power-down) */
/* The base timer frequency, * 27 if selected */
#define HRT_FREQ 1000000
static cycle_t read_hrt(struct clocksource *cs)
{
/* Read the timer value */
return (cycle_t) inl(scx200_cb_base + SCx200_TIMER_OFFSET);
}
static struct clocksource cs_hrt = {
.name = "scx200_hrt",
.rating = 250,
.read = read_hrt,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
/* mult, shift are set based on mhz27 flag */
};
static int __init init_hrt_clocksource(void)
{
u32 freq;
/* Make sure scx200 has initialized the configuration block */
if (!scx200_cb_present())
return -ENODEV;
/* Reserve the timer's ISA io-region for ourselves */
if (!request_region(scx200_cb_base + SCx200_TIMER_OFFSET,
SCx200_TIMER_SIZE,
"NatSemi SCx200 High-Resolution Timer")) {
pr_warn("unable to lock timer region\n");
return -ENODEV;
}
/* write timer config */
outb(HR_TMEN | (mhz27 ? HR_TMCLKSEL : 0),
scx200_cb_base + SCx200_TMCNFG_OFFSET);
freq = (HRT_FREQ + ppm);
if (mhz27)
freq *= 27;
pr_info("enabling scx200 high-res timer (%s MHz +%d ppm)\n", mhz27 ? "27":"1", ppm);
return clocksource_register_hz(&cs_hrt, freq);
}
module_init(init_hrt_clocksource);
MODULE_AUTHOR("Jim Cromie <jim.cromie@gmail.com>");
MODULE_DESCRIPTION("clocksource on SCx200 HiRes Timer");
MODULE_LICENSE("GPL");
| gpl-2.0 |
CPDroid/Samsung_STE_Kernel | arch/cris/arch-v10/lib/memset.c | 27906 | 7459 | /* A memset for CRIS.
Copyright (C) 1999-2005 Axis Communications.
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. Neither the name of Axis Communications nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY AXIS COMMUNICATIONS AND ITS CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AXIS
COMMUNICATIONS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. */
/* FIXME: This file should really only be used for reference, as the
result is somewhat depending on gcc generating what we expect rather
than what we describe. An assembly file should be used instead. */
/* Note the multiple occurrence of the expression "12*4", including the
asm. It is hard to get it into the asm in a good way. Thus better to
expose the problem everywhere: no macro. */
/* Assuming one cycle per dword written or read (ok, not really true; the
world is not ideal), and one cycle per instruction, then 43+3*(n/48-1)
<= 24+24*(n/48-1) so n >= 45.7; n >= 0.9; we win on the first full
48-byte block to set. */
#define MEMSET_BY_BLOCK_THRESHOLD (1 * 48)
/* No name ambiguities in this file. */
__asm__ (".syntax no_register_prefix");
void *memset(void *pdst, int c, unsigned int plen)
{
/* Now we want the parameters in special registers. Make sure the
compiler does something usable with this. */
register char *return_dst __asm__ ("r10") = pdst;
register int n __asm__ ("r12") = plen;
register int lc __asm__ ("r11") = c;
/* Most apps use memset sanely. Memsetting about 3..4 bytes or less get
penalized here compared to the generic implementation. */
/* This is fragile performancewise at best. Check with newer GCC
releases, if they compile cascaded "x |= x << 8" to sane code. */
__asm__("movu.b %0,r13 \n\
lslq 8,r13 \n\
move.b %0,r13 \n\
move.d r13,%0 \n\
lslq 16,r13 \n\
or.d r13,%0"
: "=r" (lc) /* Inputs. */
: "0" (lc) /* Outputs. */
: "r13"); /* Trash. */
{
register char *dst __asm__ ("r13") = pdst;
if (((unsigned long) pdst & 3) != 0
/* Oops! n = 0 must be a valid call, regardless of alignment. */
&& n >= 3)
{
if ((unsigned long) dst & 1)
{
*dst = (char) lc;
n--;
dst++;
}
if ((unsigned long) dst & 2)
{
*(short *) dst = lc;
n -= 2;
dst += 2;
}
}
/* Decide which setting method to use. */
if (n >= MEMSET_BY_BLOCK_THRESHOLD)
{
/* It is not optimal to tell the compiler about clobbering any
registers; that will move the saving/restoring of those registers
to the function prologue/epilogue, and make non-block sizes
suboptimal. */
__asm__ volatile
("\
;; GCC does promise correct register allocations, but let's \n\
;; make sure it keeps its promises. \n\
.ifnc %0-%1-%4,$r13-$r12-$r11 \n\
.error \"GCC reg alloc bug: %0-%1-%4 != $r13-$r12-$r11\" \n\
.endif \n\
\n\
;; Save the registers we'll clobber in the movem process \n\
;; on the stack. Don't mention them to gcc, it will only be \n\
;; upset. \n\
subq 11*4,sp \n\
movem r10,[sp] \n\
\n\
move.d r11,r0 \n\
move.d r11,r1 \n\
move.d r11,r2 \n\
move.d r11,r3 \n\
move.d r11,r4 \n\
move.d r11,r5 \n\
move.d r11,r6 \n\
move.d r11,r7 \n\
move.d r11,r8 \n\
move.d r11,r9 \n\
move.d r11,r10 \n\
\n\
;; Now we've got this: \n\
;; r13 - dst \n\
;; r12 - n \n\
\n\
;; Update n for the first loop \n\
subq 12*4,r12 \n\
0: \n\
"
#ifdef __arch_common_v10_v32
/* Cater to branch offset difference between v32 and v10. We
assume the branch below has an 8-bit offset. */
" setf\n"
#endif
" subq 12*4,r12 \n\
bge 0b \n\
movem r11,[r13+] \n\
\n\
;; Compensate for last loop underflowing n. \n\
addq 12*4,r12 \n\
\n\
;; Restore registers from stack. \n\
movem [sp+],r10"
/* Outputs. */
: "=r" (dst), "=r" (n)
/* Inputs. */
: "0" (dst), "1" (n), "r" (lc));
}
/* An ad-hoc unroll, used for 4*12-1..16 bytes. */
while (n >= 16)
{
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
n -= 16;
}
switch (n)
{
case 0:
break;
case 1:
*dst = (char) lc;
break;
case 2:
*(short *) dst = (short) lc;
break;
case 3:
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 4:
*(long *) dst = lc;
break;
case 5:
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 6:
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 7:
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 8:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc;
break;
case 9:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 10:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 11:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 12:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc;
break;
case 13:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 14:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 15:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
}
}
return return_dst;
}
| gpl-2.0 |
droidroidz/USCC_R970_kernel | arch/cris/arch-v32/lib/memset.c | 27906 | 7459 | /* A memset for CRIS.
Copyright (C) 1999-2005 Axis Communications.
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. Neither the name of Axis Communications nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY AXIS COMMUNICATIONS AND ITS CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AXIS
COMMUNICATIONS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. */
/* FIXME: This file should really only be used for reference, as the
result is somewhat depending on gcc generating what we expect rather
than what we describe. An assembly file should be used instead. */
/* Note the multiple occurrence of the expression "12*4", including the
asm. It is hard to get it into the asm in a good way. Thus better to
expose the problem everywhere: no macro. */
/* Assuming one cycle per dword written or read (ok, not really true; the
world is not ideal), and one cycle per instruction, then 43+3*(n/48-1)
<= 24+24*(n/48-1) so n >= 45.7; n >= 0.9; we win on the first full
48-byte block to set. */
#define MEMSET_BY_BLOCK_THRESHOLD (1 * 48)
/* No name ambiguities in this file. */
__asm__ (".syntax no_register_prefix");
void *memset(void *pdst, int c, unsigned int plen)
{
/* Now we want the parameters in special registers. Make sure the
compiler does something usable with this. */
register char *return_dst __asm__ ("r10") = pdst;
register int n __asm__ ("r12") = plen;
register int lc __asm__ ("r11") = c;
/* Most apps use memset sanely. Memsetting about 3..4 bytes or less get
penalized here compared to the generic implementation. */
/* This is fragile performancewise at best. Check with newer GCC
releases, if they compile cascaded "x |= x << 8" to sane code. */
__asm__("movu.b %0,r13 \n\
lslq 8,r13 \n\
move.b %0,r13 \n\
move.d r13,%0 \n\
lslq 16,r13 \n\
or.d r13,%0"
: "=r" (lc) /* Inputs. */
: "0" (lc) /* Outputs. */
: "r13"); /* Trash. */
{
register char *dst __asm__ ("r13") = pdst;
if (((unsigned long) pdst & 3) != 0
/* Oops! n = 0 must be a valid call, regardless of alignment. */
&& n >= 3)
{
if ((unsigned long) dst & 1)
{
*dst = (char) lc;
n--;
dst++;
}
if ((unsigned long) dst & 2)
{
*(short *) dst = lc;
n -= 2;
dst += 2;
}
}
/* Decide which setting method to use. */
if (n >= MEMSET_BY_BLOCK_THRESHOLD)
{
/* It is not optimal to tell the compiler about clobbering any
registers; that will move the saving/restoring of those registers
to the function prologue/epilogue, and make non-block sizes
suboptimal. */
__asm__ volatile
("\
;; GCC does promise correct register allocations, but let's \n\
;; make sure it keeps its promises. \n\
.ifnc %0-%1-%4,$r13-$r12-$r11 \n\
.error \"GCC reg alloc bug: %0-%1-%4 != $r13-$r12-$r11\" \n\
.endif \n\
\n\
;; Save the registers we'll clobber in the movem process \n\
;; on the stack. Don't mention them to gcc, it will only be \n\
;; upset. \n\
subq 11*4,sp \n\
movem r10,[sp] \n\
\n\
move.d r11,r0 \n\
move.d r11,r1 \n\
move.d r11,r2 \n\
move.d r11,r3 \n\
move.d r11,r4 \n\
move.d r11,r5 \n\
move.d r11,r6 \n\
move.d r11,r7 \n\
move.d r11,r8 \n\
move.d r11,r9 \n\
move.d r11,r10 \n\
\n\
;; Now we've got this: \n\
;; r13 - dst \n\
;; r12 - n \n\
\n\
;; Update n for the first loop \n\
subq 12*4,r12 \n\
0: \n\
"
#ifdef __arch_common_v10_v32
/* Cater to branch offset difference between v32 and v10. We
assume the branch below has an 8-bit offset. */
" setf\n"
#endif
" subq 12*4,r12 \n\
bge 0b \n\
movem r11,[r13+] \n\
\n\
;; Compensate for last loop underflowing n. \n\
addq 12*4,r12 \n\
\n\
;; Restore registers from stack. \n\
movem [sp+],r10"
/* Outputs. */
: "=r" (dst), "=r" (n)
/* Inputs. */
: "0" (dst), "1" (n), "r" (lc));
}
/* An ad-hoc unroll, used for 4*12-1..16 bytes. */
while (n >= 16)
{
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
n -= 16;
}
switch (n)
{
case 0:
break;
case 1:
*dst = (char) lc;
break;
case 2:
*(short *) dst = (short) lc;
break;
case 3:
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 4:
*(long *) dst = lc;
break;
case 5:
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 6:
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 7:
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 8:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc;
break;
case 9:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 10:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 11:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 12:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc;
break;
case 13:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 14:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 15:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
}
}
return return_dst;
}
| gpl-2.0 |
tuxkids/kernel_cyanogen_gio | drivers/misc/sec_jack.c | 3 | 13436 | /*
* headset/ear-jack device detection driver.
*
* Copyright (C) 2010 Samsung Electronics Co.Ltd
*
* 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.
*/
#include <linux/module.h>
#include <linux/sysdev.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/input.h>
#include <linux/platform_device.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/switch.h>
#include <linux/input.h>
#include <linux/timer.h>
#include <linux/wakelock.h>
#include <linux/slab.h>
#include <linux/sec_jack.h>
#define MODULE_NAME "sec_jack:"
#define MAX_ZONE_LIMIT 10
#define SEND_KEY_CHECK_TIME_MS 60 /* 60ms */
#define DET_CHECK_TIME_MS 200 /* 200ms */
#define WAKE_LOCK_TIME (HZ * 5) /* 5 sec */
#if (defined(CONFIG_MACH_COOPER) || defined(CONFIG_MACH_GIO))
#undef FEATURE_HSSD
#endif
#define SUPPORT_PBA
#ifdef CONFIG_MACH_CALLISTO
#define SUPPORT_EARADC_CHECK
#endif
#ifdef SUPPORT_PBA
struct class *jack_class;
EXPORT_SYMBOL(jack_class);
/* Sysfs device, this is used for communication with Cal App. */
static struct device *jack_selector_fs;
EXPORT_SYMBOL(jack_selector_fs);
#endif
extern unsigned int on_call;
struct sec_jack_info {
struct sec_jack_platform_data *pdata;
struct delayed_work jack_detect_work;
struct input_dev *input;
struct wake_lock det_wake_lock;
struct sec_jack_zone *zone;
bool send_key_pressed;
bool send_key_irq_enabled;
unsigned int cur_jack_type;
};
/* sysfs name HeadsetObserver.java looks for to track headset state
*/
struct switch_dev switch_jack_detection = {
.name = "h2w",
};
/* To support samsung factory test */
struct switch_dev switch_sendend = {
.name = "sec_earbutton",
};
static void set_send_key_state(struct sec_jack_info *hi, int state)
{
input_report_key(hi->input, KEY_MEDIA, state);
input_sync(hi->input);
switch_set_state(&switch_sendend, state);
hi->send_key_pressed = state;
}
static void sec_jack_set_type(struct sec_jack_info *hi, int jack_type)
{
struct sec_jack_platform_data *pdata = hi->pdata;
/* this can happen during slow inserts where we think we identified
* the type but then we get another interrupt and do it again
*/
if (jack_type == hi->cur_jack_type)
return;
if (jack_type == SEC_HEADSET_4POLE) {
/* for a 4 pole headset, enable irq
for detecting send/end key presses */
if (!hi->send_key_irq_enabled) {
enable_irq(pdata->send_int);
enable_irq_wake(pdata->send_int);
hi->send_key_irq_enabled = 1;
}
} else {
/* for all other jacks, disable send/end irq */
if (hi->send_key_irq_enabled) {
disable_irq(pdata->send_int);
disable_irq_wake(pdata->send_int);
hi->send_key_irq_enabled = 0;
}
if (hi->send_key_pressed) {
set_send_key_state(hi, 0);
pr_info(MODULE_NAME "%s : BTN set released by jack switch to %d\n",
__func__, jack_type);
}
}
/* micbias is left enabled for 4pole and disabled otherwise */
//pdata->set_micbias_state(hi->send_key_irq_enabled);
/* because of ESD, micbias always remain high. for only 7x27 device*/
//pdata->set_micbias_state(true);
hi->cur_jack_type = jack_type;
pr_info(MODULE_NAME "%s : jack_type = %d\n", __func__, jack_type);
/* prevent suspend to allow user space to respond to switch */
wake_lock_timeout(&hi->det_wake_lock, WAKE_LOCK_TIME);
switch_set_state(&switch_jack_detection, jack_type);
}
static void handle_jack_not_inserted(struct sec_jack_info *hi)
{
sec_jack_set_type(hi, SEC_JACK_NO_DEVICE);
/* because of ESD, micbias always remain high. for only 7x27 device*/
//hi->pdata->set_micbias_state(false);
}
static void determine_jack_type(struct sec_jack_info *hi)
{
struct sec_jack_zone *zones = hi->pdata->zones;
int size = hi->pdata->num_zones;
int count[MAX_ZONE_LIMIT] = {0};
int adc;
int i;
while (hi->pdata->get_det_jack_state()) {
adc = hi->pdata->get_adc_value();
pr_debug(MODULE_NAME "adc = %d\n", adc);
/* determine the type of headset based on the
* adc value. An adc value can fall in various
* ranges or zones. Within some ranges, the type
* can be returned immediately. Within others, the
* value is considered unstable and we need to sample
* a few more types (up to the limit determined by
* the range) before we return the type for that range.
*/
for (i = 0; i < size; i++) {
if (adc <= zones[i].adc_high) {
if (++count[i] > zones[i].check_count) {
sec_jack_set_type(hi,
zones[i].jack_type);
return;
}
msleep(zones[i].delay_ms);
break;
}
}
}
/* jack removed before detection complete */
handle_jack_not_inserted(hi);
}
/* thread run whenever the headset detect state changes (either insertion
* or removal).
*/
static irqreturn_t sec_jack_detect_irq_thread(int irq, void *dev_id)
{
struct sec_jack_info *hi = dev_id;
struct sec_jack_platform_data *pdata = hi->pdata;
int time_left_ms = DET_CHECK_TIME_MS;
/* debounce headset jack. don't try to determine the type of
* headset until the detect state is true for a while.
*/
while (time_left_ms > 0) {
if (!pdata->get_det_jack_state()) {
/* jack not detected. */
handle_jack_not_inserted(hi);
return IRQ_HANDLED;
}
msleep(10);
time_left_ms -= 10;
}
/* set mic bias to enable adc */
pdata->set_micbias_state(true);
/* jack presence was detected the whole time, figure out which type */
determine_jack_type(hi);
return IRQ_HANDLED;
}
#ifdef SUPPORT_PBA
static ssize_t select_jack_show(struct device *dev, struct device_attribute *attr, char *buf)
{
pr_info("%s : operate nothing\n", __func__);
return 0;
}
static ssize_t select_jack_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size)
{
struct sec_jack_info *hi = dev_get_drvdata(dev);
struct sec_jack_platform_data *pdata = hi->pdata;
int value = 0;
sscanf(buf, "%d", &value);
pr_err("%s: User selection : 0X%x", __func__, value);
if (value == SEC_HEADSET_4POLE) {
pdata->set_micbias_state(true);
msleep(100);
}
sec_jack_set_type(hi, value);
return size;
}
static DEVICE_ATTR(select_jack, S_IRUGO | S_IWUSR | S_IWGRP , select_jack_show, select_jack_store);
#endif
/* thread run whenever the send/end key state changes. irq thread
* handles don't need wake locks and since this one reports using
* input_dev, input_dev guarantees that user space gets event
* without needing a wake_lock.
*/
static irqreturn_t sec_jack_send_key_irq_thread(int irq, void *dev_id)
{
struct sec_jack_info *hi = dev_id;
struct sec_jack_platform_data *pdata = hi->pdata;
int time_left_ms = SEND_KEY_CHECK_TIME_MS;
int send_key_state=0;
#ifdef SUPPORT_EARADC_CHECK
int adc;
#endif
/* debounce send/end key */
while (time_left_ms > 0 && !hi->send_key_pressed) {
send_key_state = pdata->get_send_key_state();
#ifdef SUPPORT_EARADC_CHECK
adc = hi->pdata->get_adc_value();
pr_debug(MODULE_NAME "sendend adc = %d\n", adc);
#endif
if (!send_key_state || !pdata->get_det_jack_state() ||
hi->cur_jack_type != SEC_HEADSET_4POLE) {
/* button released or jack removed or more
* strangely a non-4pole headset
*/
pr_info(MODULE_NAME "%s : ignored button (%d %d %d)\n", __func__,
!send_key_state, !pdata->get_det_jack_state(),
hi->cur_jack_type != SEC_HEADSET_4POLE );
return IRQ_HANDLED;
}
#ifdef SUPPORT_EARADC_CHECK
else if (adc > 120)
{
return IRQ_HANDLED;
}
#endif
msleep(10);
time_left_ms -= 10;
}
/* report state change of the send_end_key */
if (hi->send_key_pressed != send_key_state) {
set_send_key_state(hi, send_key_state);
pr_info(MODULE_NAME "%s : BTN is %s.\n",
__func__, send_key_state ? "pressed" : "released");
}
return IRQ_HANDLED;
}
static int sec_jack_probe(struct platform_device *pdev)
{
struct sec_jack_info *hi;
struct sec_jack_platform_data *pdata = pdev->dev.platform_data;
int ret;
pr_info(MODULE_NAME "%s : Registering jack driver\n", __func__);
if (!pdata) {
pr_err("%s : pdata is NULL.\n", __func__);
return -ENODEV;
}
if (!pdata->get_adc_value || !pdata->get_det_jack_state ||
!pdata->get_send_key_state || !pdata->zones ||
!pdata->set_micbias_state || pdata->num_zones > MAX_ZONE_LIMIT) {
pr_err("%s : need to check pdata\n", __func__);
return -ENODEV;
}
hi = kzalloc(sizeof(struct sec_jack_info), GFP_KERNEL);
if (hi == NULL) {
pr_err("%s : Failed to allocate memory.\n", __func__);
return -ENOMEM;
}
hi->pdata = pdata;
#ifndef FEATURE_HSSD
hi->input = input_allocate_device();
if (hi->input == NULL) {
ret = -ENOMEM;
pr_err("%s : Failed to allocate input device.\n", __func__);
goto err_request_input_dev;
}
hi->input->name = "sec_jack";
input_set_capability(hi->input, EV_KEY, KEY_MEDIA);
ret = input_register_device(hi->input);
if (ret) {
pr_err("%s : Failed to register driver\n", __func__);
goto err_register_input_dev;
}
#endif
ret = switch_dev_register(&switch_jack_detection);
if (ret < 0) {
pr_err("%s : Failed to register switch device\n", __func__);
goto err_switch_dev_register;
}
#ifndef FEATURE_HSSD
ret = switch_dev_register(&switch_sendend);
if (ret < 0) {
pr_err("%s : Failed to register switch device\n", __func__);
goto err_switch_dev_register;
}
#endif
wake_lock_init(&hi->det_wake_lock, WAKE_LOCK_SUSPEND, "sec_jack_det");
#ifdef SUPPORT_PBA
/* Create JACK Device file in Sysfs */
jack_class = class_create(THIS_MODULE, "jack");
if(IS_ERR(jack_class))
{
printk(KERN_ERR "Failed to create class(sec_jack)\n");
}
jack_selector_fs = device_create(jack_class, NULL, 0, hi, "jack_selector");
if (IS_ERR(jack_selector_fs))
printk(KERN_ERR "Failed to create device(sec_jack)!= %ld\n", IS_ERR(jack_selector_fs));
if (device_create_file(jack_selector_fs, &dev_attr_select_jack) < 0)
printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_select_jack.attr.name);
#endif
ret = request_threaded_irq(pdata->det_int, NULL,
sec_jack_detect_irq_thread,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING |
IRQF_ONESHOT, "sec_headset_detect", hi);
if (ret) {
pr_err("%s : Failed to request_irq.\n", __func__);
goto err_request_detect_irq;
}
/* to handle insert/removal when we're sleeping in a call */
ret = enable_irq_wake(pdata->det_int);
if (ret) {
pr_err("%s : Failed to enable_irq_wake.\n", __func__);
goto err_enable_irq_wake;
}
#ifndef FEATURE_HSSD
ret = request_threaded_irq(pdata->send_int, NULL,
sec_jack_send_key_irq_thread,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING |
IRQF_ONESHOT,
"sec_headset_send_key", hi);
if (ret) {
pr_err("%s : Failed to request_irq.\n", __func__);
goto err_request_send_key_irq;
}
/* start with send/end interrupt disable. we only enable it
* when we detect a 4 pole headset
*/
disable_irq(pdata->send_int);
#endif
dev_set_drvdata(&pdev->dev, hi);
return 0;
err_request_send_key_irq:
disable_irq_wake(pdata->det_int);
err_enable_irq_wake:
free_irq(pdata->det_int, hi);
err_request_detect_irq:
wake_lock_destroy(&hi->det_wake_lock);
switch_dev_unregister(&switch_jack_detection);
switch_dev_unregister(&switch_sendend);
err_switch_dev_register:
input_unregister_device(hi->input);
goto err_request_input_dev;
err_register_input_dev:
input_free_device(hi->input);
err_request_input_dev:
kfree(hi);
return ret;
}
static int sec_jack_remove(struct platform_device *pdev)
{
struct sec_jack_info *hi = dev_get_drvdata(&pdev->dev);
pr_info(MODULE_NAME "%s :\n", __func__);
/* rebalance before free */
if (hi->send_key_irq_enabled)
disable_irq_wake(hi->pdata->send_int);
else
enable_irq(hi->pdata->send_int);
free_irq(hi->pdata->send_int, hi);
disable_irq_wake(hi->pdata->det_int);
free_irq(hi->pdata->det_int, hi);
wake_lock_destroy(&hi->det_wake_lock);
switch_dev_unregister(&switch_jack_detection);
switch_dev_unregister(&switch_sendend);
input_unregister_device(hi->input);
kfree(hi);
return 0;
}
static int sec_jack_suspend(struct platform_device *pdev, pm_message_t state)
{
struct sec_jack_info *hi = dev_get_drvdata(&pdev->dev);
struct sec_jack_platform_data *pdata = hi->pdata;
if((!(hi->pdata->get_det_jack_state())) && (!on_call))
{
pr_info(MODULE_NAME "%s :micbias_reg5 off\n", __func__);
pdata->set_micbias_state_reg5(false);
}
else
pr_info(MODULE_NAME "%s :\n", __func__);
return 0;
}
static struct platform_driver sec_jack_driver = {
.probe = sec_jack_probe,
.remove = sec_jack_remove,
.suspend = sec_jack_suspend,
.driver = {
.name = "sec_jack",
.owner = THIS_MODULE,
},
};
static int __init sec_jack_init(void)
{
return platform_driver_register(&sec_jack_driver);
}
static void __exit sec_jack_exit(void)
{
platform_driver_unregister(&sec_jack_driver);
}
module_init(sec_jack_init);
module_exit(sec_jack_exit);
MODULE_AUTHOR("ms17.kim@samsung.com");
MODULE_DESCRIPTION("Samsung Electronics Corp Ear-Jack detection driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
arne-cl/frodo-wii | Src/gui/dialogue_box.cpp | 3 | 1876 | #include "dialogue_box.hh"
void DialogueListener::escapeCallback(DialogueBox *which, int selected)
{
Gui::gui->popDialogueBox();
}
void DialogueListener::selectCallback(DialogueBox *which, int selected)
{
Gui::gui->popDialogueBox();
}
DialogueBox::DialogueBox(const char *msgs[], bool delete_on_action) : Menu(NULL), ListenerManager()
{
this->setFont(Gui::gui->default_font);
this->setSelectedBackground(NULL, NULL, NULL,
Gui::gui->bg_left, Gui::gui->bg_middle,
Gui::gui->bg_right);
this->setText(msgs, NULL);
/* Place on the second to last entry */
this->cur_sel = this->n_entries - 2;
this->delete_on_action = delete_on_action;
}
int DialogueBox::selectNext(event_t ev)
{
/* No up/down movement please! */
if (ev == KEY_UP || ev == KEY_DOWN)
return this->cur_sel;
return Menu::selectNext(ev);
}
void DialogueBox::selectCallback(int which)
{
for (int i = 0; i < this->nListeners(); i++)
if (this->listeners[i])
((DialogueListener*)this->listeners[i])->selectCallback(this,
this->p_submenus[0].sel);
Gui::gui->popDialogueBox();
if (this->delete_on_action)
delete this;
}
void DialogueBox::hoverCallback(int which)
{
}
void DialogueBox::escapeCallback(int which)
{
for (int i = 0; i < this->nListeners(); i++)
if (this->listeners[i])
((DialogueListener*)this->listeners[i])->escapeCallback(this,
this->p_submenus[0].sel);
Gui::gui->popDialogueBox();
if (this->delete_on_action)
delete this;
}
void DialogueBox::draw(SDL_Surface *where)
{
int d_x = where->w / 2 - Gui::gui->dialogue_bg->w / 2;
int d_y = where->h / 2 - Gui::gui->dialogue_bg->h / 2;
SDL_Rect dst = (SDL_Rect){d_x, d_y,
Gui::gui->dialogue_bg->w, Gui::gui->dialogue_bg->h};
SDL_BlitSurface(Gui::gui->dialogue_bg, NULL, where, &dst);
Menu::draw(where, d_x + 10, d_y + 10,
Gui::gui->dialogue_bg->w - 10, Gui::gui->dialogue_bg->h - 10);
}
| gpl-2.0 |
HachasyDados/HD-TCore | src/server/scripts/EasternKingdoms/BlackrockSpire/boss_halycon.cpp | 3 | 3170 | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "blackrock_spire.h"
enum Spells
{
SPELL_CROWDPUMMEL = 10887,
SPELL_MIGHTYBLOW = 14099,
};
enum Events
{
EVENT_CROWD_PUMMEL = 1,
EVENT_MIGHTY_BLOW = 2,
};
const Position SummonLocation = { -169.839f, -324.961f, 64.401f, 3.124f };
class boss_halycon : public CreatureScript
{
public:
boss_halycon() : CreatureScript("boss_halycon") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_halyconAI(creature);
}
struct boss_halyconAI : public BossAI
{
boss_halyconAI(Creature* creature) : BossAI(creature, DATA_HALYCON) {}
bool Summoned;
void Reset()
{
_Reset();
Summoned = false;
}
void EnterCombat(Unit* /*who*/)
{
_EnterCombat();
events.ScheduleEvent(EVENT_CROWD_PUMMEL, 8 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_MIGHTY_BLOW, 14 * IN_MILLISECONDS);
}
void JustDied(Unit* /*who*/)
{
_JustDied();
}
void UpdateAI(uint32 const diff)
{
if (!UpdateVictim())
return;
//Summon Gizrul
if (!Summoned && HealthBelowPct(25))
{
me->SummonCreature(NPC_GIZRUL_THE_SLAVENER, SummonLocation, TEMPSUMMON_TIMED_DESPAWN, 300 * IN_MILLISECONDS);
Summoned = true;
}
events.Update(diff);
if (me->HasUnitState(UNIT_STAT_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CROWD_PUMMEL:
DoCast(me->getVictim(), SPELL_CROWDPUMMEL);
events.ScheduleEvent(EVENT_CROWD_PUMMEL, 14 * IN_MILLISECONDS);
break;
case EVENT_MIGHTY_BLOW:
DoCast(me->getVictim(), SPELL_MIGHTYBLOW);
events.ScheduleEvent(EVENT_MIGHTY_BLOW, 10 * IN_MILLISECONDS);
break;
}
}
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_halycon()
{
new boss_halycon();
}
| gpl-2.0 |
cottsay/u-boot | drivers/usb/gadget/fastboot.c | 3 | 14457 | /*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* Platform dependant code for Fastboot
*
* Base code of USB connection part is usbd-otg-hs.c
*
* 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 <fastboot.h>
#if defined(CONFIG_FASTBOOT)
/* S5PC110 Default Partition Table */
fastboot_ptentry ptable_default[] =
{
{
.name = "bootloader",
.start = 0x0,
.length = 0x100000,
.flags = 0
},
{
.name = "recovery",
.start = 0x100000,
.length = 0x500000,
.flags = 0
},
{
.name = "kernel",
.start = 0x600000,
.length = 0x500000,
.flags = 0
},
{
.name = "ramdisk",
.start = 0xB00000,
.length = 0x300000,
.flags = 0
},
{
.name = "system",
.start = 0xE00000,
.length = 0x6E00000,
.flags = FASTBOOT_PTENTRY_FLAGS_WRITE_YAFFS
},
{
.name = "cache",
.start = 0x7C00000,
.length = 0x5000000,
.flags = FASTBOOT_PTENTRY_FLAGS_WRITE_YAFFS
},
{
.name = "userdata",
.start = 0xCC00000,
.length = 0,
.flags = FASTBOOT_PTENTRY_FLAGS_WRITE_YAFFS
}
};
unsigned int ptable_default_size = sizeof(ptable_default);
#define FBOOT_USBD_IS_CONNECTED() (readl(S5P_OTG_GOTGCTL)&(B_SESSION_VALID|A_SESSION_VALID))
#define FBOOT_USBD_DETECT_IRQ_CPUMODE() (readl(S5P_OTG_GINTSTS) & \
(GINTSTS_WkUpInt|GINTSTS_OEPInt|GINTSTS_IEPInt| \
GINTSTS_EnumDone|GINTSTS_USBRst|GINTSTS_USBSusp|GINTSTS_RXFLvl))
#define FBOOT_USBD_DETECT_IRQ_DMAMODE() (readl(S5P_OTG_GINTSTS) & \
(GINTSTS_WkUpInt|GINTSTS_OEPInt|GINTSTS_IEPInt| \
GINTSTS_EnumDone|GINTSTS_USBRst|GINTSTS_USBSusp))
#define FBOOT_USBD_CLEAR_IRQ() do { \
writel(BIT_ALLMSK, (S5P_OTG_GINTSTS)); \
} while (0)
#define VENDOR_ID 0x18D1
#define PRODUCT_ID 0x0002
#define FB_PKT_SZ 64 // full-speed mode
#define OK 0
#define ERROR -1
/* In high speed mode packets are 512
In full speed mode packets are 64 */
#define RX_ENDPOINT_MAXIMUM_PACKET_SIZE_2_0 (0x0200)//512
#define RX_ENDPOINT_MAXIMUM_PACKET_SIZE_1_1 (0x0040)// 64
#define TX_ENDPOINT_MAXIMUM_PACKET_SIZE_2_0 (0x0200)
#define TX_ENDPOINT_MAXIMUM_PACKET_SIZE_1_1 (0x0040)
/* String 0 is the language id */
#define DEVICE_STRING_MANUFACTURER_INDEX 1
#define DEVICE_STRING_PRODUCT_INDEX 2
#define DEVICE_STRING_SERIAL_NUMBER_INDEX 3
#define DEVICE_STRING_CONFIG_INDEX 4
#define DEVICE_STRING_INTERFACE_INDEX 5
#define DEVICE_STRING_MAX_INDEX DEVICE_STRING_INTERFACE_INDEX
#define DEVICE_STRING_LANGUAGE_ID 0x0409 /* English (United States) */
static char *device_strings[DEVICE_STRING_MAX_INDEX+1];
static struct cmd_fastboot_interface *fastboot_interface = NULL;
/* The packet size is dependend of the speed mode
In high speed mode packets are 512
In full speed mode packets are 64
Set to maximum of 512 */
/* Note: The start address must be double word aligned */
static u8 fastboot_bulk_fifo[0x0200+1]; //__attribute__ ((aligned(0x4)));
const char* reply_msg;
unsigned int transfer_size;
u32 fboot_response_flag=0;
/* codes representing languages */
const u8 fboot_string_desc1[] = /* Manufacturer */
{
(0x16+2), STRING_DESCRIPTOR,
'G', 0x0, 'o', 0x0, 'o', 0x0, 'g', 0x0, 'l', 0x0,
'e', 0x0, ',', 0x0, ' ', 0x0, 'I', 0x0, 'n', 0x0,
'c', 0x0
};
const u8 fboot_string_desc2[] = /* Product */
{
(0x16+2), STRING_DESCRIPTOR,
'A', 0x0, 'n', 0x0, 'd', 0x0, 'r', 0x0, 'o', 0x0,
'i', 0x0, 'd', 0x0, ' ', 0x0, '1', 0x0, '.', 0x0,
'0', 0x0
};
const u8 fboot_string_desc3[] = /* Test Serial ID */
{
(0x16+2), STRING_DESCRIPTOR,
'S', 0x0, 'M', 0x0, 'D', 0x0, 'K', 0x0,
#if defined(CONFIG_EXYNOS4X12) || defined(CONFIG_ARCH_EXYNOS)
'E', 0x0,'X', 0x0, 'Y', 0x0, 'N', 0x0, 'O', 0x0, 'S', 0x0, '-', 0x0, '0', 0x0, '1', 0x0
#elif defined(CONFIG_S5PC210)
'C', 0x0,'2', 0x0, '1', 0x0, '0', 0x0, '-', 0x0, '0', 0x0, '1', 0x0
#elif defined(CONFIG_S5PV310)
'V', 0x0,'3', 0x0, '1', 0x0, '0', 0x0, '-', 0x0, '0', 0x0, '1', 0x0
#elif defined(CONFIG_S5PC110)
'C', 0x0,'1', 0x0, '1', 0x0, '0', 0x0, '-', 0x0, '0', 0x0, '1', 0x0
#elif defined(CONFIG_S5P6450)
'6', 0x0,'4', 0x0, '5', 0x0, '0', 0x0, '-', 0x0, '0', 0x0, '1', 0x0
#else
#error "* CFG_ERROR : you have to select proper CPU for Android Fastboot"
#endif
};
/* setting the device qualifier descriptor and a string descriptor */
const u8 fboot_qualifier_desc[] =
{
0x0a, /* 0 desc size */
0x06, /* 1 desc type (DEVICE_QUALIFIER)*/
0x00, /* 2 USB release */
0x02, /* 3 => 2.00*/
0xFF, /* 4 class */
0x42, /* 5 subclass */
0x03, /* 6 protocol */
64, /* 7 max pack size */
0x01, /* 8 number of other-speed configuration */
0x00, /* 9 reserved */
};
int fboot_usbctl_init(void)
{
s3c_usbctl_init();
is_fastboot = 1;
return 0;
}
void fboot_usb_int_bulkin(void)
{
u32 tmp;
DBG_BULK0("~~~~~~~~~~~~~~~~ bulkin Function ~~~~~~~~~~~~\n");
if ((fboot_response_flag==1)&&(reply_msg)) {
#ifdef CONFIG_USB_CPUMODE
s3c_usb_set_inep_xfersize(EP_TYPE_BULK, 1, strlen(reply_msg));
/*ep3 enable, clear nak, bulk, usb active, next ep3, max pkt 64*/
writel(1u<<31|1<<26|2<<18|1<<15|otg.bulkin_max_pktsize<<0, S5P_OTG_DIEPCTL_IN);
s3c_usb_write_in_fifo((u8 *)reply_msg,strlen(reply_msg));
#else
s3c_usb_bulk_inep_setdma((u8 *)reply_msg, strlen(reply_msg));
#endif
fboot_response_flag=0;
}
else if (fboot_response_flag==0)
{
/*ep3 enable, clear nak, bulk, usb active, next ep3, max pkt 64*/
//writel(1u<<31|1<<26|2<<18|1<<15|otg.bulkin_max_pktsize<<0, S5P_OTG_DIEPCTL_IN);
//writel((DEPCTL_SNAK|DEPCTL_BULK_TYPE), S5P_OTG_DIEPCTL_IN);
// NAK should be cleared. why??
tmp = readl(S5P_OTG_DOEPCTL0+0x20*BULK_OUT_EP);
tmp |= (DEPCTL_CNAK);
writel(tmp, S5P_OTG_DOEPCTL0+0x20*BULK_OUT_EP);
}
//DBG_BULK1("fboot_response_flag=%d S5P_OTG_DIEPCTL_IN=0x%x\n",fboot_response_flag,DIEPCTL_IN);
return;
}
#ifdef CONFIG_USB_CPUMODE
void fboot_usb_int_bulkout(u32 fifo_cnt_byte)
#else
void fboot_usb_int_bulkout( void )
#endif
{
DBG_BULK0("@@\n Bulk Out Function : otg.dn_filesize=0x%x\n", otg.dn_filesize);
#ifdef CONFIG_USB_CPUMODE
s3c_usb_read_out_fifo((u8 *)fastboot_bulk_fifo, fifo_cnt_byte);
if (fifo_cnt_byte<64) {
fastboot_bulk_fifo[fifo_cnt_byte] = 0x00; // append null
printf("Received %d bytes: %s\n",fifo_cnt_byte, fastboot_bulk_fifo);
}
/*ep3 enable, clear nak, bulk, usb active, next ep3, max pkt 64*/
writel(1u<<31|1<<26|2<<18|1<<15|otg.bulkout_max_pktsize<<0,
S5P_OTG_DOEPCTL_OUT);
#else
u32 xfer_size, cnt_byte;
xfer_size = readl(S5P_OTG_DOEPTSIZ_OUT) & 0x7FFF;
cnt_byte = HS_BULK_PKT_SIZE - xfer_size;
if(cnt_byte < HS_BULK_PKT_SIZE)
tmp_buf[cnt_byte] = 0x00;
#endif
/* Pass this up to the interface's handler */
if (fastboot_interface && fastboot_interface->rx_handler) {
/* Call rx_handler at common/cmd_fastboot.c */
#ifdef CONFIG_USB_CPUMODE
if (!fastboot_interface->rx_handler(&fastboot_bulk_fifo[0], fifo_cnt_byte));//OK
}
#else
if (!fastboot_interface->rx_handler(&tmp_buf, cnt_byte));
}
s3c_usb_bulk_outep_setdma(tmp_buf, HS_BULK_PKT_SIZE);
#endif
}
void fboot_usb_set_descriptors(void)
{
/* Standard device descriptor */
otg.desc.dev.bLength=DEVICE_DESC_SIZE; /*0x12*/
otg.desc.dev.bDescriptorType=DEVICE_DESCRIPTOR;
otg.desc.dev.bMaxPacketSize0=otg.ctrl_max_pktsize;
otg.desc.dev.bDeviceClass=0x0; /* 0x0*/
otg.desc.dev.bDeviceSubClass=0x0;
otg.desc.dev.bDeviceProtocol=0x0;
otg.desc.dev.idVendorL=VENDOR_ID&0xff;//0xB4; /**/
otg.desc.dev.idVendorH=VENDOR_ID>>8;//0x0B; /**/
otg.desc.dev.idProductL=PRODUCT_ID&0xff;//0xFF; /**/
otg.desc.dev.idProductH=PRODUCT_ID>>8;//0x0F; /**/
otg.desc.dev.bcdDeviceL=0x00;
otg.desc.dev.bcdDeviceH=0x01;
otg.desc.dev.iManufacturer=DEVICE_STRING_MANUFACTURER_INDEX; /* index of string descriptor */
otg.desc.dev.iProduct=DEVICE_STRING_PRODUCT_INDEX; /* index of string descriptor */
otg.desc.dev.iSerialNumber=DEVICE_STRING_SERIAL_NUMBER_INDEX;
otg.desc.dev.bNumConfigurations=0x1;
if (otg.speed == USB_FULL) {
otg.desc.dev.bcdUSBL=0x10;
otg.desc.dev.bcdUSBH=0x01; /* Ver 1.10*/
}
else {
otg.desc.dev.bcdUSBL=0x00;
//otg.desc.dev.bcdUSBL=0x10;
otg.desc.dev.bcdUSBH=0x02; /* Ver 2.0*/
}
/* Standard configuration descriptor */
otg.desc.config.bLength=CONFIG_DESC_SIZE; /* 0x9 bytes */
otg.desc.config.bDescriptorType=CONFIGURATION_DESCRIPTOR;
otg.desc.config.wTotalLengthL=CONFIG_DESC_TOTAL_SIZE;
otg.desc.config.wTotalLengthH=0;
otg.desc.config.bNumInterfaces=1;
/* dbg descConf.bConfigurationValue=2; // why 2? There's no reason.*/
otg.desc.config.bConfigurationValue=1;
otg.desc.config.iConfiguration=0;
otg.desc.config.bmAttributes=CONF_ATTR_DEFAULT|CONF_ATTR_SELFPOWERED; /* bus powered only.*/
otg.desc.config.maxPower=25; /* draws 50mA current from the USB bus.*/
/* Standard interface descriptor */
otg.desc.intf.bLength=INTERFACE_DESC_SIZE; /* 9*/
otg.desc.intf.bDescriptorType=INTERFACE_DESCRIPTOR;
otg.desc.intf.bInterfaceNumber=0x0;
otg.desc.intf.bAlternateSetting=0x0; /* ?*/
otg.desc.intf.bNumEndpoints = 2; /* # of endpoints except EP0*/
otg.desc.intf.bInterfaceClass= FASTBOOT_INTERFACE_CLASS;// 0xff; /* 0x0 ?*/
otg.desc.intf.bInterfaceSubClass= FASTBOOT_INTERFACE_SUB_CLASS;// 0x42;
otg.desc.intf.bInterfaceProtocol= FASTBOOT_INTERFACE_PROTOCOL;//0x03;
otg.desc.intf.iInterface=0x0;
/* Standard endpoint0 descriptor */
otg.desc.ep1.bLength=ENDPOINT_DESC_SIZE;
otg.desc.ep1.bDescriptorType=ENDPOINT_DESCRIPTOR;
otg.desc.ep1.bEndpointAddress=BULK_IN_EP|EP_ADDR_IN;
otg.desc.ep1.bmAttributes=EP_ATTR_BULK;
otg.desc.ep1.wMaxPacketSizeL=(u8)otg.bulkin_max_pktsize; /* 64*/
otg.desc.ep1.wMaxPacketSizeH=(u8)(otg.bulkin_max_pktsize>>8);
otg.desc.ep1.bInterval=0x0; /* not used */
/* Standard endpoint1 descriptor */
otg.desc.ep2.bLength=ENDPOINT_DESC_SIZE;
otg.desc.ep2.bDescriptorType=ENDPOINT_DESCRIPTOR;
otg.desc.ep2.bEndpointAddress=BULK_OUT_EP|EP_ADDR_OUT;
otg.desc.ep2.bmAttributes=EP_ATTR_BULK;
otg.desc.ep2.wMaxPacketSizeL=(u8)otg.bulkout_max_pktsize; /* 64*/
otg.desc.ep2.wMaxPacketSizeH=(u8)(otg.bulkout_max_pktsize>>8);
otg.desc.ep2.bInterval=0x0; /* not used */
}
int fboot_usb_int_hndlr(void)
{
return s3c_udc_int_hndlr();
}
//-----------------------------------------------------------------------------------
// FASTBOOT codes
//-----------------------------------------------------------------------------------
static void set_serial_number(void)
{
char *dieid = getenv("dieid#");
if (dieid == NULL) {
device_strings[DEVICE_STRING_SERIAL_NUMBER_INDEX] = "SLSI0123";
} else {
static char serial_number[32];
int len;
memset(&serial_number[0], 0, 32);
len = strlen(dieid);
if (len > 30)
len = 30;
strncpy(&serial_number[0], dieid, len);
device_strings[DEVICE_STRING_SERIAL_NUMBER_INDEX] =
&serial_number[0];
}
}
/* Initizes the board specific fastboot
Returns 0 on success
Returns 1 on failure */
int fastboot_init(struct cmd_fastboot_interface *interface)
{
int ret = 1;
// usbd init
fboot_usbctl_init();
device_strings[DEVICE_STRING_MANUFACTURER_INDEX] = "Samsung S.LSI";
device_strings[DEVICE_STRING_PRODUCT_INDEX] = "smdk";
set_serial_number();
/* These are just made up */
device_strings[DEVICE_STRING_CONFIG_INDEX] = "Android Fastboot";
device_strings[DEVICE_STRING_INTERFACE_INDEX] = "Android Fastboot";
/* The interface structure */
fastboot_interface = interface;
fastboot_interface->product_name = device_strings[DEVICE_STRING_PRODUCT_INDEX];
fastboot_interface->serial_no = device_strings[DEVICE_STRING_SERIAL_NUMBER_INDEX];
fastboot_interface->nand_block_size = CFG_FASTBOOT_PAGESIZE * 64;
fastboot_interface->transfer_buffer = (unsigned char *) CFG_FASTBOOT_TRANSFER_BUFFER;
fastboot_interface->transfer_buffer_size = CFG_FASTBOOT_TRANSFER_BUFFER_SIZE;
memset((unsigned char *) CFG_FASTBOOT_TRANSFER_BUFFER, 0x0, FASTBOOT_REBOOT_MAGIC_SIZE);
ret = 0; // This is a fake return value, because we do not initialize USB yet!
return ret;
}
/* Cleans up the board specific fastboot */
void fastboot_shutdown(void)
{
/* when operation is done, usbd must be stopped */
s3c_usb_stop();
}
int fastboot_fifo_size(void)
{
return (otg.speed== USB_HIGH) ? RX_ENDPOINT_MAXIMUM_PACKET_SIZE_2_0 : RX_ENDPOINT_MAXIMUM_PACKET_SIZE_1_1;
}
/*
* Handles board specific usb protocol exchanges
* Returns 0 on success
* Returns 1 on disconnects, break out of loop
* Returns 2 if no USB activity detected
* Returns -1 on failure, unhandled usb requests and other error conditions
*/
int fastboot_poll(void)
{
//printf("DEBUG: %s is called.\n", __FUNCTION__);
/* No activity */
int ret = FASTBOOT_INACTIVE;
u32 intrusb;
/* Look at the interrupt registers */
intrusb = readl(S5P_OTG_GINTSTS);
/* A disconnect happended, this signals that the cable
has been disconnected, return immediately */
if (!FBOOT_USBD_IS_CONNECTED())
return FASTBOOT_DISCONNECT;
#ifdef CONFIG_USB_CPUMODE
else if (FBOOT_USBD_DETECT_IRQ_CPUMODE()) {
#else
else if (FBOOT_USBD_DETECT_IRQ_DMAMODE()) {
#endif
if (!fboot_usb_int_hndlr())
ret = FASTBOOT_OK;
else
ret = FASTBOOT_ERROR;
FBOOT_USBD_CLEAR_IRQ();
}
return ret;
}
/* Send a status reply to the client app
buffer does not have to be null terminated.
buffer_size must be not be larger than what is returned by
fastboot_fifo_size
Returns 0 on success
Returns 1 on failure */
int fastboot_tx_status(const char *buffer, unsigned int buffer_size, const u32 need_sync_flag)
{
/* fastboot client only reads back at most 64 */
transfer_size = MIN(64, buffer_size);
//------------------------------ kdj
//printf(" Response - \"%s\" (%d bytes)\n", buffer, buffer_size);
reply_msg = buffer;
fboot_response_flag=1;
#ifndef CONFIG_USB_CPUMODE
fboot_usb_int_bulkin();
#endif
if (need_sync_flag)
{
while(fboot_response_flag)
fastboot_poll();
}
return 1;
}
/* A board specific variable handler.
The size of the buffers is governed by the fastboot spec.
rx_buffer is at most 57 bytes
tx_buffer is at most 60 bytes
Returns 0 on success
Returns 1 on failure */
int fastboot_getvar(const char *rx_buffer, char *tx_buffer)
{
/* Place board specific variables here */
return 1;
}
#endif /* CONFIG_FASTBOOT */
| gpl-2.0 |
Pavuucek/VirtualDub | src/VirtualDub/source/backface.cpp | 3 | 14218 | // VirtualDub - Video processing and capture application
// Copyright (C) 1998-2005 Avery Lee
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include <windows.h>
#include <richedit.h>
#include <malloc.h>
#include <stdio.h>
#include <vd2/system/thread.h>
#include <vd2/system/refcount.h>
#include <vd2/system/vdstl.h>
#include <vd2/system/w32assist.h>
#include "backface.h"
extern HINSTANCE g_hInst;
#pragma warning(disable: 4073)
#pragma init_seg(lib)
#if VD_BACKFACE_ENABLED
///////////////////////////////////////////////////////////////////////////
class IVDBackfaceStream {
public:
virtual void operator<<(const char *s) = 0;
};
class VDBackfaceClass : public vdlist_node {
public:
VDBackfaceClass(const char *shortname, const char *longname);
const char *mpShortName;
const char *mpLongName;
uint32 mObjectCount;
VDBackfaceObjectNode mObjects;
};
VDBackfaceClass::VDBackfaceClass(const char *shortname, const char *longname)
: mpShortName(shortname)
, mpLongName(longname)
, mObjectCount(0)
{
mObjects.mpObjNext = mObjects.mpObjPrev = &mObjects;
}
class VDBackfaceService : public IVDBackfaceOutput {
public:
VDBackfaceService();
~VDBackfaceService();
VDBackfaceClass *AddClass(const char *shortname, const char *longname);
void AddObject(VDBackfaceObjectBase *pObject);
void RemoveObject(VDBackfaceObjectBase *pObject);
void DumpStatus(IVDBackfaceStream& out);
void Execute(IVDBackfaceStream& out, char *cmd);
void operator<<(const char *s);
void operator()(const char *format, ...);
VDStringA GetTag(VDBackfaceObjectBase *p);
VDStringA GetBlurb(VDBackfaceObjectBase *p);
protected:
VDBackfaceClass *GetClassByName(const VDStringSpanA& name);
VDBackfaceObjectBase *GetObjectByName(const char *name);
VDCriticalSection mLock;
uint32 mObjectCount;
uint32 mClassCount;
uint32 mNextInstance;
VDStringA *mpCaptureString;
IVDBackfaceStream *mpOutput;
vdlist<VDBackfaceClass> mClasses;
};
VDBackfaceService g_VDBackfaceService;
VDBackfaceService::VDBackfaceService()
: mObjectCount(0)
, mClassCount(0)
, mNextInstance(1)
, mpCaptureString(NULL)
{
}
VDBackfaceService::~VDBackfaceService() {
while(!mClasses.empty()) {
VDBackfaceClass *pNode = mClasses.back();
mClasses.pop_back();
delete pNode;
}
}
VDBackfaceClass *VDBackfaceService::AddClass(const char *shortname, const char *longname) {
vdsynchronized(mLock) {
VDBackfaceClass *pNode = new VDBackfaceClass(shortname, longname);
mClasses.push_back(pNode);
++mClassCount;
return pNode;
}
}
void VDBackfaceService::AddObject(VDBackfaceObjectBase *pObject) {
vdsynchronized(mLock) {
++mObjectCount;
pObject->mInstance = mNextInstance++;
VDBackfaceClass& cl = *pObject->mpClass;
++cl.mObjectCount;
cl.mObjects.mpObjNext->mpObjPrev = pObject;
pObject->mpObjNext = cl.mObjects.mpObjNext;
pObject->mpObjPrev = &cl.mObjects;
cl.mObjects.mpObjNext = pObject;
}
}
void VDBackfaceService::RemoveObject(VDBackfaceObjectBase *pObject) {
vdsynchronized(mLock) {
--mObjectCount;
--pObject->mpClass->mObjectCount;
pObject->mpObjNext->mpObjPrev = pObject->mpObjPrev;
pObject->mpObjPrev->mpObjNext = pObject->mpObjNext;
}
}
void VDBackfaceService::DumpStatus(IVDBackfaceStream& out) {
vdsynchronized(mLock) {
mpOutput = &out;
operator<<("Backface status:");
operator()(" %d objects being tracked", mObjectCount);
operator()(" %d classes being tracked", mClassCount);
out << "backface> ";
}
}
void VDBackfaceService::Execute(IVDBackfaceStream& out, char *s) {
vdsynchronized(mLock) {
mpOutput = &out;
operator<<(s);
const char *argv[64];
int argc = 0;
while(argc < 63) {
while(*s && *s == ' ')
++s;
if (!*s)
break;
argv[argc++] = s;
if (*s == '"') {
while(*s && *s != '"')
++s;
} else {
while(*s && *s != ' ')
++s;
}
if (!*s)
break;
*s++ = 0;
}
argv[argc] = NULL;
if (argc) {
VDStringSpanA cmd(argv[0]);
if (cmd == "lc") {
operator<<("");
operator<<("Count Class Name");
operator<<("---------------------------------------------");
vdlist<VDBackfaceClass>::iterator it(mClasses.begin()), itEnd(mClasses.end());
for(; it!=itEnd; ++it) {
VDBackfaceClass& cl = **it;
operator()("%5d %-8s (%s)", cl.mObjectCount, cl.mpShortName, cl.mpLongName);
}
} else if (cmd == "lo") {
const char *cname = argv[1];
if (cname) {
VDBackfaceClass *cl = GetClassByName(VDStringSpanA(cname));
if (!cl)
operator()("Unknown class \"%s.\"", cname);
else {
VDBackfaceObjectNode *p = cl->mObjects.mpObjNext;
operator<<("");
operator<<("Pointer Instance Desc");
operator<<("---------------------------------------------");
for(; p != &cl->mObjects; p = p->mpObjNext) {
VDBackfaceObjectBase *pObj = static_cast<VDBackfaceObjectBase *>(p);
operator()("%p #%-5d %s", pObj, pObj->mInstance, GetBlurb(pObj).c_str());
}
}
}
} else if (cmd == "dump") {
const char *objname = argv[1];
if (objname) {
VDBackfaceObjectBase *obj = GetObjectByName(objname);
if (obj) {
operator()("Object %s | %p | %s:", objname, obj, GetBlurb(obj).c_str());
obj->BackfaceDumpObject(*this);
} else {
operator()("Unknown object %s.", objname);
}
}
} else if (cmd == "?") {
operator<<("lc List classes");
operator<<("lo <class> List objects by class");
operator<<("dump <class>:<inst> Dump object");
} else {
operator<<("Unrecognized command -- ? for help.");
}
}
out << ("backface> ");
}
}
void VDBackfaceService::operator<<(const char *s) {
if (mpCaptureString)
mpCaptureString->assign(s);
else {
*mpOutput << s;
*mpOutput << "\n";
}
}
void VDBackfaceService::operator()(const char *format, ...) {
char buf[3072];
va_list val;
va_start(val, format);
if ((unsigned)_vsnprintf(buf, 3072, format, val) < 3072) {
if (mpCaptureString)
mpCaptureString->assign(buf);
else {
*mpOutput << buf;
*mpOutput << "\n";
}
} else if (mpCaptureString)
mpCaptureString->clear();
va_end(val);
}
VDStringA VDBackfaceService::GetTag(VDBackfaceObjectBase *p) {
VDStringA tag;
if (p)
tag.sprintf("%s:%u", p->mpClass->mpShortName, p->mInstance);
else
tag = "null";
return tag;
}
VDStringA VDBackfaceService::GetBlurb(VDBackfaceObjectBase *pObject) {
VDStringA s;
VDStringA *pOldCapture = mpCaptureString;
mpCaptureString = &s;
pObject->BackfaceDumpBlurb(*this);
mpCaptureString = pOldCapture;
return s;
}
VDBackfaceClass *VDBackfaceService::GetClassByName(const VDStringSpanA& name) {
vdlist<VDBackfaceClass>::iterator it(mClasses.begin()), itEnd(mClasses.end());
for(; it!=itEnd; ++it) {
VDBackfaceClass *p = *it;
if (name == p->mpShortName || name == p->mpLongName)
return p;
}
return NULL;
}
VDBackfaceObjectBase *VDBackfaceService::GetObjectByName(const char *name) {
VDStringSpanA names(name);
VDStringSpanA::size_type colonPos = names.find(':');
if (colonPos == VDStringSpanA::npos)
return NULL;
const char *s = name + colonPos + 1;
unsigned index;
if (!*s || 1 != sscanf(s, "%u", &index))
return NULL;
VDBackfaceClass *cl = GetClassByName(names.subspan(0, colonPos));
if (!cl)
return NULL;
VDBackfaceObjectNode *p = cl->mObjects.mpObjNext;
for(; p != &cl->mObjects; p = p->mpObjNext) {
VDBackfaceObjectBase *pObj = static_cast<VDBackfaceObjectBase *>(p);
if (pObj->mInstance == index)
return pObj;
}
return NULL;
}
///////////////////////////////////////////////////////////////////////////
VDBackfaceObjectBase::VDBackfaceObjectBase(const VDBackfaceObjectBase& src)
: mpClass(src.mpClass)
{
g_VDBackfaceService.AddObject(this);
}
VDBackfaceObjectBase::~VDBackfaceObjectBase() {
g_VDBackfaceService.RemoveObject(this);
}
VDBackfaceClass *VDBackfaceObjectBase::BackfaceInitClass(const char *shortname, const char *longname) {
return g_VDBackfaceService.AddClass(shortname, longname);
}
void VDBackfaceObjectBase::BackfaceInitObject(VDBackfaceClass *pClass) {
mpClass = pClass;
g_VDBackfaceService.AddObject(this);
}
void VDBackfaceObjectBase::BackfaceDumpObject(IVDBackfaceOutput&) {
}
void VDBackfaceObjectBase::BackfaceDumpBlurb(IVDBackfaceOutput&) {
}
///////////////////////////////////////////////////////////////////////////
class VDBackfaceConsole : public IVDBackfaceStream {
public:
VDBackfaceConsole();
~VDBackfaceConsole();
int AddRef();
int Release();
void Init();
protected:
static ATOM RegisterWindowClass();
static LRESULT CALLBACK StaticWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam);
bool OnCreate();
void OnDestroy();
void OnSize();
LRESULT OnNotify(NMHDR *);
void operator<<(const char *s);
HWND mhwnd;
HWND mhwndLog;
HWND mhwndEdit;
HFONT mFont;
HMODULE mhmodRichEdit;
VDAtomicInt mRefCount;
};
VDBackfaceConsole::VDBackfaceConsole()
: mRefCount(0)
, mFont(NULL)
, mhmodRichEdit(NULL)
{
}
VDBackfaceConsole::~VDBackfaceConsole() {
if (mFont)
DeleteObject(mFont);
}
int VDBackfaceConsole::AddRef() {
return ++mRefCount;
}
int VDBackfaceConsole::Release() {
int rv = --mRefCount;
if (!rv)
delete this;
return 0;
}
void VDBackfaceConsole::Init() {
static ATOM a = RegisterWindowClass();
CreateWindow((LPCTSTR)a, "Backface", WS_OVERLAPPEDWINDOW|WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, g_hInst, this);
}
ATOM VDBackfaceConsole::RegisterWindowClass() {
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = StaticWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = sizeof(void *);
wc.hInstance = g_hInst;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = "Backface";
return RegisterClass(&wc);
}
LRESULT CALLBACK VDBackfaceConsole::StaticWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
VDBackfaceConsole *pThis;
if (msg == WM_NCCREATE) {
pThis = (VDBackfaceConsole *)(((const CREATESTRUCT *)lParam)->lpCreateParams);
pThis->AddRef();
pThis->mhwnd = hwnd;
SetWindowLongPtr(hwnd, 0, (LONG_PTR)pThis);
} else {
pThis = (VDBackfaceConsole *)GetWindowLongPtr(hwnd, 0);
if (pThis) {
if (msg != WM_NCCREATE) {
pThis->AddRef();
LRESULT lr = pThis->WndProc(msg, wParam, lParam);
pThis->Release();
return lr;
}
pThis->mhwnd = NULL;
pThis->Release();
}
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
LRESULT VDBackfaceConsole::WndProc(UINT msg, WPARAM wParam, LPARAM lParam) {
switch(msg) {
case WM_CREATE:
return OnCreate() ? 0 : -1;
case WM_DESTROY:
OnDestroy();
break;
case WM_SIZE:
OnSize();
return 0;
case WM_NOTIFY:
return OnNotify((NMHDR *)lParam);
case WM_SETFOCUS:
SetFocus(mhwndEdit);
return 0;
}
return DefWindowProc(mhwnd, msg, wParam, lParam);
}
bool VDBackfaceConsole::OnCreate() {
mhmodRichEdit = LoadLibrary("riched32");
if (!mFont) {
mFont = CreateFont(-10, 0, 0, 0, 0, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_CHARACTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Lucida Console");
if (!mFont)
return false;
}
mhwndLog = CreateWindowEx(WS_EX_CLIENTEDGE, "RICHEDIT", "", ES_READONLY|ES_MULTILINE|ES_AUTOVSCROLL|WS_VSCROLL|WS_VISIBLE|WS_CHILD, 0, 0, 0, 0, mhwnd, (HMENU)100, g_hInst, NULL);
if (!mhwndLog)
return false;
SendMessage(mhwndLog, WM_SETFONT, (WPARAM)mFont, NULL);
mhwndEdit = CreateWindowEx(WS_EX_CLIENTEDGE, "RICHEDIT", "", WS_VISIBLE|WS_CHILD, 0, 0, 0, 0, mhwnd, (HMENU)100, g_hInst, NULL);
if (!mhwndEdit)
return false;
SendMessage(mhwndEdit, EM_SETEVENTMASK, 0, ENM_KEYEVENTS);
SendMessage(mhwndEdit, WM_SETFONT, (WPARAM)mFont, NULL);
OnSize();
g_VDBackfaceService.DumpStatus(*this);
return true;
}
void VDBackfaceConsole::OnDestroy() {
if (mhwndLog) {
DestroyWindow(mhwndLog);
mhwndLog = NULL;
}
if (mhwndEdit) {
DestroyWindow(mhwndEdit);
mhwndEdit = NULL;
}
if (mhmodRichEdit) {
FreeLibrary(mhmodRichEdit);
mhmodRichEdit = NULL;
}
}
void VDBackfaceConsole::OnSize() {
RECT r;
if (GetClientRect(mhwnd, &r)) {
int h = 20;
SetWindowPos(mhwndLog, NULL, 0, 0, r.right, r.bottom > h ? r.bottom - h : 0, SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
SetWindowPos(mhwndEdit, NULL, 0, r.bottom - h, r.right, h, SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
}
}
LRESULT VDBackfaceConsole::OnNotify(NMHDR *pHdr) {
if (pHdr->hwndFrom == mhwndEdit) {
if (pHdr->code == EN_MSGFILTER) {
const MSGFILTER& mf = *(const MSGFILTER *)pHdr;
if (mf.msg == WM_CHAR) {
if (mf.wParam == '\r') {
int len = GetWindowTextLength(mhwndEdit);
if (len) {
char *buf = (char *)_alloca(len+1);
buf[0] = 0;
if (GetWindowText(mhwndEdit, buf, len+1)) {
SetWindowText(mhwndEdit, "");
g_VDBackfaceService.Execute(*this, buf);
}
}
return true;
}
}
return false;
}
}
return 0;
}
void VDBackfaceConsole::operator<<(const char *s) {
SendMessage(mhwndLog, EM_SETSEL, -1, -1);
SendMessage(mhwndLog, EM_REPLACESEL, FALSE, (LPARAM)s);
}
///////////////////////////////////////////////////////////////////////////
void VDBackfaceOpenConsole() {
vdrefptr<VDBackfaceConsole> pConsole(new VDBackfaceConsole);
pConsole->Init();
}
///////////////////////////////////////////////////////////////////////////
#else
void VDBackfaceOpenConsole() {}
#endif | gpl-2.0 |
xmxjq/phoneyc-SjtuISADTeam | modules/honeyjs/spidermonkey/runtime.c | 3 | 5635 | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This file is originally written by Paul J. Davis, Z. Chen has modified it to
* make the honeyjs package
*
* Copyright 2009 Paul J. Davis <paul.joseph.davis@gmail.com>
*
* This file is part of the python-spidermonkey package released
* under the MIT license.
*
*/
#include "spidermonkey.h"
PyObject*
Runtime_new(PyTypeObject* type, PyObject* args, PyObject* kwargs)
{
Runtime* self = NULL;
unsigned int stacksize = 0x2000000; // 32 MiB heap size.
if(!PyArg_ParseTuple(args, "|I", &stacksize)) goto error;
self = (Runtime*) type->tp_alloc(type, 0);
if(self == NULL) goto error;
self->rt = JS_NewRuntime(stacksize);
if(self->rt == NULL)
{
PyErr_SetString(JSError, "Failed to allocate new JSRuntime.");
goto error;
}
self->is_traced = 0;
goto success;
error:
Py_XDECREF(self);
self = NULL;
success:
return (PyObject*) self;
}
int
Runtime_init(Runtime* self, PyObject* args, PyObject* kwargs)
{
return 0;
}
void
Runtime_dealloc(Runtime* self)
{
if(self->rt != NULL)
{
JS_DestroyRuntime(self->rt);
}
}
PyObject*
Runtime_new_context(Runtime* self, PyObject* args, PyObject* kwargs)
{
PyObject* cx = NULL;
PyObject* tpl = NULL;
PyObject* global = Py_None;
PyObject* access = Py_None;
PyObject* alertlist = Py_None;
char* keywords[] = {"glbl", "access", "alertlist", NULL};
if(!PyArg_ParseTupleAndKeywords(
args, kwargs,
"|OOO",
keywords,
&global,
&access,
&alertlist
)) goto error;
tpl = Py_BuildValue("OOOO", self, global, access, alertlist);
if(tpl == NULL) goto error;
cx = PyObject_CallObject((PyObject*) ContextType, tpl);
goto success;
error:
Py_XDECREF(cx);
success:
Py_XDECREF(tpl);
return cx;
}
PyObject*
Runtime_switch_tracing(Runtime* self, PyObject* args, PyObject* kwargs)
{
int status = 1-self->is_traced;
char* keywords[] = {"status", NULL};
if(!PyArg_ParseTupleAndKeywords(
args, kwargs,
"|i",
keywords,
&status
)) goto error;
if ( status != self->is_traced )
{
if ( status == 0 )
{
JS_ClearInterrupt(self->rt,NULL,NULL);
//fprintf(stderr,"DEBUG: Switch tracing, now is %d.\n",status);
}
else
{
JS_SetInterrupt(self->rt,js_interrupt_handler,NULL);
//fprintf(stderr,"DEBUG: Switch tracing, now is %d.\n",status);
}
}
self->is_traced = status;
return Py_None;
error:
PyErr_SetString(JSError, "Failed to Set/Clear Interrupt handler.");
return Py_None;
}
static PyMemberDef Runtime_members[] = {
{NULL}
};
static PyMethodDef Runtime_methods[] = {
{
"new_context",
(PyCFunction)Runtime_new_context,
METH_VARARGS | METH_KEYWORDS,
"Create a new JavaScript Context."
},
{
"switch_tracing",
(PyCFunction)Runtime_switch_tracing,
METH_VARARGS | METH_KEYWORDS,
"Set/Clear Interrupt Handler to trace opcodes."
},
{NULL}
};
PyTypeObject _RuntimeType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"spidermonkey.Runtime", /*tp_name*/
sizeof(Runtime), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)Runtime_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"JavaScript Runtime", /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
Runtime_methods, /*tp_methods*/
Runtime_members, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
(initproc)Runtime_init, /*tp_init*/
0, /*tp_alloc*/
Runtime_new, /*tp_new*/
};
| gpl-2.0 |
ajm-asiaa/test | carta/cpp/core/Data/Image/Draw/DrawImageViewsSynchronizer.cpp | 3 | 3156 | #include "DrawImageViewsSynchronizer.h"
#include "DrawStackSynchronizer.h"
#include <QDebug>
namespace Carta {
namespace Data {
DrawImageViewsSynchronizer::DrawImageViewsSynchronizer( QObject* parent)
: QObject( parent ),
m_drawMain( nullptr ),
m_drawContext( nullptr ),
m_drawZoom( nullptr ){
m_busy = false;
}
void DrawImageViewsSynchronizer::_doneMain( bool /*drawn*/){
m_busy = false;
_startNextDraw();
}
void DrawImageViewsSynchronizer::_doneContext( bool /*drawn*/ ){
m_busy = false;
_startNextDraw();
}
void DrawImageViewsSynchronizer::_doneZoom( bool /*drawn*/){
m_busy = false;
_startNextDraw();
}
bool DrawImageViewsSynchronizer::isContextView() const {
bool contextView = false;
if ( m_drawContext ){
contextView = true;
}
return contextView;
}
bool DrawImageViewsSynchronizer::_isRequested( const std::shared_ptr<RenderRequest>& request ) const {
bool requested = false;
int requestCount = m_requests.size();
for ( int i = 0; i < requestCount; i++ ){
if ( m_requests[i]->operator==( *request.get() ) ){
requested = true;
break;
}
}
return requested;
}
bool DrawImageViewsSynchronizer::isZoomView() const {
bool zoomView = false;
if ( m_drawZoom ){
zoomView = true;
}
return zoomView;
}
void DrawImageViewsSynchronizer::render( const std::shared_ptr<RenderRequest>& request ){
if ( !_isRequested( request) ){
m_requests.enqueue( request );
if ( m_busy ){
return;
}
//Store the data & request.
_startNextDraw();
}
}
void DrawImageViewsSynchronizer::setViewDraw( std::shared_ptr<DrawStackSynchronizer> stackDraw ){
m_drawMain = stackDraw;
if ( m_drawMain.get() ){
connect ( m_drawMain.get(), SIGNAL( done(bool) ), this, SLOT(_doneMain(bool)));
}
}
void DrawImageViewsSynchronizer::setViewDrawContext( std::shared_ptr<DrawStackSynchronizer> stackDraw ){
m_drawContext = stackDraw;
if ( m_drawContext.get()){
connect( m_drawContext.get(), SIGNAL( done(bool)), this, SLOT( _doneContext(bool)));
}
}
void DrawImageViewsSynchronizer::setViewDrawZoom( std::shared_ptr<DrawStackSynchronizer> stackDraw ){
m_drawZoom = stackDraw;
if ( m_drawZoom.get() ){
connect( m_drawZoom.get(), SIGNAL( done(bool)), this, SLOT( _doneZoom(bool)));
}
}
void DrawImageViewsSynchronizer::_startNextDraw(){
if ( m_requests.size() > 0 ){
m_busy = true;
std::shared_ptr<RenderRequest> request = m_requests.dequeue();
if ( request->isRequestMain() ){
//Start the main renderer
request->setOutputSize( m_drawMain->getClientSize() );
m_drawMain-> _render( request);
}
else if ( request->isRequestContext() ){
request->setOutputSize( m_drawContext->getClientSize() );
m_drawContext-> _render(request);
}
else if ( request->isRequestZoom() ){
request->setOutputSize( m_drawZoom->getClientSize() );
m_drawZoom->_render(request);
}
}
}
DrawImageViewsSynchronizer::~DrawImageViewsSynchronizer(){
}
}
}
| gpl-2.0 |
lizj3624/xbmc | xbmc/interfaces/legacy/WindowXML.cpp | 3 | 17674 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.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.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "WindowXML.h"
#include "WindowInterceptor.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/TextureManager.h"
#include "addons/Skin.h"
#include "filesystem/File.h"
#include "utils/URIUtils.h"
#include "utils/StringUtils.h"
#include "addons/Addon.h"
#include "WindowException.h"
// These #defs are for WindowXML
#define CONTROL_BTNVIEWASICONS 2
#define CONTROL_BTNSORTBY 3
#define CONTROL_BTNSORTASC 4
#define CONTROL_LABELFILES 12
#define A(x) interceptor->x
namespace XBMCAddon
{
namespace xbmcgui
{
template class Interceptor<CGUIMediaWindow>;
/**
* This class extends the Interceptor<CGUIMediaWindow> in order to
* add behavior for a few more virtual functions that were unneccessary
* in the Window or WindowDialog.
*/
#define checkedb(methcall) ( window.isNotNull() ? xwin-> methcall : false )
#define checkedv(methcall) { if (window.isNotNull()) xwin-> methcall ; }
// TODO: This should be done with template specialization
class WindowXMLInterceptor : public InterceptorDialog<CGUIMediaWindow>
{
WindowXML* xwin;
public:
WindowXMLInterceptor(WindowXML* _window, int windowid,const char* xmlfile) :
InterceptorDialog<CGUIMediaWindow>("CGUIMediaWindow",_window,windowid,xmlfile), xwin(_window)
{ }
virtual void AllocResources(bool forceLoad = false)
{ XBMC_TRACE; if(up()) CGUIMediaWindow::AllocResources(forceLoad); else checkedv(AllocResources(forceLoad)); }
virtual void FreeResources(bool forceUnLoad = false)
{ XBMC_TRACE; if(up()) CGUIMediaWindow::FreeResources(forceUnLoad); else checkedv(FreeResources(forceUnLoad)); }
virtual bool OnClick(int iItem) { XBMC_TRACE; return up() ? CGUIMediaWindow::OnClick(iItem) : checkedb(OnClick(iItem)); }
virtual void Process(unsigned int currentTime, CDirtyRegionList &dirtyregions)
{ XBMC_TRACE; if(up()) CGUIMediaWindow::Process(currentTime,dirtyregions); else checkedv(Process(currentTime,dirtyregions)); }
// this is a hack to SKIP the CGUIMediaWindow
virtual bool OnAction(const CAction &action)
{ XBMC_TRACE; return up() ? CGUIWindow::OnAction(action) : checkedb(OnAction(action)); }
protected:
// CGUIWindow
virtual bool LoadXML(const std::string &strPath, const std::string &strPathLower)
{ XBMC_TRACE; return up() ? CGUIMediaWindow::LoadXML(strPath,strPathLower) : xwin->LoadXML(strPath,strPathLower); }
// CGUIMediaWindow
virtual void GetContextButtons(int itemNumber, CContextButtons &buttons)
{ XBMC_TRACE; if (up()) CGUIMediaWindow::GetContextButtons(itemNumber,buttons); else xwin->GetContextButtons(itemNumber,buttons); }
virtual bool Update(const std::string &strPath)
{ XBMC_TRACE; return up() ? CGUIMediaWindow::Update(strPath) : xwin->Update(strPath); }
virtual void SetupShares() { XBMC_TRACE; if(up()) CGUIMediaWindow::SetupShares(); else checkedv(SetupShares()); }
friend class WindowXML;
friend class WindowXMLDialog;
};
WindowXML::~WindowXML() { XBMC_TRACE; deallocating(); }
WindowXML::WindowXML(const String& xmlFilename,
const String& scriptPath,
const String& defaultSkin,
const String& defaultRes) :
Window(true)
{
XBMC_TRACE;
RESOLUTION_INFO res;
std::string strSkinPath = g_SkinInfo->GetSkinPath(xmlFilename, &res);
if (!XFILE::CFile::Exists(strSkinPath))
{
std::string str("none");
ADDON::AddonProps props(str, ADDON::ADDON_SKIN, "", "");
ADDON::CSkinInfo::TranslateResolution(defaultRes, res);
// Check for the matching folder for the skin in the fallback skins folder
std::string fallbackPath = URIUtils::AddFileToFolder(scriptPath, "resources");
fallbackPath = URIUtils::AddFileToFolder(fallbackPath, "skins");
std::string basePath = URIUtils::AddFileToFolder(fallbackPath, g_SkinInfo->ID());
strSkinPath = g_SkinInfo->GetSkinPath(xmlFilename, &res, basePath);
// Check for the matching folder for the skin in the fallback skins folder (if it exists)
if (XFILE::CFile::Exists(basePath))
{
props.path = basePath;
ADDON::CSkinInfo skinInfo(props, res);
skinInfo.Start();
strSkinPath = skinInfo.GetSkinPath(xmlFilename, &res);
}
if (!XFILE::CFile::Exists(strSkinPath))
{
// Finally fallback to the DefaultSkin as it didn't exist in either the XBMC Skin folder or the fallback skin folder
props.path = URIUtils::AddFileToFolder(fallbackPath, defaultSkin);
ADDON::CSkinInfo skinInfo(props, res);
skinInfo.Start();
strSkinPath = skinInfo.GetSkinPath(xmlFilename, &res);
if (!XFILE::CFile::Exists(strSkinPath))
throw WindowException("XML File for Window is missing");
}
}
m_scriptPath = scriptPath;
// sXMLFileName = strSkinPath;
interceptor = new WindowXMLInterceptor(this, lockingGetNextAvailalbeWindowId(),strSkinPath.c_str());
setWindow(interceptor);
interceptor->SetCoordsRes(res);
}
int WindowXML::lockingGetNextAvailalbeWindowId()
{
XBMC_TRACE;
CSingleLock lock(g_graphicsContext);
return getNextAvailalbeWindowId();
}
void WindowXML::addItem(const Alternative<String, const ListItem*>& item, int position)
{
XBMC_TRACE;
// item could be deleted if the reference count is 0.
// so I MAY need to check prior to using a Ref just in
// case this object is managed by Python. I'm not sure
// though.
AddonClass::Ref<ListItem> ritem = item.which() == XBMCAddon::first ? ListItem::fromString(item.former()) : AddonClass::Ref<ListItem>(item.later());
// Tells the window to add the item to FileItem vector
{
LOCKGUI;
//----------------------------------------------------
// Former AddItem call
//AddItem(ritem->item, pos);
{
CFileItemPtr& fileItem = ritem->item;
if (position == INT_MAX || position > A(m_vecItems)->Size())
{
A(m_vecItems)->Add(fileItem);
}
else if (position < -1 && !(position*-1 < A(m_vecItems)->Size()))
{
A(m_vecItems)->AddFront(fileItem,0);
}
else
{
A(m_vecItems)->AddFront(fileItem,position);
}
A(m_viewControl).SetItems(*(A(m_vecItems)));
A(UpdateButtons());
}
//----------------------------------------------------
}
}
void WindowXML::removeItem(int position)
{
XBMC_TRACE;
// Tells the window to remove the item at the specified position from the FileItem vector
LOCKGUI;
A(m_vecItems)->Remove(position);
A(m_viewControl).SetItems(*(A(m_vecItems)));
A(UpdateButtons());
}
int WindowXML::getCurrentListPosition()
{
XBMC_TRACE;
LOCKGUI;
int listPos = A(m_viewControl).GetSelectedItem();
return listPos;
}
void WindowXML::setCurrentListPosition(int position)
{
XBMC_TRACE;
LOCKGUI;
A(m_viewControl).SetSelectedItem(position);
}
ListItem* WindowXML::getListItem(int position)
{
LOCKGUI;
//CFileItemPtr fi = pwx->GetListItem(listPos);
CFileItemPtr fi;
{
if (position < 0 || position >= A(m_vecItems)->Size())
return new ListItem();
fi = A(m_vecItems)->Get(position);
}
if (fi == NULL)
{
XBMCAddonUtils::guiUnlock();
throw WindowException("Index out of range (%i)",position);
}
ListItem* sListItem = new ListItem();
sListItem->item = fi;
// let's hope someone reference counts this.
return sListItem;
}
int WindowXML::getListSize()
{
XBMC_TRACE;
return A(m_vecItems)->Size();
}
void WindowXML::clearList()
{
XBMC_TRACE;
LOCKGUI;
A(ClearFileItems());
A(m_viewControl).SetItems(*(A(m_vecItems)));
A(UpdateButtons());
}
void WindowXML::setProperty(const String& key, const String& value)
{
XBMC_TRACE;
A(m_vecItems)->SetProperty(key, value);
}
bool WindowXML::OnAction(const CAction &action)
{
XBMC_TRACE;
// do the base class window first, and the call to python after this
bool ret = ref(window)->OnAction(action); // we don't currently want the mediawindow actions here
// look at the WindowXMLInterceptor onAction, it skips
// the CGUIMediaWindow::OnAction and calls directly to
// CGUIWindow::OnAction
AddonClass::Ref<Action> inf(new Action(action));
invokeCallback(new CallbackFunction<WindowXML,AddonClass::Ref<Action> >(this,&WindowXML::onAction,inf.get()));
PulseActionEvent();
return ret;
}
bool WindowXML::OnMessage(CGUIMessage& message)
{
#ifdef ENABLE_XBMC_TRACE_API
XBMC_TRACE;
CLog::Log(LOGDEBUG,"%sMessage id:%d",_tg.getSpaces(),(int)message.GetMessage());
#endif
// TODO: We shouldn't be dropping down to CGUIWindow in any of this ideally.
// We have to make up our minds about what python should be doing and
// what this side of things should be doing
switch (message.GetMessage())
{
case GUI_MSG_WINDOW_DEINIT:
{
return ref(window)->OnMessage(message);
}
break;
case GUI_MSG_WINDOW_INIT:
{
ref(window)->OnMessage(message);
invokeCallback(new CallbackFunction<WindowXML>(this,&WindowXML::onInit));
PulseActionEvent();
return true;
}
break;
case GUI_MSG_FOCUSED:
{
if (A(m_viewControl).HasControl(message.GetControlId()) &&
A(m_viewControl).GetCurrentControl() != (int)message.GetControlId())
{
A(m_viewControl).SetFocused();
return true;
}
// check if our focused control is one of our category buttons
int iControl=message.GetControlId();
invokeCallback(new CallbackFunction<WindowXML,int>(this,&WindowXML::onFocus,iControl));
PulseActionEvent();
}
break;
case GUI_MSG_CLICKED:
{
int iControl=message.GetSenderId();
// Handle Sort/View internally. Scripters shouldn't use ID 2, 3 or 4.
if (iControl == CONTROL_BTNSORTASC) // sort asc
{
CLog::Log(LOGINFO, "WindowXML: Internal asc/dsc button not implemented");
/*if (m_guiState.get())
m_guiState->SetNextSortOrder();
UpdateFileList();*/
return true;
}
else if (iControl == CONTROL_BTNSORTBY) // sort by
{
CLog::Log(LOGINFO, "WindowXML: Internal sort button not implemented");
/*if (m_guiState.get())
m_guiState->SetNextSortMethod();
UpdateFileList();*/
return true;
}
if(iControl && iControl != (int)interceptor->GetID()) // pCallbackWindow && != this->GetID())
{
CGUIControl* controlClicked = (CGUIControl*)interceptor->GetControl(iControl);
// The old python way used to check list AND SELECITEM method
// or if its a button, checkmark.
// Its done this way for now to allow other controls without a
// python version like togglebutton to still raise a onAction event
if (controlClicked) // Will get problems if we the id is not on the window
// and we try to do GetControlType on it. So check to make sure it exists
{
if ((controlClicked->IsContainer() && (message.GetParam1() == ACTION_SELECT_ITEM || message.GetParam1() == ACTION_MOUSE_LEFT_CLICK)) || !controlClicked->IsContainer())
{
invokeCallback(new CallbackFunction<WindowXML,int>(this,&WindowXML::onClick,iControl));
PulseActionEvent();
return true;
}
else if (controlClicked->IsContainer() && message.GetParam1() == ACTION_MOUSE_DOUBLE_CLICK)
{
invokeCallback(new CallbackFunction<WindowXML,int>(this,&WindowXML::onDoubleClick,iControl));
PulseActionEvent();
return true;
}
else if (controlClicked->IsContainer() && message.GetParam1() == ACTION_MOUSE_RIGHT_CLICK)
{
AddonClass::Ref<Action> inf(new Action(CAction(ACTION_CONTEXT_MENU)));
invokeCallback(new CallbackFunction<WindowXML,AddonClass::Ref<Action> >(this,&WindowXML::onAction,inf.get()));
PulseActionEvent();
return true;
}
}
}
}
break;
}
return A(CGUIMediaWindow::OnMessage(message));
}
void WindowXML::AllocResources(bool forceLoad /*= FALSE */)
{
XBMC_TRACE;
std::string tmpDir = URIUtils::GetDirectory(ref(window)->GetProperty("xmlfile").asString());
std::string fallbackMediaPath;
URIUtils::GetParentPath(tmpDir, fallbackMediaPath);
URIUtils::RemoveSlashAtEnd(fallbackMediaPath);
m_mediaDir = fallbackMediaPath;
//CLog::Log(LOGDEBUG, "CGUIPythonWindowXML::AllocResources called: %s", fallbackMediaPath.c_str());
g_TextureManager.AddTexturePath(m_mediaDir);
ref(window)->AllocResources(forceLoad);
g_TextureManager.RemoveTexturePath(m_mediaDir);
}
void WindowXML::FreeResources(bool forceUnLoad /*= FALSE */)
{
XBMC_TRACE;
ref(window)->FreeResources(forceUnLoad);
}
void WindowXML::Process(unsigned int currentTime, CDirtyRegionList ®ions)
{
XBMC_TRACE;
g_TextureManager.AddTexturePath(m_mediaDir);
ref(window)->Process(currentTime, regions);
g_TextureManager.RemoveTexturePath(m_mediaDir);
}
bool WindowXML::OnClick(int iItem)
{
XBMC_TRACE;
// Hook Over calling CGUIMediaWindow::OnClick(iItem) results in it trying to PLAY the file item
// which if its not media is BAD and 99 out of 100 times undesireable.
return false;
}
bool WindowXML::OnDoubleClick(int iItem)
{
XBMC_TRACE;
return false;
}
void WindowXML::GetContextButtons(int itemNumber, CContextButtons &buttons)
{
XBMC_TRACE;
// maybe on day we can make an easy way to do this context menu
// with out this method overriding the MediaWindow version, it will display 'Add to Favorites'
}
bool WindowXML::LoadXML(const String &strPath, const String &strLowerPath)
{
XBMC_TRACE;
// load our window
CXBMCTinyXML xmlDoc;
std::string strPathLower = strPath;
StringUtils::ToLower(strPathLower);
if (!xmlDoc.LoadFile(strPath) && !xmlDoc.LoadFile(strPathLower) && !xmlDoc.LoadFile(strLowerPath))
{
// fail - can't load the file
CLog::Log(LOGERROR, "%s: Unable to load skin file %s", __FUNCTION__, strPath.c_str());
return false;
}
return interceptor->Load(xmlDoc.RootElement());
}
void WindowXML::SetupShares()
{
XBMC_TRACE;
A(UpdateButtons());
}
bool WindowXML::Update(const String &strPath)
{
XBMC_TRACE;
return true;
}
WindowXMLDialog::WindowXMLDialog(const String& xmlFilename, const String& scriptPath,
const String& defaultSkin,
const String& defaultRes) :
WindowXML(xmlFilename, scriptPath, defaultSkin, defaultRes),
WindowDialogMixin(this)
{ XBMC_TRACE; }
WindowXMLDialog::~WindowXMLDialog() { XBMC_TRACE; deallocating(); }
bool WindowXMLDialog::OnMessage(CGUIMessage &message)
{
XBMC_TRACE;
if (message.GetMessage() == GUI_MSG_WINDOW_DEINIT)
{
CGUIWindow *pWindow = g_windowManager.GetWindow(g_windowManager.GetActiveWindow());
if (pWindow)
g_windowManager.ShowOverlay(pWindow->GetOverlayState());
return A(CGUIWindow::OnMessage(message));
}
return WindowXML::OnMessage(message);
}
bool WindowXMLDialog::OnAction(const CAction &action)
{
XBMC_TRACE;
return WindowDialogMixin::OnAction(action) ? true : WindowXML::OnAction(action);
}
void WindowXMLDialog::OnDeinitWindow(int nextWindowID)
{
XBMC_TRACE;
g_windowManager.RemoveDialog(interceptor->GetID());
WindowXML::OnDeinitWindow(nextWindowID);
}
}
}
| gpl-2.0 |
zimmy76/git | builtin/merge-tree.c | 3 | 9008 | #include "builtin.h"
#include "tree-walk.h"
#include "xdiff-interface.h"
#include "blob.h"
#include "exec_cmd.h"
#include "merge-blobs.h"
static const char merge_tree_usage[] = "git merge-tree <base-tree> <branch1> <branch2>";
struct merge_list {
struct merge_list *next;
struct merge_list *link; /* other stages for this object */
unsigned int stage : 2;
unsigned int mode;
const char *path;
struct blob *blob;
};
static struct merge_list *merge_result, **merge_result_end = &merge_result;
static void add_merge_entry(struct merge_list *entry)
{
*merge_result_end = entry;
merge_result_end = &entry->next;
}
static void merge_trees_recursive(struct tree_desc t[3], const char *base, int df_conflict);
static const char *explanation(struct merge_list *entry)
{
switch (entry->stage) {
case 0:
return "merged";
case 3:
return "added in remote";
case 2:
if (entry->link)
return "added in both";
return "added in local";
}
/* Existed in base */
entry = entry->link;
if (!entry)
return "removed in both";
if (entry->link)
return "changed in both";
if (entry->stage == 3)
return "removed in local";
return "removed in remote";
}
static void *result(struct merge_list *entry, unsigned long *size)
{
enum object_type type;
struct blob *base, *our, *their;
const char *path = entry->path;
if (!entry->stage)
return read_sha1_file(entry->blob->object.sha1, &type, size);
base = NULL;
if (entry->stage == 1) {
base = entry->blob;
entry = entry->link;
}
our = NULL;
if (entry && entry->stage == 2) {
our = entry->blob;
entry = entry->link;
}
their = NULL;
if (entry)
their = entry->blob;
return merge_blobs(path, base, our, their, size);
}
static void *origin(struct merge_list *entry, unsigned long *size)
{
enum object_type type;
while (entry) {
if (entry->stage == 2)
return read_sha1_file(entry->blob->object.sha1, &type, size);
entry = entry->link;
}
return NULL;
}
static int show_outf(void *priv_, mmbuffer_t *mb, int nbuf)
{
int i;
for (i = 0; i < nbuf; i++)
printf("%.*s", (int) mb[i].size, mb[i].ptr);
return 0;
}
static void show_diff(struct merge_list *entry)
{
unsigned long size;
mmfile_t src, dst;
xpparam_t xpp;
xdemitconf_t xecfg;
xdemitcb_t ecb;
xpp.flags = 0;
memset(&xecfg, 0, sizeof(xecfg));
xecfg.ctxlen = 3;
ecb.outf = show_outf;
ecb.priv = NULL;
src.ptr = origin(entry, &size);
if (!src.ptr)
size = 0;
src.size = size;
dst.ptr = result(entry, &size);
if (!dst.ptr)
size = 0;
dst.size = size;
xdi_diff(&src, &dst, &xpp, &xecfg, &ecb);
free(src.ptr);
free(dst.ptr);
}
static void show_result_list(struct merge_list *entry)
{
printf("%s\n", explanation(entry));
do {
struct merge_list *link = entry->link;
static const char *desc[4] = { "result", "base", "our", "their" };
printf(" %-6s %o %s %s\n", desc[entry->stage], entry->mode, sha1_to_hex(entry->blob->object.sha1), entry->path);
entry = link;
} while (entry);
}
static void show_result(void)
{
struct merge_list *walk;
walk = merge_result;
while (walk) {
show_result_list(walk);
show_diff(walk);
walk = walk->next;
}
}
/* An empty entry never compares same, not even to another empty entry */
static int same_entry(struct name_entry *a, struct name_entry *b)
{
return a->sha1 &&
b->sha1 &&
!hashcmp(a->sha1, b->sha1) &&
a->mode == b->mode;
}
static struct merge_list *create_entry(unsigned stage, unsigned mode, const unsigned char *sha1, const char *path)
{
struct merge_list *res = xcalloc(1, sizeof(*res));
res->stage = stage;
res->path = path;
res->mode = mode;
res->blob = lookup_blob(sha1);
return res;
}
static char *traverse_path(const struct traverse_info *info, const struct name_entry *n)
{
char *path = xmalloc(traverse_path_len(info, n) + 1);
return make_traverse_path(path, info, n);
}
static void resolve(const struct traverse_info *info, struct name_entry *ours, struct name_entry *result)
{
struct merge_list *orig, *final;
const char *path;
/* If it's already ours, don't bother showing it */
if (!ours)
return;
path = traverse_path(info, result);
orig = create_entry(2, ours->mode, ours->sha1, path);
final = create_entry(0, result->mode, result->sha1, path);
final->link = orig;
add_merge_entry(final);
}
static void unresolved_directory(const struct traverse_info *info, struct name_entry n[3],
int df_conflict)
{
char *newbase;
struct name_entry *p;
struct tree_desc t[3];
void *buf0, *buf1, *buf2;
for (p = n; p < n + 3; p++) {
if (p->mode && S_ISDIR(p->mode))
break;
}
if (n + 3 <= p)
return; /* there is no tree here */
newbase = traverse_path(info, p);
#define ENTRY_SHA1(e) (((e)->mode && S_ISDIR((e)->mode)) ? (e)->sha1 : NULL)
buf0 = fill_tree_descriptor(t+0, ENTRY_SHA1(n + 0));
buf1 = fill_tree_descriptor(t+1, ENTRY_SHA1(n + 1));
buf2 = fill_tree_descriptor(t+2, ENTRY_SHA1(n + 2));
#undef ENTRY_SHA1
merge_trees_recursive(t, newbase, df_conflict);
free(buf0);
free(buf1);
free(buf2);
free(newbase);
}
static struct merge_list *link_entry(unsigned stage, const struct traverse_info *info, struct name_entry *n, struct merge_list *entry)
{
const char *path;
struct merge_list *link;
if (!n->mode)
return entry;
if (entry)
path = entry->path;
else
path = traverse_path(info, n);
link = create_entry(stage, n->mode, n->sha1, path);
link->link = entry;
return link;
}
static void unresolved(const struct traverse_info *info, struct name_entry n[3])
{
struct merge_list *entry = NULL;
int i;
unsigned dirmask = 0, mask = 0;
for (i = 0; i < 3; i++) {
mask |= (1 << i);
if (n[i].mode && S_ISDIR(n[i].mode))
dirmask |= (1 << i);
}
unresolved_directory(info, n, dirmask && (dirmask != mask));
if (dirmask == mask)
return;
if (n[2].mode && !S_ISDIR(n[2].mode))
entry = link_entry(3, info, n + 2, entry);
if (n[1].mode && !S_ISDIR(n[1].mode))
entry = link_entry(2, info, n + 1, entry);
if (n[0].mode && !S_ISDIR(n[0].mode))
entry = link_entry(1, info, n + 0, entry);
add_merge_entry(entry);
}
/*
* Merge two trees together (t[1] and t[2]), using a common base (t[0])
* as the origin.
*
* This walks the (sorted) trees in lock-step, checking every possible
* name. Note that directories automatically sort differently from other
* files (see "base_name_compare"), so you'll never see file/directory
* conflicts, because they won't ever compare the same.
*
* IOW, if a directory changes to a filename, it will automatically be
* seen as the directory going away, and the filename being created.
*
* Think of this as a three-way diff.
*
* The output will be either:
* - successful merge
* "0 mode sha1 filename"
* NOTE NOTE NOTE! FIXME! We really really need to walk the index
* in parallel with this too!
*
* - conflict:
* "1 mode sha1 filename"
* "2 mode sha1 filename"
* "3 mode sha1 filename"
* where not all of the 1/2/3 lines may exist, of course.
*
* The successful merge rules are the same as for the three-way merge
* in git-read-tree.
*/
static int threeway_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *entry, struct traverse_info *info)
{
/* Same in both? */
if (same_entry(entry+1, entry+2)) {
if (entry[0].sha1) {
/* Modified identically */
resolve(info, NULL, entry+1);
return mask;
}
/* "Both added the same" is left unresolved */
}
if (same_entry(entry+0, entry+1)) {
if (entry[2].sha1 && !S_ISDIR(entry[2].mode)) {
/* We did not touch, they modified -- take theirs */
resolve(info, entry+1, entry+2);
return mask;
}
/*
* If we did not touch a directory but they made it
* into a file, we fall through and unresolved()
* recurses down. Likewise for the opposite case.
*/
}
if (same_entry(entry+0, entry+2)) {
if (entry[1].sha1 && !S_ISDIR(entry[1].mode)) {
/* We modified, they did not touch -- take ours */
resolve(info, NULL, entry+1);
return mask;
}
}
unresolved(info, entry);
return mask;
}
static void merge_trees_recursive(struct tree_desc t[3], const char *base, int df_conflict)
{
struct traverse_info info;
setup_traverse_info(&info, base);
info.data = &df_conflict;
info.fn = threeway_callback;
traverse_trees(3, t, &info);
}
static void merge_trees(struct tree_desc t[3], const char *base)
{
merge_trees_recursive(t, base, 0);
}
static void *get_tree_descriptor(struct tree_desc *desc, const char *rev)
{
unsigned char sha1[20];
void *buf;
if (get_sha1(rev, sha1))
die("unknown rev %s", rev);
buf = fill_tree_descriptor(desc, sha1);
if (!buf)
die("%s is not a tree", rev);
return buf;
}
int cmd_merge_tree(int argc, const char **argv, const char *prefix)
{
struct tree_desc t[3];
void *buf1, *buf2, *buf3;
if (argc != 4)
usage(merge_tree_usage);
buf1 = get_tree_descriptor(t+0, argv[1]);
buf2 = get_tree_descriptor(t+1, argv[2]);
buf3 = get_tree_descriptor(t+2, argv[3]);
merge_trees(t, "");
free(buf1);
free(buf2);
free(buf3);
show_result();
return 0;
}
| gpl-2.0 |
morogoku/MoRoKernel-G935F-601 | crypto/algapi.c | 3 | 22327 | /*
* Cryptographic API for algorithms (i.e., low-level API).
*
* Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au>
*
* 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 <linux/err.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/rtnetlink.h>
#include <linux/slab.h>
#include <linux/string.h>
#include "internal.h"
static LIST_HEAD(crypto_template_list);
static inline int crypto_set_driver_name(struct crypto_alg *alg)
{
static const char suffix[] = "-generic";
char *driver_name = alg->cra_driver_name;
int len;
if (*driver_name)
return 0;
len = strlcpy(driver_name, alg->cra_name, CRYPTO_MAX_ALG_NAME);
if (len + sizeof(suffix) > CRYPTO_MAX_ALG_NAME)
return -ENAMETOOLONG;
memcpy(driver_name + len, suffix, sizeof(suffix));
return 0;
}
static int crypto_check_alg(struct crypto_alg *alg)
{
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err())) {
printk(KERN_ERR
"crypto_check_alg failed due to FIPS error: %s",
alg->cra_name);
return -EACCES;
}
#endif
if (alg->cra_alignmask & (alg->cra_alignmask + 1))
return -EINVAL;
if (alg->cra_blocksize > PAGE_SIZE / 8)
return -EINVAL;
if (alg->cra_priority < 0)
return -EINVAL;
return crypto_set_driver_name(alg);
}
static void crypto_destroy_instance(struct crypto_alg *alg)
{
struct crypto_instance *inst = (void *)alg;
struct crypto_template *tmpl = inst->tmpl;
tmpl->free(inst);
crypto_tmpl_put(tmpl);
}
static struct list_head *crypto_more_spawns(struct crypto_alg *alg,
struct list_head *stack,
struct list_head *top,
struct list_head *secondary_spawns)
{
struct crypto_spawn *spawn, *n;
if (list_empty(stack))
return NULL;
spawn = list_first_entry(stack, struct crypto_spawn, list);
n = list_entry(spawn->list.next, struct crypto_spawn, list);
if (spawn->alg && &n->list != stack && !n->alg)
n->alg = (n->list.next == stack) ? alg :
&list_entry(n->list.next, struct crypto_spawn,
list)->inst->alg;
list_move(&spawn->list, secondary_spawns);
return &n->list == stack ? top : &n->inst->alg.cra_users;
}
static void crypto_remove_spawn(struct crypto_spawn *spawn,
struct list_head *list)
{
struct crypto_instance *inst = spawn->inst;
struct crypto_template *tmpl = inst->tmpl;
if (crypto_is_dead(&inst->alg))
return;
inst->alg.cra_flags |= CRYPTO_ALG_DEAD;
if (hlist_unhashed(&inst->list))
return;
if (!tmpl || !crypto_tmpl_get(tmpl))
return;
crypto_notify(CRYPTO_MSG_ALG_UNREGISTER, &inst->alg);
list_move(&inst->alg.cra_list, list);
hlist_del(&inst->list);
inst->alg.cra_destroy = crypto_destroy_instance;
BUG_ON(!list_empty(&inst->alg.cra_users));
}
void crypto_remove_spawns(struct crypto_alg *alg, struct list_head *list,
struct crypto_alg *nalg)
{
u32 new_type = (nalg ?: alg)->cra_flags;
struct crypto_spawn *spawn, *n;
LIST_HEAD(secondary_spawns);
struct list_head *spawns;
LIST_HEAD(stack);
LIST_HEAD(top);
spawns = &alg->cra_users;
list_for_each_entry_safe(spawn, n, spawns, list) {
if ((spawn->alg->cra_flags ^ new_type) & spawn->mask)
continue;
list_move(&spawn->list, &top);
}
spawns = ⊤
do {
while (!list_empty(spawns)) {
struct crypto_instance *inst;
spawn = list_first_entry(spawns, struct crypto_spawn,
list);
inst = spawn->inst;
BUG_ON(&inst->alg == alg);
list_move(&spawn->list, &stack);
if (&inst->alg == nalg)
break;
spawn->alg = NULL;
spawns = &inst->alg.cra_users;
}
} while ((spawns = crypto_more_spawns(alg, &stack, &top,
&secondary_spawns)));
list_for_each_entry_safe(spawn, n, &secondary_spawns, list) {
if (spawn->alg)
list_move(&spawn->list, &spawn->alg->cra_users);
else
crypto_remove_spawn(spawn, list);
}
}
EXPORT_SYMBOL_GPL(crypto_remove_spawns);
static struct crypto_larval *__crypto_register_alg(struct crypto_alg *alg)
{
struct crypto_alg *q;
struct crypto_larval *larval;
int ret = -EAGAIN;
if (crypto_is_dead(alg))
goto err;
INIT_LIST_HEAD(&alg->cra_users);
/* No cheating! */
alg->cra_flags &= ~CRYPTO_ALG_TESTED;
ret = -EEXIST;
atomic_set(&alg->cra_refcnt, 1);
list_for_each_entry(q, &crypto_alg_list, cra_list) {
if (q == alg)
goto err;
if (crypto_is_moribund(q))
continue;
if (crypto_is_larval(q)) {
if (!strcmp(alg->cra_driver_name, q->cra_driver_name))
goto err;
continue;
}
if (!strcmp(q->cra_driver_name, alg->cra_name) ||
!strcmp(q->cra_name, alg->cra_driver_name))
goto err;
}
larval = crypto_larval_alloc(alg->cra_name,
alg->cra_flags | CRYPTO_ALG_TESTED, 0);
if (IS_ERR(larval))
goto out;
ret = -ENOENT;
larval->adult = crypto_mod_get(alg);
if (!larval->adult)
goto free_larval;
atomic_set(&larval->alg.cra_refcnt, 1);
memcpy(larval->alg.cra_driver_name, alg->cra_driver_name,
CRYPTO_MAX_ALG_NAME);
larval->alg.cra_priority = alg->cra_priority;
list_add(&alg->cra_list, &crypto_alg_list);
list_add(&larval->alg.cra_list, &crypto_alg_list);
out:
return larval;
free_larval:
kfree(larval);
err:
larval = ERR_PTR(ret);
goto out;
}
void crypto_alg_tested(const char *name, int err)
{
struct crypto_larval *test;
struct crypto_alg *alg;
struct crypto_alg *q;
LIST_HEAD(list);
down_write(&crypto_alg_sem);
list_for_each_entry(q, &crypto_alg_list, cra_list) {
if (crypto_is_moribund(q) || !crypto_is_larval(q))
continue;
test = (struct crypto_larval *)q;
if (!strcmp(q->cra_driver_name, name))
goto found;
}
printk(KERN_ERR "alg: Unexpected test result for %s: %d\n", name, err);
goto unlock;
found:
q->cra_flags |= CRYPTO_ALG_DEAD;
alg = test->adult;
#ifndef CONFIG_CRYPTO_FIPS
if (err || list_empty(&alg->cra_list))
goto complete;
#else
/* change@dtl.ksingh - starts
* Self-test failure is not reported when it fails for HMAC
* as it runs in a tertiary thread. Hence appropirate failure
* notification must be sent to prevent 60sec thread sleep
*/
if (err || list_empty(&alg->cra_list)) {
list_for_each_entry(q, &crypto_alg_list, cra_list) {
if (q == alg) {
continue;
}
if (crypto_is_moribund(q)) {
continue;
}
if (crypto_is_larval(q)) {
struct crypto_larval *larval = (void *)q;
if (strcmp(alg->cra_name, q->cra_name) &&
strcmp(alg->cra_driver_name, q->cra_name)) {
continue;
}
larval->adult = alg;
complete_all(&larval->completion);
continue;
}
}
goto complete;
}
#endif
// change@dtl.ksingh - ends
if (err || list_empty(&alg->cra_list))
goto complete;
alg->cra_flags |= CRYPTO_ALG_TESTED;
list_for_each_entry(q, &crypto_alg_list, cra_list) {
if (q == alg)
continue;
if (crypto_is_moribund(q))
continue;
if (crypto_is_larval(q)) {
struct crypto_larval *larval = (void *)q;
/*
* Check to see if either our generic name or
* specific name can satisfy the name requested
* by the larval entry q.
*/
if (strcmp(alg->cra_name, q->cra_name) &&
strcmp(alg->cra_driver_name, q->cra_name))
continue;
if (larval->adult)
continue;
if ((q->cra_flags ^ alg->cra_flags) & larval->mask)
continue;
if (!crypto_mod_get(alg))
continue;
larval->adult = alg;
continue;
}
if (strcmp(alg->cra_name, q->cra_name))
continue;
if (strcmp(alg->cra_driver_name, q->cra_driver_name) &&
q->cra_priority > alg->cra_priority)
continue;
crypto_remove_spawns(q, &list, alg);
}
complete:
complete_all(&test->completion);
unlock:
up_write(&crypto_alg_sem);
crypto_remove_final(&list);
}
EXPORT_SYMBOL_GPL(crypto_alg_tested);
void crypto_remove_final(struct list_head *list)
{
struct crypto_alg *alg;
struct crypto_alg *n;
list_for_each_entry_safe(alg, n, list, cra_list) {
list_del_init(&alg->cra_list);
crypto_alg_put(alg);
}
}
EXPORT_SYMBOL_GPL(crypto_remove_final);
static void crypto_wait_for_test(struct crypto_larval *larval)
{
int err;
err = crypto_probing_notify(CRYPTO_MSG_ALG_REGISTER, larval->adult);
if (err != NOTIFY_STOP) {
if (WARN_ON(err != NOTIFY_DONE))
goto out;
crypto_alg_tested(larval->alg.cra_driver_name, 0);
}
err = wait_for_completion_killable(&larval->completion);
WARN_ON(err);
out:
crypto_larval_kill(&larval->alg);
}
int crypto_register_alg(struct crypto_alg *alg)
{
struct crypto_larval *larval;
int err;
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err())) {
printk(KERN_ERR
"Unable to registrer alg: %s because of FIPS ERROR\n"
, alg->cra_name);
return -EACCES;
}
#endif
err = crypto_check_alg(alg);
if (err)
return err;
down_write(&crypto_alg_sem);
larval = __crypto_register_alg(alg);
up_write(&crypto_alg_sem);
if (IS_ERR(larval))
return PTR_ERR(larval);
crypto_wait_for_test(larval);
return 0;
}
EXPORT_SYMBOL_GPL(crypto_register_alg);
static int crypto_remove_alg(struct crypto_alg *alg, struct list_head *list)
{
if (unlikely(list_empty(&alg->cra_list)))
return -ENOENT;
alg->cra_flags |= CRYPTO_ALG_DEAD;
crypto_notify(CRYPTO_MSG_ALG_UNREGISTER, alg);
list_del_init(&alg->cra_list);
crypto_remove_spawns(alg, list, NULL);
return 0;
}
int crypto_unregister_alg(struct crypto_alg *alg)
{
int ret;
LIST_HEAD(list);
down_write(&crypto_alg_sem);
ret = crypto_remove_alg(alg, &list);
up_write(&crypto_alg_sem);
if (ret)
return ret;
BUG_ON(atomic_read(&alg->cra_refcnt) != 1);
if (alg->cra_destroy)
alg->cra_destroy(alg);
crypto_remove_final(&list);
return 0;
}
EXPORT_SYMBOL_GPL(crypto_unregister_alg);
int crypto_register_algs(struct crypto_alg *algs, int count)
{
int i, ret;
for (i = 0; i < count; i++) {
ret = crypto_register_alg(&algs[i]);
if (ret)
goto err;
}
return 0;
err:
for (--i; i >= 0; --i)
crypto_unregister_alg(&algs[i]);
return ret;
}
EXPORT_SYMBOL_GPL(crypto_register_algs);
int crypto_unregister_algs(struct crypto_alg *algs, int count)
{
int i, ret;
for (i = 0; i < count; i++) {
ret = crypto_unregister_alg(&algs[i]);
if (ret)
pr_err("Failed to unregister %s %s: %d\n",
algs[i].cra_driver_name, algs[i].cra_name, ret);
}
return 0;
}
EXPORT_SYMBOL_GPL(crypto_unregister_algs);
int crypto_register_template(struct crypto_template *tmpl)
{
struct crypto_template *q;
int err = -EEXIST;
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err()))
return -EACCES;
#endif
down_write(&crypto_alg_sem);
//crypto_check_module_sig(tmpl->module);
list_for_each_entry(q, &crypto_template_list, list) {
if (q == tmpl)
goto out;
}
list_add(&tmpl->list, &crypto_template_list);
crypto_notify(CRYPTO_MSG_TMPL_REGISTER, tmpl);
err = 0;
out:
up_write(&crypto_alg_sem);
return err;
}
EXPORT_SYMBOL_GPL(crypto_register_template);
void crypto_unregister_template(struct crypto_template *tmpl)
{
struct crypto_instance *inst;
struct hlist_node *n;
struct hlist_head *list;
LIST_HEAD(users);
down_write(&crypto_alg_sem);
BUG_ON(list_empty(&tmpl->list));
list_del_init(&tmpl->list);
list = &tmpl->instances;
hlist_for_each_entry(inst, list, list) {
int err = crypto_remove_alg(&inst->alg, &users);
BUG_ON(err);
}
crypto_notify(CRYPTO_MSG_TMPL_UNREGISTER, tmpl);
up_write(&crypto_alg_sem);
hlist_for_each_entry_safe(inst, n, list, list) {
BUG_ON(atomic_read(&inst->alg.cra_refcnt) != 1);
tmpl->free(inst);
}
crypto_remove_final(&users);
}
EXPORT_SYMBOL_GPL(crypto_unregister_template);
static struct crypto_template *__crypto_lookup_template(const char *name)
{
struct crypto_template *q, *tmpl = NULL;
down_read(&crypto_alg_sem);
list_for_each_entry(q, &crypto_template_list, list) {
if (strcmp(q->name, name))
continue;
if (unlikely(!crypto_tmpl_get(q)))
continue;
tmpl = q;
break;
}
up_read(&crypto_alg_sem);
return tmpl;
}
struct crypto_template *crypto_lookup_template(const char *name)
{
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err())) {
printk(KERN_ERR
"crypto_lookup failed due to FIPS error: %s", name);
return ERR_PTR(-EACCES);
}
#endif
return try_then_request_module(__crypto_lookup_template(name),
"crypto-%s", name);
}
EXPORT_SYMBOL_GPL(crypto_lookup_template);
int crypto_register_instance(struct crypto_template *tmpl,
struct crypto_instance *inst)
{
struct crypto_larval *larval;
int err;
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err()))
return -EACCES;
#endif
err = crypto_check_alg(&inst->alg);
if (err)
goto err;
inst->alg.cra_module = tmpl->module;
inst->alg.cra_flags |= CRYPTO_ALG_INSTANCE;
down_write(&crypto_alg_sem);
larval = __crypto_register_alg(&inst->alg);
if (IS_ERR(larval))
goto unlock;
hlist_add_head(&inst->list, &tmpl->instances);
inst->tmpl = tmpl;
unlock:
up_write(&crypto_alg_sem);
err = PTR_ERR(larval);
if (IS_ERR(larval))
goto err;
crypto_wait_for_test(larval);
err = 0;
err:
return err;
}
EXPORT_SYMBOL_GPL(crypto_register_instance);
int crypto_unregister_instance(struct crypto_alg *alg)
{
int err;
struct crypto_instance *inst = (void *)alg;
struct crypto_template *tmpl = inst->tmpl;
LIST_HEAD(users);
if (!(alg->cra_flags & CRYPTO_ALG_INSTANCE))
return -EINVAL;
BUG_ON(atomic_read(&alg->cra_refcnt) != 1);
down_write(&crypto_alg_sem);
hlist_del_init(&inst->list);
err = crypto_remove_alg(alg, &users);
up_write(&crypto_alg_sem);
if (err)
return err;
tmpl->free(inst);
crypto_remove_final(&users);
return 0;
}
EXPORT_SYMBOL_GPL(crypto_unregister_instance);
int crypto_init_spawn(struct crypto_spawn *spawn, struct crypto_alg *alg,
struct crypto_instance *inst, u32 mask)
{
int err = -EAGAIN;
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err()))
return -EACCES;
#endif
spawn->inst = inst;
spawn->mask = mask;
down_write(&crypto_alg_sem);
if (!crypto_is_moribund(alg)) {
list_add(&spawn->list, &alg->cra_users);
spawn->alg = alg;
err = 0;
}
up_write(&crypto_alg_sem);
return err;
}
EXPORT_SYMBOL_GPL(crypto_init_spawn);
int crypto_init_spawn2(struct crypto_spawn *spawn, struct crypto_alg *alg,
struct crypto_instance *inst,
const struct crypto_type *frontend)
{
int err = -EINVAL;
if ((alg->cra_flags ^ frontend->type) & frontend->maskset)
goto out;
spawn->frontend = frontend;
err = crypto_init_spawn(spawn, alg, inst, frontend->maskset);
out:
return err;
}
EXPORT_SYMBOL_GPL(crypto_init_spawn2);
void crypto_drop_spawn(struct crypto_spawn *spawn)
{
if (!spawn->alg)
return;
down_write(&crypto_alg_sem);
list_del(&spawn->list);
up_write(&crypto_alg_sem);
}
EXPORT_SYMBOL_GPL(crypto_drop_spawn);
static struct crypto_alg *crypto_spawn_alg(struct crypto_spawn *spawn)
{
struct crypto_alg *alg;
struct crypto_alg *alg2;
down_read(&crypto_alg_sem);
alg = spawn->alg;
alg2 = alg;
if (alg2)
alg2 = crypto_mod_get(alg2);
up_read(&crypto_alg_sem);
if (!alg2) {
if (alg)
crypto_shoot_alg(alg);
return ERR_PTR(-EAGAIN);
}
return alg;
}
struct crypto_tfm *crypto_spawn_tfm(struct crypto_spawn *spawn, u32 type,
u32 mask)
{
struct crypto_alg *alg;
struct crypto_tfm *tfm;
alg = crypto_spawn_alg(spawn);
if (IS_ERR(alg))
return ERR_CAST(alg);
tfm = ERR_PTR(-EINVAL);
if (unlikely((alg->cra_flags ^ type) & mask))
goto out_put_alg;
tfm = __crypto_alloc_tfm(alg, type, mask);
if (IS_ERR(tfm))
goto out_put_alg;
return tfm;
out_put_alg:
crypto_mod_put(alg);
return tfm;
}
EXPORT_SYMBOL_GPL(crypto_spawn_tfm);
void *crypto_spawn_tfm2(struct crypto_spawn *spawn)
{
struct crypto_alg *alg;
struct crypto_tfm *tfm;
alg = crypto_spawn_alg(spawn);
if (IS_ERR(alg))
return ERR_CAST(alg);
tfm = crypto_create_tfm(alg, spawn->frontend);
if (IS_ERR(tfm))
goto out_put_alg;
return tfm;
out_put_alg:
crypto_mod_put(alg);
return tfm;
}
EXPORT_SYMBOL_GPL(crypto_spawn_tfm2);
int crypto_register_notifier(struct notifier_block *nb)
{
return blocking_notifier_chain_register(&crypto_chain, nb);
}
EXPORT_SYMBOL_GPL(crypto_register_notifier);
int crypto_unregister_notifier(struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(&crypto_chain, nb);
}
EXPORT_SYMBOL_GPL(crypto_unregister_notifier);
struct crypto_attr_type *crypto_get_attr_type(struct rtattr **tb)
{
struct rtattr *rta = tb[0];
struct crypto_attr_type *algt;
if (!rta)
return ERR_PTR(-ENOENT);
if (RTA_PAYLOAD(rta) < sizeof(*algt))
return ERR_PTR(-EINVAL);
if (rta->rta_type != CRYPTOA_TYPE)
return ERR_PTR(-EINVAL);
algt = RTA_DATA(rta);
return algt;
}
EXPORT_SYMBOL_GPL(crypto_get_attr_type);
int crypto_check_attr_type(struct rtattr **tb, u32 type)
{
struct crypto_attr_type *algt;
algt = crypto_get_attr_type(tb);
if (IS_ERR(algt))
return PTR_ERR(algt);
if ((algt->type ^ type) & algt->mask)
return -EINVAL;
return 0;
}
EXPORT_SYMBOL_GPL(crypto_check_attr_type);
const char *crypto_attr_alg_name(struct rtattr *rta)
{
struct crypto_attr_alg *alga;
if (!rta)
return ERR_PTR(-ENOENT);
if (RTA_PAYLOAD(rta) < sizeof(*alga))
return ERR_PTR(-EINVAL);
if (rta->rta_type != CRYPTOA_ALG)
return ERR_PTR(-EINVAL);
alga = RTA_DATA(rta);
alga->name[CRYPTO_MAX_ALG_NAME - 1] = 0;
return alga->name;
}
EXPORT_SYMBOL_GPL(crypto_attr_alg_name);
struct crypto_alg *crypto_attr_alg2(struct rtattr *rta,
const struct crypto_type *frontend,
u32 type, u32 mask)
{
const char *name;
name = crypto_attr_alg_name(rta);
if (IS_ERR(name))
return ERR_CAST(name);
return crypto_find_alg(name, frontend, type, mask);
}
EXPORT_SYMBOL_GPL(crypto_attr_alg2);
int crypto_attr_u32(struct rtattr *rta, u32 *num)
{
struct crypto_attr_u32 *nu32;
if (!rta)
return -ENOENT;
if (RTA_PAYLOAD(rta) < sizeof(*nu32))
return -EINVAL;
if (rta->rta_type != CRYPTOA_U32)
return -EINVAL;
nu32 = RTA_DATA(rta);
*num = nu32->num;
return 0;
}
EXPORT_SYMBOL_GPL(crypto_attr_u32);
void *crypto_alloc_instance2(const char *name, struct crypto_alg *alg,
unsigned int head)
{
struct crypto_instance *inst;
char *p;
int err;
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err()))
return ERR_PTR(-EACCES);
#endif
p = kzalloc(head + sizeof(*inst) + sizeof(struct crypto_spawn),
GFP_KERNEL);
if (!p)
return ERR_PTR(-ENOMEM);
inst = (void *)(p + head);
err = -ENAMETOOLONG;
if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", name,
alg->cra_name) >= CRYPTO_MAX_ALG_NAME)
goto err_free_inst;
if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME, "%s(%s)",
name, alg->cra_driver_name) >= CRYPTO_MAX_ALG_NAME)
goto err_free_inst;
return p;
err_free_inst:
kfree(p);
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(crypto_alloc_instance2);
struct crypto_instance *crypto_alloc_instance(const char *name,
struct crypto_alg *alg)
{
struct crypto_instance *inst;
struct crypto_spawn *spawn;
int err;
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err()))
return ERR_PTR(-EACCES);
#endif
inst = crypto_alloc_instance2(name, alg, 0);
if (IS_ERR(inst))
goto out;
spawn = crypto_instance_ctx(inst);
err = crypto_init_spawn(spawn, alg, inst,
CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_ASYNC);
if (err)
goto err_free_inst;
return inst;
err_free_inst:
kfree(inst);
inst = ERR_PTR(err);
out:
return inst;
}
EXPORT_SYMBOL_GPL(crypto_alloc_instance);
void crypto_init_queue(struct crypto_queue *queue, unsigned int max_qlen)
{
INIT_LIST_HEAD(&queue->list);
queue->backlog = &queue->list;
queue->qlen = 0;
queue->max_qlen = max_qlen;
}
EXPORT_SYMBOL_GPL(crypto_init_queue);
int crypto_enqueue_request(struct crypto_queue *queue,
struct crypto_async_request *request)
{
int err = -EINPROGRESS;
#ifdef CONFIG_CRYPTO_FIPS
if (unlikely(in_fips_err()))
return -EACCES;
#endif
if (unlikely(queue->qlen >= queue->max_qlen)) {
err = -EBUSY;
if (!(request->flags & CRYPTO_TFM_REQ_MAY_BACKLOG))
goto out;
if (queue->backlog == &queue->list)
queue->backlog = &request->list;
}
queue->qlen++;
list_add_tail(&request->list, &queue->list);
out:
return err;
}
EXPORT_SYMBOL_GPL(crypto_enqueue_request);
void *__crypto_dequeue_request(struct crypto_queue *queue, unsigned int offset)
{
struct list_head *request;
if (unlikely(!queue->qlen))
return NULL;
queue->qlen--;
if (queue->backlog != &queue->list)
queue->backlog = queue->backlog->next;
request = queue->list.next;
list_del(request);
return (char *)list_entry(request, struct crypto_async_request, list) -
offset;
}
EXPORT_SYMBOL_GPL(__crypto_dequeue_request);
struct crypto_async_request *crypto_dequeue_request(struct crypto_queue *queue)
{
return __crypto_dequeue_request(queue, 0);
}
EXPORT_SYMBOL_GPL(crypto_dequeue_request);
int crypto_tfm_in_queue(struct crypto_queue *queue, struct crypto_tfm *tfm)
{
struct crypto_async_request *req;
list_for_each_entry(req, &queue->list, list) {
if (req->tfm == tfm)
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(crypto_tfm_in_queue);
static inline void crypto_inc_byte(u8 *a, unsigned int size)
{
u8 *b = (a + size);
u8 c;
for (; size; size--) {
c = *--b + 1;
*b = c;
if (c)
break;
}
}
void crypto_inc(u8 *a, unsigned int size)
{
__be32 *b = (__be32 *)(a + size);
u32 c;
for (; size >= 4; size -= 4) {
c = be32_to_cpu(*--b) + 1;
*b = cpu_to_be32(c);
if (c)
return;
}
crypto_inc_byte(a, size);
}
EXPORT_SYMBOL_GPL(crypto_inc);
static inline void crypto_xor_byte(u8 *a, const u8 *b, unsigned int size)
{
for (; size; size--)
*a++ ^= *b++;
}
void crypto_xor(u8 *dst, const u8 *src, unsigned int size)
{
u32 *a = (u32 *)dst;
u32 *b = (u32 *)src;
for (; size >= 4; size -= 4)
*a++ ^= *b++;
crypto_xor_byte((u8 *)a, (u8 *)b, size);
}
EXPORT_SYMBOL_GPL(crypto_xor);
static int __init crypto_algapi_init(void)
{
#ifndef CONFIG_CRYPTO_FIPS
crypto_init_proc();
#else
//Moved to testmgr
#endif
return 0;
}
static void __exit crypto_algapi_exit(void)
{
#ifndef CONFIG_CRYPTO_FIPS
crypto_exit_proc();
#else
//Moved to testmgr
#endif
}
module_init(crypto_algapi_init);
module_exit(crypto_algapi_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Cryptographic algorithms API");
| gpl-2.0 |
vivalto/android_kernel_samsung_vivalto3gvn | arch/arm/mach-sc/board-vivalto3g-battery.c | 3 | 19874 | /* arch/arm/mach-sc8825/board-logantd-battery.c
*
* Copyright (C) 2012 Samsung Electronics Co, Ltd.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/kernel.h>
#include <linux/switch.h>
#include <linux/i2c.h>
#include <linux/i2c-gpio.h>
#include <linux/regulator/machine.h>
#include <linux/platform_device.h>
#include <mach/sci_glb_regs.h>
#include <mach/adi.h>
#include <linux/battery/sec_battery.h>
#include <linux/battery/sec_fuelgauge.h>
#include <linux/battery/sec_charger.h>
#include <linux/gpio_event.h>
#include <mach/globalregs.h>
#include <mach/gpio.h>
#include <mach/usb.h>
#include <mach/adc.h>
#include <mach/sci.h>
#include <mach/pinmap.h>
#include <asm/io.h>
#include "board-vivalto3g.h"
#define BATT_DETECT 43
#define SEC_STC3117_I2C_ID 4
#define SEC_STC3117_I2C_SLAVEADDR (0xE0 >> 1)
#define ADC_CHANNEL_TEMP 3
#define STBC_LOW_BATT 59
#define SEC_BATTERY_PMIC_NAME ""
#define USB_DM_GPIO 215
#define USB_DP_GPIO 216
#define TA_ADC_LOW 800
#define TA_ADC_HIGH 2200
/* cable state */
bool is_cable_attached;
unsigned int lpcharge;
unsigned int lp_boot_mode;
EXPORT_SYMBOL(lpcharge);
static struct s3c_adc_client *temp_adc_client;
static sec_bat_adc_table_data_t logantd_temp_table[] = {
{1031 , 650}, /* 65 */
{1178 , 600}, /* 60 */
{1339 , 550}, /* 55 */
{1511 , 500}, /* 50 */
{1658 , 460},/* 46 */
{1892 , 400}, /* 40 */
{2080 , 350}, /* 35 */
{2289 , 300}, /* 30 */
{2484 , 250}, /* 25 */
{2661 , 200}, /* 20 */
{2825 , 150}, /* 15 */
{2990 , 100}, /* 10 */
{3118 , 50}, /* 5 */
{3248 , 0}, /* 0 */
{3364 , -50}, /* -5 */
{3462 , -100}, /* -10 */
{3528 , -150}, /* -15 */
{3587 , -200}, /* -20 */
};
static sec_bat_adc_region_t cable_adc_value_table[] = {
{ 0, 0 }, /* POWER_SUPPLY_TYPE_UNKNOWN */
{ 0, 500 }, /* POWER_SUPPLY_TYPE_BATTERY */
{ 0, 0 }, /* POWER_SUPPLY_TYPE_UPS */
{ 1000, 1500 }, /* POWER_SUPPLY_TYPE_MAINS */
{ 0, 0 }, /* POWER_SUPPLY_TYPE_USB */
{ 0, 0 }, /* POWER_SUPPLY_TYPE_OTG */
{ 0, 0 }, /* POWER_SUPPLY_TYPE_DOCK */
{ 0, 0 }, /* POWER_SUPPLY_TYPE_MISC */
};
static sec_charging_current_t charging_current_table[] = {
{0, 0, 0, 0}, /* POWER_SUPPLY_TYPE_UNKNOWN */
{0, 0, 0, 0}, /* POWER_SUPPLY_TYPE_BATTERY */
{0, 0, 0, 0}, /* POWER_SUPPLY_TYPE_UPS */
{600, 600, 120, 20 * 60}, /* POWER_SUPPLY_TYPE_MAINS */
{450, 450, 120, 20 * 60}, /* POWER_SUPPLY_TYPE_USB */
{450, 450, 120, 20 * 60}, /* POWER_SUPPLY_TYPE_USB_DCP */
{450, 450, 120, 20 * 60}, /* POWER_SUPPLY_TYPE_USB_CDP */
{450, 450, 120, 20 * 60}, /* POWER_SUPPLY_TYPE_USB_ACA */
{550, 500, 120, 20 * 60}, /* POWER_SUPPLY_TYPE_MISC */
{0, 0, 0, 0}, /* POWER_SUPPLY_TYPE_BMS */
{0, 0, 0, 0}, /* POWER_SUPPLY_TYPE_CARDOCK */
{500, 500, 120, 20 * 60}, /* POWER_SUPPLY_TYPE_WPC */
{600, 600, 120, 20 * 60}, /* POWER_SUPPLY_TYPE_UARTOFF */
};
/* unit: seconds */
static int polling_time_table[] = {
10, /* BASIC */
30, /* CHARGING */
30, /* DISCHARGING */
30, /* NOT_CHARGING */
1800, /* SLEEP */
};
static struct power_supply *charger_supply;
extern bool is_jig_on;
int current_cable_type = POWER_SUPPLY_TYPE_BATTERY;
EXPORT_SYMBOL(current_cable_type);
//u8 attached_cable;
static bool sec_bat_gpio_init(void)
{
return true;
}
static bool sec_fg_gpio_init(void)
{
return true;
}
static bool sec_chg_gpio_init(void)
{
return true;
}
/* Get LP charging mode state */
static int battery_get_lpm_state(char *str)
{
get_option(&str, &lpcharge);
pr_info("%s: Low power charging mode: %d\n", __func__, lpcharge);
lp_boot_mode = lpcharge;
return lpcharge;
}
__setup("lpcharge=", battery_get_lpm_state);
static bool sec_bat_is_lpm(void)
{
return lpcharge == 1 ? true : false;
}
static bool sec_bat_check_jig_status(void)
{
return is_jig_on;
}
#if 0
void sec_charger_cb(u8 attached)
{
return 0;
}
#endif
static int sec_bat_check_cable_callback(void)
{
int ta_nconnected;
union power_supply_propval value;
struct power_supply *psy = power_supply_get_by_name("battery");
int ret;
return current_cable_type;
}
#define EIC_KEY_POWER_2 (A_EIC_START + 7)
#define EIC_VCHG_OVI (A_EIC_START + 6)
static void sec_bat_initial_check(void)
{
union power_supply_propval value;
if (POWER_SUPPLY_TYPE_BATTERY < current_cable_type) {
value.intval = current_cable_type;
psy_do_property("battery", set,
POWER_SUPPLY_PROP_ONLINE, value);
} else {
psy_do_property("sec-charger", get,
POWER_SUPPLY_PROP_ONLINE, value);
value.intval =
POWER_SUPPLY_TYPE_BATTERY;
psy_do_property("sec-charger", set,
POWER_SUPPLY_PROP_ONLINE, value);
}
}
static bool sec_bat_check_cable_result_callback(int cable_type)
{
bool ret = true;
current_cable_type = cable_type;
switch (cable_type) {
case POWER_SUPPLY_TYPE_USB:
pr_info("%s set vbus applied\n",
__func__);
break;
case POWER_SUPPLY_TYPE_BATTERY:
pr_info("%s set vbus cut\n",
__func__);
break;
case POWER_SUPPLY_TYPE_MAINS:
break;
default:
pr_err("%s cable type (%d)\n",
__func__, cable_type);
ret = false;
break;
}
/* omap4_tab3_tsp_ta_detect(cable_type); */
return ret;
}
/* callback for battery check
* return : bool
* true - battery detected, false battery NOT detected
*/
static bool sec_bat_check_callback(void) { return true; }
static bool sec_bat_check_result_callback(void) { return true; }
/* callback for OVP/UVLO check
* return : int
* battery health
*/
static int sec_bat_ovp_uvlo_callback(void)
{
int health;
health = POWER_SUPPLY_HEALTH_GOOD;
return health;
}
static bool sec_bat_ovp_uvlo_result_callback(int health) { return true; }
/*
* val.intval : temperature
*/
static bool sec_bat_get_temperature_callback(
enum power_supply_property psp,
union power_supply_propval *val) { return true; }
static bool sec_fg_fuelalert_process(bool is_fuel_alerted) { return true; }
#define CHECK_BATTERY_INTERVAL 358
int battery_updata(void)
{
pr_info("[%s] start\n", __func__);
int ret_val;
static int BatteryCheckCount = 0;
if ((current_cable_type == POWER_SUPPLY_TYPE_USB) ||
(current_cable_type == POWER_SUPPLY_TYPE_MAINS)) {
ret_val = 1;
} else if(BatteryCheckCount > CHECK_BATTERY_INTERVAL) {
ret_val = 1;
} else {
ret_val = 0;
}
return ret_val;
}
int Temperature_fn(void)
{
return (25);
}
#ifdef CONFIG_FUELGAUGE_STC3117
static struct battery_data_t stc3117_battery_data[] = {
{
.Vmode= 0, /*REG_MODE, BIT_VMODE 1=Voltage mode, 0=mixed mode */
.Alm_SOC = 10, /* SOC alm level %*/
.Alm_Vbat = 3600, /* Vbat alm level mV*/
.CC_cnf = 302, /* nominal CC_cnf, coming from battery characterisation*/
.VM_cnf = 408, /* nominal VM cnf , coming from battery characterisation*/
.Rint = 266, /* nominal internal impedance*/
.Cnom = 1500, /* nominal capacity in mAh, coming from battery characterisation*/
.Rsense = 10, /* sense resistor mOhms*/
.RelaxCurrent = 75, /* current for relaxation in mA (< C/20) */
.Adaptive = 1, /* 1=Adaptive mode enabled, 0=Adaptive mode disabled */
/* Elentec Co Ltd Battery pack - 80 means 8% */
.CapDerating[6] = 200, /* capacity derating in 0.1%, for temp = -20C */
.CapDerating[5] = 120, /* capacity derating in 0.1%, for temp = -10C */
.CapDerating[4] = 50, /* capacity derating in 0.1%, for temp = 0C */
.CapDerating[3] = 20, /* capacity derating in 0.1%, for temp = 10C */
.CapDerating[2] = 0, /* capacity derating in 0.1%, for temp = 25C */
.CapDerating[1] = 0, /* capacity derating in 0.1%, for temp = 40C */
.CapDerating[0] = 0, /* capacity derating in 0.1%, for temp = 60C */
.OCVValue[15] = 4306, /* OCV curve adjustment */
.OCVValue[14] = 4190, /* OCV curve adjustment */
.OCVValue[13] = 4090, /* OCV curve adjustment */
.OCVValue[12] = 3981, /* OCV curve adjustment */
.OCVValue[11] = 3957, /* OCV curve adjustment */
.OCVValue[10] = 3917, /* OCV curve adjustment */
.OCVValue[9] = 3830, /* OCV curve adjustment */
.OCVValue[8] = 3796, /* OCV curve adjustment */
.OCVValue[7] = 3772, /* OCV curve adjustment */
.OCVValue[6] = 3762, /* OCV curve adjustment */
.OCVValue[5] = 3745, /* OCV curve adjustment */
.OCVValue[4] = 3712, /* OCV curve adjustment */
.OCVValue[3] = 3687, /* OCV curve adjustment */
.OCVValue[2] = 3679, /* OCV curve adjustment */
.OCVValue[1] = 3629, /* OCV curve adjustment */
.OCVValue[0] = 3300, /* OCV curve adjustment */
/*if the application temperature data is preferred than the STC3117 temperature*/
.ExternalTemperature = Temperature_fn, /*External temperature fonction, return C*/
.ForceExternalTemperature = 0, /* 1=External temperature, 0=STC3117 temperature */
}
};
#endif
#ifdef CONFIG_FUELGAUGE_SPRD2713
static struct battery_data_t sprd2713_battery_data[] = {
{
.vmode = 0, /* 1=Voltage mode, 0=mixed mode */
.alm_soc = 5, /* SOC alm level %*/
.alm_vbat = 3470, /* Vbat alm level mV*/
.rint =250, /*battery internal impedance*/
.cnom = 1500, /* nominal capacity in mAh */
.rsense_real = 202, /* sense resistor 0.1mOhm from real environment*/
.rsense_spec = 200, /* sense resistor 0.1mOhm from specification*/
.relax_current = 50, /* current for relaxation in mA (< C/20) */
.externaltemperature = Temperature_fn, /*External temperature fonction, return C*/
.ocv_table = {
{4330, 100}
,
{4251, 95}
,
{4188, 90}
,
{4131, 85}
,
{4085, 80}
,
{4041, 75}
,
{3997, 70}
,
{3956, 65}
,
{3911, 60}
,
{3861, 55}
,
{3838, 50}
,
{3825, 45}
,
{3810, 40}
,
{3799, 35}
,
{3792, 30}
,
{3783, 25}
,
{3765, 20}
,
{3740, 15}
,
{3670, 10}
,
{3582, 5}
,
{SPRDFGU_BATTERY_SHUTDOWN_VOL, 0}
,
} /* OCV curve adjustment */
}
};
#endif
static void sec_bat_check_vf_callback(void)
{
return;
}
static bool sec_bat_adc_none_init(struct platform_device *pdev) { return true; }
static bool sec_bat_adc_none_exit(void) { return true; }
static int sec_bat_adc_none_read(unsigned int channel) { return 0; }
static bool sec_bat_adc_ap_init(struct platform_device *pdev) { return true; }
static bool sec_bat_adc_ap_exit(void) { return true; }
static int sec_bat_adc_ap_read(unsigned int channel)
{
int data;
int ret = 0;
data = sci_adc_get_value(ADC_CHANNEL_TEMP, false);
return data;
}
static bool sec_bat_adc_ic_init(struct platform_device *pdev) { return true; }
static bool sec_bat_adc_ic_exit(void) { return true; }
static int sec_bat_adc_ic_read(unsigned int channel) { return 0; }
sec_battery_platform_data_t sec_battery_pdata = {
/* NO NEED TO BE CHANGED */
.initial_check = sec_bat_initial_check,
.bat_gpio_init = sec_bat_gpio_init,
.fg_gpio_init = sec_fg_gpio_init,
.chg_gpio_init = sec_chg_gpio_init,
.is_lpm = sec_bat_is_lpm,
.check_jig_status = sec_bat_check_jig_status,
.check_cable_callback =
sec_bat_check_cable_callback,
.check_cable_result_callback =
sec_bat_check_cable_result_callback,
.check_battery_callback =
sec_bat_check_callback,
.check_battery_result_callback =
sec_bat_check_result_callback,
.ovp_uvlo_callback = sec_bat_ovp_uvlo_callback,
.ovp_uvlo_result_callback =
sec_bat_ovp_uvlo_result_callback,
.fuelalert_process = sec_fg_fuelalert_process,
.get_temperature_callback =
sec_bat_get_temperature_callback,
.adc_api[SEC_BATTERY_ADC_TYPE_NONE] = {
.init = sec_bat_adc_none_init,
.exit = sec_bat_adc_none_exit,
.read = sec_bat_adc_none_read
},
.adc_api[SEC_BATTERY_ADC_TYPE_AP] = {
.init = sec_bat_adc_ap_init,
.exit = sec_bat_adc_ap_exit,
.read = sec_bat_adc_ap_read
},
.adc_api[SEC_BATTERY_ADC_TYPE_IC] = {
.init = sec_bat_adc_ic_init,
.exit = sec_bat_adc_ic_exit,
.read = sec_bat_adc_ic_read
},
.cable_adc_value = cable_adc_value_table,
.charging_current = charging_current_table,
.polling_time = polling_time_table,
/* NO NEED TO BE CHANGED */
.pmic_name = SEC_BATTERY_PMIC_NAME,
.adc_check_count = 5,
.adc_type = {
SEC_BATTERY_ADC_TYPE_NONE, /* CABLE_CHECK */
SEC_BATTERY_ADC_TYPE_NONE, /* BAT_CHECK */
SEC_BATTERY_ADC_TYPE_AP, /* TEMP */
SEC_BATTERY_ADC_TYPE_NONE, /* TEMP_AMB */
SEC_BATTERY_ADC_TYPE_NONE, /* FULL_CHECK */
},
/* Battery */
.vendor = "SDI SDI",
.technology = POWER_SUPPLY_TECHNOLOGY_LION,
#ifdef CONFIG_FUELGAUGE_STC3117
.battery_data = (void *)stc3117_battery_data,
#else
.battery_data = (void *)sprd2713_battery_data,
#endif
.bat_polarity_ta_nconnected = 1, /* active HIGH */
.bat_irq_attr = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
.cable_check_type =
SEC_BATTERY_CABLE_CHECK_INT,
.cable_source_type = SEC_BATTERY_CABLE_SOURCE_CALLBACK |
SEC_BATTERY_CABLE_SOURCE_EXTERNAL,
.event_check = false,
.event_waiting_time = 60,
/* Monitor setting */
.polling_type = SEC_BATTERY_MONITOR_WORKQUEUE,
.monitor_initial_count = 3,
/* Battery check */
.battery_check_type = SEC_BATTERY_CHECK_CHARGER,
.check_count = 0,
/* Battery check by ADC */
.check_adc_max = 0,
.check_adc_min = 0,
/* OVP/UVLO check */
.ovp_uvlo_check_type = SEC_BATTERY_OVP_UVLO_CHGPOLLING,
.thermal_source = SEC_BATTERY_THERMAL_SOURCE_ADC,
.temp_check_type = SEC_BATTERY_TEMP_CHECK_TEMP,
.temp_adc_table = logantd_temp_table,
.temp_adc_table_size =
sizeof(logantd_temp_table)/sizeof(sec_bat_adc_table_data_t),
.temp_amb_adc_table = logantd_temp_table,
.temp_amb_adc_table_size =
sizeof(logantd_temp_table)/sizeof(sec_bat_adc_table_data_t),
.temp_check_count = 1,
.temp_high_threshold_event = 600,
.temp_high_recovery_event = 490,
.temp_low_threshold_event = -50,
.temp_low_recovery_event = 20,
.temp_high_threshold_normal = 600,
.temp_high_recovery_normal = 490,
.temp_low_threshold_normal = -50,
.temp_low_recovery_normal = 20,
.temp_high_threshold_lpm = 600,
.temp_high_recovery_lpm = 490,
.temp_low_threshold_lpm = -50,
.temp_low_recovery_lpm = 20,
.full_check_type = SEC_BATTERY_FULLCHARGED_CHGPSY,
.full_check_type_2nd = SEC_BATTERY_FULLCHARGED_TIME,
.full_check_count = 1,
.chg_polarity_full_check = 1,
.full_condition_type = SEC_BATTERY_FULL_CONDITION_NOTIMEFULL |
SEC_BATTERY_FULL_CONDITION_SOC |
SEC_BATTERY_FULL_CONDITION_VCELL,
.full_condition_soc = 95,
.full_condition_vcell = 4300,
.recharge_condition_type =
SEC_BATTERY_RECHARGE_CONDITION_VCELL,
.recharge_condition_soc = 98,
.recharge_condition_avgvcell = 4300,
.recharge_condition_vcell = 4300,
.charging_total_time = 6 * 60 * 60,
.recharging_total_time = 90 * 60,
.charging_reset_time = 0,
/* Fuel Gauge */
.fuelgauge_name = "sec-fuelgauge",
#ifdef CONFIG_FUELGAUGE_STC3117
.fg_irq = STBC_LOW_BATT,
#endif
.fg_irq_attr = IRQF_TRIGGER_FALLING |
IRQF_TRIGGER_RISING,
//.fuel_alert_soc = 1,
.repeated_fuelalert = false,
.capacity_calculation_type =
SEC_FUELGAUGE_CAPACITY_TYPE_RAW,
.capacity_max = 1000,
.capacity_min = 0,
.capacity_max_margin = 0,
/* Charger */
.charger_name = "sec-charger",
.chg_polarity_en = 0, /* active LOW charge enable */
.chg_polarity_status = 0,
//.chg_irq = 0,
.chg_irq_attr = IRQF_NO_SUSPEND | IRQF_ONESHOT,
.chg_float_voltage = 4350,
};
static struct platform_device sec_device_battery = {
.name = "sec-battery",
.id = -1,
.dev = {
.platform_data = &sec_battery_pdata,
},
};
static struct platform_device sec_device_charger = {
.name = "sec-charger",
.id = -1,
.dev = {
.platform_data = &sec_battery_pdata,
},
};
#ifdef CONFIG_FUELGAUGE_SPRD2713
static struct platform_device sec_device_fuelgauge = {
.name = "sec-fuelgauge",
.id = -1,
.dev = {
.platform_data = &sec_battery_pdata,
},
};
#endif
#ifdef CONFIG_FUELGAUGE_STC3117
static struct i2c_board_info sec_brdinfo_stc3115[] __initdata = {
{
I2C_BOARD_INFO("sec-fuelgauge",
SEC_STC3117_I2C_SLAVEADDR),
.platform_data = &sec_battery_pdata,
},
};
#endif
static struct platform_device *sec_battery_devices[] __initdata = {
&sec_device_battery,
&sec_device_charger,
#ifdef CONFIG_FUELGAUGE_SPRD2713
&sec_device_fuelgauge,
#endif
};
void __init sprd_battery_init(void)
{
pr_info("%s: vivalto battery init\n", __func__);
#ifdef CONFIG_FUELGAUGE_STC3117
i2c_register_board_info(SEC_STC3117_I2C_ID, sec_brdinfo_stc3115,
ARRAY_SIZE(sec_brdinfo_stc3115));
#endif
platform_add_devices(sec_battery_devices,
ARRAY_SIZE(sec_battery_devices));
__raw_writel((BITS_PIN_DS(1)|BITS_PIN_AF(3)|BIT_PIN_WPU|BIT_PIN_SLP_WPU|BIT_PIN_SLP_IE), SCI_ADDR(SPRD_PIN_BASE, 0x00D0));
}
#if 0 /* using muic model, disable */
static int charger_is_adapter(void)
{
int ret = 0;
int charger_status;
charger_status = sci_adi_read(ANA_REG_GLB_CHGR_STATUS)
& (BIT_CDP_INT | BIT_DCP_INT | BIT_SDP_INT);
switch (charger_status) {
case BIT_CDP_INT:
ret = 0;
break;
case BIT_DCP_INT:
ret = 1;
break;
case BIT_SDP_INT:
ret = 0;
break;
default:
ret = 0;
break;
}
return ret;
}
static int charger_plugin(int usb_cable, void *data)
{
union power_supply_propval value;
struct power_supply *psy = power_supply_get_by_name("battery");
pr_info("charger plug in interrupt happen[%d]\n", usb_cable);
if (usb_cable || !charger_is_adapter()) {
value.intval = POWER_SUPPLY_TYPE_USB;
} else {
value.intval = POWER_SUPPLY_TYPE_MAINS;
}
current_cable_type = value.intval;
psy->set_property(psy, POWER_SUPPLY_PROP_ONLINE, &value);
return 0;
}
static int charger_plugout(int usb_cable, void *data)
{
union power_supply_propval value;
struct power_supply *psy = power_supply_get_by_name("battery");
value.intval = POWER_SUPPLY_TYPE_BATTERY;
current_cable_type = value.intval;
psy->set_property(psy, POWER_SUPPLY_PROP_ONLINE, &value);
pr_info("charger plug out interrupt happen\n");
return 0;
}
static struct usb_hotplug_callback charger_cb = {
.plugin = charger_plugin,
.plugout = charger_plugout,
.data = NULL,
};
void __init sprd_stbc_init(void)
{
pr_info("[%s] charger callback\n", __func__);
int ret;
ret = usb_register_hotplug_callback(&charger_cb);
}
late_initcall(sprd_stbc_init);
#endif
| gpl-2.0 |
vifm/vifm | src/ipc.c | 3 | 20791 | /* vifm
* Copyright (C) 2011 xaizek.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "ipc.h"
#ifdef ENABLE_REMOTE_CMDS
#if defined(_WIN32) || defined(__CYGWIN__)
/* Named pipes don't work very well on Cygwin neither directly nor indirectly
* (using //./pipe/ paths with POSIX API), so use Win32 API on Cygwin. */
# define WIN32_PIPE_READ
#endif
#ifndef WIN32_PIPE_READ
# include <sys/types.h>
# include <sys/select.h> /* FD_* select() */
#else
# define O_NONBLOCK 0
# include <windows.h>
# ifndef PIPE_REJECT_REMOTE_CLIENTS
# define PIPE_REJECT_REMOTE_CLIENTS 1
# endif
# ifdef KEY_EVENT
# undef KEY_EVENT /* curses also defines a macro with such name. */
# endif
#endif
#include <sys/stat.h> /* mkfifo() stat() */
#include <dirent.h> /* DIR closedir() opendir() readdir() */
#include <fcntl.h>
#include <unistd.h> /* close() open() select() unlink() usleep() */
#include <errno.h> /* EACCES EEXIST EDQUOT ENOSPC ENXIO errno */
#include <stddef.h> /* NULL size_t ssize_t */
#include <stdio.h> /* FILE fclose() fdopen() fread() fwrite() */
#include <stdlib.h> /* free() malloc() snprintf() */
#include <string.h> /* strcmp() strcpy() strlen() */
#include "compat/os.h"
#include "utils/fs.h"
#include "utils/log.h"
#include "utils/macros.h"
#include "utils/path.h"
#include "utils/str.h"
#include "utils/string_array.h"
#include "utils/utils.h"
#include "status.h"
/**
* When IPC is enabled, it exchanges packets between instances which are just
* arrays of strings. Each package looks like this:
*
* "version:{...}" -\
* "from:{name}" --\
* "body:{type}" ---\
* some sort of a header that ends on `body:`
* "string #1" -\
* "string #2" --\
* {...} ---\
* "string #N" ----\
* payload (might be prepended by this unit)
* "\0" -\
* terminator
*
* Or in sequential form:
* "version:{...}\0body:{type}\0string #1\0string #2\0{...}string #N\0\0"
*
* {name} is a name of another instance.
*
* {type} can be:
* - "args" to pass list of arguments, in which case body is prepended with CWD
* unconditionally;
* - "eval" to pass an expression for evaluation in a single line;
* - "eval-result" to communicate result of successful evaluation in a single
* line;
* - "eval-error" to communicate failure of evaluation with no strings.
*
* On version mismatch or unknown field name, packet is discarded which is
* logged.
*/
/* Prefix for names of all pipes to distinguish them from other pipes. */
#define PREFIX "vifm-ipc-"
#ifndef WIN32_PIPE_READ
typedef FILE *read_pipe_t;
#define NULL_READ_PIPE NULL
#else
typedef HANDLE read_pipe_t;
#define NULL_READ_PIPE INVALID_HANDLE_VALUE
#endif
/* Holds list information for add_to_list(). */
typedef struct
{
char **lst; /* List of strings. */
size_t len; /* Number of items. */
const char *ipc_dir; /* Root of IPC objects. */
const ipc_t *ipc; /* Handle to an IPC instance or NULL. */
}
list_data_t;
/* Storage of data of an instance. */
struct ipc_t
{
/* Stores callback to report received messages. */
ipc_args_cb args_cb;
/* Stores callback used for evaluation of expressions. */
ipc_eval_cb eval_cb;
/* Whether this IPC instance should ignore check requests from outside. */
int locked;
/* Path to the pipe used by this instance. */
char pipe_path[PATH_MAX + 1];
/* Opened file of the pipe. */
read_pipe_t pipe_file;
/* Holds result of expression evaluation or NULL on evaluation error. */
char *eval_result;
};
static read_pipe_t create_pipe(const char name[], char path_buf[], size_t len);
static char * receive_pkg(ipc_t *ipc, int *len);
static read_pipe_t try_use_pipe(const char path[], int *fatal);
static void handle_pkg(ipc_t *ipc, const char pkg[], const char *end);
static void handle_args(ipc_t *ipc, char ***array, int len);
static void handle_expr(ipc_t *ipc, const char from[], char *array[], int len);
static void handle_eval_result(ipc_t *ipc, char *array[], int len);
static int format_and_send(ipc_t *ipc, const char whom[], char *data[],
const char type[]);
static int send_pkg(const char whom[], const char what[], size_t len);
static char * get_the_only_target(const ipc_t *ipc);
static char ** list_servers(const ipc_t *ipc, int *len);
static int add_to_list(const char name[], const void *data, void *param);
static const char * get_ipc_dir(void);
static int sorter(const void *first, const void *second);
#ifndef WIN32_PIPE_READ
static int pipe_is_in_use(const char path[]);
#endif
/* Current version string. */
static const char IPC_VERSION[] = "version:1";
/* Request to process remote arguments. */
static const char ARGS_TYPE[] = "args";
/* Request to process remote expression. */
static const char EVAL_TYPE[] = "eval";
/* Reply to remote expression with the result after successful evaluation. */
static const char EVAL_RESULT_TYPE[] = "eval-result";
/* Reply to remote expression on error. */
static const char EVAL_ERROR_TYPE[] = "eval-error";
int
ipc_enabled(void)
{
return 1;
}
ipc_t *
ipc_init(const char name[], ipc_args_cb args_cb, ipc_eval_cb eval_cb)
{
ipc_t *const ipc = malloc(sizeof(*ipc));
if(ipc == NULL)
{
return NULL;
}
ipc->args_cb = args_cb;
ipc->eval_cb = eval_cb;
ipc->locked = 0;
if(name == NULL)
{
name = "vifm";
}
ipc->pipe_file = create_pipe(name, ipc->pipe_path, sizeof(ipc->pipe_path));
if(ipc->pipe_file == NULL_READ_PIPE)
{
free(ipc);
return NULL;
}
return ipc;
}
void
ipc_free(ipc_t *ipc)
{
if(ipc == NULL)
{
return;
}
#ifndef WIN32_PIPE_READ
fclose(ipc->pipe_file);
unlink(ipc->pipe_path);
#else
CloseHandle(ipc->pipe_file);
#endif
free(ipc);
}
const char *
ipc_get_name(const ipc_t *ipc)
{
return get_last_path_component(ipc->pipe_path) + (sizeof(PREFIX) - 1U);
}
int
ipc_check(ipc_t *ipc)
{
int len;
char *pkg;
if(ipc->locked)
{
return 0;
}
pkg = receive_pkg(ipc, &len);
if(pkg != NULL)
{
handle_pkg(ipc, pkg, pkg + len);
free(pkg);
return 1;
}
return 0;
}
/* Receives message addressed to this instance. Returns NULL if there was no
* message or on failure to read it, otherwise newly allocated string is
* returned. */
static char *
receive_pkg(ipc_t *ipc, int *len)
{
#ifndef WIN32_PIPE_READ
uint32_t size;
char *pkg;
char *p;
fd_set ready;
int max_fd;
struct timeval ts = { .tv_sec = 0, .tv_usec = 10000 };
/* At least on OS X pipe might get into EOF state, so reset it. This will
* also reset any errors, which is fine with us. */
clearerr(ipc->pipe_file);
if(fread(&size, sizeof(size), 1U, ipc->pipe_file) != 1U ||
size >= 4294967294U)
{
return NULL;
}
pkg = malloc(size + 1U);
if(pkg == NULL)
{
LOG_ERROR_MSG("Failed to allocate memory: %lu", (unsigned long)(size + 1));
return NULL;
}
max_fd = fileno(ipc->pipe_file);
FD_ZERO(&ready);
FD_SET(max_fd, &ready);
p = pkg;
while(size != 0U && select(max_fd + 1, &ready, NULL, NULL, &ts) > 0)
{
const size_t nread = fread(p, 1U, size, ipc->pipe_file);
size -= nread;
p += nread;
if(nread == 0U)
{
break;
}
ts.tv_sec = 0;
ts.tv_usec = 10000;
}
if(size != 0U)
{
free(pkg);
LOG_ERROR_MSG("Failed to read whole packet, left: %lu",
(unsigned long)size);
return NULL;
}
/* Make sure we have a trailing zero. */
*p = '\0';
*len = p - pkg;
return pkg;
#else
uint32_t size;
char *pkg;
char *p;
DWORD nread;
if(ReadFile(ipc->pipe_file, &size, sizeof(size), &nread, NULL) == FALSE ||
size >= 4294967294U)
{
return NULL;
}
pkg = malloc(size + 1U);
if(pkg == NULL)
{
return NULL;
}
p = pkg;
while(size != 0U)
{
/* TODO: maybe use OVERLAPPED I/O on Windows instead, it's just so
* inconvenient... */
usleep(10000);
if(ReadFile(ipc->pipe_file, p, size, &nread, NULL) == FALSE || nread == 0U)
{
break;
}
size -= nread;
p += nread;
}
/* Weird requirement for named pipes, need to break and set connection every
* time. */
DisconnectNamedPipe(ipc->pipe_file);
ConnectNamedPipe(ipc->pipe_file, NULL);
if(size != 0U)
{
free(pkg);
return NULL;
}
/* Make sure we have a trailing zero. */
*p = '\0';
*len = p - pkg;
return pkg;
#endif
}
/* Tries to open a pipe for communication. Returns NULL_READ_PIPE on error or
* opened file descriptor otherwise. */
static read_pipe_t
create_pipe(const char name[], char path_buf[], size_t len)
{
unsigned int id = 0U;
read_pipe_t rp;
int fatal;
/* Try to use name as is at first. */
snprintf(path_buf, len, "%s/" PREFIX "%s", get_ipc_dir(), name);
rp = try_use_pipe(path_buf, &fatal);
while(rp == NULL_READ_PIPE && !fatal)
{
snprintf(path_buf, len, "%s/" PREFIX "%s%u", get_ipc_dir(), name, ++id);
if(id == 0)
{
return NULL_READ_PIPE;
}
rp = try_use_pipe(path_buf, &fatal);
}
return rp;
}
/* Either creates a pipe or reused previously abandoned one. Returns
* NULL_READ_PIPE on failure (with *fatal set to non-zero if further tries don't
* make any sense) or valid file descriptor otherwise. */
static read_pipe_t
try_use_pipe(const char path[], int *fatal)
{
#ifndef WIN32_PIPE_READ
FILE *f;
int fd;
*fatal = 0;
/* Try to create a pipe. */
if(mkfifo(path, 0600) == 0)
{
/* Open if created. */
const int fd = open(path, O_RDONLY | O_NONBLOCK);
if(fd == -1)
{
if(errno == EACCES)
{
/* If we created a file that we can't open, remove it and assume that
* something is fundamentally wrong with the system setup. */
(void)unlink(path);
*fatal = 1;
}
return NULL_READ_PIPE;
}
return fdopen(fd, "r");
}
/* Fail fast if the error is not related to existence of the file or pipe
* exists and is in use. */
if(errno != EEXIST || pipe_is_in_use(path))
{
/* No retries if file-system is unable to create more files. */
*fatal = (errno == EDQUOT || errno == ENOSPC);
return NULL_READ_PIPE;
}
/* Use this file if we're the only one willing to read from it. */
fd = open(path, O_RDONLY | O_NONBLOCK);
if(fd == -1)
{
return NULL_READ_PIPE;
}
f = fdopen(fd, "r");
if(f == NULL_READ_PIPE)
{
close(fd);
}
return f;
#else
*fatal = 0;
return CreateNamedPipeA(path,
PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_NOWAIT | PIPE_REJECT_REMOTE_CLIENTS,
PIPE_UNLIMITED_INSTANCES, 4096, 4096, 10, NULL);
#endif
}
/* Parses pkg into array of strings and invokes callback. */
static void
handle_pkg(ipc_t *ipc, const char pkg[], const char *end)
{
char **array = NULL;
size_t len = 0U;
int in_body = 0;
const char *type = NULL;
const char *from = NULL;
while(pkg != end)
{
if(in_body)
{
len = add_to_string_array(&array, len, pkg);
}
else if(starts_with_lit(pkg, "version:"))
{
if(strcmp(pkg, IPC_VERSION) != 0)
{
break;
}
}
else if(starts_with_lit(pkg, "from:"))
{
from = after_first(pkg, ':');
}
else if(starts_with_lit(pkg, "body:"))
{
type = after_first(pkg, ':');
in_body = 1;
}
else
{
break;
}
pkg += strlen(pkg) + 1;
}
if(pkg != end)
{
LOG_ERROR_MSG("Discarded remote package due to field: `%s`", pkg);
}
else if(from == NULL)
{
LOG_ERROR_MSG("Discarded remote package due to missing from field");
}
else if(type == NULL)
{
LOG_ERROR_MSG("Discarded remote package due to missing body field");
}
else if(strcmp(type, ARGS_TYPE) == 0)
{
handle_args(ipc, &array, len);
}
else if(strcmp(type, EVAL_TYPE) == 0)
{
handle_expr(ipc, from, array, len);
}
else if(strcmp(type, EVAL_RESULT_TYPE) == 0)
{
handle_eval_result(ipc, array, len);
}
else if(strcmp(type, EVAL_ERROR_TYPE) == 0)
{
ipc->eval_result = NULL;
}
else
{
LOG_ERROR_MSG("Discarded remote package due to unknown type: `%s`", type);
}
free_string_array(array, len);
}
/* Handles received message with arguments. */
static void
handle_args(ipc_t *ipc, char ***array, int len)
{
if(len == 0U)
{
return;
}
if(put_into_string_array(array, len, NULL) == len + 1)
{
ipc->locked = 1;
ipc->args_cb(*array);
ipc->locked = 0;
}
}
/* Handles received message with expression to evaluate. */
static void
handle_expr(ipc_t *ipc, const char from[], char *array[], int len)
{
char *result;
if(len != 1U)
{
LOG_ERROR_MSG("Incorrect number of lines in expr packet: %d", len);
return;
}
ipc->locked = 1;
result = ipc->eval_cb(array[0]);
ipc->locked = 0;
if(result == NULL)
{
char *data[] = { NULL };
if(format_and_send(ipc, from, data, EVAL_ERROR_TYPE) != 0)
{
LOG_ERROR_MSG("Failed to report evaluation failure");
}
}
else
{
char *data[] = { result, NULL };
if(format_and_send(ipc, from, data, EVAL_RESULT_TYPE) != 0)
{
LOG_ERROR_MSG("Failed to report evaluation result");
}
free(result);
}
}
/* Handles answer about successful evaluation of expression. */
static void
handle_eval_result(ipc_t *ipc, char *array[], int len)
{
if(len == 1U)
{
ipc->eval_result = array[0];
array[0] = NULL;
}
}
int
ipc_send(ipc_t *ipc, const char whom[], char *data[])
{
return format_and_send(ipc, whom, data, ARGS_TYPE);
}
char *
ipc_eval(ipc_t *ipc, const char whom[], const char expr[])
{
enum { MAX_USEC = 1000000, MAX_REPEATS = 20 };
int repeats;
char *data[] = { (char *)expr, NULL };
if(format_and_send(ipc, whom, data, EVAL_TYPE) != 0)
{
LOG_ERROR_MSG("Failed to send expression");
return NULL;
}
/* Using sleep is just easier than doing read with timeout due to differences
* between platforms... */
repeats = 0;
while(!ipc_check(ipc))
{
if(++repeats > MAX_REPEATS)
{
LOG_ERROR_MSG("Timed out on waiting for --remote-expr response");
return NULL;
}
usleep(MAX_USEC/MAX_REPEATS);
}
return ipc->eval_result;
}
/* Formats and sends a message of specified type. The data array should be NULL
* terminated. Returns zero on successful send and non-zero otherwise. */
static int
format_and_send(ipc_t *ipc, const char whom[], char *data[], const char type[])
{
/* FIXME: this shouldn't have fixed size. Or maybe it should be PIPE_BUF to
* guarantee atomic operation. */
char pkg[8192];
size_t len;
char *name = NULL;
int ret;
/* Compose "header". */
len = copy_str(pkg, sizeof(pkg), IPC_VERSION);
len += MIN(snprintf(pkg + len, sizeof(pkg) - len, "from:%s",
ipc_get_name(ipc)) + 1,
(int)(sizeof(pkg) - len));
len += MIN(snprintf(pkg + len, sizeof(pkg) - len, "body:%s", type) + 1,
(int)(sizeof(pkg) - len));
if(strcmp(type, ARGS_TYPE) == 0)
{
if(get_cwd(pkg + len, sizeof(pkg) - len) == NULL)
{
LOG_ERROR_MSG("Can't get working directory");
return 1;
}
len += strlen(pkg + len) + 1;
}
while(*data != NULL)
{
len += copy_str(pkg + len, sizeof(pkg) - len, *data);
++data;
}
if(whom == NULL)
{
name = get_the_only_target(ipc);
if(name == NULL)
{
return 1;
}
whom = name;
}
ret = send_pkg(whom, pkg, len);
free(name);
return ret;
}
/* Performs actual sending of package to another instance. Returns zero on
* success and non-zero otherwise. */
static int
send_pkg(const char whom[], const char what[], size_t len)
{
#ifndef WIN32_PIPE_READ
char path[PATH_MAX + 1];
int fd;
FILE *dst;
uint32_t size;
snprintf(path, sizeof(path), "%s/" PREFIX "%s", get_ipc_dir(), whom);
fd = open(path, O_WRONLY);
if(fd == -1)
{
LOG_SERROR_MSG(errno, "Failed to open destination pipe");
return 1;
}
dst = fdopen(fd, "w");
if(dst == NULL)
{
LOG_SERROR_MSG(errno, "Failed to turn file descriptor into a FILE");
close(fd);
return 1;
}
size = len;
if(fwrite(&size, sizeof(size), 1U, dst) != 1U ||
fwrite(what, len, 1U, dst) != 1U)
{
LOG_SERROR_MSG(errno, "Failed to write into a pipe");
(void)fclose(dst);
return 1;
}
if(fclose(dst) != 0)
{
LOG_SERROR_MSG(errno, "Failure on close a pipe");
}
return 0;
#else
char path[PATH_MAX + 1];
HANDLE h;
uint32_t size;
DWORD nwritten;
snprintf(path, sizeof(path), "%s/" PREFIX "%s", get_ipc_dir(), whom);
h = CreateFileA(path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
0, NULL);
if(h == INVALID_HANDLE_VALUE)
{
return 1;
}
size = len;
if(WriteFile(h, &size, sizeof(size), &nwritten, NULL) == FALSE ||
nwritten != sizeof(size) ||
WriteFile(h, what, len, &nwritten, NULL) == FALSE || nwritten != len)
{
CloseHandle(h);
return 1;
}
CloseHandle(h);
return 0;
#endif
}
/* Automatically picks target instance to send data to. Returns newly allocated
* string or NULL on error (no other instances or memory allocation failure). */
static char *
get_the_only_target(const ipc_t *ipc)
{
int len;
char *name;
char **list = list_servers(ipc, &len);
if(len == 0)
{
return NULL;
}
name = list[0];
list[0] = NULL;
free_string_array(list, len);
return name;
}
char **
ipc_list(int *len)
{
return list_servers(NULL, len);
}
/* Retrieves list with names of servers available for IPC excluding the one
* specified by the ipc parameter, which can be NULL. Returns the list which is
* of the *len length. */
static char **
list_servers(const ipc_t *ipc, int *len)
{
list_data_t data = { .ipc_dir = get_ipc_dir(), .ipc = ipc };
#ifndef WIN32_PIPE_READ
if(enum_dir_content(data.ipc_dir, &add_to_list, &data) != 0)
{
*len = 0;
return NULL;
}
#else
{
char find_pat[PATH_MAX + 1];
HANDLE hfind;
WIN32_FIND_DATAA ffd;
snprintf(find_pat, sizeof(find_pat), "%s/*", data.ipc_dir);
hfind = FindFirstFileA(find_pat, &ffd);
if(hfind == INVALID_HANDLE_VALUE)
{
*len = 0;
return NULL;
}
do
{
if(add_to_list(ffd.cFileName, &ffd, &data) != 0)
{
break;
}
}
while(FindNextFileA(hfind, &ffd));
FindClose(hfind);
}
#endif
safe_qsort(data.lst, data.len, sizeof(*data.lst), &sorter);
*len = data.len;
return data.lst;
}
/* Analyzes pipe and adds it to the list of pipes. Returns zero on success or
* non-zero on error. */
static int
add_to_list(const char name[], const void *data, void *param)
{
list_data_t *const list_data = param;
const ipc_t *ipc = list_data->ipc;
if(!starts_with_lit(name, PREFIX))
{
return 0;
}
/* Skip ourself. */
if(ipc != NULL &&
stroscmp(name, get_last_path_component(ipc->pipe_path)) == 0)
{
return 0;
}
/* On Windows it's guaranteed to be a valid pipe. */
#ifndef WIN32_PIPE_READ
{
char path[PATH_MAX + 1];
struct stat statbuf;
snprintf(path, sizeof(path), "%s/%s", list_data->ipc_dir, name);
if(stat(path, &statbuf) != 0 || !S_ISFIFO(statbuf.st_mode) ||
!pipe_is_in_use(path) || os_access(path, R_OK) != 0)
{
return 0;
}
}
#endif
list_data->len = add_to_string_array(&list_data->lst, list_data->len,
name + strlen(PREFIX));
return 0;
}
/* Retrieves directory where FIFO objects are created. Returns the path. */
static const char *
get_ipc_dir(void)
{
#ifndef WIN32_PIPE_READ
return get_tmpdir();
#else
return "//./pipe";
#endif
}
/* Wraps strcmp() for use with qsort(). */
static int
sorter(const void *first, const void *second)
{
const char *const *const a = first;
const char *const *const b = second;
return strcmp(*a, *b);
}
#ifndef WIN32_PIPE_READ
/* Tries to open a pipe to check whether it has any readers or it's
* abandoned. Returns non-zero if somebody is reading from the pipe and zero
* otherwise. */
static int
pipe_is_in_use(const char path[])
{
const int fd = open(path, O_WRONLY | O_NONBLOCK);
if(fd != -1 || errno != ENXIO)
{
if(fd != -1)
{
close(fd);
}
return 1;
}
return 0;
}
#endif
#else
#include <stddef.h> /* NULL */
int
ipc_enabled(void)
{
return 0;
}
char **
ipc_list(int *len)
{
*len = 0;
return NULL;
}
ipc_t *
ipc_init(const char name[], ipc_args_cb args_cb, ipc_eval_cb eval_cb)
{
return NULL;
}
void
ipc_free(ipc_t *ipc)
{
}
const char *
ipc_get_name(const ipc_t *ipc)
{
return "";
}
int
ipc_check(ipc_t *ipc)
{
return 0;
}
int
ipc_send(ipc_t *ipc, const char whom[], char *data[])
{
return 1;
}
char *
ipc_eval(ipc_t *ipc, const char whom[], const char expr[])
{
return NULL;
}
#endif
/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */
/* vim: set cinoptions+=t0 filetype=c : */
| gpl-2.0 |
dragonfax/Xbox360ControllerOsxDriver | WirelessGamingReceiver/WirelessDevice.cpp | 3 | 3354 | /*
MICE Xbox 360 Controller driver for Mac OS X
Copyright (C) 2006-2012 Colin Munro
WirelessDevice.cpp - generic Wireless 360 device driver
This file is part of Xbox360Controller.
Xbox360Controller 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.
Xbox360Controller is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "WirelessDevice.h"
#include "WirelessGamingReceiver.h"
OSDefineMetaClassAndStructors(WirelessDevice, IOService)
#define super IOService
// Initialise wireless device
bool WirelessDevice::init(OSDictionary *dictionary)
{
if (!super::init(dictionary))
return false;
index = -1;
function = NULL;
return true;
}
// Checks if there's any data for us
bool WirelessDevice::IsDataAvailable(void)
{
if (index == -1)
return false;
WirelessGamingReceiver *receiver = OSDynamicCast(WirelessGamingReceiver, getProvider());
if (receiver == NULL)
return false;
return receiver->IsDataQueued(index);
}
// Gets the next item from our buffer
IOMemoryDescriptor* WirelessDevice::NextPacket(void)
{
if (index == -1)
return NULL;
WirelessGamingReceiver *receiver = OSDynamicCast(WirelessGamingReceiver, getProvider());
if (receiver == NULL)
return false;
return receiver->ReadBuffer(index);
}
// Sends a buffer for this controller
void WirelessDevice::SendPacket(const void *data, size_t length)
{
if (index == -1)
return;
WirelessGamingReceiver *receiver = OSDynamicCast(WirelessGamingReceiver, getProvider());
if (receiver == NULL)
return;
receiver->QueueWrite(index, data, length);
}
// Registers a callback function
void WirelessDevice::RegisterWatcher(void *target, WirelessDeviceWatcher function, void *parameter)
{
this->target = target;
this->parameter = parameter;
this->function = function;
if ((function != NULL) && IsDataAvailable())
NewData();
}
// For internal use, sets this instances index on the wireless gaming receiver
void WirelessDevice::SetIndex(int i)
{
index = i;
}
// Called when new data arrives
void WirelessDevice::NewData(void)
{
if (function != NULL)
function(target, this, parameter);
}
// Gets the location ID for this device
OSNumber* WirelessDevice::newLocationIDNumber() const
{
OSNumber *owner;
UInt32 location = 0;
if (index == -1)
return NULL;
WirelessGamingReceiver *receiver = OSDynamicCast(WirelessGamingReceiver, getProvider());
if (receiver == NULL)
return NULL;
owner = receiver->newLocationIDNumber();
if (owner != NULL)
{
location = owner->unsigned32BitValue() + 1 + index;
owner->release();
}
return OSNumber::withNumber(location, 32);
}
| gpl-2.0 |
trastejant/Jarvis | Software/MergearDondeCorresponda/Calidad del aire/controlAmbientalJarvis/alarm.cpp | 3 | 3537 | /*
alarm.cpp - Library for Jarvis alarm.
Created by Crakernano, May 27, 2015. Released into the public domain.
http://www.trastejant.es
*/
#include "Arduino.h"
#include "alarm.h"
alarm::alarm(int LEDpin, int altavozPin){
pinMode(LEDpin, OUTPUT);
pinMode(altavozPin, OUTPUT);
_LEDpin = LEDpin;
_altavozPin = altavozPin;
}
//Alarma Sonora
void alarm::soundAlarm(int t){
analogWrite(_altavozPin,20);
delay(t);
}
void alarm::soundAlarm(int t1, int frecuency){
analogWrite(_altavozPin,frecuency);
delay(t);
}
void alarm::soundAlarm(int t1, int frecuency, int repeat){
for(int i = 1; i< repeat; i++){
analogWrite(_altavozPin,frecuency);
delay(t);
}
}
//Alarma visual
void alarm::ligthAlarm(int t, int d){
digitalWrite(_LEDpin, HIGH);
delay(t);
digitalWrite(_LEDpin, LOW);
delay(d);
}
void alarm::typeAlarm(int type){
/*
0 -> Alarma de incendios
1 -> Alarma de gases explosivos
2 -> Alarma de CO
3 -> Alarma de CO2
4 -> Alarma de humo
5 -> Alarma de temperatura
6 -> Alarma de alimentacion
7 -> Alarma de cambio de modo
8 -> Alarma de modo ahorro
9 -> Alarma de desabilitacion
10 -> Mal funcionamiento de la tarjeta SD
*/
//Tiempos de encedido y apagado de la alarma visual
int fireLight[] = {200,100};
int gasLight[] = {200,100};
int COLight[] = {200,100};
int COOLight[] = {200,100};
int smokeLight[] = {200,100};
int tempLight[] = {200,100};
int vccLight[] = {200,100};
int modeLight[] = {200,100};
int lowEnergyModeLight[] = {200,100};
int disableLight[] = {200,100};
int SDfailLight[] = {200,100};
//Frecuencia de sonido de al alarma acustica
int fireSound = 200;
int gasSound = 200;
int COSound = 200;
int COOSound = 200;
int smokeSound = 200;
int tempSound = 200;
int vccSound = 200;
int modeSound = 200;
int lowEnergyModeSound = 200;
int disableSound = 200;
int SDfailSound = 200;
switch (type) {
case 0: //Alarma de incendios
soundAlarm(fireSound);
ligthAlarm(fireLight[0],fireLight[1]);
break;
case 1: //Alarma de gases explisivos
soundAlarm(gasSound);
ligthAlarm(gasLight[0],gasLight[1]);
break;
case 2: // Alarma de monoxido de carbono
soundAlarm(COSound);
ligthAlarm(COLight[0],COLight[1]);
break;
case 3: // Alarma de dioxido de carbono
soundAlarm(COOSound);
ligthAlarm(COOLight[0],COOLight[1]);
break;
case 4: // Alarma de humo
soundAlarm(smokeSound);
ligthAlarm(smokeLight[0],smokeLight[1]);
break;
case 5: //Alarma de temperatura
soundAlarm(tempSound);
ligthAlarm(tempLight[0],tempLight[1]);
break;
case 6: // Alarma de alimentacion
soundAlarm(vccSound);
ligthAlarm(vccLight[0],vccLight[1]);
break;
case 7: // Alarma de cambio de modo
soundAlarm(modeSound);
ligthAlarm(modeLight[0],modeLight[1]);
break;
case 8: // Alarma de modo LowEnergy
soundAlarm(lowEnergyModeSound);
ligthAlarm(lowEnergyModeLight[0],lowEnergyModeLight[1]);
break;
case 9: // Alarma de
soundAlarm(disableSound);
ligthAlarm(disableLight[0],disableLight[1]);
break;
case 10: // Alarma de desabilitacion de la placa
soundAlarm(SDfailSound);
ligthAlarm(SDfailLight[0],SDfailLight[1]);
break;
default: // your hand is nowhere near the sensor
soundAlarm(300);
break;
}
}
| gpl-2.0 |
aharrison24/XCSoar | src/NMEA/InputLine.cpp | 3 | 1108 | /*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2012 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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 "NMEA/InputLine.hpp"
#include <string.h>
NMEAInputLine::NMEAInputLine(const char* line):
CSVLine(line)
{
const char* asterisk = strchr(line, '*');
if (asterisk != NULL)
end = asterisk;
}
| gpl-2.0 |
ggrekhov/ugene | src/plugins_3rdparty/umuscle/src/muscle/glbalign.cpp | 3 | 3584 | #include "muscle.h"
#include "pwpath.h"
#include "timing.h"
#include "textfile.h"
#include "msa.h"
#include "profile.h"
#if !VER_3_52
#define COMPARE_SIMPLE 0
#if TIMING
TICKS g_ticksDP = 0;
#endif
#if 1
SCORE NWSmall(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path);
SCORE NWDASmall(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path);
SCORE NWDASimple(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path);
SCORE NWDASimple2(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path);
SCORE GlobalAlignSimple(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path);
SCORE GlobalAlignNoDiags(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path)
{
return GlobalAlign(PA, uLengthA, PB, uLengthB, Path);
}
#if COMPARE_SIMPLE
SCORE GlobalAlign(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path)
{
#if TIMING
TICKS t1 = GetClockTicks();
#endif
g_bKeepSimpleDP = true;
PWPath SimplePath;
GlobalAlignSimple(PA, uLengthA, PB, uLengthB, SimplePath);
SCORE Score = NWSmall(PA, uLengthA, PB, uLengthB, Path);
if (!Path.Equal(SimplePath))
{
Log("Simple:\n");
SimplePath.LogMe();
Log("Small:\n");
Path.LogMe();
Quit("Paths differ");
}
#if TIMING
TICKS t2 = GetClockTicks();
g_ticksDP += (t2 - t1);
#endif
return Score;
}
#else // COMPARE_SIMPLE
SCORE GlobalAlign(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path)
{
#if TIMING
TICKS t1 = GetClockTicks();
#endif
SCORE Score = NWSmall(PA, uLengthA, PB, uLengthB, Path);
#if TIMING
TICKS t2 = GetClockTicks();
g_ticksDP += (t2 - t1);
#endif
return Score;
}
#endif
#else // 1
static void AllInserts(PWPath &Path, unsigned uLengthB)
{
Path.Clear();
PWEdge Edge;
Edge.cType = 'I';
Edge.uPrefixLengthA = 0;
for (unsigned uPrefixLengthB = 1; uPrefixLengthB <= uLengthB; ++uPrefixLengthB)
{
Edge.uPrefixLengthB = uPrefixLengthB;
Path.AppendEdge(Edge);
}
}
static void AllDeletes(PWPath &Path, unsigned uLengthA)
{
Path.Clear();
PWEdge Edge;
Edge.cType = 'D';
Edge.uPrefixLengthB = 0;
for (unsigned uPrefixLengthA = 1; uPrefixLengthA <= uLengthA; ++uPrefixLengthA)
{
Edge.uPrefixLengthA = uPrefixLengthA;
Path.AppendEdge(Edge);
}
}
SCORE GlobalAlign(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path)
{
#if TIMING
TICKS t1 = GetClockTicks();
#endif
if (0 == uLengthA)
{
AllInserts(Path, uLengthB);
return 0;
}
else if (0 == uLengthB)
{
AllDeletes(Path, uLengthA);
return 0;
}
SCORE Score = 0;
if (g_bDiags)
Score = GlobalAlignDiags(PA, uLengthA, PB, uLengthB, Path);
else
Score = GlobalAlignNoDiags(PA, uLengthA, PB, uLengthB, Path);
#if TIMING
TICKS t2 = GetClockTicks();
g_ticksDP += (t2 - t1);
#endif
return Score;
}
SCORE GlobalAlignNoDiags(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
unsigned uLengthB, PWPath &Path)
{
if (g_bDimer)
return GlobalAlignDimer(PA, uLengthA, PB, uLengthB, Path);
switch (g_PPScore)
{
case PPSCORE_LE:
return GlobalAlignLE(PA, uLengthA, PB, uLengthB, Path);
case PPSCORE_SP:
case PPSCORE_SV:
return GlobalAlignSP(PA, uLengthA, PB, uLengthB, Path);
case PPSCORE_SPN:
return GlobalAlignSPN(PA, uLengthA, PB, uLengthB, Path);
}
Quit("Invalid PP score (GlobalAlignNoDiags)");
return 0;
}
#endif
#endif // !VER_3_52
| gpl-2.0 |
sensysnetworks/uClinux | glibc/rt/tst-aio6.c | 3 | 2454 | /* Test for timeout handling.
Copyright (C) 2000 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <aio.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
/* We expect to wait for 3 seconds so we have to increase the timeout. */
#define TIMEOUT 10 /* sec */
#define TEST_FUNCTION do_test ()
static int
do_test (void)
{
struct aiocb *arr[1];
struct aiocb cb;
char buf[100];
struct timeval before;
struct timeval after;
struct timespec timeout;
int fd[2];
int result = 0;
if (pipe (fd) != 0)
{
printf ("cannot create pipe: %m\n");
return 1;
}
arr[0] = &cb;
cb.aio_fildes = fd[0];
cb.aio_lio_opcode = LIO_WRITE;
cb.aio_reqprio = 0;
cb.aio_buf = (void *) buf;
cb.aio_nbytes = sizeof (buf) - 1;
cb.aio_offset = 0;
cb.aio_sigevent.sigev_notify = SIGEV_NONE;
/* Try to read from stdin where nothing will be available. */
if (aio_read (arr[0]) < 0)
{
printf ("aio_read failed: %m\n");
return 1;
}
/* Get the current time. */
gettimeofday (&before, NULL);
/* Wait for input which is unsuccess and therefore the function will
time out. */
timeout.tv_sec = 3;
timeout.tv_nsec = 0;
if (aio_suspend ((const struct aiocb *const*) arr, 1, &timeout) != -1)
{
puts ("aio_suspend() didn't return -1");
result = 1;
}
else if (errno != EAGAIN)
{
puts ("error not set to EAGAIN");
result = 1;
}
else
{
gettimeofday (&after, NULL);
if (after.tv_sec < before.tv_sec + 1)
{
puts ("timeout came too early");
result = 1;
}
}
return result;
}
#include "../test-skeleton.c"
| gpl-2.0 |
Puri321/lge-kernel-bssq | fs/cifs/smbencrypt.c | 259 | 8368 | /*
Unix SMB/Netbios implementation.
Version 1.9.
SMB parameters and setup
Copyright (C) Andrew Tridgell 1992-2000
Copyright (C) Luke Kenneth Casson Leighton 1996-2000
Modified by Jeremy Allison 1995.
Copyright (C) Andrew Bartlett <abartlet@samba.org> 2002-2003
Modified by Steve French (sfrench@us.ibm.com) 2002-2003
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/random.h>
#include "cifs_unicode.h"
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifs_debug.h"
#include "cifsproto.h"
#ifndef false
#define false 0
#endif
#ifndef true
#define true 1
#endif
/* following came from the other byteorder.h to avoid include conflicts */
#define CVAL(buf,pos) (((unsigned char *)(buf))[pos])
#define SSVALX(buf,pos,val) (CVAL(buf,pos)=(val)&0xFF,CVAL(buf,pos+1)=(val)>>8)
#define SSVAL(buf,pos,val) SSVALX((buf),(pos),((__u16)(val)))
/* produce a md4 message digest from data of length n bytes */
int
mdfour(unsigned char *md4_hash, unsigned char *link_str, int link_len)
{
int rc;
unsigned int size;
struct crypto_shash *md4;
struct sdesc *sdescmd4;
md4 = crypto_alloc_shash("md4", 0, 0);
if (IS_ERR(md4)) {
rc = PTR_ERR(md4);
cERROR(1, "%s: Crypto md4 allocation error %d\n", __func__, rc);
return rc;
}
size = sizeof(struct shash_desc) + crypto_shash_descsize(md4);
sdescmd4 = kmalloc(size, GFP_KERNEL);
if (!sdescmd4) {
rc = -ENOMEM;
cERROR(1, "%s: Memory allocation failure\n", __func__);
goto mdfour_err;
}
sdescmd4->shash.tfm = md4;
sdescmd4->shash.flags = 0x0;
rc = crypto_shash_init(&sdescmd4->shash);
if (rc) {
cERROR(1, "%s: Could not init md4 shash\n", __func__);
goto mdfour_err;
}
crypto_shash_update(&sdescmd4->shash, link_str, link_len);
rc = crypto_shash_final(&sdescmd4->shash, md4_hash);
mdfour_err:
crypto_free_shash(md4);
kfree(sdescmd4);
return rc;
}
/* Does the des encryption from the NT or LM MD4 hash. */
static void
SMBOWFencrypt(unsigned char passwd[16], const unsigned char *c8,
unsigned char p24[24])
{
unsigned char p21[21];
memset(p21, '\0', 21);
memcpy(p21, passwd, 16);
E_P24(p21, c8, p24);
}
/*
This implements the X/Open SMB password encryption
It takes a password, a 8 byte "crypt key" and puts 24 bytes of
encrypted password into p24 */
/* Note that password must be uppercased and null terminated */
void
SMBencrypt(unsigned char *passwd, const unsigned char *c8, unsigned char *p24)
{
unsigned char p14[15], p21[21];
memset(p21, '\0', 21);
memset(p14, '\0', 14);
strncpy((char *) p14, (char *) passwd, 14);
/* strupper((char *)p14); *//* BB at least uppercase the easy range */
E_P16(p14, p21);
SMBOWFencrypt(p21, c8, p24);
memset(p14, 0, 15);
memset(p21, 0, 21);
}
/* Routines for Windows NT MD4 Hash functions. */
static int
_my_wcslen(__u16 *str)
{
int len = 0;
while (*str++ != 0)
len++;
return len;
}
/*
* Convert a string into an NT UNICODE string.
* Note that regardless of processor type
* this must be in intel (little-endian)
* format.
*/
static int
_my_mbstowcs(__u16 *dst, const unsigned char *src, int len)
{ /* BB not a very good conversion routine - change/fix */
int i;
__u16 val;
for (i = 0; i < len; i++) {
val = *src;
SSVAL(dst, 0, val);
dst++;
src++;
if (val == 0)
break;
}
return i;
}
/*
* Creates the MD4 Hash of the users password in NT UNICODE.
*/
int
E_md4hash(const unsigned char *passwd, unsigned char *p16)
{
int rc;
int len;
__u16 wpwd[129];
/* Password cannot be longer than 128 characters */
if (passwd) {
len = strlen((char *) passwd);
if (len > 128)
len = 128;
/* Password must be converted to NT unicode */
_my_mbstowcs(wpwd, passwd, len);
} else
len = 0;
wpwd[len] = 0; /* Ensure string is null terminated */
/* Calculate length in bytes */
len = _my_wcslen(wpwd) * sizeof(__u16);
rc = mdfour(p16, (unsigned char *) wpwd, len);
memset(wpwd, 0, 129 * 2);
return rc;
}
#if 0 /* currently unused */
/* Does both the NT and LM owfs of a user's password */
static void
nt_lm_owf_gen(char *pwd, unsigned char nt_p16[16], unsigned char p16[16])
{
char passwd[514];
memset(passwd, '\0', 514);
if (strlen(pwd) < 513)
strcpy(passwd, pwd);
else
memcpy(passwd, pwd, 512);
/* Calculate the MD4 hash (NT compatible) of the password */
memset(nt_p16, '\0', 16);
E_md4hash(passwd, nt_p16);
/* Mangle the passwords into Lanman format */
passwd[14] = '\0';
/* strupper(passwd); */
/* Calculate the SMB (lanman) hash functions of the password */
memset(p16, '\0', 16);
E_P16((unsigned char *) passwd, (unsigned char *) p16);
/* clear out local copy of user's password (just being paranoid). */
memset(passwd, '\0', sizeof(passwd));
}
#endif
/* Does the NTLMv2 owfs of a user's password */
#if 0 /* function not needed yet - but will be soon */
static void
ntv2_owf_gen(const unsigned char owf[16], const char *user_n,
const char *domain_n, unsigned char kr_buf[16],
const struct nls_table *nls_codepage)
{
wchar_t *user_u;
wchar_t *dom_u;
int user_l, domain_l;
struct HMACMD5Context ctx;
/* might as well do one alloc to hold both (user_u and dom_u) */
user_u = kmalloc(2048 * sizeof(wchar_t), GFP_KERNEL);
if (user_u == NULL)
return;
dom_u = user_u + 1024;
/* push_ucs2(NULL, user_u, user_n, (user_l+1)*2,
STR_UNICODE|STR_NOALIGN|STR_TERMINATE|STR_UPPER);
push_ucs2(NULL, dom_u, domain_n, (domain_l+1)*2,
STR_UNICODE|STR_NOALIGN|STR_TERMINATE|STR_UPPER); */
/* BB user and domain may need to be uppercased */
user_l = cifs_strtoUCS(user_u, user_n, 511, nls_codepage);
domain_l = cifs_strtoUCS(dom_u, domain_n, 511, nls_codepage);
user_l++; /* trailing null */
domain_l++;
hmac_md5_init_limK_to_64(owf, 16, &ctx);
hmac_md5_update((const unsigned char *) user_u, user_l * 2, &ctx);
hmac_md5_update((const unsigned char *) dom_u, domain_l * 2, &ctx);
hmac_md5_final(kr_buf, &ctx);
kfree(user_u);
}
#endif
/* Does the des encryption from the FIRST 8 BYTES of the NT or LM MD4 hash. */
#if 0 /* currently unused */
static void
NTLMSSPOWFencrypt(unsigned char passwd[8],
unsigned char *ntlmchalresp, unsigned char p24[24])
{
unsigned char p21[21];
memset(p21, '\0', 21);
memcpy(p21, passwd, 8);
memset(p21 + 8, 0xbd, 8);
E_P24(p21, ntlmchalresp, p24);
}
#endif
/* Does the NT MD4 hash then des encryption. */
int
SMBNTencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24)
{
int rc;
unsigned char p21[21];
memset(p21, '\0', 21);
rc = E_md4hash(passwd, p21);
if (rc) {
cFYI(1, "%s Can't generate NT hash, error: %d", __func__, rc);
return rc;
}
SMBOWFencrypt(p21, c8, p24);
return rc;
}
/* Does the md5 encryption from the NT hash for NTLMv2. */
/* These routines will be needed later */
#if 0
static void
SMBOWFencrypt_ntv2(const unsigned char kr[16],
const struct data_blob *srv_chal,
const struct data_blob *cli_chal, unsigned char resp_buf[16])
{
struct HMACMD5Context ctx;
hmac_md5_init_limK_to_64(kr, 16, &ctx);
hmac_md5_update(srv_chal->data, srv_chal->length, &ctx);
hmac_md5_update(cli_chal->data, cli_chal->length, &ctx);
hmac_md5_final(resp_buf, &ctx);
}
static void
SMBsesskeygen_ntv2(const unsigned char kr[16],
const unsigned char *nt_resp, __u8 sess_key[16])
{
struct HMACMD5Context ctx;
hmac_md5_init_limK_to_64(kr, 16, &ctx);
hmac_md5_update(nt_resp, 16, &ctx);
hmac_md5_final((unsigned char *) sess_key, &ctx);
}
static void
SMBsesskeygen_ntv1(const unsigned char kr[16],
const unsigned char *nt_resp, __u8 sess_key[16])
{
mdfour((unsigned char *) sess_key, (unsigned char *) kr, 16);
}
#endif
| gpl-2.0 |
EPDCenterSpain/kernel_odys_genio | net/802/stp.c | 3075 | 2663 | /*
* STP SAP demux
*
* Copyright (c) 2008 Patrick McHardy <kaber@trash.net>
*
* 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 <linux/mutex.h>
#include <linux/skbuff.h>
#include <linux/etherdevice.h>
#include <linux/llc.h>
#include <linux/slab.h>
#include <net/llc.h>
#include <net/llc_pdu.h>
#include <net/stp.h>
/* 01:80:c2:00:00:20 - 01:80:c2:00:00:2F */
#define GARP_ADDR_MIN 0x20
#define GARP_ADDR_MAX 0x2F
#define GARP_ADDR_RANGE (GARP_ADDR_MAX - GARP_ADDR_MIN)
static const struct stp_proto __rcu *garp_protos[GARP_ADDR_RANGE + 1] __read_mostly;
static const struct stp_proto __rcu *stp_proto __read_mostly;
static struct llc_sap *sap __read_mostly;
static unsigned int sap_registered;
static DEFINE_MUTEX(stp_proto_mutex);
/* Called under rcu_read_lock from LLC */
static int stp_pdu_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
const struct ethhdr *eh = eth_hdr(skb);
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
const struct stp_proto *proto;
if (pdu->ssap != LLC_SAP_BSPAN ||
pdu->dsap != LLC_SAP_BSPAN ||
pdu->ctrl_1 != LLC_PDU_TYPE_U)
goto err;
if (eh->h_dest[5] >= GARP_ADDR_MIN && eh->h_dest[5] <= GARP_ADDR_MAX) {
proto = rcu_dereference(garp_protos[eh->h_dest[5] -
GARP_ADDR_MIN]);
if (proto &&
compare_ether_addr(eh->h_dest, proto->group_address))
goto err;
} else
proto = rcu_dereference(stp_proto);
if (!proto)
goto err;
proto->rcv(proto, skb, dev);
return 0;
err:
kfree_skb(skb);
return 0;
}
int stp_proto_register(const struct stp_proto *proto)
{
int err = 0;
mutex_lock(&stp_proto_mutex);
if (sap_registered++ == 0) {
sap = llc_sap_open(LLC_SAP_BSPAN, stp_pdu_rcv);
if (!sap) {
err = -ENOMEM;
goto out;
}
}
if (is_zero_ether_addr(proto->group_address))
rcu_assign_pointer(stp_proto, proto);
else
rcu_assign_pointer(garp_protos[proto->group_address[5] -
GARP_ADDR_MIN], proto);
out:
mutex_unlock(&stp_proto_mutex);
return err;
}
EXPORT_SYMBOL_GPL(stp_proto_register);
void stp_proto_unregister(const struct stp_proto *proto)
{
mutex_lock(&stp_proto_mutex);
if (is_zero_ether_addr(proto->group_address))
rcu_assign_pointer(stp_proto, NULL);
else
rcu_assign_pointer(garp_protos[proto->group_address[5] -
GARP_ADDR_MIN], NULL);
synchronize_rcu();
if (--sap_registered == 0)
llc_sap_put(sap);
mutex_unlock(&stp_proto_mutex);
}
EXPORT_SYMBOL_GPL(stp_proto_unregister);
MODULE_LICENSE("GPL");
| gpl-2.0 |
javelinanddart/android_kernel_htc_pyramid | drivers/gpio/gpio-samsung.c | 4611 | 69663 | /*
* Copyright (c) 2009-2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* Copyright 2008 Openmoko, Inc.
* Copyright 2008 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
* http://armlinux.simtec.co.uk/
*
* SAMSUNG - GPIOlib support
*
* 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 <linux/kernel.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/ioport.h>
#include <linux/of.h>
#include <linux/slab.h>
#include <linux/of_address.h>
#include <asm/irq.h>
#include <mach/hardware.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <mach/regs-gpio.h>
#include <plat/cpu.h>
#include <plat/gpio-core.h>
#include <plat/gpio-cfg.h>
#include <plat/gpio-cfg-helpers.h>
#include <plat/gpio-fns.h>
#include <plat/pm.h>
#ifndef DEBUG_GPIO
#define gpio_dbg(x...) do { } while (0)
#else
#define gpio_dbg(x...) printk(KERN_DEBUG x)
#endif
int samsung_gpio_setpull_updown(struct samsung_gpio_chip *chip,
unsigned int off, samsung_gpio_pull_t pull)
{
void __iomem *reg = chip->base + 0x08;
int shift = off * 2;
u32 pup;
pup = __raw_readl(reg);
pup &= ~(3 << shift);
pup |= pull << shift;
__raw_writel(pup, reg);
return 0;
}
samsung_gpio_pull_t samsung_gpio_getpull_updown(struct samsung_gpio_chip *chip,
unsigned int off)
{
void __iomem *reg = chip->base + 0x08;
int shift = off * 2;
u32 pup = __raw_readl(reg);
pup >>= shift;
pup &= 0x3;
return (__force samsung_gpio_pull_t)pup;
}
int s3c2443_gpio_setpull(struct samsung_gpio_chip *chip,
unsigned int off, samsung_gpio_pull_t pull)
{
switch (pull) {
case S3C_GPIO_PULL_NONE:
pull = 0x01;
break;
case S3C_GPIO_PULL_UP:
pull = 0x00;
break;
case S3C_GPIO_PULL_DOWN:
pull = 0x02;
break;
}
return samsung_gpio_setpull_updown(chip, off, pull);
}
samsung_gpio_pull_t s3c2443_gpio_getpull(struct samsung_gpio_chip *chip,
unsigned int off)
{
samsung_gpio_pull_t pull;
pull = samsung_gpio_getpull_updown(chip, off);
switch (pull) {
case 0x00:
pull = S3C_GPIO_PULL_UP;
break;
case 0x01:
case 0x03:
pull = S3C_GPIO_PULL_NONE;
break;
case 0x02:
pull = S3C_GPIO_PULL_DOWN;
break;
}
return pull;
}
static int s3c24xx_gpio_setpull_1(struct samsung_gpio_chip *chip,
unsigned int off, samsung_gpio_pull_t pull,
samsung_gpio_pull_t updown)
{
void __iomem *reg = chip->base + 0x08;
u32 pup = __raw_readl(reg);
if (pull == updown)
pup &= ~(1 << off);
else if (pull == S3C_GPIO_PULL_NONE)
pup |= (1 << off);
else
return -EINVAL;
__raw_writel(pup, reg);
return 0;
}
static samsung_gpio_pull_t s3c24xx_gpio_getpull_1(struct samsung_gpio_chip *chip,
unsigned int off,
samsung_gpio_pull_t updown)
{
void __iomem *reg = chip->base + 0x08;
u32 pup = __raw_readl(reg);
pup &= (1 << off);
return pup ? S3C_GPIO_PULL_NONE : updown;
}
samsung_gpio_pull_t s3c24xx_gpio_getpull_1up(struct samsung_gpio_chip *chip,
unsigned int off)
{
return s3c24xx_gpio_getpull_1(chip, off, S3C_GPIO_PULL_UP);
}
int s3c24xx_gpio_setpull_1up(struct samsung_gpio_chip *chip,
unsigned int off, samsung_gpio_pull_t pull)
{
return s3c24xx_gpio_setpull_1(chip, off, pull, S3C_GPIO_PULL_UP);
}
samsung_gpio_pull_t s3c24xx_gpio_getpull_1down(struct samsung_gpio_chip *chip,
unsigned int off)
{
return s3c24xx_gpio_getpull_1(chip, off, S3C_GPIO_PULL_DOWN);
}
int s3c24xx_gpio_setpull_1down(struct samsung_gpio_chip *chip,
unsigned int off, samsung_gpio_pull_t pull)
{
return s3c24xx_gpio_setpull_1(chip, off, pull, S3C_GPIO_PULL_DOWN);
}
static int exynos_gpio_setpull(struct samsung_gpio_chip *chip,
unsigned int off, samsung_gpio_pull_t pull)
{
if (pull == S3C_GPIO_PULL_UP)
pull = 3;
return samsung_gpio_setpull_updown(chip, off, pull);
}
static samsung_gpio_pull_t exynos_gpio_getpull(struct samsung_gpio_chip *chip,
unsigned int off)
{
samsung_gpio_pull_t pull;
pull = samsung_gpio_getpull_updown(chip, off);
if (pull == 3)
pull = S3C_GPIO_PULL_UP;
return pull;
}
/*
* samsung_gpio_setcfg_2bit - Samsung 2bit style GPIO configuration.
* @chip: The gpio chip that is being configured.
* @off: The offset for the GPIO being configured.
* @cfg: The configuration value to set.
*
* This helper deal with the GPIO cases where the control register
* has two bits of configuration per gpio, which have the following
* functions:
* 00 = input
* 01 = output
* 1x = special function
*/
static int samsung_gpio_setcfg_2bit(struct samsung_gpio_chip *chip,
unsigned int off, unsigned int cfg)
{
void __iomem *reg = chip->base;
unsigned int shift = off * 2;
u32 con;
if (samsung_gpio_is_cfg_special(cfg)) {
cfg &= 0xf;
if (cfg > 3)
return -EINVAL;
cfg <<= shift;
}
con = __raw_readl(reg);
con &= ~(0x3 << shift);
con |= cfg;
__raw_writel(con, reg);
return 0;
}
/*
* samsung_gpio_getcfg_2bit - Samsung 2bit style GPIO configuration read.
* @chip: The gpio chip that is being configured.
* @off: The offset for the GPIO being configured.
*
* The reverse of samsung_gpio_setcfg_2bit(). Will return a value which
* could be directly passed back to samsung_gpio_setcfg_2bit(), from the
* S3C_GPIO_SPECIAL() macro.
*/
static unsigned int samsung_gpio_getcfg_2bit(struct samsung_gpio_chip *chip,
unsigned int off)
{
u32 con;
con = __raw_readl(chip->base);
con >>= off * 2;
con &= 3;
/* this conversion works for IN and OUT as well as special mode */
return S3C_GPIO_SPECIAL(con);
}
/*
* samsung_gpio_setcfg_4bit - Samsung 4bit single register GPIO config.
* @chip: The gpio chip that is being configured.
* @off: The offset for the GPIO being configured.
* @cfg: The configuration value to set.
*
* This helper deal with the GPIO cases where the control register has 4 bits
* of control per GPIO, generally in the form of:
* 0000 = Input
* 0001 = Output
* others = Special functions (dependent on bank)
*
* Note, since the code to deal with the case where there are two control
* registers instead of one, we do not have a separate set of functions for
* each case.
*/
static int samsung_gpio_setcfg_4bit(struct samsung_gpio_chip *chip,
unsigned int off, unsigned int cfg)
{
void __iomem *reg = chip->base;
unsigned int shift = (off & 7) * 4;
u32 con;
if (off < 8 && chip->chip.ngpio > 8)
reg -= 4;
if (samsung_gpio_is_cfg_special(cfg)) {
cfg &= 0xf;
cfg <<= shift;
}
con = __raw_readl(reg);
con &= ~(0xf << shift);
con |= cfg;
__raw_writel(con, reg);
return 0;
}
/*
* samsung_gpio_getcfg_4bit - Samsung 4bit single register GPIO config read.
* @chip: The gpio chip that is being configured.
* @off: The offset for the GPIO being configured.
*
* The reverse of samsung_gpio_setcfg_4bit(), turning a gpio configuration
* register setting into a value the software can use, such as could be passed
* to samsung_gpio_setcfg_4bit().
*
* @sa samsung_gpio_getcfg_2bit
*/
static unsigned samsung_gpio_getcfg_4bit(struct samsung_gpio_chip *chip,
unsigned int off)
{
void __iomem *reg = chip->base;
unsigned int shift = (off & 7) * 4;
u32 con;
if (off < 8 && chip->chip.ngpio > 8)
reg -= 4;
con = __raw_readl(reg);
con >>= shift;
con &= 0xf;
/* this conversion works for IN and OUT as well as special mode */
return S3C_GPIO_SPECIAL(con);
}
#ifdef CONFIG_PLAT_S3C24XX
/*
* s3c24xx_gpio_setcfg_abank - S3C24XX style GPIO configuration (Bank A)
* @chip: The gpio chip that is being configured.
* @off: The offset for the GPIO being configured.
* @cfg: The configuration value to set.
*
* This helper deal with the GPIO cases where the control register
* has one bit of configuration for the gpio, where setting the bit
* means the pin is in special function mode and unset means output.
*/
static int s3c24xx_gpio_setcfg_abank(struct samsung_gpio_chip *chip,
unsigned int off, unsigned int cfg)
{
void __iomem *reg = chip->base;
unsigned int shift = off;
u32 con;
if (samsung_gpio_is_cfg_special(cfg)) {
cfg &= 0xf;
/* Map output to 0, and SFN2 to 1 */
cfg -= 1;
if (cfg > 1)
return -EINVAL;
cfg <<= shift;
}
con = __raw_readl(reg);
con &= ~(0x1 << shift);
con |= cfg;
__raw_writel(con, reg);
return 0;
}
/*
* s3c24xx_gpio_getcfg_abank - S3C24XX style GPIO configuration read (Bank A)
* @chip: The gpio chip that is being configured.
* @off: The offset for the GPIO being configured.
*
* The reverse of s3c24xx_gpio_setcfg_abank() turning an GPIO into a usable
* GPIO configuration value.
*
* @sa samsung_gpio_getcfg_2bit
* @sa samsung_gpio_getcfg_4bit
*/
static unsigned s3c24xx_gpio_getcfg_abank(struct samsung_gpio_chip *chip,
unsigned int off)
{
u32 con;
con = __raw_readl(chip->base);
con >>= off;
con &= 1;
con++;
return S3C_GPIO_SFN(con);
}
#endif
#if defined(CONFIG_CPU_S5P6440) || defined(CONFIG_CPU_S5P6450)
static int s5p64x0_gpio_setcfg_rbank(struct samsung_gpio_chip *chip,
unsigned int off, unsigned int cfg)
{
void __iomem *reg = chip->base;
unsigned int shift;
u32 con;
switch (off) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
shift = (off & 7) * 4;
reg -= 4;
break;
case 6:
shift = ((off + 1) & 7) * 4;
reg -= 4;
default:
shift = ((off + 1) & 7) * 4;
break;
}
if (samsung_gpio_is_cfg_special(cfg)) {
cfg &= 0xf;
cfg <<= shift;
}
con = __raw_readl(reg);
con &= ~(0xf << shift);
con |= cfg;
__raw_writel(con, reg);
return 0;
}
#endif
static void __init samsung_gpiolib_set_cfg(struct samsung_gpio_cfg *chipcfg,
int nr_chips)
{
for (; nr_chips > 0; nr_chips--, chipcfg++) {
if (!chipcfg->set_config)
chipcfg->set_config = samsung_gpio_setcfg_4bit;
if (!chipcfg->get_config)
chipcfg->get_config = samsung_gpio_getcfg_4bit;
if (!chipcfg->set_pull)
chipcfg->set_pull = samsung_gpio_setpull_updown;
if (!chipcfg->get_pull)
chipcfg->get_pull = samsung_gpio_getpull_updown;
}
}
struct samsung_gpio_cfg s3c24xx_gpiocfg_default = {
.set_config = samsung_gpio_setcfg_2bit,
.get_config = samsung_gpio_getcfg_2bit,
};
#ifdef CONFIG_PLAT_S3C24XX
static struct samsung_gpio_cfg s3c24xx_gpiocfg_banka = {
.set_config = s3c24xx_gpio_setcfg_abank,
.get_config = s3c24xx_gpio_getcfg_abank,
};
#endif
#if defined(CONFIG_ARCH_EXYNOS4) || defined(CONFIG_ARCH_EXYNOS5)
static struct samsung_gpio_cfg exynos_gpio_cfg = {
.set_pull = exynos_gpio_setpull,
.get_pull = exynos_gpio_getpull,
.set_config = samsung_gpio_setcfg_4bit,
.get_config = samsung_gpio_getcfg_4bit,
};
#endif
#if defined(CONFIG_CPU_S5P6440) || defined(CONFIG_CPU_S5P6450)
static struct samsung_gpio_cfg s5p64x0_gpio_cfg_rbank = {
.cfg_eint = 0x3,
.set_config = s5p64x0_gpio_setcfg_rbank,
.get_config = samsung_gpio_getcfg_4bit,
.set_pull = samsung_gpio_setpull_updown,
.get_pull = samsung_gpio_getpull_updown,
};
#endif
static struct samsung_gpio_cfg samsung_gpio_cfgs[] = {
[0] = {
.cfg_eint = 0x0,
},
[1] = {
.cfg_eint = 0x3,
},
[2] = {
.cfg_eint = 0x7,
},
[3] = {
.cfg_eint = 0xF,
},
[4] = {
.cfg_eint = 0x0,
.set_config = samsung_gpio_setcfg_2bit,
.get_config = samsung_gpio_getcfg_2bit,
},
[5] = {
.cfg_eint = 0x2,
.set_config = samsung_gpio_setcfg_2bit,
.get_config = samsung_gpio_getcfg_2bit,
},
[6] = {
.cfg_eint = 0x3,
.set_config = samsung_gpio_setcfg_2bit,
.get_config = samsung_gpio_getcfg_2bit,
},
[7] = {
.set_config = samsung_gpio_setcfg_2bit,
.get_config = samsung_gpio_getcfg_2bit,
},
[8] = {
.set_pull = exynos_gpio_setpull,
.get_pull = exynos_gpio_getpull,
},
[9] = {
.cfg_eint = 0x3,
.set_pull = exynos_gpio_setpull,
.get_pull = exynos_gpio_getpull,
}
};
/*
* Default routines for controlling GPIO, based on the original S3C24XX
* GPIO functions which deal with the case where each gpio bank of the
* chip is as following:
*
* base + 0x00: Control register, 2 bits per gpio
* gpio n: 2 bits starting at (2*n)
* 00 = input, 01 = output, others mean special-function
* base + 0x04: Data register, 1 bit per gpio
* bit n: data bit n
*/
static int samsung_gpiolib_2bit_input(struct gpio_chip *chip, unsigned offset)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
unsigned long flags;
unsigned long con;
samsung_gpio_lock(ourchip, flags);
con = __raw_readl(base + 0x00);
con &= ~(3 << (offset * 2));
__raw_writel(con, base + 0x00);
samsung_gpio_unlock(ourchip, flags);
return 0;
}
static int samsung_gpiolib_2bit_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
unsigned long flags;
unsigned long dat;
unsigned long con;
samsung_gpio_lock(ourchip, flags);
dat = __raw_readl(base + 0x04);
dat &= ~(1 << offset);
if (value)
dat |= 1 << offset;
__raw_writel(dat, base + 0x04);
con = __raw_readl(base + 0x00);
con &= ~(3 << (offset * 2));
con |= 1 << (offset * 2);
__raw_writel(con, base + 0x00);
__raw_writel(dat, base + 0x04);
samsung_gpio_unlock(ourchip, flags);
return 0;
}
/*
* The samsung_gpiolib_4bit routines are to control the gpio banks where
* the gpio configuration register (GPxCON) has 4 bits per GPIO, as the
* following example:
*
* base + 0x00: Control register, 4 bits per gpio
* gpio n: 4 bits starting at (4*n)
* 0000 = input, 0001 = output, others mean special-function
* base + 0x04: Data register, 1 bit per gpio
* bit n: data bit n
*
* Note, since the data register is one bit per gpio and is at base + 0x4
* we can use samsung_gpiolib_get and samsung_gpiolib_set to change the
* state of the output.
*/
static int samsung_gpiolib_4bit_input(struct gpio_chip *chip,
unsigned int offset)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
unsigned long con;
con = __raw_readl(base + GPIOCON_OFF);
con &= ~(0xf << con_4bit_shift(offset));
__raw_writel(con, base + GPIOCON_OFF);
gpio_dbg("%s: %p: CON now %08lx\n", __func__, base, con);
return 0;
}
static int samsung_gpiolib_4bit_output(struct gpio_chip *chip,
unsigned int offset, int value)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
unsigned long con;
unsigned long dat;
con = __raw_readl(base + GPIOCON_OFF);
con &= ~(0xf << con_4bit_shift(offset));
con |= 0x1 << con_4bit_shift(offset);
dat = __raw_readl(base + GPIODAT_OFF);
if (value)
dat |= 1 << offset;
else
dat &= ~(1 << offset);
__raw_writel(dat, base + GPIODAT_OFF);
__raw_writel(con, base + GPIOCON_OFF);
__raw_writel(dat, base + GPIODAT_OFF);
gpio_dbg("%s: %p: CON %08lx, DAT %08lx\n", __func__, base, con, dat);
return 0;
}
/*
* The next set of routines are for the case where the GPIO configuration
* registers are 4 bits per GPIO but there is more than one register (the
* bank has more than 8 GPIOs.
*
* This case is the similar to the 4 bit case, but the registers are as
* follows:
*
* base + 0x00: Control register, 4 bits per gpio (lower 8 GPIOs)
* gpio n: 4 bits starting at (4*n)
* 0000 = input, 0001 = output, others mean special-function
* base + 0x04: Control register, 4 bits per gpio (up to 8 additions GPIOs)
* gpio n: 4 bits starting at (4*n)
* 0000 = input, 0001 = output, others mean special-function
* base + 0x08: Data register, 1 bit per gpio
* bit n: data bit n
*
* To allow us to use the samsung_gpiolib_get and samsung_gpiolib_set
* routines we store the 'base + 0x4' address so that these routines see
* the data register at ourchip->base + 0x04.
*/
static int samsung_gpiolib_4bit2_input(struct gpio_chip *chip,
unsigned int offset)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
void __iomem *regcon = base;
unsigned long con;
if (offset > 7)
offset -= 8;
else
regcon -= 4;
con = __raw_readl(regcon);
con &= ~(0xf << con_4bit_shift(offset));
__raw_writel(con, regcon);
gpio_dbg("%s: %p: CON %08lx\n", __func__, base, con);
return 0;
}
static int samsung_gpiolib_4bit2_output(struct gpio_chip *chip,
unsigned int offset, int value)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
void __iomem *regcon = base;
unsigned long con;
unsigned long dat;
unsigned con_offset = offset;
if (con_offset > 7)
con_offset -= 8;
else
regcon -= 4;
con = __raw_readl(regcon);
con &= ~(0xf << con_4bit_shift(con_offset));
con |= 0x1 << con_4bit_shift(con_offset);
dat = __raw_readl(base + GPIODAT_OFF);
if (value)
dat |= 1 << offset;
else
dat &= ~(1 << offset);
__raw_writel(dat, base + GPIODAT_OFF);
__raw_writel(con, regcon);
__raw_writel(dat, base + GPIODAT_OFF);
gpio_dbg("%s: %p: CON %08lx, DAT %08lx\n", __func__, base, con, dat);
return 0;
}
#ifdef CONFIG_PLAT_S3C24XX
/* The next set of routines are for the case of s3c24xx bank a */
static int s3c24xx_gpiolib_banka_input(struct gpio_chip *chip, unsigned offset)
{
return -EINVAL;
}
static int s3c24xx_gpiolib_banka_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
unsigned long flags;
unsigned long dat;
unsigned long con;
local_irq_save(flags);
con = __raw_readl(base + 0x00);
dat = __raw_readl(base + 0x04);
dat &= ~(1 << offset);
if (value)
dat |= 1 << offset;
__raw_writel(dat, base + 0x04);
con &= ~(1 << offset);
__raw_writel(con, base + 0x00);
__raw_writel(dat, base + 0x04);
local_irq_restore(flags);
return 0;
}
#endif
/* The next set of routines are for the case of s5p64x0 bank r */
static int s5p64x0_gpiolib_rbank_input(struct gpio_chip *chip,
unsigned int offset)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
void __iomem *regcon = base;
unsigned long con;
unsigned long flags;
switch (offset) {
case 6:
offset += 1;
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
regcon -= 4;
break;
default:
offset -= 7;
break;
}
samsung_gpio_lock(ourchip, flags);
con = __raw_readl(regcon);
con &= ~(0xf << con_4bit_shift(offset));
__raw_writel(con, regcon);
samsung_gpio_unlock(ourchip, flags);
return 0;
}
static int s5p64x0_gpiolib_rbank_output(struct gpio_chip *chip,
unsigned int offset, int value)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
void __iomem *regcon = base;
unsigned long con;
unsigned long dat;
unsigned long flags;
unsigned con_offset = offset;
switch (con_offset) {
case 6:
con_offset += 1;
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
regcon -= 4;
break;
default:
con_offset -= 7;
break;
}
samsung_gpio_lock(ourchip, flags);
con = __raw_readl(regcon);
con &= ~(0xf << con_4bit_shift(con_offset));
con |= 0x1 << con_4bit_shift(con_offset);
dat = __raw_readl(base + GPIODAT_OFF);
if (value)
dat |= 1 << offset;
else
dat &= ~(1 << offset);
__raw_writel(con, regcon);
__raw_writel(dat, base + GPIODAT_OFF);
samsung_gpio_unlock(ourchip, flags);
return 0;
}
static void samsung_gpiolib_set(struct gpio_chip *chip,
unsigned offset, int value)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
void __iomem *base = ourchip->base;
unsigned long flags;
unsigned long dat;
samsung_gpio_lock(ourchip, flags);
dat = __raw_readl(base + 0x04);
dat &= ~(1 << offset);
if (value)
dat |= 1 << offset;
__raw_writel(dat, base + 0x04);
samsung_gpio_unlock(ourchip, flags);
}
static int samsung_gpiolib_get(struct gpio_chip *chip, unsigned offset)
{
struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip);
unsigned long val;
val = __raw_readl(ourchip->base + 0x04);
val >>= offset;
val &= 1;
return val;
}
/*
* CONFIG_S3C_GPIO_TRACK enables the tracking of the s3c specific gpios
* for use with the configuration calls, and other parts of the s3c gpiolib
* support code.
*
* Not all s3c support code will need this, as some configurations of cpu
* may only support one or two different configuration options and have an
* easy gpio to samsung_gpio_chip mapping function. If this is the case, then
* the machine support file should provide its own samsung_gpiolib_getchip()
* and any other necessary functions.
*/
#ifdef CONFIG_S3C_GPIO_TRACK
struct samsung_gpio_chip *s3c_gpios[S3C_GPIO_END];
static __init void s3c_gpiolib_track(struct samsung_gpio_chip *chip)
{
unsigned int gpn;
int i;
gpn = chip->chip.base;
for (i = 0; i < chip->chip.ngpio; i++, gpn++) {
BUG_ON(gpn >= ARRAY_SIZE(s3c_gpios));
s3c_gpios[gpn] = chip;
}
}
#endif /* CONFIG_S3C_GPIO_TRACK */
/*
* samsung_gpiolib_add() - add the Samsung gpio_chip.
* @chip: The chip to register
*
* This is a wrapper to gpiochip_add() that takes our specific gpio chip
* information and makes the necessary alterations for the platform and
* notes the information for use with the configuration systems and any
* other parts of the system.
*/
static void __init samsung_gpiolib_add(struct samsung_gpio_chip *chip)
{
struct gpio_chip *gc = &chip->chip;
int ret;
BUG_ON(!chip->base);
BUG_ON(!gc->label);
BUG_ON(!gc->ngpio);
spin_lock_init(&chip->lock);
if (!gc->direction_input)
gc->direction_input = samsung_gpiolib_2bit_input;
if (!gc->direction_output)
gc->direction_output = samsung_gpiolib_2bit_output;
if (!gc->set)
gc->set = samsung_gpiolib_set;
if (!gc->get)
gc->get = samsung_gpiolib_get;
#ifdef CONFIG_PM
if (chip->pm != NULL) {
if (!chip->pm->save || !chip->pm->resume)
printk(KERN_ERR "gpio: %s has missing PM functions\n",
gc->label);
} else
printk(KERN_ERR "gpio: %s has no PM function\n", gc->label);
#endif
/* gpiochip_add() prints own failure message on error. */
ret = gpiochip_add(gc);
if (ret >= 0)
s3c_gpiolib_track(chip);
}
static void __init s3c24xx_gpiolib_add_chips(struct samsung_gpio_chip *chip,
int nr_chips, void __iomem *base)
{
int i;
struct gpio_chip *gc = &chip->chip;
for (i = 0 ; i < nr_chips; i++, chip++) {
/* skip banks not present on SoC */
if (chip->chip.base >= S3C_GPIO_END)
continue;
if (!chip->config)
chip->config = &s3c24xx_gpiocfg_default;
if (!chip->pm)
chip->pm = __gpio_pm(&samsung_gpio_pm_2bit);
if ((base != NULL) && (chip->base == NULL))
chip->base = base + ((i) * 0x10);
if (!gc->direction_input)
gc->direction_input = samsung_gpiolib_2bit_input;
if (!gc->direction_output)
gc->direction_output = samsung_gpiolib_2bit_output;
samsung_gpiolib_add(chip);
}
}
static void __init samsung_gpiolib_add_2bit_chips(struct samsung_gpio_chip *chip,
int nr_chips, void __iomem *base,
unsigned int offset)
{
int i;
for (i = 0 ; i < nr_chips; i++, chip++) {
chip->chip.direction_input = samsung_gpiolib_2bit_input;
chip->chip.direction_output = samsung_gpiolib_2bit_output;
if (!chip->config)
chip->config = &samsung_gpio_cfgs[7];
if (!chip->pm)
chip->pm = __gpio_pm(&samsung_gpio_pm_2bit);
if ((base != NULL) && (chip->base == NULL))
chip->base = base + ((i) * offset);
samsung_gpiolib_add(chip);
}
}
/*
* samsung_gpiolib_add_4bit_chips - 4bit single register GPIO config.
* @chip: The gpio chip that is being configured.
* @nr_chips: The no of chips (gpio ports) for the GPIO being configured.
*
* This helper deal with the GPIO cases where the control register has 4 bits
* of control per GPIO, generally in the form of:
* 0000 = Input
* 0001 = Output
* others = Special functions (dependent on bank)
*
* Note, since the code to deal with the case where there are two control
* registers instead of one, we do not have a separate set of function
* (samsung_gpiolib_add_4bit2_chips)for each case.
*/
static void __init samsung_gpiolib_add_4bit_chips(struct samsung_gpio_chip *chip,
int nr_chips, void __iomem *base)
{
int i;
for (i = 0 ; i < nr_chips; i++, chip++) {
chip->chip.direction_input = samsung_gpiolib_4bit_input;
chip->chip.direction_output = samsung_gpiolib_4bit_output;
if (!chip->config)
chip->config = &samsung_gpio_cfgs[2];
if (!chip->pm)
chip->pm = __gpio_pm(&samsung_gpio_pm_4bit);
if ((base != NULL) && (chip->base == NULL))
chip->base = base + ((i) * 0x20);
samsung_gpiolib_add(chip);
}
}
static void __init samsung_gpiolib_add_4bit2_chips(struct samsung_gpio_chip *chip,
int nr_chips)
{
for (; nr_chips > 0; nr_chips--, chip++) {
chip->chip.direction_input = samsung_gpiolib_4bit2_input;
chip->chip.direction_output = samsung_gpiolib_4bit2_output;
if (!chip->config)
chip->config = &samsung_gpio_cfgs[2];
if (!chip->pm)
chip->pm = __gpio_pm(&samsung_gpio_pm_4bit);
samsung_gpiolib_add(chip);
}
}
static void __init s5p64x0_gpiolib_add_rbank(struct samsung_gpio_chip *chip,
int nr_chips)
{
for (; nr_chips > 0; nr_chips--, chip++) {
chip->chip.direction_input = s5p64x0_gpiolib_rbank_input;
chip->chip.direction_output = s5p64x0_gpiolib_rbank_output;
if (!chip->pm)
chip->pm = __gpio_pm(&samsung_gpio_pm_4bit);
samsung_gpiolib_add(chip);
}
}
int samsung_gpiolib_to_irq(struct gpio_chip *chip, unsigned int offset)
{
struct samsung_gpio_chip *samsung_chip = container_of(chip, struct samsung_gpio_chip, chip);
return samsung_chip->irq_base + offset;
}
#ifdef CONFIG_PLAT_S3C24XX
static int s3c24xx_gpiolib_fbank_to_irq(struct gpio_chip *chip, unsigned offset)
{
if (offset < 4)
return IRQ_EINT0 + offset;
if (offset < 8)
return IRQ_EINT4 + offset - 4;
return -EINVAL;
}
#endif
#ifdef CONFIG_PLAT_S3C64XX
static int s3c64xx_gpiolib_mbank_to_irq(struct gpio_chip *chip, unsigned pin)
{
return pin < 5 ? IRQ_EINT(23) + pin : -ENXIO;
}
static int s3c64xx_gpiolib_lbank_to_irq(struct gpio_chip *chip, unsigned pin)
{
return pin >= 8 ? IRQ_EINT(16) + pin - 8 : -ENXIO;
}
#endif
struct samsung_gpio_chip s3c24xx_gpios[] = {
#ifdef CONFIG_PLAT_S3C24XX
{
.config = &s3c24xx_gpiocfg_banka,
.chip = {
.base = S3C2410_GPA(0),
.owner = THIS_MODULE,
.label = "GPIOA",
.ngpio = 24,
.direction_input = s3c24xx_gpiolib_banka_input,
.direction_output = s3c24xx_gpiolib_banka_output,
},
}, {
.chip = {
.base = S3C2410_GPB(0),
.owner = THIS_MODULE,
.label = "GPIOB",
.ngpio = 16,
},
}, {
.chip = {
.base = S3C2410_GPC(0),
.owner = THIS_MODULE,
.label = "GPIOC",
.ngpio = 16,
},
}, {
.chip = {
.base = S3C2410_GPD(0),
.owner = THIS_MODULE,
.label = "GPIOD",
.ngpio = 16,
},
}, {
.chip = {
.base = S3C2410_GPE(0),
.label = "GPIOE",
.owner = THIS_MODULE,
.ngpio = 16,
},
}, {
.chip = {
.base = S3C2410_GPF(0),
.owner = THIS_MODULE,
.label = "GPIOF",
.ngpio = 8,
.to_irq = s3c24xx_gpiolib_fbank_to_irq,
},
}, {
.irq_base = IRQ_EINT8,
.chip = {
.base = S3C2410_GPG(0),
.owner = THIS_MODULE,
.label = "GPIOG",
.ngpio = 16,
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.chip = {
.base = S3C2410_GPH(0),
.owner = THIS_MODULE,
.label = "GPIOH",
.ngpio = 11,
},
},
/* GPIOS for the S3C2443 and later devices. */
{
.base = S3C2440_GPJCON,
.chip = {
.base = S3C2410_GPJ(0),
.owner = THIS_MODULE,
.label = "GPIOJ",
.ngpio = 16,
},
}, {
.base = S3C2443_GPKCON,
.chip = {
.base = S3C2410_GPK(0),
.owner = THIS_MODULE,
.label = "GPIOK",
.ngpio = 16,
},
}, {
.base = S3C2443_GPLCON,
.chip = {
.base = S3C2410_GPL(0),
.owner = THIS_MODULE,
.label = "GPIOL",
.ngpio = 15,
},
}, {
.base = S3C2443_GPMCON,
.chip = {
.base = S3C2410_GPM(0),
.owner = THIS_MODULE,
.label = "GPIOM",
.ngpio = 2,
},
},
#endif
};
/*
* GPIO bank summary:
*
* Bank GPIOs Style SlpCon ExtInt Group
* A 8 4Bit Yes 1
* B 7 4Bit Yes 1
* C 8 4Bit Yes 2
* D 5 4Bit Yes 3
* E 5 4Bit Yes None
* F 16 2Bit Yes 4 [1]
* G 7 4Bit Yes 5
* H 10 4Bit[2] Yes 6
* I 16 2Bit Yes None
* J 12 2Bit Yes None
* K 16 4Bit[2] No None
* L 15 4Bit[2] No None
* M 6 4Bit No IRQ_EINT
* N 16 2Bit No IRQ_EINT
* O 16 2Bit Yes 7
* P 15 2Bit Yes 8
* Q 9 2Bit Yes 9
*
* [1] BANKF pins 14,15 do not form part of the external interrupt sources
* [2] BANK has two control registers, GPxCON0 and GPxCON1
*/
static struct samsung_gpio_chip s3c64xx_gpios_4bit[] = {
#ifdef CONFIG_PLAT_S3C64XX
{
.chip = {
.base = S3C64XX_GPA(0),
.ngpio = S3C64XX_GPIO_A_NR,
.label = "GPA",
},
}, {
.chip = {
.base = S3C64XX_GPB(0),
.ngpio = S3C64XX_GPIO_B_NR,
.label = "GPB",
},
}, {
.chip = {
.base = S3C64XX_GPC(0),
.ngpio = S3C64XX_GPIO_C_NR,
.label = "GPC",
},
}, {
.chip = {
.base = S3C64XX_GPD(0),
.ngpio = S3C64XX_GPIO_D_NR,
.label = "GPD",
},
}, {
.config = &samsung_gpio_cfgs[0],
.chip = {
.base = S3C64XX_GPE(0),
.ngpio = S3C64XX_GPIO_E_NR,
.label = "GPE",
},
}, {
.base = S3C64XX_GPG_BASE,
.chip = {
.base = S3C64XX_GPG(0),
.ngpio = S3C64XX_GPIO_G_NR,
.label = "GPG",
},
}, {
.base = S3C64XX_GPM_BASE,
.config = &samsung_gpio_cfgs[1],
.chip = {
.base = S3C64XX_GPM(0),
.ngpio = S3C64XX_GPIO_M_NR,
.label = "GPM",
.to_irq = s3c64xx_gpiolib_mbank_to_irq,
},
},
#endif
};
static struct samsung_gpio_chip s3c64xx_gpios_4bit2[] = {
#ifdef CONFIG_PLAT_S3C64XX
{
.base = S3C64XX_GPH_BASE + 0x4,
.chip = {
.base = S3C64XX_GPH(0),
.ngpio = S3C64XX_GPIO_H_NR,
.label = "GPH",
},
}, {
.base = S3C64XX_GPK_BASE + 0x4,
.config = &samsung_gpio_cfgs[0],
.chip = {
.base = S3C64XX_GPK(0),
.ngpio = S3C64XX_GPIO_K_NR,
.label = "GPK",
},
}, {
.base = S3C64XX_GPL_BASE + 0x4,
.config = &samsung_gpio_cfgs[1],
.chip = {
.base = S3C64XX_GPL(0),
.ngpio = S3C64XX_GPIO_L_NR,
.label = "GPL",
.to_irq = s3c64xx_gpiolib_lbank_to_irq,
},
},
#endif
};
static struct samsung_gpio_chip s3c64xx_gpios_2bit[] = {
#ifdef CONFIG_PLAT_S3C64XX
{
.base = S3C64XX_GPF_BASE,
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S3C64XX_GPF(0),
.ngpio = S3C64XX_GPIO_F_NR,
.label = "GPF",
},
}, {
.config = &samsung_gpio_cfgs[7],
.chip = {
.base = S3C64XX_GPI(0),
.ngpio = S3C64XX_GPIO_I_NR,
.label = "GPI",
},
}, {
.config = &samsung_gpio_cfgs[7],
.chip = {
.base = S3C64XX_GPJ(0),
.ngpio = S3C64XX_GPIO_J_NR,
.label = "GPJ",
},
}, {
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S3C64XX_GPO(0),
.ngpio = S3C64XX_GPIO_O_NR,
.label = "GPO",
},
}, {
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S3C64XX_GPP(0),
.ngpio = S3C64XX_GPIO_P_NR,
.label = "GPP",
},
}, {
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S3C64XX_GPQ(0),
.ngpio = S3C64XX_GPIO_Q_NR,
.label = "GPQ",
},
}, {
.base = S3C64XX_GPN_BASE,
.irq_base = IRQ_EINT(0),
.config = &samsung_gpio_cfgs[5],
.chip = {
.base = S3C64XX_GPN(0),
.ngpio = S3C64XX_GPIO_N_NR,
.label = "GPN",
.to_irq = samsung_gpiolib_to_irq,
},
},
#endif
};
/*
* S5P6440 GPIO bank summary:
*
* Bank GPIOs Style SlpCon ExtInt Group
* A 6 4Bit Yes 1
* B 7 4Bit Yes 1
* C 8 4Bit Yes 2
* F 2 2Bit Yes 4 [1]
* G 7 4Bit Yes 5
* H 10 4Bit[2] Yes 6
* I 16 2Bit Yes None
* J 12 2Bit Yes None
* N 16 2Bit No IRQ_EINT
* P 8 2Bit Yes 8
* R 15 4Bit[2] Yes 8
*/
static struct samsung_gpio_chip s5p6440_gpios_4bit[] = {
#ifdef CONFIG_CPU_S5P6440
{
.chip = {
.base = S5P6440_GPA(0),
.ngpio = S5P6440_GPIO_A_NR,
.label = "GPA",
},
}, {
.chip = {
.base = S5P6440_GPB(0),
.ngpio = S5P6440_GPIO_B_NR,
.label = "GPB",
},
}, {
.chip = {
.base = S5P6440_GPC(0),
.ngpio = S5P6440_GPIO_C_NR,
.label = "GPC",
},
}, {
.base = S5P64X0_GPG_BASE,
.chip = {
.base = S5P6440_GPG(0),
.ngpio = S5P6440_GPIO_G_NR,
.label = "GPG",
},
},
#endif
};
static struct samsung_gpio_chip s5p6440_gpios_4bit2[] = {
#ifdef CONFIG_CPU_S5P6440
{
.base = S5P64X0_GPH_BASE + 0x4,
.chip = {
.base = S5P6440_GPH(0),
.ngpio = S5P6440_GPIO_H_NR,
.label = "GPH",
},
},
#endif
};
static struct samsung_gpio_chip s5p6440_gpios_rbank[] = {
#ifdef CONFIG_CPU_S5P6440
{
.base = S5P64X0_GPR_BASE + 0x4,
.config = &s5p64x0_gpio_cfg_rbank,
.chip = {
.base = S5P6440_GPR(0),
.ngpio = S5P6440_GPIO_R_NR,
.label = "GPR",
},
},
#endif
};
static struct samsung_gpio_chip s5p6440_gpios_2bit[] = {
#ifdef CONFIG_CPU_S5P6440
{
.base = S5P64X0_GPF_BASE,
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S5P6440_GPF(0),
.ngpio = S5P6440_GPIO_F_NR,
.label = "GPF",
},
}, {
.base = S5P64X0_GPI_BASE,
.config = &samsung_gpio_cfgs[4],
.chip = {
.base = S5P6440_GPI(0),
.ngpio = S5P6440_GPIO_I_NR,
.label = "GPI",
},
}, {
.base = S5P64X0_GPJ_BASE,
.config = &samsung_gpio_cfgs[4],
.chip = {
.base = S5P6440_GPJ(0),
.ngpio = S5P6440_GPIO_J_NR,
.label = "GPJ",
},
}, {
.base = S5P64X0_GPN_BASE,
.config = &samsung_gpio_cfgs[5],
.chip = {
.base = S5P6440_GPN(0),
.ngpio = S5P6440_GPIO_N_NR,
.label = "GPN",
},
}, {
.base = S5P64X0_GPP_BASE,
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S5P6440_GPP(0),
.ngpio = S5P6440_GPIO_P_NR,
.label = "GPP",
},
},
#endif
};
/*
* S5P6450 GPIO bank summary:
*
* Bank GPIOs Style SlpCon ExtInt Group
* A 6 4Bit Yes 1
* B 7 4Bit Yes 1
* C 8 4Bit Yes 2
* D 8 4Bit Yes None
* F 2 2Bit Yes None
* G 14 4Bit[2] Yes 5
* H 10 4Bit[2] Yes 6
* I 16 2Bit Yes None
* J 12 2Bit Yes None
* K 5 4Bit Yes None
* N 16 2Bit No IRQ_EINT
* P 11 2Bit Yes 8
* Q 14 2Bit Yes None
* R 15 4Bit[2] Yes None
* S 8 2Bit Yes None
*
* [1] BANKF pins 14,15 do not form part of the external interrupt sources
* [2] BANK has two control registers, GPxCON0 and GPxCON1
*/
static struct samsung_gpio_chip s5p6450_gpios_4bit[] = {
#ifdef CONFIG_CPU_S5P6450
{
.chip = {
.base = S5P6450_GPA(0),
.ngpio = S5P6450_GPIO_A_NR,
.label = "GPA",
},
}, {
.chip = {
.base = S5P6450_GPB(0),
.ngpio = S5P6450_GPIO_B_NR,
.label = "GPB",
},
}, {
.chip = {
.base = S5P6450_GPC(0),
.ngpio = S5P6450_GPIO_C_NR,
.label = "GPC",
},
}, {
.chip = {
.base = S5P6450_GPD(0),
.ngpio = S5P6450_GPIO_D_NR,
.label = "GPD",
},
}, {
.base = S5P6450_GPK_BASE,
.chip = {
.base = S5P6450_GPK(0),
.ngpio = S5P6450_GPIO_K_NR,
.label = "GPK",
},
},
#endif
};
static struct samsung_gpio_chip s5p6450_gpios_4bit2[] = {
#ifdef CONFIG_CPU_S5P6450
{
.base = S5P64X0_GPG_BASE + 0x4,
.chip = {
.base = S5P6450_GPG(0),
.ngpio = S5P6450_GPIO_G_NR,
.label = "GPG",
},
}, {
.base = S5P64X0_GPH_BASE + 0x4,
.chip = {
.base = S5P6450_GPH(0),
.ngpio = S5P6450_GPIO_H_NR,
.label = "GPH",
},
},
#endif
};
static struct samsung_gpio_chip s5p6450_gpios_rbank[] = {
#ifdef CONFIG_CPU_S5P6450
{
.base = S5P64X0_GPR_BASE + 0x4,
.config = &s5p64x0_gpio_cfg_rbank,
.chip = {
.base = S5P6450_GPR(0),
.ngpio = S5P6450_GPIO_R_NR,
.label = "GPR",
},
},
#endif
};
static struct samsung_gpio_chip s5p6450_gpios_2bit[] = {
#ifdef CONFIG_CPU_S5P6450
{
.base = S5P64X0_GPF_BASE,
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S5P6450_GPF(0),
.ngpio = S5P6450_GPIO_F_NR,
.label = "GPF",
},
}, {
.base = S5P64X0_GPI_BASE,
.config = &samsung_gpio_cfgs[4],
.chip = {
.base = S5P6450_GPI(0),
.ngpio = S5P6450_GPIO_I_NR,
.label = "GPI",
},
}, {
.base = S5P64X0_GPJ_BASE,
.config = &samsung_gpio_cfgs[4],
.chip = {
.base = S5P6450_GPJ(0),
.ngpio = S5P6450_GPIO_J_NR,
.label = "GPJ",
},
}, {
.base = S5P64X0_GPN_BASE,
.config = &samsung_gpio_cfgs[5],
.chip = {
.base = S5P6450_GPN(0),
.ngpio = S5P6450_GPIO_N_NR,
.label = "GPN",
},
}, {
.base = S5P64X0_GPP_BASE,
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S5P6450_GPP(0),
.ngpio = S5P6450_GPIO_P_NR,
.label = "GPP",
},
}, {
.base = S5P6450_GPQ_BASE,
.config = &samsung_gpio_cfgs[5],
.chip = {
.base = S5P6450_GPQ(0),
.ngpio = S5P6450_GPIO_Q_NR,
.label = "GPQ",
},
}, {
.base = S5P6450_GPS_BASE,
.config = &samsung_gpio_cfgs[6],
.chip = {
.base = S5P6450_GPS(0),
.ngpio = S5P6450_GPIO_S_NR,
.label = "GPS",
},
},
#endif
};
/*
* S5PC100 GPIO bank summary:
*
* Bank GPIOs Style INT Type
* A0 8 4Bit GPIO_INT0
* A1 5 4Bit GPIO_INT1
* B 8 4Bit GPIO_INT2
* C 5 4Bit GPIO_INT3
* D 7 4Bit GPIO_INT4
* E0 8 4Bit GPIO_INT5
* E1 6 4Bit GPIO_INT6
* F0 8 4Bit GPIO_INT7
* F1 8 4Bit GPIO_INT8
* F2 8 4Bit GPIO_INT9
* F3 4 4Bit GPIO_INT10
* G0 8 4Bit GPIO_INT11
* G1 3 4Bit GPIO_INT12
* G2 7 4Bit GPIO_INT13
* G3 7 4Bit GPIO_INT14
* H0 8 4Bit WKUP_INT
* H1 8 4Bit WKUP_INT
* H2 8 4Bit WKUP_INT
* H3 8 4Bit WKUP_INT
* I 8 4Bit GPIO_INT15
* J0 8 4Bit GPIO_INT16
* J1 5 4Bit GPIO_INT17
* J2 8 4Bit GPIO_INT18
* J3 8 4Bit GPIO_INT19
* J4 4 4Bit GPIO_INT20
* K0 8 4Bit None
* K1 6 4Bit None
* K2 8 4Bit None
* K3 8 4Bit None
* L0 8 4Bit None
* L1 8 4Bit None
* L2 8 4Bit None
* L3 8 4Bit None
*/
static struct samsung_gpio_chip s5pc100_gpios_4bit[] = {
#ifdef CONFIG_CPU_S5PC100
{
.chip = {
.base = S5PC100_GPA0(0),
.ngpio = S5PC100_GPIO_A0_NR,
.label = "GPA0",
},
}, {
.chip = {
.base = S5PC100_GPA1(0),
.ngpio = S5PC100_GPIO_A1_NR,
.label = "GPA1",
},
}, {
.chip = {
.base = S5PC100_GPB(0),
.ngpio = S5PC100_GPIO_B_NR,
.label = "GPB",
},
}, {
.chip = {
.base = S5PC100_GPC(0),
.ngpio = S5PC100_GPIO_C_NR,
.label = "GPC",
},
}, {
.chip = {
.base = S5PC100_GPD(0),
.ngpio = S5PC100_GPIO_D_NR,
.label = "GPD",
},
}, {
.chip = {
.base = S5PC100_GPE0(0),
.ngpio = S5PC100_GPIO_E0_NR,
.label = "GPE0",
},
}, {
.chip = {
.base = S5PC100_GPE1(0),
.ngpio = S5PC100_GPIO_E1_NR,
.label = "GPE1",
},
}, {
.chip = {
.base = S5PC100_GPF0(0),
.ngpio = S5PC100_GPIO_F0_NR,
.label = "GPF0",
},
}, {
.chip = {
.base = S5PC100_GPF1(0),
.ngpio = S5PC100_GPIO_F1_NR,
.label = "GPF1",
},
}, {
.chip = {
.base = S5PC100_GPF2(0),
.ngpio = S5PC100_GPIO_F2_NR,
.label = "GPF2",
},
}, {
.chip = {
.base = S5PC100_GPF3(0),
.ngpio = S5PC100_GPIO_F3_NR,
.label = "GPF3",
},
}, {
.chip = {
.base = S5PC100_GPG0(0),
.ngpio = S5PC100_GPIO_G0_NR,
.label = "GPG0",
},
}, {
.chip = {
.base = S5PC100_GPG1(0),
.ngpio = S5PC100_GPIO_G1_NR,
.label = "GPG1",
},
}, {
.chip = {
.base = S5PC100_GPG2(0),
.ngpio = S5PC100_GPIO_G2_NR,
.label = "GPG2",
},
}, {
.chip = {
.base = S5PC100_GPG3(0),
.ngpio = S5PC100_GPIO_G3_NR,
.label = "GPG3",
},
}, {
.chip = {
.base = S5PC100_GPI(0),
.ngpio = S5PC100_GPIO_I_NR,
.label = "GPI",
},
}, {
.chip = {
.base = S5PC100_GPJ0(0),
.ngpio = S5PC100_GPIO_J0_NR,
.label = "GPJ0",
},
}, {
.chip = {
.base = S5PC100_GPJ1(0),
.ngpio = S5PC100_GPIO_J1_NR,
.label = "GPJ1",
},
}, {
.chip = {
.base = S5PC100_GPJ2(0),
.ngpio = S5PC100_GPIO_J2_NR,
.label = "GPJ2",
},
}, {
.chip = {
.base = S5PC100_GPJ3(0),
.ngpio = S5PC100_GPIO_J3_NR,
.label = "GPJ3",
},
}, {
.chip = {
.base = S5PC100_GPJ4(0),
.ngpio = S5PC100_GPIO_J4_NR,
.label = "GPJ4",
},
}, {
.chip = {
.base = S5PC100_GPK0(0),
.ngpio = S5PC100_GPIO_K0_NR,
.label = "GPK0",
},
}, {
.chip = {
.base = S5PC100_GPK1(0),
.ngpio = S5PC100_GPIO_K1_NR,
.label = "GPK1",
},
}, {
.chip = {
.base = S5PC100_GPK2(0),
.ngpio = S5PC100_GPIO_K2_NR,
.label = "GPK2",
},
}, {
.chip = {
.base = S5PC100_GPK3(0),
.ngpio = S5PC100_GPIO_K3_NR,
.label = "GPK3",
},
}, {
.chip = {
.base = S5PC100_GPL0(0),
.ngpio = S5PC100_GPIO_L0_NR,
.label = "GPL0",
},
}, {
.chip = {
.base = S5PC100_GPL1(0),
.ngpio = S5PC100_GPIO_L1_NR,
.label = "GPL1",
},
}, {
.chip = {
.base = S5PC100_GPL2(0),
.ngpio = S5PC100_GPIO_L2_NR,
.label = "GPL2",
},
}, {
.chip = {
.base = S5PC100_GPL3(0),
.ngpio = S5PC100_GPIO_L3_NR,
.label = "GPL3",
},
}, {
.chip = {
.base = S5PC100_GPL4(0),
.ngpio = S5PC100_GPIO_L4_NR,
.label = "GPL4",
},
}, {
.base = (S5P_VA_GPIO + 0xC00),
.irq_base = IRQ_EINT(0),
.chip = {
.base = S5PC100_GPH0(0),
.ngpio = S5PC100_GPIO_H0_NR,
.label = "GPH0",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.base = (S5P_VA_GPIO + 0xC20),
.irq_base = IRQ_EINT(8),
.chip = {
.base = S5PC100_GPH1(0),
.ngpio = S5PC100_GPIO_H1_NR,
.label = "GPH1",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.base = (S5P_VA_GPIO + 0xC40),
.irq_base = IRQ_EINT(16),
.chip = {
.base = S5PC100_GPH2(0),
.ngpio = S5PC100_GPIO_H2_NR,
.label = "GPH2",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.base = (S5P_VA_GPIO + 0xC60),
.irq_base = IRQ_EINT(24),
.chip = {
.base = S5PC100_GPH3(0),
.ngpio = S5PC100_GPIO_H3_NR,
.label = "GPH3",
.to_irq = samsung_gpiolib_to_irq,
},
},
#endif
};
/*
* Followings are the gpio banks in S5PV210/S5PC110
*
* The 'config' member when left to NULL, is initialized to the default
* structure samsung_gpio_cfgs[3] in the init function below.
*
* The 'base' member is also initialized in the init function below.
* Note: The initialization of 'base' member of samsung_gpio_chip structure
* uses the above macro and depends on the banks being listed in order here.
*/
static struct samsung_gpio_chip s5pv210_gpios_4bit[] = {
#ifdef CONFIG_CPU_S5PV210
{
.chip = {
.base = S5PV210_GPA0(0),
.ngpio = S5PV210_GPIO_A0_NR,
.label = "GPA0",
},
}, {
.chip = {
.base = S5PV210_GPA1(0),
.ngpio = S5PV210_GPIO_A1_NR,
.label = "GPA1",
},
}, {
.chip = {
.base = S5PV210_GPB(0),
.ngpio = S5PV210_GPIO_B_NR,
.label = "GPB",
},
}, {
.chip = {
.base = S5PV210_GPC0(0),
.ngpio = S5PV210_GPIO_C0_NR,
.label = "GPC0",
},
}, {
.chip = {
.base = S5PV210_GPC1(0),
.ngpio = S5PV210_GPIO_C1_NR,
.label = "GPC1",
},
}, {
.chip = {
.base = S5PV210_GPD0(0),
.ngpio = S5PV210_GPIO_D0_NR,
.label = "GPD0",
},
}, {
.chip = {
.base = S5PV210_GPD1(0),
.ngpio = S5PV210_GPIO_D1_NR,
.label = "GPD1",
},
}, {
.chip = {
.base = S5PV210_GPE0(0),
.ngpio = S5PV210_GPIO_E0_NR,
.label = "GPE0",
},
}, {
.chip = {
.base = S5PV210_GPE1(0),
.ngpio = S5PV210_GPIO_E1_NR,
.label = "GPE1",
},
}, {
.chip = {
.base = S5PV210_GPF0(0),
.ngpio = S5PV210_GPIO_F0_NR,
.label = "GPF0",
},
}, {
.chip = {
.base = S5PV210_GPF1(0),
.ngpio = S5PV210_GPIO_F1_NR,
.label = "GPF1",
},
}, {
.chip = {
.base = S5PV210_GPF2(0),
.ngpio = S5PV210_GPIO_F2_NR,
.label = "GPF2",
},
}, {
.chip = {
.base = S5PV210_GPF3(0),
.ngpio = S5PV210_GPIO_F3_NR,
.label = "GPF3",
},
}, {
.chip = {
.base = S5PV210_GPG0(0),
.ngpio = S5PV210_GPIO_G0_NR,
.label = "GPG0",
},
}, {
.chip = {
.base = S5PV210_GPG1(0),
.ngpio = S5PV210_GPIO_G1_NR,
.label = "GPG1",
},
}, {
.chip = {
.base = S5PV210_GPG2(0),
.ngpio = S5PV210_GPIO_G2_NR,
.label = "GPG2",
},
}, {
.chip = {
.base = S5PV210_GPG3(0),
.ngpio = S5PV210_GPIO_G3_NR,
.label = "GPG3",
},
}, {
.chip = {
.base = S5PV210_GPI(0),
.ngpio = S5PV210_GPIO_I_NR,
.label = "GPI",
},
}, {
.chip = {
.base = S5PV210_GPJ0(0),
.ngpio = S5PV210_GPIO_J0_NR,
.label = "GPJ0",
},
}, {
.chip = {
.base = S5PV210_GPJ1(0),
.ngpio = S5PV210_GPIO_J1_NR,
.label = "GPJ1",
},
}, {
.chip = {
.base = S5PV210_GPJ2(0),
.ngpio = S5PV210_GPIO_J2_NR,
.label = "GPJ2",
},
}, {
.chip = {
.base = S5PV210_GPJ3(0),
.ngpio = S5PV210_GPIO_J3_NR,
.label = "GPJ3",
},
}, {
.chip = {
.base = S5PV210_GPJ4(0),
.ngpio = S5PV210_GPIO_J4_NR,
.label = "GPJ4",
},
}, {
.chip = {
.base = S5PV210_MP01(0),
.ngpio = S5PV210_GPIO_MP01_NR,
.label = "MP01",
},
}, {
.chip = {
.base = S5PV210_MP02(0),
.ngpio = S5PV210_GPIO_MP02_NR,
.label = "MP02",
},
}, {
.chip = {
.base = S5PV210_MP03(0),
.ngpio = S5PV210_GPIO_MP03_NR,
.label = "MP03",
},
}, {
.chip = {
.base = S5PV210_MP04(0),
.ngpio = S5PV210_GPIO_MP04_NR,
.label = "MP04",
},
}, {
.chip = {
.base = S5PV210_MP05(0),
.ngpio = S5PV210_GPIO_MP05_NR,
.label = "MP05",
},
}, {
.base = (S5P_VA_GPIO + 0xC00),
.irq_base = IRQ_EINT(0),
.chip = {
.base = S5PV210_GPH0(0),
.ngpio = S5PV210_GPIO_H0_NR,
.label = "GPH0",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.base = (S5P_VA_GPIO + 0xC20),
.irq_base = IRQ_EINT(8),
.chip = {
.base = S5PV210_GPH1(0),
.ngpio = S5PV210_GPIO_H1_NR,
.label = "GPH1",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.base = (S5P_VA_GPIO + 0xC40),
.irq_base = IRQ_EINT(16),
.chip = {
.base = S5PV210_GPH2(0),
.ngpio = S5PV210_GPIO_H2_NR,
.label = "GPH2",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.base = (S5P_VA_GPIO + 0xC60),
.irq_base = IRQ_EINT(24),
.chip = {
.base = S5PV210_GPH3(0),
.ngpio = S5PV210_GPIO_H3_NR,
.label = "GPH3",
.to_irq = samsung_gpiolib_to_irq,
},
},
#endif
};
/*
* Followings are the gpio banks in EXYNOS SoCs
*
* The 'config' member when left to NULL, is initialized to the default
* structure exynos_gpio_cfg in the init function below.
*
* The 'base' member is also initialized in the init function below.
* Note: The initialization of 'base' member of samsung_gpio_chip structure
* uses the above macro and depends on the banks being listed in order here.
*/
#ifdef CONFIG_ARCH_EXYNOS4
static struct samsung_gpio_chip exynos4_gpios_1[] = {
{
.chip = {
.base = EXYNOS4_GPA0(0),
.ngpio = EXYNOS4_GPIO_A0_NR,
.label = "GPA0",
},
}, {
.chip = {
.base = EXYNOS4_GPA1(0),
.ngpio = EXYNOS4_GPIO_A1_NR,
.label = "GPA1",
},
}, {
.chip = {
.base = EXYNOS4_GPB(0),
.ngpio = EXYNOS4_GPIO_B_NR,
.label = "GPB",
},
}, {
.chip = {
.base = EXYNOS4_GPC0(0),
.ngpio = EXYNOS4_GPIO_C0_NR,
.label = "GPC0",
},
}, {
.chip = {
.base = EXYNOS4_GPC1(0),
.ngpio = EXYNOS4_GPIO_C1_NR,
.label = "GPC1",
},
}, {
.chip = {
.base = EXYNOS4_GPD0(0),
.ngpio = EXYNOS4_GPIO_D0_NR,
.label = "GPD0",
},
}, {
.chip = {
.base = EXYNOS4_GPD1(0),
.ngpio = EXYNOS4_GPIO_D1_NR,
.label = "GPD1",
},
}, {
.chip = {
.base = EXYNOS4_GPE0(0),
.ngpio = EXYNOS4_GPIO_E0_NR,
.label = "GPE0",
},
}, {
.chip = {
.base = EXYNOS4_GPE1(0),
.ngpio = EXYNOS4_GPIO_E1_NR,
.label = "GPE1",
},
}, {
.chip = {
.base = EXYNOS4_GPE2(0),
.ngpio = EXYNOS4_GPIO_E2_NR,
.label = "GPE2",
},
}, {
.chip = {
.base = EXYNOS4_GPE3(0),
.ngpio = EXYNOS4_GPIO_E3_NR,
.label = "GPE3",
},
}, {
.chip = {
.base = EXYNOS4_GPE4(0),
.ngpio = EXYNOS4_GPIO_E4_NR,
.label = "GPE4",
},
}, {
.chip = {
.base = EXYNOS4_GPF0(0),
.ngpio = EXYNOS4_GPIO_F0_NR,
.label = "GPF0",
},
}, {
.chip = {
.base = EXYNOS4_GPF1(0),
.ngpio = EXYNOS4_GPIO_F1_NR,
.label = "GPF1",
},
}, {
.chip = {
.base = EXYNOS4_GPF2(0),
.ngpio = EXYNOS4_GPIO_F2_NR,
.label = "GPF2",
},
}, {
.chip = {
.base = EXYNOS4_GPF3(0),
.ngpio = EXYNOS4_GPIO_F3_NR,
.label = "GPF3",
},
},
};
#endif
#ifdef CONFIG_ARCH_EXYNOS4
static struct samsung_gpio_chip exynos4_gpios_2[] = {
{
.chip = {
.base = EXYNOS4_GPJ0(0),
.ngpio = EXYNOS4_GPIO_J0_NR,
.label = "GPJ0",
},
}, {
.chip = {
.base = EXYNOS4_GPJ1(0),
.ngpio = EXYNOS4_GPIO_J1_NR,
.label = "GPJ1",
},
}, {
.chip = {
.base = EXYNOS4_GPK0(0),
.ngpio = EXYNOS4_GPIO_K0_NR,
.label = "GPK0",
},
}, {
.chip = {
.base = EXYNOS4_GPK1(0),
.ngpio = EXYNOS4_GPIO_K1_NR,
.label = "GPK1",
},
}, {
.chip = {
.base = EXYNOS4_GPK2(0),
.ngpio = EXYNOS4_GPIO_K2_NR,
.label = "GPK2",
},
}, {
.chip = {
.base = EXYNOS4_GPK3(0),
.ngpio = EXYNOS4_GPIO_K3_NR,
.label = "GPK3",
},
}, {
.chip = {
.base = EXYNOS4_GPL0(0),
.ngpio = EXYNOS4_GPIO_L0_NR,
.label = "GPL0",
},
}, {
.chip = {
.base = EXYNOS4_GPL1(0),
.ngpio = EXYNOS4_GPIO_L1_NR,
.label = "GPL1",
},
}, {
.chip = {
.base = EXYNOS4_GPL2(0),
.ngpio = EXYNOS4_GPIO_L2_NR,
.label = "GPL2",
},
}, {
.config = &samsung_gpio_cfgs[8],
.chip = {
.base = EXYNOS4_GPY0(0),
.ngpio = EXYNOS4_GPIO_Y0_NR,
.label = "GPY0",
},
}, {
.config = &samsung_gpio_cfgs[8],
.chip = {
.base = EXYNOS4_GPY1(0),
.ngpio = EXYNOS4_GPIO_Y1_NR,
.label = "GPY1",
},
}, {
.config = &samsung_gpio_cfgs[8],
.chip = {
.base = EXYNOS4_GPY2(0),
.ngpio = EXYNOS4_GPIO_Y2_NR,
.label = "GPY2",
},
}, {
.config = &samsung_gpio_cfgs[8],
.chip = {
.base = EXYNOS4_GPY3(0),
.ngpio = EXYNOS4_GPIO_Y3_NR,
.label = "GPY3",
},
}, {
.config = &samsung_gpio_cfgs[8],
.chip = {
.base = EXYNOS4_GPY4(0),
.ngpio = EXYNOS4_GPIO_Y4_NR,
.label = "GPY4",
},
}, {
.config = &samsung_gpio_cfgs[8],
.chip = {
.base = EXYNOS4_GPY5(0),
.ngpio = EXYNOS4_GPIO_Y5_NR,
.label = "GPY5",
},
}, {
.config = &samsung_gpio_cfgs[8],
.chip = {
.base = EXYNOS4_GPY6(0),
.ngpio = EXYNOS4_GPIO_Y6_NR,
.label = "GPY6",
},
}, {
.config = &samsung_gpio_cfgs[9],
.irq_base = IRQ_EINT(0),
.chip = {
.base = EXYNOS4_GPX0(0),
.ngpio = EXYNOS4_GPIO_X0_NR,
.label = "GPX0",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.config = &samsung_gpio_cfgs[9],
.irq_base = IRQ_EINT(8),
.chip = {
.base = EXYNOS4_GPX1(0),
.ngpio = EXYNOS4_GPIO_X1_NR,
.label = "GPX1",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.config = &samsung_gpio_cfgs[9],
.irq_base = IRQ_EINT(16),
.chip = {
.base = EXYNOS4_GPX2(0),
.ngpio = EXYNOS4_GPIO_X2_NR,
.label = "GPX2",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.config = &samsung_gpio_cfgs[9],
.irq_base = IRQ_EINT(24),
.chip = {
.base = EXYNOS4_GPX3(0),
.ngpio = EXYNOS4_GPIO_X3_NR,
.label = "GPX3",
.to_irq = samsung_gpiolib_to_irq,
},
},
};
#endif
#ifdef CONFIG_ARCH_EXYNOS4
static struct samsung_gpio_chip exynos4_gpios_3[] = {
{
.chip = {
.base = EXYNOS4_GPZ(0),
.ngpio = EXYNOS4_GPIO_Z_NR,
.label = "GPZ",
},
},
};
#endif
#ifdef CONFIG_ARCH_EXYNOS5
static struct samsung_gpio_chip exynos5_gpios_1[] = {
{
.chip = {
.base = EXYNOS5_GPA0(0),
.ngpio = EXYNOS5_GPIO_A0_NR,
.label = "GPA0",
},
}, {
.chip = {
.base = EXYNOS5_GPA1(0),
.ngpio = EXYNOS5_GPIO_A1_NR,
.label = "GPA1",
},
}, {
.chip = {
.base = EXYNOS5_GPA2(0),
.ngpio = EXYNOS5_GPIO_A2_NR,
.label = "GPA2",
},
}, {
.chip = {
.base = EXYNOS5_GPB0(0),
.ngpio = EXYNOS5_GPIO_B0_NR,
.label = "GPB0",
},
}, {
.chip = {
.base = EXYNOS5_GPB1(0),
.ngpio = EXYNOS5_GPIO_B1_NR,
.label = "GPB1",
},
}, {
.chip = {
.base = EXYNOS5_GPB2(0),
.ngpio = EXYNOS5_GPIO_B2_NR,
.label = "GPB2",
},
}, {
.chip = {
.base = EXYNOS5_GPB3(0),
.ngpio = EXYNOS5_GPIO_B3_NR,
.label = "GPB3",
},
}, {
.chip = {
.base = EXYNOS5_GPC0(0),
.ngpio = EXYNOS5_GPIO_C0_NR,
.label = "GPC0",
},
}, {
.chip = {
.base = EXYNOS5_GPC1(0),
.ngpio = EXYNOS5_GPIO_C1_NR,
.label = "GPC1",
},
}, {
.chip = {
.base = EXYNOS5_GPC2(0),
.ngpio = EXYNOS5_GPIO_C2_NR,
.label = "GPC2",
},
}, {
.chip = {
.base = EXYNOS5_GPC3(0),
.ngpio = EXYNOS5_GPIO_C3_NR,
.label = "GPC3",
},
}, {
.chip = {
.base = EXYNOS5_GPD0(0),
.ngpio = EXYNOS5_GPIO_D0_NR,
.label = "GPD0",
},
}, {
.chip = {
.base = EXYNOS5_GPD1(0),
.ngpio = EXYNOS5_GPIO_D1_NR,
.label = "GPD1",
},
}, {
.chip = {
.base = EXYNOS5_GPY0(0),
.ngpio = EXYNOS5_GPIO_Y0_NR,
.label = "GPY0",
},
}, {
.chip = {
.base = EXYNOS5_GPY1(0),
.ngpio = EXYNOS5_GPIO_Y1_NR,
.label = "GPY1",
},
}, {
.chip = {
.base = EXYNOS5_GPY2(0),
.ngpio = EXYNOS5_GPIO_Y2_NR,
.label = "GPY2",
},
}, {
.chip = {
.base = EXYNOS5_GPY3(0),
.ngpio = EXYNOS5_GPIO_Y3_NR,
.label = "GPY3",
},
}, {
.chip = {
.base = EXYNOS5_GPY4(0),
.ngpio = EXYNOS5_GPIO_Y4_NR,
.label = "GPY4",
},
}, {
.chip = {
.base = EXYNOS5_GPY5(0),
.ngpio = EXYNOS5_GPIO_Y5_NR,
.label = "GPY5",
},
}, {
.chip = {
.base = EXYNOS5_GPY6(0),
.ngpio = EXYNOS5_GPIO_Y6_NR,
.label = "GPY6",
},
}, {
.config = &samsung_gpio_cfgs[9],
.irq_base = IRQ_EINT(0),
.chip = {
.base = EXYNOS5_GPX0(0),
.ngpio = EXYNOS5_GPIO_X0_NR,
.label = "GPX0",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.config = &samsung_gpio_cfgs[9],
.irq_base = IRQ_EINT(8),
.chip = {
.base = EXYNOS5_GPX1(0),
.ngpio = EXYNOS5_GPIO_X1_NR,
.label = "GPX1",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.config = &samsung_gpio_cfgs[9],
.irq_base = IRQ_EINT(16),
.chip = {
.base = EXYNOS5_GPX2(0),
.ngpio = EXYNOS5_GPIO_X2_NR,
.label = "GPX2",
.to_irq = samsung_gpiolib_to_irq,
},
}, {
.config = &samsung_gpio_cfgs[9],
.irq_base = IRQ_EINT(24),
.chip = {
.base = EXYNOS5_GPX3(0),
.ngpio = EXYNOS5_GPIO_X3_NR,
.label = "GPX3",
.to_irq = samsung_gpiolib_to_irq,
},
},
};
#endif
#ifdef CONFIG_ARCH_EXYNOS5
static struct samsung_gpio_chip exynos5_gpios_2[] = {
{
.chip = {
.base = EXYNOS5_GPE0(0),
.ngpio = EXYNOS5_GPIO_E0_NR,
.label = "GPE0",
},
}, {
.chip = {
.base = EXYNOS5_GPE1(0),
.ngpio = EXYNOS5_GPIO_E1_NR,
.label = "GPE1",
},
}, {
.chip = {
.base = EXYNOS5_GPF0(0),
.ngpio = EXYNOS5_GPIO_F0_NR,
.label = "GPF0",
},
}, {
.chip = {
.base = EXYNOS5_GPF1(0),
.ngpio = EXYNOS5_GPIO_F1_NR,
.label = "GPF1",
},
}, {
.chip = {
.base = EXYNOS5_GPG0(0),
.ngpio = EXYNOS5_GPIO_G0_NR,
.label = "GPG0",
},
}, {
.chip = {
.base = EXYNOS5_GPG1(0),
.ngpio = EXYNOS5_GPIO_G1_NR,
.label = "GPG1",
},
}, {
.chip = {
.base = EXYNOS5_GPG2(0),
.ngpio = EXYNOS5_GPIO_G2_NR,
.label = "GPG2",
},
}, {
.chip = {
.base = EXYNOS5_GPH0(0),
.ngpio = EXYNOS5_GPIO_H0_NR,
.label = "GPH0",
},
}, {
.chip = {
.base = EXYNOS5_GPH1(0),
.ngpio = EXYNOS5_GPIO_H1_NR,
.label = "GPH1",
},
},
};
#endif
#ifdef CONFIG_ARCH_EXYNOS5
static struct samsung_gpio_chip exynos5_gpios_3[] = {
{
.chip = {
.base = EXYNOS5_GPV0(0),
.ngpio = EXYNOS5_GPIO_V0_NR,
.label = "GPV0",
},
}, {
.chip = {
.base = EXYNOS5_GPV1(0),
.ngpio = EXYNOS5_GPIO_V1_NR,
.label = "GPV1",
},
}, {
.chip = {
.base = EXYNOS5_GPV2(0),
.ngpio = EXYNOS5_GPIO_V2_NR,
.label = "GPV2",
},
}, {
.chip = {
.base = EXYNOS5_GPV3(0),
.ngpio = EXYNOS5_GPIO_V3_NR,
.label = "GPV3",
},
}, {
.chip = {
.base = EXYNOS5_GPV4(0),
.ngpio = EXYNOS5_GPIO_V4_NR,
.label = "GPV4",
},
},
};
#endif
#ifdef CONFIG_ARCH_EXYNOS5
static struct samsung_gpio_chip exynos5_gpios_4[] = {
{
.chip = {
.base = EXYNOS5_GPZ(0),
.ngpio = EXYNOS5_GPIO_Z_NR,
.label = "GPZ",
},
},
};
#endif
#if defined(CONFIG_ARCH_EXYNOS) && defined(CONFIG_OF)
static int exynos_gpio_xlate(struct gpio_chip *gc,
const struct of_phandle_args *gpiospec, u32 *flags)
{
unsigned int pin;
if (WARN_ON(gc->of_gpio_n_cells < 4))
return -EINVAL;
if (WARN_ON(gpiospec->args_count < gc->of_gpio_n_cells))
return -EINVAL;
if (gpiospec->args[0] > gc->ngpio)
return -EINVAL;
pin = gc->base + gpiospec->args[0];
if (s3c_gpio_cfgpin(pin, S3C_GPIO_SFN(gpiospec->args[1])))
pr_warn("gpio_xlate: failed to set pin function\n");
if (s3c_gpio_setpull(pin, gpiospec->args[2]))
pr_warn("gpio_xlate: failed to set pin pull up/down\n");
if (s5p_gpio_set_drvstr(pin, gpiospec->args[3]))
pr_warn("gpio_xlate: failed to set pin drive strength\n");
return gpiospec->args[0];
}
static const struct of_device_id exynos_gpio_dt_match[] __initdata = {
{ .compatible = "samsung,exynos4-gpio", },
{}
};
static __init void exynos_gpiolib_attach_ofnode(struct samsung_gpio_chip *chip,
u64 base, u64 offset)
{
struct gpio_chip *gc = &chip->chip;
u64 address;
if (!of_have_populated_dt())
return;
address = chip->base ? base + ((u32)chip->base & 0xfff) : base + offset;
gc->of_node = of_find_matching_node_by_address(NULL,
exynos_gpio_dt_match, address);
if (!gc->of_node) {
pr_info("gpio: device tree node not found for gpio controller"
" with base address %08llx\n", address);
return;
}
gc->of_gpio_n_cells = 4;
gc->of_xlate = exynos_gpio_xlate;
}
#elif defined(CONFIG_ARCH_EXYNOS)
static __init void exynos_gpiolib_attach_ofnode(struct samsung_gpio_chip *chip,
u64 base, u64 offset)
{
return;
}
#endif /* defined(CONFIG_ARCH_EXYNOS) && defined(CONFIG_OF) */
/* TODO: cleanup soc_is_* */
static __init int samsung_gpiolib_init(void)
{
struct samsung_gpio_chip *chip;
int i, nr_chips;
#if defined(CONFIG_CPU_EXYNOS4210) || defined(CONFIG_SOC_EXYNOS5250)
void __iomem *gpio_base1, *gpio_base2, *gpio_base3, *gpio_base4;
#endif
int group = 0;
samsung_gpiolib_set_cfg(samsung_gpio_cfgs, ARRAY_SIZE(samsung_gpio_cfgs));
if (soc_is_s3c24xx()) {
s3c24xx_gpiolib_add_chips(s3c24xx_gpios,
ARRAY_SIZE(s3c24xx_gpios), S3C24XX_VA_GPIO);
} else if (soc_is_s3c64xx()) {
samsung_gpiolib_add_2bit_chips(s3c64xx_gpios_2bit,
ARRAY_SIZE(s3c64xx_gpios_2bit),
S3C64XX_VA_GPIO + 0xE0, 0x20);
samsung_gpiolib_add_4bit_chips(s3c64xx_gpios_4bit,
ARRAY_SIZE(s3c64xx_gpios_4bit),
S3C64XX_VA_GPIO);
samsung_gpiolib_add_4bit2_chips(s3c64xx_gpios_4bit2,
ARRAY_SIZE(s3c64xx_gpios_4bit2));
} else if (soc_is_s5p6440()) {
samsung_gpiolib_add_2bit_chips(s5p6440_gpios_2bit,
ARRAY_SIZE(s5p6440_gpios_2bit), NULL, 0x0);
samsung_gpiolib_add_4bit_chips(s5p6440_gpios_4bit,
ARRAY_SIZE(s5p6440_gpios_4bit), S5P_VA_GPIO);
samsung_gpiolib_add_4bit2_chips(s5p6440_gpios_4bit2,
ARRAY_SIZE(s5p6440_gpios_4bit2));
s5p64x0_gpiolib_add_rbank(s5p6440_gpios_rbank,
ARRAY_SIZE(s5p6440_gpios_rbank));
} else if (soc_is_s5p6450()) {
samsung_gpiolib_add_2bit_chips(s5p6450_gpios_2bit,
ARRAY_SIZE(s5p6450_gpios_2bit), NULL, 0x0);
samsung_gpiolib_add_4bit_chips(s5p6450_gpios_4bit,
ARRAY_SIZE(s5p6450_gpios_4bit), S5P_VA_GPIO);
samsung_gpiolib_add_4bit2_chips(s5p6450_gpios_4bit2,
ARRAY_SIZE(s5p6450_gpios_4bit2));
s5p64x0_gpiolib_add_rbank(s5p6450_gpios_rbank,
ARRAY_SIZE(s5p6450_gpios_rbank));
} else if (soc_is_s5pc100()) {
group = 0;
chip = s5pc100_gpios_4bit;
nr_chips = ARRAY_SIZE(s5pc100_gpios_4bit);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &samsung_gpio_cfgs[3];
chip->group = group++;
}
}
samsung_gpiolib_add_4bit_chips(s5pc100_gpios_4bit, nr_chips, S5P_VA_GPIO);
#if defined(CONFIG_CPU_S5PC100) && defined(CONFIG_S5P_GPIO_INT)
s5p_register_gpioint_bank(IRQ_GPIOINT, 0, S5P_GPIOINT_GROUP_MAXNR);
#endif
} else if (soc_is_s5pv210()) {
group = 0;
chip = s5pv210_gpios_4bit;
nr_chips = ARRAY_SIZE(s5pv210_gpios_4bit);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &samsung_gpio_cfgs[3];
chip->group = group++;
}
}
samsung_gpiolib_add_4bit_chips(s5pv210_gpios_4bit, nr_chips, S5P_VA_GPIO);
#if defined(CONFIG_CPU_S5PV210) && defined(CONFIG_S5P_GPIO_INT)
s5p_register_gpioint_bank(IRQ_GPIOINT, 0, S5P_GPIOINT_GROUP_MAXNR);
#endif
} else if (soc_is_exynos4210()) {
#ifdef CONFIG_CPU_EXYNOS4210
void __iomem *gpx_base;
/* gpio part1 */
gpio_base1 = ioremap(EXYNOS4_PA_GPIO1, SZ_4K);
if (gpio_base1 == NULL) {
pr_err("unable to ioremap for gpio_base1\n");
goto err_ioremap1;
}
chip = exynos4_gpios_1;
nr_chips = ARRAY_SIZE(exynos4_gpios_1);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &exynos_gpio_cfg;
chip->group = group++;
}
exynos_gpiolib_attach_ofnode(chip,
EXYNOS4_PA_GPIO1, i * 0x20);
}
samsung_gpiolib_add_4bit_chips(exynos4_gpios_1,
nr_chips, gpio_base1);
/* gpio part2 */
gpio_base2 = ioremap(EXYNOS4_PA_GPIO2, SZ_4K);
if (gpio_base2 == NULL) {
pr_err("unable to ioremap for gpio_base2\n");
goto err_ioremap2;
}
/* need to set base address for gpx */
chip = &exynos4_gpios_2[16];
gpx_base = gpio_base2 + 0xC00;
for (i = 0; i < 4; i++, chip++, gpx_base += 0x20)
chip->base = gpx_base;
chip = exynos4_gpios_2;
nr_chips = ARRAY_SIZE(exynos4_gpios_2);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &exynos_gpio_cfg;
chip->group = group++;
}
exynos_gpiolib_attach_ofnode(chip,
EXYNOS4_PA_GPIO2, i * 0x20);
}
samsung_gpiolib_add_4bit_chips(exynos4_gpios_2,
nr_chips, gpio_base2);
/* gpio part3 */
gpio_base3 = ioremap(EXYNOS4_PA_GPIO3, SZ_256);
if (gpio_base3 == NULL) {
pr_err("unable to ioremap for gpio_base3\n");
goto err_ioremap3;
}
chip = exynos4_gpios_3;
nr_chips = ARRAY_SIZE(exynos4_gpios_3);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &exynos_gpio_cfg;
chip->group = group++;
}
exynos_gpiolib_attach_ofnode(chip,
EXYNOS4_PA_GPIO3, i * 0x20);
}
samsung_gpiolib_add_4bit_chips(exynos4_gpios_3,
nr_chips, gpio_base3);
#if defined(CONFIG_CPU_EXYNOS4210) && defined(CONFIG_S5P_GPIO_INT)
s5p_register_gpioint_bank(IRQ_GPIO_XA, 0, IRQ_GPIO1_NR_GROUPS);
s5p_register_gpioint_bank(IRQ_GPIO_XB, IRQ_GPIO1_NR_GROUPS, IRQ_GPIO2_NR_GROUPS);
#endif
#endif /* CONFIG_CPU_EXYNOS4210 */
} else if (soc_is_exynos5250()) {
#ifdef CONFIG_SOC_EXYNOS5250
void __iomem *gpx_base;
/* gpio part1 */
gpio_base1 = ioremap(EXYNOS5_PA_GPIO1, SZ_4K);
if (gpio_base1 == NULL) {
pr_err("unable to ioremap for gpio_base1\n");
goto err_ioremap1;
}
/* need to set base address for gpx */
chip = &exynos5_gpios_1[20];
gpx_base = gpio_base1 + 0xC00;
for (i = 0; i < 4; i++, chip++, gpx_base += 0x20)
chip->base = gpx_base;
chip = exynos5_gpios_1;
nr_chips = ARRAY_SIZE(exynos5_gpios_1);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &exynos_gpio_cfg;
chip->group = group++;
}
exynos_gpiolib_attach_ofnode(chip,
EXYNOS5_PA_GPIO1, i * 0x20);
}
samsung_gpiolib_add_4bit_chips(exynos5_gpios_1,
nr_chips, gpio_base1);
/* gpio part2 */
gpio_base2 = ioremap(EXYNOS5_PA_GPIO2, SZ_4K);
if (gpio_base2 == NULL) {
pr_err("unable to ioremap for gpio_base2\n");
goto err_ioremap2;
}
chip = exynos5_gpios_2;
nr_chips = ARRAY_SIZE(exynos5_gpios_2);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &exynos_gpio_cfg;
chip->group = group++;
}
exynos_gpiolib_attach_ofnode(chip,
EXYNOS5_PA_GPIO2, i * 0x20);
}
samsung_gpiolib_add_4bit_chips(exynos5_gpios_2,
nr_chips, gpio_base2);
/* gpio part3 */
gpio_base3 = ioremap(EXYNOS5_PA_GPIO3, SZ_4K);
if (gpio_base3 == NULL) {
pr_err("unable to ioremap for gpio_base3\n");
goto err_ioremap3;
}
/* need to set base address for gpv */
exynos5_gpios_3[0].base = gpio_base3;
exynos5_gpios_3[1].base = gpio_base3 + 0x20;
exynos5_gpios_3[2].base = gpio_base3 + 0x60;
exynos5_gpios_3[3].base = gpio_base3 + 0x80;
exynos5_gpios_3[4].base = gpio_base3 + 0xC0;
chip = exynos5_gpios_3;
nr_chips = ARRAY_SIZE(exynos5_gpios_3);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &exynos_gpio_cfg;
chip->group = group++;
}
exynos_gpiolib_attach_ofnode(chip,
EXYNOS5_PA_GPIO3, i * 0x20);
}
samsung_gpiolib_add_4bit_chips(exynos5_gpios_3,
nr_chips, gpio_base3);
/* gpio part4 */
gpio_base4 = ioremap(EXYNOS5_PA_GPIO4, SZ_4K);
if (gpio_base4 == NULL) {
pr_err("unable to ioremap for gpio_base4\n");
goto err_ioremap4;
}
chip = exynos5_gpios_4;
nr_chips = ARRAY_SIZE(exynos5_gpios_4);
for (i = 0; i < nr_chips; i++, chip++) {
if (!chip->config) {
chip->config = &exynos_gpio_cfg;
chip->group = group++;
}
exynos_gpiolib_attach_ofnode(chip,
EXYNOS5_PA_GPIO4, i * 0x20);
}
samsung_gpiolib_add_4bit_chips(exynos5_gpios_4,
nr_chips, gpio_base4);
#endif /* CONFIG_SOC_EXYNOS5250 */
} else {
WARN(1, "Unknown SoC in gpio-samsung, no GPIOs added\n");
return -ENODEV;
}
return 0;
#if defined(CONFIG_CPU_EXYNOS4210) || defined(CONFIG_SOC_EXYNOS5250)
err_ioremap4:
iounmap(gpio_base3);
err_ioremap3:
iounmap(gpio_base2);
err_ioremap2:
iounmap(gpio_base1);
err_ioremap1:
return -ENOMEM;
#endif
}
core_initcall(samsung_gpiolib_init);
int s3c_gpio_cfgpin(unsigned int pin, unsigned int config)
{
struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin);
unsigned long flags;
int offset;
int ret;
if (!chip)
return -EINVAL;
offset = pin - chip->chip.base;
samsung_gpio_lock(chip, flags);
ret = samsung_gpio_do_setcfg(chip, offset, config);
samsung_gpio_unlock(chip, flags);
return ret;
}
EXPORT_SYMBOL(s3c_gpio_cfgpin);
int s3c_gpio_cfgpin_range(unsigned int start, unsigned int nr,
unsigned int cfg)
{
int ret;
for (; nr > 0; nr--, start++) {
ret = s3c_gpio_cfgpin(start, cfg);
if (ret != 0)
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(s3c_gpio_cfgpin_range);
int s3c_gpio_cfgall_range(unsigned int start, unsigned int nr,
unsigned int cfg, samsung_gpio_pull_t pull)
{
int ret;
for (; nr > 0; nr--, start++) {
s3c_gpio_setpull(start, pull);
ret = s3c_gpio_cfgpin(start, cfg);
if (ret != 0)
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(s3c_gpio_cfgall_range);
unsigned s3c_gpio_getcfg(unsigned int pin)
{
struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin);
unsigned long flags;
unsigned ret = 0;
int offset;
if (chip) {
offset = pin - chip->chip.base;
samsung_gpio_lock(chip, flags);
ret = samsung_gpio_do_getcfg(chip, offset);
samsung_gpio_unlock(chip, flags);
}
return ret;
}
EXPORT_SYMBOL(s3c_gpio_getcfg);
int s3c_gpio_setpull(unsigned int pin, samsung_gpio_pull_t pull)
{
struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin);
unsigned long flags;
int offset, ret;
if (!chip)
return -EINVAL;
offset = pin - chip->chip.base;
samsung_gpio_lock(chip, flags);
ret = samsung_gpio_do_setpull(chip, offset, pull);
samsung_gpio_unlock(chip, flags);
return ret;
}
EXPORT_SYMBOL(s3c_gpio_setpull);
samsung_gpio_pull_t s3c_gpio_getpull(unsigned int pin)
{
struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin);
unsigned long flags;
int offset;
u32 pup = 0;
if (chip) {
offset = pin - chip->chip.base;
samsung_gpio_lock(chip, flags);
pup = samsung_gpio_do_getpull(chip, offset);
samsung_gpio_unlock(chip, flags);
}
return (__force samsung_gpio_pull_t)pup;
}
EXPORT_SYMBOL(s3c_gpio_getpull);
/* gpiolib wrappers until these are totally eliminated */
void s3c2410_gpio_pullup(unsigned int pin, unsigned int to)
{
int ret;
WARN_ON(to); /* should be none of these left */
if (!to) {
/* if pull is enabled, try first with up, and if that
* fails, try using down */
ret = s3c_gpio_setpull(pin, S3C_GPIO_PULL_UP);
if (ret)
s3c_gpio_setpull(pin, S3C_GPIO_PULL_DOWN);
} else {
s3c_gpio_setpull(pin, S3C_GPIO_PULL_NONE);
}
}
EXPORT_SYMBOL(s3c2410_gpio_pullup);
void s3c2410_gpio_setpin(unsigned int pin, unsigned int to)
{
/* do this via gpiolib until all users removed */
gpio_request(pin, "temporary");
gpio_set_value(pin, to);
gpio_free(pin);
}
EXPORT_SYMBOL(s3c2410_gpio_setpin);
unsigned int s3c2410_gpio_getpin(unsigned int pin)
{
struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin);
unsigned long offs = pin - chip->chip.base;
return __raw_readl(chip->base + 0x04) & (1 << offs);
}
EXPORT_SYMBOL(s3c2410_gpio_getpin);
#ifdef CONFIG_S5P_GPIO_DRVSTR
s5p_gpio_drvstr_t s5p_gpio_get_drvstr(unsigned int pin)
{
struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin);
unsigned int off;
void __iomem *reg;
int shift;
u32 drvstr;
if (!chip)
return -EINVAL;
off = pin - chip->chip.base;
shift = off * 2;
reg = chip->base + 0x0C;
drvstr = __raw_readl(reg);
drvstr = drvstr >> shift;
drvstr &= 0x3;
return (__force s5p_gpio_drvstr_t)drvstr;
}
EXPORT_SYMBOL(s5p_gpio_get_drvstr);
int s5p_gpio_set_drvstr(unsigned int pin, s5p_gpio_drvstr_t drvstr)
{
struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin);
unsigned int off;
void __iomem *reg;
int shift;
u32 tmp;
if (!chip)
return -EINVAL;
off = pin - chip->chip.base;
shift = off * 2;
reg = chip->base + 0x0C;
tmp = __raw_readl(reg);
tmp &= ~(0x3 << shift);
tmp |= drvstr << shift;
__raw_writel(tmp, reg);
return 0;
}
EXPORT_SYMBOL(s5p_gpio_set_drvstr);
#endif /* CONFIG_S5P_GPIO_DRVSTR */
#ifdef CONFIG_PLAT_S3C24XX
unsigned int s3c2410_modify_misccr(unsigned int clear, unsigned int change)
{
unsigned long flags;
unsigned long misccr;
local_irq_save(flags);
misccr = __raw_readl(S3C24XX_MISCCR);
misccr &= ~clear;
misccr ^= change;
__raw_writel(misccr, S3C24XX_MISCCR);
local_irq_restore(flags);
return misccr;
}
EXPORT_SYMBOL(s3c2410_modify_misccr);
#endif
| gpl-2.0 |
showp1984/bricked-shooteru-ics-sense | lib/syscall.c | 5123 | 2475 | #include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/module.h>
#include <asm/syscall.h>
static int collect_syscall(struct task_struct *target, long *callno,
unsigned long args[6], unsigned int maxargs,
unsigned long *sp, unsigned long *pc)
{
struct pt_regs *regs = task_pt_regs(target);
if (unlikely(!regs))
return -EAGAIN;
*sp = user_stack_pointer(regs);
*pc = instruction_pointer(regs);
*callno = syscall_get_nr(target, regs);
if (*callno != -1L && maxargs > 0)
syscall_get_arguments(target, regs, 0, maxargs, args);
return 0;
}
/**
* task_current_syscall - Discover what a blocked task is doing.
* @target: thread to examine
* @callno: filled with system call number or -1
* @args: filled with @maxargs system call arguments
* @maxargs: number of elements in @args to fill
* @sp: filled with user stack pointer
* @pc: filled with user PC
*
* If @target is blocked in a system call, returns zero with *@callno
* set to the the call's number and @args filled in with its arguments.
* Registers not used for system call arguments may not be available and
* it is not kosher to use &struct user_regset calls while the system
* call is still in progress. Note we may get this result if @target
* has finished its system call but not yet returned to user mode, such
* as when it's stopped for signal handling or syscall exit tracing.
*
* If @target is blocked in the kernel during a fault or exception,
* returns zero with *@callno set to -1 and does not fill in @args.
* If so, it's now safe to examine @target using &struct user_regset
* get() calls as long as we're sure @target won't return to user mode.
*
* Returns -%EAGAIN if @target does not remain blocked.
*
* Returns -%EINVAL if @maxargs is too large (maximum is six).
*/
int task_current_syscall(struct task_struct *target, long *callno,
unsigned long args[6], unsigned int maxargs,
unsigned long *sp, unsigned long *pc)
{
long state;
unsigned long ncsw;
if (unlikely(maxargs > 6))
return -EINVAL;
if (target == current)
return collect_syscall(target, callno, args, maxargs, sp, pc);
state = target->state;
if (unlikely(!state))
return -EAGAIN;
ncsw = wait_task_inactive(target, state);
if (unlikely(!ncsw) ||
unlikely(collect_syscall(target, callno, args, maxargs, sp, pc)) ||
unlikely(wait_task_inactive(target, state) != ncsw))
return -EAGAIN;
return 0;
}
EXPORT_SYMBOL_GPL(task_current_syscall);
| gpl-2.0 |
rmcc/commtiva-kernel-z71 | arch/mips/pmc-sierra/yosemite/setup.c | 8963 | 6008 | /*
* Copyright (C) 2003 PMC-Sierra Inc.
* Author: Manish Lachwani (lachwani@pmc-sierra.com)
*
* Copyright (C) 2004 by Ralf Baechle (ralf@linux-mips.org)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``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.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/bcd.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/bootmem.h>
#include <linux/swap.h>
#include <linux/ioport.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/timex.h>
#include <linux/termios.h>
#include <linux/tty.h>
#include <linux/serial.h>
#include <linux/serial_core.h>
#include <linux/serial_8250.h>
#include <asm/time.h>
#include <asm/bootinfo.h>
#include <asm/page.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/processor.h>
#include <asm/reboot.h>
#include <asm/serial.h>
#include <asm/titan_dep.h>
#include <asm/m48t37.h>
#include "setup.h"
unsigned char titan_ge_mac_addr_base[6] = {
// 0x00, 0x03, 0xcc, 0x1d, 0x22, 0x00
0x00, 0xe0, 0x04, 0x00, 0x00, 0x21
};
unsigned long cpu_clock_freq;
unsigned long yosemite_base;
static struct m48t37_rtc *m48t37_base;
void __init bus_error_init(void)
{
/* Do nothing */
}
void read_persistent_clock(struct timespec *ts)
{
unsigned int year, month, day, hour, min, sec;
unsigned long flags;
spin_lock_irqsave(&rtc_lock, flags);
/* Stop the update to the time */
m48t37_base->control = 0x40;
year = bcd2bin(m48t37_base->year);
year += bcd2bin(m48t37_base->century) * 100;
month = bcd2bin(m48t37_base->month);
day = bcd2bin(m48t37_base->date);
hour = bcd2bin(m48t37_base->hour);
min = bcd2bin(m48t37_base->min);
sec = bcd2bin(m48t37_base->sec);
/* Start the update to the time again */
m48t37_base->control = 0x00;
spin_unlock_irqrestore(&rtc_lock, flags);
ts->tv_sec = mktime(year, month, day, hour, min, sec);
ts->tv_nsec = 0;
}
int rtc_mips_set_time(unsigned long tim)
{
struct rtc_time tm;
unsigned long flags;
/*
* Convert to a more useful format -- note months count from 0
* and years from 1900
*/
rtc_time_to_tm(tim, &tm);
tm.tm_year += 1900;
tm.tm_mon += 1;
spin_lock_irqsave(&rtc_lock, flags);
/* enable writing */
m48t37_base->control = 0x80;
/* year */
m48t37_base->year = bin2bcd(tm.tm_year % 100);
m48t37_base->century = bin2bcd(tm.tm_year / 100);
/* month */
m48t37_base->month = bin2bcd(tm.tm_mon);
/* day */
m48t37_base->date = bin2bcd(tm.tm_mday);
/* hour/min/sec */
m48t37_base->hour = bin2bcd(tm.tm_hour);
m48t37_base->min = bin2bcd(tm.tm_min);
m48t37_base->sec = bin2bcd(tm.tm_sec);
/* day of week -- not really used, but let's keep it up-to-date */
m48t37_base->day = bin2bcd(tm.tm_wday + 1);
/* disable writing */
m48t37_base->control = 0x00;
spin_unlock_irqrestore(&rtc_lock, flags);
return 0;
}
void __init plat_time_init(void)
{
mips_hpt_frequency = cpu_clock_freq / 2;
mips_hpt_frequency = 33000000 * 3 * 5;
}
unsigned long ocd_base;
EXPORT_SYMBOL(ocd_base);
/*
* Common setup before any secondaries are started
*/
#define TITAN_UART_CLK 3686400
#define TITAN_SERIAL_BASE_BAUD (TITAN_UART_CLK / 16)
#define TITAN_SERIAL_IRQ 4
#define TITAN_SERIAL_BASE 0xfd000008UL
static void __init py_map_ocd(void)
{
ocd_base = (unsigned long) ioremap(OCD_BASE, OCD_SIZE);
if (!ocd_base)
panic("Mapping OCD failed - game over. Your score is 0.");
/* Kludge for PMON bug ... */
OCD_WRITE(0x0710, 0x0ffff029);
}
static void __init py_uart_setup(void)
{
#ifdef CONFIG_SERIAL_8250
struct uart_port up;
/*
* Register to interrupt zero because we share the interrupt with
* the serial driver which we don't properly support yet.
*/
memset(&up, 0, sizeof(up));
up.membase = (unsigned char *) ioremap(TITAN_SERIAL_BASE, 8);
up.irq = TITAN_SERIAL_IRQ;
up.uartclk = TITAN_UART_CLK;
up.regshift = 0;
up.iotype = UPIO_MEM;
up.flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST;
up.line = 0;
if (early_serial_setup(&up))
printk(KERN_ERR "Early serial init of port 0 failed\n");
#endif /* CONFIG_SERIAL_8250 */
}
static void __init py_rtc_setup(void)
{
m48t37_base = ioremap(YOSEMITE_RTC_BASE, YOSEMITE_RTC_SIZE);
if (!m48t37_base)
printk(KERN_ERR "Mapping the RTC failed\n");
}
/* Not only time init but that's what the hook it's called through is named */
static void __init py_late_time_init(void)
{
py_map_ocd();
py_uart_setup();
py_rtc_setup();
}
void __init plat_mem_setup(void)
{
late_time_init = py_late_time_init;
/* Add memory regions */
add_memory_region(0x00000000, 0x10000000, BOOT_MEM_RAM);
#if 0 /* XXX Crash ... */
OCD_WRITE(RM9000x2_OCD_HTSC,
OCD_READ(RM9000x2_OCD_HTSC) | HYPERTRANSPORT_ENABLE);
/* Set the BAR. Shifted mode */
OCD_WRITE(RM9000x2_OCD_HTBAR0, HYPERTRANSPORT_BAR0_ADDR);
OCD_WRITE(RM9000x2_OCD_HTMASK0, HYPERTRANSPORT_SIZE0);
#endif
}
| gpl-2.0 |
invisiblek/android_kernel_htc_msm8974 | arch/mips/sgi-ip22/ip22-berr.c | 8963 | 3587 | /*
* ip22-berr.c: Bus error handling.
*
* Copyright (C) 2002, 2003 Ladislav Michl (ladis@linux-mips.org)
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <asm/addrspace.h>
#include <asm/traps.h>
#include <asm/branch.h>
#include <asm/irq_regs.h>
#include <asm/sgi/mc.h>
#include <asm/sgi/hpc3.h>
#include <asm/sgi/ioc.h>
#include <asm/sgi/ip22.h>
static unsigned int cpu_err_stat; /* Status reg for CPU */
static unsigned int gio_err_stat; /* Status reg for GIO */
static unsigned int cpu_err_addr; /* Error address reg for CPU */
static unsigned int gio_err_addr; /* Error address reg for GIO */
static unsigned int extio_stat;
static unsigned int hpc3_berr_stat; /* Bus error interrupt status */
static void save_and_clear_buserr(void)
{
/* save status registers */
cpu_err_addr = sgimc->cerr;
cpu_err_stat = sgimc->cstat;
gio_err_addr = sgimc->gerr;
gio_err_stat = sgimc->gstat;
extio_stat = ip22_is_fullhouse() ? sgioc->extio : (sgint->errstat << 4);
hpc3_berr_stat = hpc3c0->bestat;
sgimc->cstat = sgimc->gstat = 0;
}
#define GIO_ERRMASK 0xff00
#define CPU_ERRMASK 0x3f00
static void print_buserr(void)
{
if (extio_stat & EXTIO_MC_BUSERR)
printk(KERN_ERR "MC Bus Error\n");
if (extio_stat & EXTIO_HPC3_BUSERR)
printk(KERN_ERR "HPC3 Bus Error 0x%x:<id=0x%x,%s,lane=0x%x>\n",
hpc3_berr_stat,
(hpc3_berr_stat & HPC3_BESTAT_PIDMASK) >>
HPC3_BESTAT_PIDSHIFT,
(hpc3_berr_stat & HPC3_BESTAT_CTYPE) ? "PIO" : "DMA",
hpc3_berr_stat & HPC3_BESTAT_BLMASK);
if (extio_stat & EXTIO_EISA_BUSERR)
printk(KERN_ERR "EISA Bus Error\n");
if (cpu_err_stat & CPU_ERRMASK)
printk(KERN_ERR "CPU error 0x%x<%s%s%s%s%s%s> @ 0x%08x\n",
cpu_err_stat,
cpu_err_stat & SGIMC_CSTAT_RD ? "RD " : "",
cpu_err_stat & SGIMC_CSTAT_PAR ? "PAR " : "",
cpu_err_stat & SGIMC_CSTAT_ADDR ? "ADDR " : "",
cpu_err_stat & SGIMC_CSTAT_SYSAD_PAR ? "SYSAD " : "",
cpu_err_stat & SGIMC_CSTAT_SYSCMD_PAR ? "SYSCMD " : "",
cpu_err_stat & SGIMC_CSTAT_BAD_DATA ? "BAD_DATA " : "",
cpu_err_addr);
if (gio_err_stat & GIO_ERRMASK)
printk(KERN_ERR "GIO error 0x%x:<%s%s%s%s%s%s%s%s> @ 0x%08x\n",
gio_err_stat,
gio_err_stat & SGIMC_GSTAT_RD ? "RD " : "",
gio_err_stat & SGIMC_GSTAT_WR ? "WR " : "",
gio_err_stat & SGIMC_GSTAT_TIME ? "TIME " : "",
gio_err_stat & SGIMC_GSTAT_PROM ? "PROM " : "",
gio_err_stat & SGIMC_GSTAT_ADDR ? "ADDR " : "",
gio_err_stat & SGIMC_GSTAT_BC ? "BC " : "",
gio_err_stat & SGIMC_GSTAT_PIO_RD ? "PIO_RD " : "",
gio_err_stat & SGIMC_GSTAT_PIO_WR ? "PIO_WR " : "",
gio_err_addr);
}
/*
* MC sends an interrupt whenever bus or parity errors occur. In addition,
* if the error happened during a CPU read, it also asserts the bus error
* pin on the R4K. Code in bus error handler save the MC bus error registers
* and then clear the interrupt when this happens.
*/
void ip22_be_interrupt(int irq)
{
const int field = 2 * sizeof(unsigned long);
struct pt_regs *regs = get_irq_regs();
save_and_clear_buserr();
print_buserr();
printk(KERN_ALERT "%s bus error, epc == %0*lx, ra == %0*lx\n",
(regs->cp0_cause & 4) ? "Data" : "Instruction",
field, regs->cp0_epc, field, regs->regs[31]);
/* Assume it would be too dangerous to continue ... */
die_if_kernel("Oops", regs);
force_sig(SIGBUS, current);
}
static int ip22_be_handler(struct pt_regs *regs, int is_fixup)
{
save_and_clear_buserr();
if (is_fixup)
return MIPS_BE_FIXUP;
print_buserr();
return MIPS_BE_FATAL;
}
void __init ip22_be_init(void)
{
board_be_handler = ip22_be_handler;
}
| gpl-2.0 |
JaganTeki/streak_4.05_kernel | net/llc/llc_c_ac.c | 13827 | 36292 | /*
* llc_c_ac.c - actions performed during connection state transition.
*
* Description:
* Functions in this module are implementation of connection component actions
* Details of actions can be found in IEEE-802.2 standard document.
* All functions have one connection and one event as input argument. All of
* them return 0 On success and 1 otherwise.
*
* Copyright (c) 1997 by Procom Technology, Inc.
* 2001-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program can be redistributed or modified under the terms of the
* GNU General Public License as published by the Free Software Foundation.
* This program is distributed without any warranty or implied warranty
* of merchantability or fitness for a particular purpose.
*
* See the GNU General Public License for more details.
*/
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <net/llc_conn.h>
#include <net/llc_sap.h>
#include <net/sock.h>
#include <net/llc_c_ev.h>
#include <net/llc_c_ac.h>
#include <net/llc_c_st.h>
#include <net/llc_pdu.h>
#include <net/llc.h>
static int llc_conn_ac_inc_vs_by_1(struct sock *sk, struct sk_buff *skb);
static void llc_process_tmr_ev(struct sock *sk, struct sk_buff *skb);
static int llc_conn_ac_data_confirm(struct sock *sk, struct sk_buff *ev);
static int llc_conn_ac_inc_npta_value(struct sock *sk, struct sk_buff *skb);
static int llc_conn_ac_send_rr_rsp_f_set_ackpf(struct sock *sk,
struct sk_buff *skb);
static int llc_conn_ac_set_p_flag_1(struct sock *sk, struct sk_buff *skb);
#define INCORRECT 0
int llc_conn_ac_clear_remote_busy(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
if (llc->remote_busy_flag) {
u8 nr;
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
llc->remote_busy_flag = 0;
del_timer(&llc->busy_state_timer.timer);
nr = LLC_I_GET_NR(pdu);
llc_conn_resend_i_pdu_as_cmd(sk, nr, 0);
}
return 0;
}
int llc_conn_ac_conn_ind(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->ind_prim = LLC_CONN_PRIM;
return 0;
}
int llc_conn_ac_conn_confirm(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->cfm_prim = LLC_CONN_PRIM;
return 0;
}
static int llc_conn_ac_data_confirm(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->cfm_prim = LLC_DATA_PRIM;
return 0;
}
int llc_conn_ac_data_ind(struct sock *sk, struct sk_buff *skb)
{
llc_conn_rtn_pdu(sk, skb);
return 0;
}
int llc_conn_ac_disc_ind(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
u8 reason = 0;
int rc = 0;
if (ev->type == LLC_CONN_EV_TYPE_PDU) {
struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
if (LLC_PDU_IS_RSP(pdu) &&
LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_DM)
reason = LLC_DISC_REASON_RX_DM_RSP_PDU;
else if (LLC_PDU_IS_CMD(pdu) &&
LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_DISC)
reason = LLC_DISC_REASON_RX_DISC_CMD_PDU;
} else if (ev->type == LLC_CONN_EV_TYPE_ACK_TMR)
reason = LLC_DISC_REASON_ACK_TMR_EXP;
else
rc = -EINVAL;
if (!rc) {
ev->reason = reason;
ev->ind_prim = LLC_DISC_PRIM;
}
return rc;
}
int llc_conn_ac_disc_confirm(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->reason = ev->status;
ev->cfm_prim = LLC_DISC_PRIM;
return 0;
}
int llc_conn_ac_rst_ind(struct sock *sk, struct sk_buff *skb)
{
u8 reason = 0;
int rc = 1;
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
struct llc_sock *llc = llc_sk(sk);
switch (ev->type) {
case LLC_CONN_EV_TYPE_PDU:
if (LLC_PDU_IS_RSP(pdu) &&
LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_FRMR) {
reason = LLC_RESET_REASON_LOCAL;
rc = 0;
} else if (LLC_PDU_IS_CMD(pdu) &&
LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_SABME) {
reason = LLC_RESET_REASON_REMOTE;
rc = 0;
}
break;
case LLC_CONN_EV_TYPE_ACK_TMR:
case LLC_CONN_EV_TYPE_P_TMR:
case LLC_CONN_EV_TYPE_REJ_TMR:
case LLC_CONN_EV_TYPE_BUSY_TMR:
if (llc->retry_count > llc->n2) {
reason = LLC_RESET_REASON_LOCAL;
rc = 0;
}
break;
}
if (!rc) {
ev->reason = reason;
ev->ind_prim = LLC_RESET_PRIM;
}
return rc;
}
int llc_conn_ac_rst_confirm(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->reason = 0;
ev->cfm_prim = LLC_RESET_PRIM;
return 0;
}
int llc_conn_ac_clear_remote_busy_if_f_eq_1(struct sock *sk,
struct sk_buff *skb)
{
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
if (LLC_PDU_IS_RSP(pdu) &&
LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) && llc_sk(sk)->ack_pf)
llc_conn_ac_clear_remote_busy(sk, skb);
return 0;
}
int llc_conn_ac_stop_rej_tmr_if_data_flag_eq_2(struct sock *sk,
struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
if (llc->data_flag == 2)
del_timer(&llc->rej_sent_timer.timer);
return 0;
}
int llc_conn_ac_send_disc_cmd_p_set_x(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_CMD);
llc_pdu_init_as_disc_cmd(nskb, 1);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
llc_conn_ac_set_p_flag_1(sk, skb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_dm_rsp_f_set_p(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
u8 f_bit;
llc_pdu_decode_pf_bit(skb, &f_bit);
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_dm_rsp(nskb, f_bit);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_dm_rsp_f_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_dm_rsp(nskb, 1);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_frmr_rsp_f_set_x(struct sock *sk, struct sk_buff *skb)
{
u8 f_bit;
int rc = -ENOBUFS;
struct sk_buff *nskb;
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
struct llc_sock *llc = llc_sk(sk);
llc->rx_pdu_hdr = *((u32 *)pdu);
if (LLC_PDU_IS_CMD(pdu))
llc_pdu_decode_pf_bit(skb, &f_bit);
else
f_bit = 0;
nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U,
sizeof(struct llc_frmr_info));
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_frmr_rsp(nskb, pdu, f_bit, llc->vS,
llc->vR, INCORRECT);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_resend_frmr_rsp_f_set_0(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U,
sizeof(struct llc_frmr_info));
if (nskb) {
struct llc_sap *sap = llc->sap;
struct llc_pdu_sn *pdu = (struct llc_pdu_sn *)&llc->rx_pdu_hdr;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_frmr_rsp(nskb, pdu, 0, llc->vS,
llc->vR, INCORRECT);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_resend_frmr_rsp_f_set_p(struct sock *sk, struct sk_buff *skb)
{
u8 f_bit;
int rc = -ENOBUFS;
struct sk_buff *nskb;
struct llc_sock *llc = llc_sk(sk);
llc_pdu_decode_pf_bit(skb, &f_bit);
nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U,
sizeof(struct llc_frmr_info));
if (nskb) {
struct llc_sap *sap = llc->sap;
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_frmr_rsp(nskb, pdu, f_bit, llc->vS,
llc->vR, INCORRECT);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_i_cmd_p_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc;
struct llc_sock *llc = llc_sk(sk);
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(skb, LLC_PDU_TYPE_I, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_CMD);
llc_pdu_init_as_i_cmd(skb, 1, llc->vS, llc->vR);
rc = llc_mac_hdr_init(skb, llc->dev->dev_addr, llc->daddr.mac);
if (likely(!rc)) {
llc_conn_send_pdu(sk, skb);
llc_conn_ac_inc_vs_by_1(sk, skb);
}
return rc;
}
static int llc_conn_ac_send_i_cmd_p_set_0(struct sock *sk, struct sk_buff *skb)
{
int rc;
struct llc_sock *llc = llc_sk(sk);
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(skb, LLC_PDU_TYPE_I, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_CMD);
llc_pdu_init_as_i_cmd(skb, 0, llc->vS, llc->vR);
rc = llc_mac_hdr_init(skb, llc->dev->dev_addr, llc->daddr.mac);
if (likely(!rc)) {
llc_conn_send_pdu(sk, skb);
llc_conn_ac_inc_vs_by_1(sk, skb);
}
return rc;
}
int llc_conn_ac_send_i_xxx_x_set_0(struct sock *sk, struct sk_buff *skb)
{
int rc;
struct llc_sock *llc = llc_sk(sk);
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(skb, LLC_PDU_TYPE_I, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_CMD);
llc_pdu_init_as_i_cmd(skb, 0, llc->vS, llc->vR);
rc = llc_mac_hdr_init(skb, llc->dev->dev_addr, llc->daddr.mac);
if (likely(!rc)) {
llc_conn_send_pdu(sk, skb);
llc_conn_ac_inc_vs_by_1(sk, skb);
}
return 0;
}
int llc_conn_ac_resend_i_xxx_x_set_0(struct sock *sk, struct sk_buff *skb)
{
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
u8 nr = LLC_I_GET_NR(pdu);
llc_conn_resend_i_pdu_as_cmd(sk, nr, 0);
return 0;
}
int llc_conn_ac_resend_i_xxx_x_set_0_or_send_rr(struct sock *sk,
struct sk_buff *skb)
{
u8 nr;
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rr_rsp(nskb, 0, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (likely(!rc))
llc_conn_send_pdu(sk, nskb);
else
kfree_skb(skb);
}
if (rc) {
nr = LLC_I_GET_NR(pdu);
rc = 0;
llc_conn_resend_i_pdu_as_cmd(sk, nr, 0);
}
return rc;
}
int llc_conn_ac_resend_i_rsp_f_set_1(struct sock *sk, struct sk_buff *skb)
{
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
u8 nr = LLC_I_GET_NR(pdu);
llc_conn_resend_i_pdu_as_rsp(sk, nr, 1);
return 0;
}
int llc_conn_ac_send_rej_cmd_p_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_CMD);
llc_pdu_init_as_rej_cmd(nskb, 1, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_rej_rsp_f_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rej_rsp(nskb, 1, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_rej_xxx_x_set_0(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rej_rsp(nskb, 0, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_rnr_cmd_p_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_CMD);
llc_pdu_init_as_rnr_cmd(nskb, 1, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_rnr_rsp_f_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rnr_rsp(nskb, 1, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_rnr_xxx_x_set_0(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rnr_rsp(nskb, 0, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_set_remote_busy(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
if (!llc->remote_busy_flag) {
llc->remote_busy_flag = 1;
mod_timer(&llc->busy_state_timer.timer,
jiffies + llc->busy_state_timer.expire);
}
return 0;
}
int llc_conn_ac_opt_send_rnr_xxx_x_set_0(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rnr_rsp(nskb, 0, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_rr_cmd_p_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_CMD);
llc_pdu_init_as_rr_cmd(nskb, 1, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_rr_rsp_f_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
u8 f_bit = 1;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rr_rsp(nskb, f_bit, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_ack_rsp_f_set_1(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rr_rsp(nskb, 1, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_rr_xxx_x_set_0(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rr_rsp(nskb, 0, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_ack_xxx_x_set_0(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rr_rsp(nskb, 0, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
void llc_conn_set_p_flag(struct sock *sk, u8 value)
{
int state_changed = llc_sk(sk)->p_flag && !value;
llc_sk(sk)->p_flag = value;
if (state_changed)
sk->sk_state_change(sk);
}
int llc_conn_ac_send_sabme_cmd_p_set_x(struct sock *sk, struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
u8 *dmac = llc->daddr.mac;
if (llc->dev->flags & IFF_LOOPBACK)
dmac = llc->dev->dev_addr;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_CMD);
llc_pdu_init_as_sabme_cmd(nskb, 1);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, dmac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
llc_conn_set_p_flag(sk, 1);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_send_ua_rsp_f_set_p(struct sock *sk, struct sk_buff *skb)
{
u8 f_bit;
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_U, 0);
llc_pdu_decode_pf_bit(skb, &f_bit);
if (nskb) {
struct llc_sap *sap = llc->sap;
nskb->dev = llc->dev;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_U, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_ua_rsp(nskb, f_bit);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
int llc_conn_ac_set_s_flag_0(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->s_flag = 0;
return 0;
}
int llc_conn_ac_set_s_flag_1(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->s_flag = 1;
return 0;
}
int llc_conn_ac_start_p_timer(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
llc_conn_set_p_flag(sk, 1);
mod_timer(&llc->pf_cycle_timer.timer,
jiffies + llc->pf_cycle_timer.expire);
return 0;
}
/**
* llc_conn_ac_send_ack_if_needed - check if ack is needed
* @sk: current connection structure
* @skb: current event
*
* Checks number of received PDUs which have not been acknowledged, yet,
* If number of them reaches to "npta"(Number of PDUs To Acknowledge) then
* sends an RR response as acknowledgement for them. Returns 0 for
* success, 1 otherwise.
*/
int llc_conn_ac_send_ack_if_needed(struct sock *sk, struct sk_buff *skb)
{
u8 pf_bit;
struct llc_sock *llc = llc_sk(sk);
llc_pdu_decode_pf_bit(skb, &pf_bit);
llc->ack_pf |= pf_bit & 1;
if (!llc->ack_must_be_send) {
llc->first_pdu_Ns = llc->vR;
llc->ack_must_be_send = 1;
llc->ack_pf = pf_bit & 1;
}
if (((llc->vR - llc->first_pdu_Ns + 1 + LLC_2_SEQ_NBR_MODULO)
% LLC_2_SEQ_NBR_MODULO) >= llc->npta) {
llc_conn_ac_send_rr_rsp_f_set_ackpf(sk, skb);
llc->ack_must_be_send = 0;
llc->ack_pf = 0;
llc_conn_ac_inc_npta_value(sk, skb);
}
return 0;
}
/**
* llc_conn_ac_rst_sendack_flag - resets ack_must_be_send flag
* @sk: current connection structure
* @skb: current event
*
* This action resets ack_must_be_send flag of given connection, this flag
* indicates if there is any PDU which has not been acknowledged yet.
* Returns 0 for success, 1 otherwise.
*/
int llc_conn_ac_rst_sendack_flag(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->ack_must_be_send = llc_sk(sk)->ack_pf = 0;
return 0;
}
/**
* llc_conn_ac_send_i_rsp_f_set_ackpf - acknowledge received PDUs
* @sk: current connection structure
* @skb: current event
*
* Sends an I response PDU with f-bit set to ack_pf flag as acknowledge to
* all received PDUs which have not been acknowledged, yet. ack_pf flag is
* set to one if one PDU with p-bit set to one is received. Returns 0 for
* success, 1 otherwise.
*/
static int llc_conn_ac_send_i_rsp_f_set_ackpf(struct sock *sk,
struct sk_buff *skb)
{
int rc;
struct llc_sock *llc = llc_sk(sk);
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(skb, LLC_PDU_TYPE_I, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_i_cmd(skb, llc->ack_pf, llc->vS, llc->vR);
rc = llc_mac_hdr_init(skb, llc->dev->dev_addr, llc->daddr.mac);
if (likely(!rc)) {
llc_conn_send_pdu(sk, skb);
llc_conn_ac_inc_vs_by_1(sk, skb);
}
return rc;
}
/**
* llc_conn_ac_send_i_as_ack - sends an I-format PDU to acknowledge rx PDUs
* @sk: current connection structure.
* @skb: current event.
*
* This action sends an I-format PDU as acknowledge to received PDUs which
* have not been acknowledged, yet, if there is any. By using of this
* action number of acknowledgements decreases, this technic is called
* piggy backing. Returns 0 for success, 1 otherwise.
*/
int llc_conn_ac_send_i_as_ack(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
if (llc->ack_must_be_send) {
llc_conn_ac_send_i_rsp_f_set_ackpf(sk, skb);
llc->ack_must_be_send = 0 ;
llc->ack_pf = 0;
} else
llc_conn_ac_send_i_cmd_p_set_0(sk, skb);
return 0;
}
/**
* llc_conn_ac_send_rr_rsp_f_set_ackpf - ack all rx PDUs not yet acked
* @sk: current connection structure.
* @skb: current event.
*
* This action sends an RR response with f-bit set to ack_pf flag as
* acknowledge to all received PDUs which have not been acknowledged, yet,
* if there is any. ack_pf flag indicates if a PDU has been received with
* p-bit set to one. Returns 0 for success, 1 otherwise.
*/
static int llc_conn_ac_send_rr_rsp_f_set_ackpf(struct sock *sk,
struct sk_buff *skb)
{
int rc = -ENOBUFS;
struct llc_sock *llc = llc_sk(sk);
struct sk_buff *nskb = llc_alloc_frame(sk, llc->dev, LLC_PDU_TYPE_S, 0);
if (nskb) {
struct llc_sap *sap = llc->sap;
llc_pdu_header_init(nskb, LLC_PDU_TYPE_S, sap->laddr.lsap,
llc->daddr.lsap, LLC_PDU_RSP);
llc_pdu_init_as_rr_rsp(nskb, llc->ack_pf, llc->vR);
rc = llc_mac_hdr_init(nskb, llc->dev->dev_addr, llc->daddr.mac);
if (unlikely(rc))
goto free;
llc_conn_send_pdu(sk, nskb);
}
out:
return rc;
free:
kfree_skb(nskb);
goto out;
}
/**
* llc_conn_ac_inc_npta_value - tries to make value of npta greater
* @sk: current connection structure.
* @skb: current event.
*
* After "inc_cntr" times calling of this action, "npta" increase by one.
* this action tries to make vale of "npta" greater as possible; number of
* acknowledgements decreases by increasing of "npta". Returns 0 for
* success, 1 otherwise.
*/
static int llc_conn_ac_inc_npta_value(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
if (!llc->inc_cntr) {
llc->dec_step = 0;
llc->dec_cntr = llc->inc_cntr = 2;
++llc->npta;
if (llc->npta > (u8) ~LLC_2_SEQ_NBR_MODULO)
llc->npta = (u8) ~LLC_2_SEQ_NBR_MODULO;
} else
--llc->inc_cntr;
return 0;
}
/**
* llc_conn_ac_adjust_npta_by_rr - decreases "npta" by one
* @sk: current connection structure.
* @skb: current event.
*
* After receiving "dec_cntr" times RR command, this action decreases
* "npta" by one. Returns 0 for success, 1 otherwise.
*/
int llc_conn_ac_adjust_npta_by_rr(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
if (!llc->connect_step && !llc->remote_busy_flag) {
if (!llc->dec_step) {
if (!llc->dec_cntr) {
llc->inc_cntr = llc->dec_cntr = 2;
if (llc->npta > 0)
llc->npta = llc->npta - 1;
} else
llc->dec_cntr -=1;
}
} else
llc->connect_step = 0 ;
return 0;
}
/**
* llc_conn_ac_adjust_npta_by_rnr - decreases "npta" by one
* @sk: current connection structure.
* @skb: current event.
*
* After receiving "dec_cntr" times RNR command, this action decreases
* "npta" by one. Returns 0 for success, 1 otherwise.
*/
int llc_conn_ac_adjust_npta_by_rnr(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
if (llc->remote_busy_flag)
if (!llc->dec_step) {
if (!llc->dec_cntr) {
llc->inc_cntr = llc->dec_cntr = 2;
if (llc->npta > 0)
--llc->npta;
} else
--llc->dec_cntr;
}
return 0;
}
/**
* llc_conn_ac_dec_tx_win_size - decreases tx window size
* @sk: current connection structure.
* @skb: current event.
*
* After receiving of a REJ command or response, transmit window size is
* decreased by number of PDUs which are outstanding yet. Returns 0 for
* success, 1 otherwise.
*/
int llc_conn_ac_dec_tx_win_size(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
u8 unacked_pdu = skb_queue_len(&llc->pdu_unack_q);
if (llc->k - unacked_pdu < 1)
llc->k = 1;
else
llc->k -= unacked_pdu;
return 0;
}
/**
* llc_conn_ac_inc_tx_win_size - tx window size is inc by 1
* @sk: current connection structure.
* @skb: current event.
*
* After receiving an RR response with f-bit set to one, transmit window
* size is increased by one. Returns 0 for success, 1 otherwise.
*/
int llc_conn_ac_inc_tx_win_size(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
llc->k += 1;
if (llc->k > (u8) ~LLC_2_SEQ_NBR_MODULO)
llc->k = (u8) ~LLC_2_SEQ_NBR_MODULO;
return 0;
}
int llc_conn_ac_stop_all_timers(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
del_timer(&llc->pf_cycle_timer.timer);
del_timer(&llc->ack_timer.timer);
del_timer(&llc->rej_sent_timer.timer);
del_timer(&llc->busy_state_timer.timer);
llc->ack_must_be_send = 0;
llc->ack_pf = 0;
return 0;
}
int llc_conn_ac_stop_other_timers(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
del_timer(&llc->rej_sent_timer.timer);
del_timer(&llc->pf_cycle_timer.timer);
del_timer(&llc->busy_state_timer.timer);
llc->ack_must_be_send = 0;
llc->ack_pf = 0;
return 0;
}
int llc_conn_ac_start_ack_timer(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
mod_timer(&llc->ack_timer.timer, jiffies + llc->ack_timer.expire);
return 0;
}
int llc_conn_ac_start_rej_timer(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
mod_timer(&llc->rej_sent_timer.timer,
jiffies + llc->rej_sent_timer.expire);
return 0;
}
int llc_conn_ac_start_ack_tmr_if_not_running(struct sock *sk,
struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
if (!timer_pending(&llc->ack_timer.timer))
mod_timer(&llc->ack_timer.timer,
jiffies + llc->ack_timer.expire);
return 0;
}
int llc_conn_ac_stop_ack_timer(struct sock *sk, struct sk_buff *skb)
{
del_timer(&llc_sk(sk)->ack_timer.timer);
return 0;
}
int llc_conn_ac_stop_p_timer(struct sock *sk, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(sk);
del_timer(&llc->pf_cycle_timer.timer);
llc_conn_set_p_flag(sk, 0);
return 0;
}
int llc_conn_ac_stop_rej_timer(struct sock *sk, struct sk_buff *skb)
{
del_timer(&llc_sk(sk)->rej_sent_timer.timer);
return 0;
}
int llc_conn_ac_upd_nr_received(struct sock *sk, struct sk_buff *skb)
{
int acked;
u16 unacked = 0;
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
struct llc_sock *llc = llc_sk(sk);
llc->last_nr = PDU_SUPV_GET_Nr(pdu);
acked = llc_conn_remove_acked_pdus(sk, llc->last_nr, &unacked);
/* On loopback we don't queue I frames in unack_pdu_q queue. */
if (acked > 0 || (llc->dev->flags & IFF_LOOPBACK)) {
llc->retry_count = 0;
del_timer(&llc->ack_timer.timer);
if (llc->failed_data_req) {
/* already, we did not accept data from upper layer
* (tx_window full or unacceptable state). Now, we
* can send data and must inform to upper layer.
*/
llc->failed_data_req = 0;
llc_conn_ac_data_confirm(sk, skb);
}
if (unacked)
mod_timer(&llc->ack_timer.timer,
jiffies + llc->ack_timer.expire);
} else if (llc->failed_data_req) {
u8 f_bit;
llc_pdu_decode_pf_bit(skb, &f_bit);
if (f_bit == 1) {
llc->failed_data_req = 0;
llc_conn_ac_data_confirm(sk, skb);
}
}
return 0;
}
int llc_conn_ac_upd_p_flag(struct sock *sk, struct sk_buff *skb)
{
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
if (LLC_PDU_IS_RSP(pdu)) {
u8 f_bit;
llc_pdu_decode_pf_bit(skb, &f_bit);
if (f_bit) {
llc_conn_set_p_flag(sk, 0);
llc_conn_ac_stop_p_timer(sk, skb);
}
}
return 0;
}
int llc_conn_ac_set_data_flag_2(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->data_flag = 2;
return 0;
}
int llc_conn_ac_set_data_flag_0(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->data_flag = 0;
return 0;
}
int llc_conn_ac_set_data_flag_1(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->data_flag = 1;
return 0;
}
int llc_conn_ac_set_data_flag_1_if_data_flag_eq_0(struct sock *sk,
struct sk_buff *skb)
{
if (!llc_sk(sk)->data_flag)
llc_sk(sk)->data_flag = 1;
return 0;
}
int llc_conn_ac_set_p_flag_0(struct sock *sk, struct sk_buff *skb)
{
llc_conn_set_p_flag(sk, 0);
return 0;
}
static int llc_conn_ac_set_p_flag_1(struct sock *sk, struct sk_buff *skb)
{
llc_conn_set_p_flag(sk, 1);
return 0;
}
int llc_conn_ac_set_remote_busy_0(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->remote_busy_flag = 0;
return 0;
}
int llc_conn_ac_set_cause_flag_0(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->cause_flag = 0;
return 0;
}
int llc_conn_ac_set_cause_flag_1(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->cause_flag = 1;
return 0;
}
int llc_conn_ac_set_retry_cnt_0(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->retry_count = 0;
return 0;
}
int llc_conn_ac_inc_retry_cnt_by_1(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->retry_count++;
return 0;
}
int llc_conn_ac_set_vr_0(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->vR = 0;
return 0;
}
int llc_conn_ac_inc_vr_by_1(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->vR = PDU_GET_NEXT_Vr(llc_sk(sk)->vR);
return 0;
}
int llc_conn_ac_set_vs_0(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->vS = 0;
return 0;
}
int llc_conn_ac_set_vs_nr(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->vS = llc_sk(sk)->last_nr;
return 0;
}
static int llc_conn_ac_inc_vs_by_1(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->vS = (llc_sk(sk)->vS + 1) % LLC_2_SEQ_NBR_MODULO;
return 0;
}
static void llc_conn_tmr_common_cb(unsigned long timeout_data, u8 type)
{
struct sock *sk = (struct sock *)timeout_data;
struct sk_buff *skb = alloc_skb(0, GFP_ATOMIC);
bh_lock_sock(sk);
if (skb) {
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
skb_set_owner_r(skb, sk);
ev->type = type;
llc_process_tmr_ev(sk, skb);
}
bh_unlock_sock(sk);
}
void llc_conn_pf_cycle_tmr_cb(unsigned long timeout_data)
{
llc_conn_tmr_common_cb(timeout_data, LLC_CONN_EV_TYPE_P_TMR);
}
void llc_conn_busy_tmr_cb(unsigned long timeout_data)
{
llc_conn_tmr_common_cb(timeout_data, LLC_CONN_EV_TYPE_BUSY_TMR);
}
void llc_conn_ack_tmr_cb(unsigned long timeout_data)
{
llc_conn_tmr_common_cb(timeout_data, LLC_CONN_EV_TYPE_ACK_TMR);
}
void llc_conn_rej_tmr_cb(unsigned long timeout_data)
{
llc_conn_tmr_common_cb(timeout_data, LLC_CONN_EV_TYPE_REJ_TMR);
}
int llc_conn_ac_rst_vs(struct sock *sk, struct sk_buff *skb)
{
llc_sk(sk)->X = llc_sk(sk)->vS;
llc_conn_ac_set_vs_nr(sk, skb);
return 0;
}
int llc_conn_ac_upd_vs(struct sock *sk, struct sk_buff *skb)
{
struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
u8 nr = PDU_SUPV_GET_Nr(pdu);
if (llc_circular_between(llc_sk(sk)->vS, nr, llc_sk(sk)->X))
llc_conn_ac_set_vs_nr(sk, skb);
return 0;
}
/*
* Non-standard actions; these not contained in IEEE specification; for
* our own usage
*/
/**
* llc_conn_disc - removes connection from SAP list and frees it
* @sk: closed connection
* @skb: occurred event
*/
int llc_conn_disc(struct sock *sk, struct sk_buff *skb)
{
/* FIXME: this thing seems to want to die */
return 0;
}
/**
* llc_conn_reset - resets connection
* @sk : reseting connection.
* @skb: occurred event.
*
* Stop all timers, empty all queues and reset all flags.
*/
int llc_conn_reset(struct sock *sk, struct sk_buff *skb)
{
llc_sk_reset(sk);
return 0;
}
/**
* llc_circular_between - designates that b is between a and c or not
* @a: lower bound
* @b: element to see if is between a and b
* @c: upper bound
*
* This function designates that b is between a and c or not (for example,
* 0 is between 127 and 1). Returns 1 if b is between a and c, 0
* otherwise.
*/
u8 llc_circular_between(u8 a, u8 b, u8 c)
{
b = b - a;
c = c - a;
return b <= c;
}
/**
* llc_process_tmr_ev - timer backend
* @sk: active connection
* @skb: occurred event
*
* This function is called from timer callback functions. When connection
* is busy (during sending a data frame) timer expiration event must be
* queued. Otherwise this event can be sent to connection state machine.
* Queued events will process by llc_backlog_rcv function after sending
* data frame.
*/
static void llc_process_tmr_ev(struct sock *sk, struct sk_buff *skb)
{
if (llc_sk(sk)->state == LLC_CONN_OUT_OF_SVC) {
printk(KERN_WARNING "%s: timer called on closed connection\n",
__func__);
kfree_skb(skb);
} else {
if (!sock_owned_by_user(sk))
llc_conn_state_process(sk, skb);
else {
llc_set_backlog_type(skb, LLC_EVENT);
__sk_add_backlog(sk, skb);
}
}
}
| gpl-2.0 |
ashwinr64/android_kernel_cyanogen_msm8916 | drivers/block/paride/bpck.c | 14851 | 9505 | /*
bpck.c (c) 1996-8 Grant R. Guenther <grant@torque.net>
Under the terms of the GNU General Public License.
bpck.c is a low-level protocol driver for the MicroSolutions
"backpack" parallel port IDE adapter.
*/
/* Changes:
1.01 GRG 1998.05.05 init_proto, release_proto, pi->delay
1.02 GRG 1998.08.15 default pi->delay returned to 4
*/
#define BPCK_VERSION "1.02"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/wait.h>
#include <asm/io.h>
#include "paride.h"
#undef r2
#undef w2
#define PC pi->private
#define r2() (PC=(in_p(2) & 0xff))
#define w2(byte) {out_p(2,byte); PC = byte;}
#define t2(pat) {PC ^= pat; out_p(2,PC);}
#define e2() {PC &= 0xfe; out_p(2,PC);}
#define o2() {PC |= 1; out_p(2,PC);}
#define j44(l,h) (((l>>3)&0x7)|((l>>4)&0x8)|((h<<1)&0x70)|(h&0x80))
/* cont = 0 - access the IDE register file
cont = 1 - access the IDE command set
cont = 2 - use internal bpck register addressing
*/
static int cont_map[3] = { 0x40, 0x48, 0 };
static int bpck_read_regr( PIA *pi, int cont, int regr )
{ int r, l, h;
r = regr + cont_map[cont];
switch (pi->mode) {
case 0: w0(r & 0xf); w0(r); t2(2); t2(4);
l = r1();
t2(4);
h = r1();
return j44(l,h);
case 1: w0(r & 0xf); w0(r); t2(2);
e2(); t2(0x20);
t2(4); h = r0();
t2(1); t2(0x20);
return h;
case 2:
case 3:
case 4: w0(r); w2(9); w2(0); w2(0x20);
h = r4();
w2(0);
return h;
}
return -1;
}
static void bpck_write_regr( PIA *pi, int cont, int regr, int val )
{ int r;
r = regr + cont_map[cont];
switch (pi->mode) {
case 0:
case 1: w0(r);
t2(2);
w0(val);
o2(); t2(4); t2(1);
break;
case 2:
case 3:
case 4: w0(r); w2(9); w2(0);
w0(val); w2(1); w2(3); w2(0);
break;
}
}
/* These macros access the bpck registers in native addressing */
#define WR(r,v) bpck_write_regr(pi,2,r,v)
#define RR(r) (bpck_read_regr(pi,2,r))
static void bpck_write_block( PIA *pi, char * buf, int count )
{ int i;
switch (pi->mode) {
case 0: WR(4,0x40);
w0(0x40); t2(2); t2(1);
for (i=0;i<count;i++) { w0(buf[i]); t2(4); }
WR(4,0);
break;
case 1: WR(4,0x50);
w0(0x40); t2(2); t2(1);
for (i=0;i<count;i++) { w0(buf[i]); t2(4); }
WR(4,0x10);
break;
case 2: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(1);
for (i=0;i<count;i++) w4(buf[i]);
w2(0);
WR(4,8);
break;
case 3: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(1);
for (i=0;i<count/2;i++) w4w(((u16 *)buf)[i]);
w2(0);
WR(4,8);
break;
case 4: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(1);
for (i=0;i<count/4;i++) w4l(((u32 *)buf)[i]);
w2(0);
WR(4,8);
break;
}
}
static void bpck_read_block( PIA *pi, char * buf, int count )
{ int i, l, h;
switch (pi->mode) {
case 0: WR(4,0x40);
w0(0x40); t2(2);
for (i=0;i<count;i++) {
t2(4); l = r1();
t2(4); h = r1();
buf[i] = j44(l,h);
}
WR(4,0);
break;
case 1: WR(4,0x50);
w0(0x40); t2(2); t2(0x20);
for(i=0;i<count;i++) { t2(4); buf[i] = r0(); }
t2(1); t2(0x20);
WR(4,0x10);
break;
case 2: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(0x20);
for (i=0;i<count;i++) buf[i] = r4();
w2(0);
WR(4,8);
break;
case 3: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(0x20);
for (i=0;i<count/2;i++) ((u16 *)buf)[i] = r4w();
w2(0);
WR(4,8);
break;
case 4: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(0x20);
for (i=0;i<count/4;i++) ((u32 *)buf)[i] = r4l();
w2(0);
WR(4,8);
break;
}
}
static int bpck_probe_unit ( PIA *pi )
{ int o1, o0, f7, id;
int t, s;
id = pi->unit;
s = 0;
w2(4); w2(0xe); r2(); t2(2);
o1 = r1()&0xf8;
o0 = r0();
w0(255-id); w2(4); w0(id);
t2(8); t2(8); t2(8);
t2(2); t = r1()&0xf8;
f7 = ((id % 8) == 7);
if ((f7) || (t != o1)) { t2(2); s = r1()&0xf8; }
if ((t == o1) && ((!f7) || (s == o1))) {
w2(0x4c); w0(o0);
return 0;
}
t2(8); w0(0); t2(2); w2(0x4c); w0(o0);
return 1;
}
static void bpck_connect ( PIA *pi )
{ pi->saved_r0 = r0();
w0(0xff-pi->unit); w2(4); w0(pi->unit);
t2(8); t2(8); t2(8);
t2(2); t2(2);
switch (pi->mode) {
case 0: t2(8); WR(4,0);
break;
case 1: t2(8); WR(4,0x10);
break;
case 2:
case 3:
case 4: w2(0); WR(4,8);
break;
}
WR(5,8);
if (pi->devtype == PI_PCD) {
WR(0x46,0x10); /* fiddle with ESS logic ??? */
WR(0x4c,0x38);
WR(0x4d,0x88);
WR(0x46,0xa0);
WR(0x41,0);
WR(0x4e,8);
}
}
static void bpck_disconnect ( PIA *pi )
{ w0(0);
if (pi->mode >= 2) { w2(9); w2(0); } else t2(2);
w2(0x4c); w0(pi->saved_r0);
}
static void bpck_force_spp ( PIA *pi )
/* This fakes the EPP protocol to turn off EPP ... */
{ pi->saved_r0 = r0();
w0(0xff-pi->unit); w2(4); w0(pi->unit);
t2(8); t2(8); t2(8);
t2(2); t2(2);
w2(0);
w0(4); w2(9); w2(0);
w0(0); w2(1); w2(3); w2(0);
w0(0); w2(9); w2(0);
w2(0x4c); w0(pi->saved_r0);
}
#define TEST_LEN 16
static int bpck_test_proto( PIA *pi, char * scratch, int verbose )
{ int i, e, l, h, om;
char buf[TEST_LEN];
bpck_force_spp(pi);
switch (pi->mode) {
case 0: bpck_connect(pi);
WR(0x13,0x7f);
w0(0x13); t2(2);
for(i=0;i<TEST_LEN;i++) {
t2(4); l = r1();
t2(4); h = r1();
buf[i] = j44(l,h);
}
bpck_disconnect(pi);
break;
case 1: bpck_connect(pi);
WR(0x13,0x7f);
w0(0x13); t2(2); t2(0x20);
for(i=0;i<TEST_LEN;i++) { t2(4); buf[i] = r0(); }
t2(1); t2(0x20);
bpck_disconnect(pi);
break;
case 2:
case 3:
case 4: om = pi->mode;
pi->mode = 0;
bpck_connect(pi);
WR(7,3);
WR(4,8);
bpck_disconnect(pi);
pi->mode = om;
bpck_connect(pi);
w0(0x13); w2(9); w2(1); w0(0); w2(3); w2(0); w2(0xe0);
switch (pi->mode) {
case 2: for (i=0;i<TEST_LEN;i++) buf[i] = r4();
break;
case 3: for (i=0;i<TEST_LEN/2;i++) ((u16 *)buf)[i] = r4w();
break;
case 4: for (i=0;i<TEST_LEN/4;i++) ((u32 *)buf)[i] = r4l();
break;
}
w2(0);
WR(7,0);
bpck_disconnect(pi);
break;
}
if (verbose) {
printk("%s: bpck: 0x%x unit %d mode %d: ",
pi->device,pi->port,pi->unit,pi->mode);
for (i=0;i<TEST_LEN;i++) printk("%3d",buf[i]);
printk("\n");
}
e = 0;
for (i=0;i<TEST_LEN;i++) if (buf[i] != (i+1)) e++;
return e;
}
static void bpck_read_eeprom ( PIA *pi, char * buf )
{ int i,j,k,n,p,v,f, om, od;
bpck_force_spp(pi);
om = pi->mode; od = pi->delay;
pi->mode = 0; pi->delay = 6;
bpck_connect(pi);
n = 0;
WR(4,0);
for (i=0;i<64;i++) {
WR(6,8);
WR(6,0xc);
p = 0x100;
for (k=0;k<9;k++) {
f = (((i + 0x180) & p) != 0) * 2;
WR(6,f+0xc);
WR(6,f+0xd);
WR(6,f+0xc);
p = (p >> 1);
}
for (j=0;j<2;j++) {
v = 0;
for (k=0;k<8;k++) {
WR(6,0xc);
WR(6,0xd);
WR(6,0xc);
f = RR(0);
v = 2*v + (f == 0x84);
}
buf[2*i+1-j] = v;
}
}
WR(6,8);
WR(6,0);
WR(5,8);
bpck_disconnect(pi);
if (om >= 2) {
bpck_connect(pi);
WR(7,3);
WR(4,8);
bpck_disconnect(pi);
}
pi->mode = om; pi->delay = od;
}
static int bpck_test_port ( PIA *pi ) /* check for 8-bit port */
{ int i, r, m;
w2(0x2c); i = r0(); w0(255-i); r = r0(); w0(i);
m = -1;
if (r == i) m = 2;
if (r == (255-i)) m = 0;
w2(0xc); i = r0(); w0(255-i); r = r0(); w0(i);
if (r != (255-i)) m = -1;
if (m == 0) { w2(6); w2(0xc); r = r0(); w0(0xaa); w0(r); w0(0xaa); }
if (m == 2) { w2(0x26); w2(0xc); }
if (m == -1) return 0;
return 5;
}
static void bpck_log_adapter( PIA *pi, char * scratch, int verbose )
{ char *mode_string[5] = { "4-bit","8-bit","EPP-8",
"EPP-16","EPP-32" };
#ifdef DUMP_EEPROM
int i;
#endif
bpck_read_eeprom(pi,scratch);
#ifdef DUMP_EEPROM
if (verbose) {
for(i=0;i<128;i++)
if ((scratch[i] < ' ') || (scratch[i] > '~'))
scratch[i] = '.';
printk("%s: bpck EEPROM: %64.64s\n",pi->device,scratch);
printk("%s: %64.64s\n",pi->device,&scratch[64]);
}
#endif
printk("%s: bpck %s, backpack %8.8s unit %d",
pi->device,BPCK_VERSION,&scratch[110],pi->unit);
printk(" at 0x%x, mode %d (%s), delay %d\n",pi->port,
pi->mode,mode_string[pi->mode],pi->delay);
}
static struct pi_protocol bpck = {
.owner = THIS_MODULE,
.name = "bpck",
.max_mode = 5,
.epp_first = 2,
.default_delay = 4,
.max_units = 255,
.write_regr = bpck_write_regr,
.read_regr = bpck_read_regr,
.write_block = bpck_write_block,
.read_block = bpck_read_block,
.connect = bpck_connect,
.disconnect = bpck_disconnect,
.test_port = bpck_test_port,
.probe_unit = bpck_probe_unit,
.test_proto = bpck_test_proto,
.log_adapter = bpck_log_adapter,
};
static int __init bpck_init(void)
{
return paride_register(&bpck);
}
static void __exit bpck_exit(void)
{
paride_unregister(&bpck);
}
MODULE_LICENSE("GPL");
module_init(bpck_init)
module_exit(bpck_exit)
| gpl-2.0 |
zeroblade1984/Cancro | drivers/block/paride/bpck.c | 14851 | 9505 | /*
bpck.c (c) 1996-8 Grant R. Guenther <grant@torque.net>
Under the terms of the GNU General Public License.
bpck.c is a low-level protocol driver for the MicroSolutions
"backpack" parallel port IDE adapter.
*/
/* Changes:
1.01 GRG 1998.05.05 init_proto, release_proto, pi->delay
1.02 GRG 1998.08.15 default pi->delay returned to 4
*/
#define BPCK_VERSION "1.02"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/wait.h>
#include <asm/io.h>
#include "paride.h"
#undef r2
#undef w2
#define PC pi->private
#define r2() (PC=(in_p(2) & 0xff))
#define w2(byte) {out_p(2,byte); PC = byte;}
#define t2(pat) {PC ^= pat; out_p(2,PC);}
#define e2() {PC &= 0xfe; out_p(2,PC);}
#define o2() {PC |= 1; out_p(2,PC);}
#define j44(l,h) (((l>>3)&0x7)|((l>>4)&0x8)|((h<<1)&0x70)|(h&0x80))
/* cont = 0 - access the IDE register file
cont = 1 - access the IDE command set
cont = 2 - use internal bpck register addressing
*/
static int cont_map[3] = { 0x40, 0x48, 0 };
static int bpck_read_regr( PIA *pi, int cont, int regr )
{ int r, l, h;
r = regr + cont_map[cont];
switch (pi->mode) {
case 0: w0(r & 0xf); w0(r); t2(2); t2(4);
l = r1();
t2(4);
h = r1();
return j44(l,h);
case 1: w0(r & 0xf); w0(r); t2(2);
e2(); t2(0x20);
t2(4); h = r0();
t2(1); t2(0x20);
return h;
case 2:
case 3:
case 4: w0(r); w2(9); w2(0); w2(0x20);
h = r4();
w2(0);
return h;
}
return -1;
}
static void bpck_write_regr( PIA *pi, int cont, int regr, int val )
{ int r;
r = regr + cont_map[cont];
switch (pi->mode) {
case 0:
case 1: w0(r);
t2(2);
w0(val);
o2(); t2(4); t2(1);
break;
case 2:
case 3:
case 4: w0(r); w2(9); w2(0);
w0(val); w2(1); w2(3); w2(0);
break;
}
}
/* These macros access the bpck registers in native addressing */
#define WR(r,v) bpck_write_regr(pi,2,r,v)
#define RR(r) (bpck_read_regr(pi,2,r))
static void bpck_write_block( PIA *pi, char * buf, int count )
{ int i;
switch (pi->mode) {
case 0: WR(4,0x40);
w0(0x40); t2(2); t2(1);
for (i=0;i<count;i++) { w0(buf[i]); t2(4); }
WR(4,0);
break;
case 1: WR(4,0x50);
w0(0x40); t2(2); t2(1);
for (i=0;i<count;i++) { w0(buf[i]); t2(4); }
WR(4,0x10);
break;
case 2: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(1);
for (i=0;i<count;i++) w4(buf[i]);
w2(0);
WR(4,8);
break;
case 3: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(1);
for (i=0;i<count/2;i++) w4w(((u16 *)buf)[i]);
w2(0);
WR(4,8);
break;
case 4: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(1);
for (i=0;i<count/4;i++) w4l(((u32 *)buf)[i]);
w2(0);
WR(4,8);
break;
}
}
static void bpck_read_block( PIA *pi, char * buf, int count )
{ int i, l, h;
switch (pi->mode) {
case 0: WR(4,0x40);
w0(0x40); t2(2);
for (i=0;i<count;i++) {
t2(4); l = r1();
t2(4); h = r1();
buf[i] = j44(l,h);
}
WR(4,0);
break;
case 1: WR(4,0x50);
w0(0x40); t2(2); t2(0x20);
for(i=0;i<count;i++) { t2(4); buf[i] = r0(); }
t2(1); t2(0x20);
WR(4,0x10);
break;
case 2: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(0x20);
for (i=0;i<count;i++) buf[i] = r4();
w2(0);
WR(4,8);
break;
case 3: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(0x20);
for (i=0;i<count/2;i++) ((u16 *)buf)[i] = r4w();
w2(0);
WR(4,8);
break;
case 4: WR(4,0x48);
w0(0x40); w2(9); w2(0); w2(0x20);
for (i=0;i<count/4;i++) ((u32 *)buf)[i] = r4l();
w2(0);
WR(4,8);
break;
}
}
static int bpck_probe_unit ( PIA *pi )
{ int o1, o0, f7, id;
int t, s;
id = pi->unit;
s = 0;
w2(4); w2(0xe); r2(); t2(2);
o1 = r1()&0xf8;
o0 = r0();
w0(255-id); w2(4); w0(id);
t2(8); t2(8); t2(8);
t2(2); t = r1()&0xf8;
f7 = ((id % 8) == 7);
if ((f7) || (t != o1)) { t2(2); s = r1()&0xf8; }
if ((t == o1) && ((!f7) || (s == o1))) {
w2(0x4c); w0(o0);
return 0;
}
t2(8); w0(0); t2(2); w2(0x4c); w0(o0);
return 1;
}
static void bpck_connect ( PIA *pi )
{ pi->saved_r0 = r0();
w0(0xff-pi->unit); w2(4); w0(pi->unit);
t2(8); t2(8); t2(8);
t2(2); t2(2);
switch (pi->mode) {
case 0: t2(8); WR(4,0);
break;
case 1: t2(8); WR(4,0x10);
break;
case 2:
case 3:
case 4: w2(0); WR(4,8);
break;
}
WR(5,8);
if (pi->devtype == PI_PCD) {
WR(0x46,0x10); /* fiddle with ESS logic ??? */
WR(0x4c,0x38);
WR(0x4d,0x88);
WR(0x46,0xa0);
WR(0x41,0);
WR(0x4e,8);
}
}
static void bpck_disconnect ( PIA *pi )
{ w0(0);
if (pi->mode >= 2) { w2(9); w2(0); } else t2(2);
w2(0x4c); w0(pi->saved_r0);
}
static void bpck_force_spp ( PIA *pi )
/* This fakes the EPP protocol to turn off EPP ... */
{ pi->saved_r0 = r0();
w0(0xff-pi->unit); w2(4); w0(pi->unit);
t2(8); t2(8); t2(8);
t2(2); t2(2);
w2(0);
w0(4); w2(9); w2(0);
w0(0); w2(1); w2(3); w2(0);
w0(0); w2(9); w2(0);
w2(0x4c); w0(pi->saved_r0);
}
#define TEST_LEN 16
static int bpck_test_proto( PIA *pi, char * scratch, int verbose )
{ int i, e, l, h, om;
char buf[TEST_LEN];
bpck_force_spp(pi);
switch (pi->mode) {
case 0: bpck_connect(pi);
WR(0x13,0x7f);
w0(0x13); t2(2);
for(i=0;i<TEST_LEN;i++) {
t2(4); l = r1();
t2(4); h = r1();
buf[i] = j44(l,h);
}
bpck_disconnect(pi);
break;
case 1: bpck_connect(pi);
WR(0x13,0x7f);
w0(0x13); t2(2); t2(0x20);
for(i=0;i<TEST_LEN;i++) { t2(4); buf[i] = r0(); }
t2(1); t2(0x20);
bpck_disconnect(pi);
break;
case 2:
case 3:
case 4: om = pi->mode;
pi->mode = 0;
bpck_connect(pi);
WR(7,3);
WR(4,8);
bpck_disconnect(pi);
pi->mode = om;
bpck_connect(pi);
w0(0x13); w2(9); w2(1); w0(0); w2(3); w2(0); w2(0xe0);
switch (pi->mode) {
case 2: for (i=0;i<TEST_LEN;i++) buf[i] = r4();
break;
case 3: for (i=0;i<TEST_LEN/2;i++) ((u16 *)buf)[i] = r4w();
break;
case 4: for (i=0;i<TEST_LEN/4;i++) ((u32 *)buf)[i] = r4l();
break;
}
w2(0);
WR(7,0);
bpck_disconnect(pi);
break;
}
if (verbose) {
printk("%s: bpck: 0x%x unit %d mode %d: ",
pi->device,pi->port,pi->unit,pi->mode);
for (i=0;i<TEST_LEN;i++) printk("%3d",buf[i]);
printk("\n");
}
e = 0;
for (i=0;i<TEST_LEN;i++) if (buf[i] != (i+1)) e++;
return e;
}
static void bpck_read_eeprom ( PIA *pi, char * buf )
{ int i,j,k,n,p,v,f, om, od;
bpck_force_spp(pi);
om = pi->mode; od = pi->delay;
pi->mode = 0; pi->delay = 6;
bpck_connect(pi);
n = 0;
WR(4,0);
for (i=0;i<64;i++) {
WR(6,8);
WR(6,0xc);
p = 0x100;
for (k=0;k<9;k++) {
f = (((i + 0x180) & p) != 0) * 2;
WR(6,f+0xc);
WR(6,f+0xd);
WR(6,f+0xc);
p = (p >> 1);
}
for (j=0;j<2;j++) {
v = 0;
for (k=0;k<8;k++) {
WR(6,0xc);
WR(6,0xd);
WR(6,0xc);
f = RR(0);
v = 2*v + (f == 0x84);
}
buf[2*i+1-j] = v;
}
}
WR(6,8);
WR(6,0);
WR(5,8);
bpck_disconnect(pi);
if (om >= 2) {
bpck_connect(pi);
WR(7,3);
WR(4,8);
bpck_disconnect(pi);
}
pi->mode = om; pi->delay = od;
}
static int bpck_test_port ( PIA *pi ) /* check for 8-bit port */
{ int i, r, m;
w2(0x2c); i = r0(); w0(255-i); r = r0(); w0(i);
m = -1;
if (r == i) m = 2;
if (r == (255-i)) m = 0;
w2(0xc); i = r0(); w0(255-i); r = r0(); w0(i);
if (r != (255-i)) m = -1;
if (m == 0) { w2(6); w2(0xc); r = r0(); w0(0xaa); w0(r); w0(0xaa); }
if (m == 2) { w2(0x26); w2(0xc); }
if (m == -1) return 0;
return 5;
}
static void bpck_log_adapter( PIA *pi, char * scratch, int verbose )
{ char *mode_string[5] = { "4-bit","8-bit","EPP-8",
"EPP-16","EPP-32" };
#ifdef DUMP_EEPROM
int i;
#endif
bpck_read_eeprom(pi,scratch);
#ifdef DUMP_EEPROM
if (verbose) {
for(i=0;i<128;i++)
if ((scratch[i] < ' ') || (scratch[i] > '~'))
scratch[i] = '.';
printk("%s: bpck EEPROM: %64.64s\n",pi->device,scratch);
printk("%s: %64.64s\n",pi->device,&scratch[64]);
}
#endif
printk("%s: bpck %s, backpack %8.8s unit %d",
pi->device,BPCK_VERSION,&scratch[110],pi->unit);
printk(" at 0x%x, mode %d (%s), delay %d\n",pi->port,
pi->mode,mode_string[pi->mode],pi->delay);
}
static struct pi_protocol bpck = {
.owner = THIS_MODULE,
.name = "bpck",
.max_mode = 5,
.epp_first = 2,
.default_delay = 4,
.max_units = 255,
.write_regr = bpck_write_regr,
.read_regr = bpck_read_regr,
.write_block = bpck_write_block,
.read_block = bpck_read_block,
.connect = bpck_connect,
.disconnect = bpck_disconnect,
.test_port = bpck_test_port,
.probe_unit = bpck_probe_unit,
.test_proto = bpck_test_proto,
.log_adapter = bpck_log_adapter,
};
static int __init bpck_init(void)
{
return paride_register(&bpck);
}
static void __exit bpck_exit(void)
{
paride_unregister(&bpck);
}
MODULE_LICENSE("GPL");
module_init(bpck_init)
module_exit(bpck_exit)
| gpl-2.0 |
thillux/coreboot | src/soc/intel/broadwell/bootblock/cpu.c | 4 | 3612 | /*
* This file is part of the coreboot project.
*
* Copyright (C) 2014 Google 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; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <stdint.h>
#include <arch/cpu.h>
#include <cpu/x86/cache.h>
#include <cpu/x86/msr.h>
#include <cpu/x86/mtrr.h>
#include <arch/io.h>
#include <halt.h>
#include <cpu/intel/microcode/microcode.c>
#include <soc/rcba.h>
#include <soc/msr.h>
static void set_var_mtrr(unsigned int reg, unsigned int base, unsigned int size,
unsigned int type)
{
/* Bit Bit 32-35 of MTRRphysMask should be set to 1 */
msr_t basem, maskm;
basem.lo = base | type;
basem.hi = 0;
wrmsr(MTRR_PHYS_BASE(reg), basem);
maskm.lo = ~(size - 1) | MTRR_PHYS_MASK_VALID;
maskm.hi = (1 << (CONFIG_CPU_ADDR_BITS - 32)) - 1;
wrmsr(MTRR_PHYS_MASK(reg), maskm);
}
static void enable_rom_caching(void)
{
msr_t msr;
disable_cache();
/* Why only top 4MiB ? */
set_var_mtrr(1, CACHE_ROM_BASE, CACHE_ROM_SIZE, MTRR_TYPE_WRPROT);
enable_cache();
/* Enable Variable MTRRs */
msr.hi = 0x00000000;
msr.lo = 0x00000800;
wrmsr(MTRR_DEF_TYPE_MSR, msr);
}
static void bootblock_mdelay(int ms)
{
u32 target = ms * 24 * 1000;
msr_t current;
msr_t start = rdmsr(MSR_COUNTER_24_MHZ);
do {
current = rdmsr(MSR_COUNTER_24_MHZ);
} while ((current.lo - start.lo) < target);
}
static void set_flex_ratio_to_tdp_nominal(void)
{
msr_t flex_ratio, msr;
u32 soft_reset;
u8 nominal_ratio;
/* Check for Flex Ratio support */
flex_ratio = rdmsr(MSR_FLEX_RATIO);
if (!(flex_ratio.lo & FLEX_RATIO_EN))
return;
/* Check for >0 configurable TDPs */
msr = rdmsr(MSR_PLATFORM_INFO);
if (((msr.hi >> 1) & 3) == 0)
return;
/* Use nominal TDP ratio for flex ratio */
msr = rdmsr(MSR_CONFIG_TDP_NOMINAL);
nominal_ratio = msr.lo & 0xff;
/* See if flex ratio is already set to nominal TDP ratio */
if (((flex_ratio.lo >> 8) & 0xff) == nominal_ratio)
return;
/* Set flex ratio to nominal TDP ratio */
flex_ratio.lo &= ~0xff00;
flex_ratio.lo |= nominal_ratio << 8;
flex_ratio.lo |= FLEX_RATIO_LOCK;
wrmsr(MSR_FLEX_RATIO, flex_ratio);
/* Set flex ratio in soft reset data register bits 11:6.
* RCBA region is enabled in southbridge bootblock */
soft_reset = RCBA32(SOFT_RESET_DATA);
soft_reset &= ~(0x3f << 6);
soft_reset |= (nominal_ratio & 0x3f) << 6;
RCBA32(SOFT_RESET_DATA) = soft_reset;
/* Set soft reset control to use register value */
RCBA32_OR(SOFT_RESET_CTRL, 1);
/* Delay before reset to avoid potential TPM lockout */
bootblock_mdelay(30);
/* Issue warm reset, will be "CPU only" due to soft reset data */
outb(0x0, 0xcf9);
outb(0x6, 0xcf9);
halt();
}
static void check_for_clean_reset(void)
{
msr_t msr;
msr = rdmsr(MTRR_DEF_TYPE_MSR);
/* Use the MTRR default type MSR as a proxy for detecting INIT#.
* Reset the system if any known bits are set in that MSR. That is
* an indication of the CPU not being properly reset. */
if (msr.lo & (MTRR_DEF_TYPE_EN | MTRR_DEF_TYPE_FIX_EN)) {
outb(0x0, 0xcf9);
outb(0x6, 0xcf9);
halt();
}
}
static void bootblock_cpu_init(void)
{
/* Set flex ratio and reset if needed */
set_flex_ratio_to_tdp_nominal();
check_for_clean_reset();
enable_rom_caching();
intel_update_microcode_from_cbfs();
}
| gpl-2.0 |
ryandoyle/wireshark | epan/dissectors/packet-bacapp.c | 4 | 408667 | /* packet-bacapp.c
* Routines for BACnet (APDU) dissection
* Copyright 2001, Hartmut Mueller <hartmut[AT]abmlinux.org>, FH Dortmund
* Enhanced by Steve Karg, 2005, <skarg[AT]users.sourceforge.net>, Atlanta
* Enhanced by Herbert Lischka, 2005, <lischka[AT]kieback-peter.de>, Berlin
* Enhanced by Felix Kraemer, 2010, <sauter-cumulus[AT]de.sauter-bc.com>,
* Sauter-Cumulus GmbH, Freiburg
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald[AT]wireshark.org>
* Copyright 1998 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <glib.h>
#include <epan/packet.h>
#include <epan/to_str.h>
#include <epan/wmem/wmem.h>
#include <epan/reassemble.h>
#include <epan/expert.h>
#include <epan/stats_tree.h>
#include "packet-bacapp.h"
static int bacapp_tap = -1;
/* formerly bacapp.h contains definitions and forward declarations */
#ifndef FAULT
#define FAULT proto_tree_add_text(subtree, tvb, offset, tvb_length(tvb) - offset, "something is going wrong here !!"); \
offset = tvb_length(tvb);
#endif
/* BACnet PDU Types */
#define BACAPP_TYPE_CONFIRMED_SERVICE_REQUEST 0
#define BACAPP_TYPE_UNCONFIRMED_SERVICE_REQUEST 1
#define BACAPP_TYPE_SIMPLE_ACK 2
#define BACAPP_TYPE_COMPLEX_ACK 3
#define BACAPP_TYPE_SEGMENT_ACK 4
#define BACAPP_TYPE_ERROR 5
#define BACAPP_TYPE_REJECT 6
#define BACAPP_TYPE_ABORT 7
#define MAX_BACAPP_TYPE 8
#define BACAPP_SEGMENTED_REQUEST 0x08
#define BACAPP_MORE_SEGMENTS 0x04
#define BACAPP_SEGMENTED_RESPONSE 0x02
#define BACAPP_SEGMENT_NAK 0x02
#define BACAPP_SENT_BY 0x01
/**
* dissect_bacapp ::= CHOICE {
* confirmed-request-PDU [0] BACnet-Confirmed-Request-PDU,
* unconfirmed-request-PDU [1] BACnet-Unconfirmed-Request-PDU,
* simpleACK-PDU [2] BACnet-SimpleACK-PDU,
* complexACK-PDU [3] BACnet-ComplexACK-PDU,
* segmentACK-PDU [4] BACnet-SegmentACK-PDU,
* error-PDU [5] BACnet-Error-PDU,
* reject-PDU [6] BACnet-Reject-PDU,
* abort-PDU [7] BACnet-Abort-PDU
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
**/
static void
dissect_bacapp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
/**
* ConfirmedRequest-PDU ::= SEQUENCE {
* pdu-type [0] Unsigned (0..15), -- 0 for this PDU Type
* segmentedMessage [1] BOOLEAN,
* moreFollows [2] BOOLEAN,
* segmented-response-accepted [3] BOOLEAN,
* reserved [4] Unsigned (0..3), -- must be set zero
* max-segments-accepted [5] Unsigned (0..7), -- as per 20.1.2.4
* max-APDU-length-accepted [5] Unsigned (0..15), -- as per 20.1.2.5
* invokeID [6] Unsigned (0..255),
* sequence-number [7] Unsigned (0..255) OPTIONAL, -- only if segmented msg
* proposed-window-size [8] Unsigned (0..127) OPTIONAL, -- only if segmented msg
* service-choice [9] BACnetConfirmedServiceChoice,
* service-request [10] BACnet-Confirmed-Service-Request OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fConfirmedRequestPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param ack - indocates whether working on request or ack
* @param svc - output variable to return service choice
* @param tt - output varable to return service choice item
* @return modified offset
*/
static guint
fStartConfirmed(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 ack,
gint *svc, proto_item **tt);
/**
* Unconfirmed-Request-PDU ::= SEQUENCE {
* pdu-type [0] Unsigned (0..15), -- 1 for this PDU type
* reserved [1] Unsigned (0..15), -- must be set zero
* service-choice [2] BACnetUnconfirmedServiceChoice,
* service-request [3] BACnetUnconfirmedServiceRequest -- Context-specific tags 0..3 are NOT used in header encoding
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fUnconfirmedRequestPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* SimpleACK-PDU ::= SEQUENCE {
* pdu-type [0] Unsigned (0..15), -- 2 for this PDU type
* reserved [1] Unsigned (0..15), -- must be set zero
* invokeID [2] Unsigned (0..255),
* service-ACK-choice [3] BACnetUnconfirmedServiceChoice -- Context-specific tags 0..3 are NOT used in header encoding
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fSimpleAckPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ComplexACK-PDU ::= SEQUENCE {
* pdu-type [0] Unsigned (0..15), -- 3 for this PDU Type
* segmentedMessage [1] BOOLEAN,
* moreFollows [2] BOOLEAN,
* reserved [3] Unsigned (0..3), -- must be set zero
* invokeID [4] Unsigned (0..255),
* sequence-number [5] Unsigned (0..255) OPTIONAL, -- only if segmented msg
* proposed-window-size [6] Unsigned (0..127) OPTIONAL, -- only if segmented msg
* service-ACK-choice [7] BACnetConfirmedServiceChoice,
* service-ACK [8] BACnet-Confirmed-Service-Request -- Context-specific tags 0..8 are NOT used in header encoding
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fComplexAckPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* SegmentACK-PDU ::= SEQUENCE {
* pdu-type [0] Unsigned (0..15), -- 4 for this PDU Type
* reserved [1] Unsigned (0..3), -- must be set zero
* negative-ACK [2] BOOLEAN,
* server [3] BOOLEAN,
* original-invokeID [4] Unsigned (0..255),
* sequence-number [5] Unsigned (0..255),
* actual-window-size [6] Unsigned (0..127)
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fSegmentAckPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Error-PDU ::= SEQUENCE {
* pdu-type [0] Unsigned (0..15), -- 5 for this PDU Type
* reserved [1] Unsigned (0..3), -- must be set zero
* original-invokeID [2] Unsigned (0..255),
* error-choice [3] BACnetConfirmedServiceChoice,
* error [4] BACnet-Error
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fErrorPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Reject-PDU ::= SEQUENCE {
* pdu-type [0] Unsigned (0..15), -- 6 for this PDU Type
* reserved [1] Unsigned (0..3), -- must be set zero
* original-invokeID [2] Unsigned (0..255),
* reject-reason [3] BACnetRejectReason
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fRejectPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Abort-PDU ::= SEQUENCE {
* pdu-type [0] Unsigned (0..15), -- 7 for this PDU Type
* reserved [1] Unsigned (0..3), -- must be set zero
* server [2] BOOLEAN,
* original-invokeID [3] Unsigned (0..255),
* abort-reason [4] BACnetAbortReason
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAbortPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* 20.2.4, adds the label with max 64Bit unsigned Integer Value to tree
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param label the label of this item
* @return modified offset
*/
static guint
fUnsignedTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* 20.2.5, adds the label with max 64Bit signed Integer Value to tree
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param label the label of this item
* @return modified offset
*/
static guint
fSignedTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* 20.2.8, adds the label with Octet String to tree; if lvt == 0 then lvt = restOfFrame
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param label the label of this item
* @param lvt length of String
* @return modified offset
*/
static guint
fOctetString(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label, guint32 lvt);
/**
* 20.2.12, adds the label with Date Value to tree
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param label the label of this item
* @return modified offset
*/
static guint
fDate(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* 20.2.13, adds the label with Time Value to tree
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param label the label of this item
* @return modified offset
*/
static guint
fTime(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* 20.2.14, adds Object Identifier to tree
* use BIG ENDIAN: Bits 31..22 Object Type, Bits 21..0 Instance Number
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fObjectIdentifier(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnet-Confirmed-Service-Request ::= CHOICE {
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param service_choice the service choice
* @return offset
*/
static guint
fConfirmedServiceRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, gint service_choice);
/**
* BACnet-Confirmed-Service-ACK ::= CHOICE {
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param service_choice the service choice
* @return offset
*/
static guint
fConfirmedServiceAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, gint service_choice);
/**
* AcknowledgeAlarm-Request ::= SEQUENCE {
* acknowledgingProcessIdentifier [0] Unsigned32,
* eventObjectIdentifier [1] BACnetObjectIdentifer,
* eventStateAcknowledge [2] BACnetEventState,
* timeStamp [3] BACnetTimeStamp,
* acknowledgementSource [4] Character String,
* timeOfAcknowledgement [5] BACnetTimeStamp
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAcknowledgeAlarmRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ConfirmedCOVNotification-Request ::= SEQUENCE {
* subscriberProcessIdentifier [0] Unsigned32,
* initiatingDeviceIdentifier [1] BACnetObjectIdentifer,
* monitoredObjectIdentifier [2] BACnetObjectIdentifer,
* timeRemaining [3] unsigned,
* listOfValues [4] SEQUENCE OF BACnetPropertyValues
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fConfirmedCOVNotificationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ConfirmedEventNotification-Request ::= SEQUENCE {
* ProcessIdentifier [0] Unsigned32,
* initiatingDeviceIdentifier [1] BACnetObjectIdentifer,
* eventObjectIdentifier [2] BACnetObjectIdentifer,
* timeStamp [3] BACnetTimeStamp,
* notificationClass [4] unsigned,
* priority [5] unsigned8,
* eventType [6] BACnetEventType,
* messageText [7] CharacterString OPTIONAL,
* notifyType [8] BACnetNotifyType,
* ackRequired [9] BOOLEAN OPTIONAL,
* fromState [10] BACnetEventState OPTIONAL,
* toState [11] BACnetEventState,
* eventValues [12] BACnetNotificationParameters OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fConfirmedEventNotificationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* GetAlarmSummary-ACK ::= SEQUENCE OF SEQUENCE {
* objectIdentifier BACnetObjectIdentifer,
* alarmState BACnetEventState,
* acknowledgedTransitions BACnetEventTransitionBits
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fGetAlarmSummaryAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* GetEnrollmentSummary-Request ::= SEQUENCE {
* acknowledgmentFilter [0] ENUMERATED {
* all (0),
* acked (1),
* not-acked (2)
* },
* enrollmentFilter [1] BACnetRecipientProcess OPTIONAL,
* eventStateFilter [2] ENUMERATED {
* offnormal (0),
* fault (1),
* normal (2),
* all (3),
* active (4)
* },
* eventTypeFilter [3] BACnetEventType OPTIONAL,
* priorityFilter [4] SEQUENCE {
* minPriority [0] Unsigned8,
* maxPriority [1] Unsigned8
* } OPTIONAL,
* notificationClassFilter [5] Unsigned OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fGetEnrollmentSummaryRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* GetEnrollmentSummary-ACK ::= SEQUENCE OF SEQUENCE {
* objectIdentifier BACnetObjectIdentifer,
* eventType BACnetEventType,
* eventState BACnetEventState,
* priority Unsigned8,
* notificationClass Unsigned OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fGetEnrollmentSummaryAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* GetEventInformation-Request ::= SEQUENCE {
* lastReceivedObjectIdentifier [0] BACnetObjectIdentifer
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fGetEventInformationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* GetEventInformation-ACK ::= SEQUENCE {
* listOfEventSummaries [0] listOfEventSummaries,
* moreEvents [1] BOOLEAN
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fGetEventInformationACK(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* LifeSafetyOperation-Request ::= SEQUENCE {
* requestingProcessIdentifier [0] Unsigned32
* requestingSource [1] CharacterString
* request [2] BACnetLifeSafetyOperation
* objectIdentifier [3] BACnetObjectIdentifier OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fLifeSafetyOperationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* SubscribeCOV-Request ::= SEQUENCE {
* subscriberProcessIdentifier [0] Unsigned32
* monitoredObjectIdentifier [1] BACnetObjectIdentifier
* issueConfirmedNotifications [2] BOOLEAN OPTIONAL
* lifetime [3] Unsigned OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fSubscribeCOVRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* SubscribeCOVProperty-Request ::= SEQUENCE {
* subscriberProcessIdentifier [0] Unsigned32
* monitoredObjectIdentifier [1] BACnetObjectIdentifier
* issueConfirmedNotifications [2] BOOLEAN OPTIONAL
* lifetime [3] Unsigned OPTIONAL
* monitoredPropertyIdentifier [4] BACnetPropertyReference OPTIONAL
* covIncrement [5] Unsigned OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fSubscribeCOVPropertyRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* AtomicReadFile-Request ::= SEQUENCE {
* fileIdentifier BACnetObjectIdentifier,
* accessMethod CHOICE {
* streamAccess [0] SEQUENCE {
* fileStartPosition INTEGER,
* requestedOctetCount Unsigned
* },
* recordAccess [1] SEQUENCE {
* fileStartRecord INTEGER,
* requestedRecordCount Unsigned
* }
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAtomicReadFileRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* AtomicWriteFile-ACK ::= SEQUENCE {
* endOfFile BOOLEAN,
* accessMethod CHOICE {
* streamAccess [0] SEQUENCE {
* fileStartPosition INTEGER,
* fileData OCTET STRING
* },
* recordAccess [1] SEQUENCE {
* fileStartRecord INTEGER,
* returnedRecordCount Unsigned,
* fileRecordData SEQUENCE OF OCTET STRING
* }
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAtomicReadFileAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* AtomicWriteFile-Request ::= SEQUENCE {
* fileIdentifier BACnetObjectIdentifier,
* accessMethod CHOICE {
* streamAccess [0] SEQUENCE {
* fileStartPosition INTEGER,
* fileData OCTET STRING
* },
* recordAccess [1] SEQUENCE {
* fileStartRecord INTEGER,
* recordCount Unsigned,
* fileRecordData SEQUENCE OF OCTET STRING
* }
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAtomicWriteFileRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* AtomicWriteFile-ACK ::= SEQUENCE {
* fileStartPosition [0] INTEGER,
* fileStartRecord [1] INTEGER,
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAtomicWriteFileAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* AddListElement-Request ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* listOfElements [3] ABSTRACT-SYNTAX.&Type
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAddListElementRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* CreateObject-Request ::= SEQUENCE {
* objectSpecifier [0] ObjectSpecifier,
* listOfInitialValues [1] SEQUENCE OF BACnetPropertyValue OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param subtree the sub tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fCreateObjectRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset);
/**
* CreateObject-Request ::= BACnetObjectIdentifier
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fCreateObjectAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* DeleteObject-Request ::= SEQUENCE {
* ObjectIdentifier BACnetObjectIdentifer
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fDeleteObjectRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReadProperty-Request ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReadPropertyRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReadProperty-ACK ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* propertyValue [3] ABSTRACT-SYNTAX.&Type
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReadPropertyAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReadPropertyConditional-Request ::= SEQUENCE {
* objectSelectionCriteria [0] objectSelectionCriteria,
* listOfPropertyReferences [1] SEQUENCE OF BACnetPropertyReference OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param subtree the sub tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReadPropertyConditionalRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset);
/**
* ReadPropertyConditional-ACK ::= SEQUENCE {
* listOfPReadAccessResults SEQUENCE OF ReadAccessResult OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReadPropertyConditionalAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReadPropertyMultiple-Request ::= SEQUENCE {
* listOfReadAccessSpecs SEQUENCE OF ReadAccessSpecification
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param subtree the sub tree to append this item to
* @param offset the offset in the tvb
* @return offset modified
*/
static guint
fReadPropertyMultipleRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset);
/**
* ReadPropertyMultiple-Ack ::= SEQUENCE {
* listOfReadAccessResults SEQUENCE OF ReadAccessResult
* }
* @param tvb the tv buffer of the current data
* @parma pinfo
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return offset modified
*/
static guint
fReadPropertyMultipleAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReadRange-Request ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* range CHOICE {
* byPosition [3] SEQUENCE {
* referencedIndex Unsigned,
* count INTEGER
* },
* byTime [4] SEQUENCE {
* referenceTime BACnetDateTime,
* count INTEGER
* },
* timeRange [5] SEQUENCE {
* beginningTime BACnetDateTime,
* endingTime BACnetDateTime
* },
* } OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReadRangeRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReadRange-ACK ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* resultFlags [3] BACnetResultFlags,
* itemCount [4] Unsigned,
* itemData [5] SEQUENCE OF ABSTRACT-SYNTAX.&Type
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReadRangeAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* RemoveListElement-Request ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* listOfElements [3] ABSTRACT-SYNTAX.&Type
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fRemoveListElementRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* WriteProperty-Request ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* propertyValue [3] ABSTRACT-SYNTAX.&Type
* priority [4] Unsigned8 (1..16) OPTIONAL --used only when property is commandable
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fWritePropertyRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* WritePropertyMultiple-Request ::= SEQUENCE {
* listOfWriteAccessSpecifications SEQUENCE OF WriteAccessSpecification
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fWritePropertyMultipleRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* DeviceCommunicationControl-Request ::= SEQUENCE {
* timeDuration [0] Unsigned16 OPTIONAL,
* enable-disable [1] ENUMERATED {
* enable (0),
* disable (1)
* },
* password [2] CharacterString (SIZE(1..20)) OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fDeviceCommunicationControlRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ConfirmedPrivateTransfer-Request ::= SEQUENCE {
* vendorID [0] Unsigned,
* serviceNumber [1] Unsigned,
* serviceParameters [2] ABSTRACT-SYNTAX.&Type OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fConfirmedPrivateTransferRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ConfirmedPrivateTransfer-ACK ::= SEQUENCE {
* vendorID [0] Unsigned,
* serviceNumber [1] Unsigned,
* resultBlock [2] ABSTRACT-SYNTAX.&Type OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fConfirmedPrivateTransferAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ConfirmedTextMessage-Request ::= SEQUENCE {
* textMessageSourceDevice [0] BACnetObjectIdentifier,
* messageClass [1] CHOICE {
* numeric [0] Unsigned,
* character [1] CharacterString
* } OPTIONAL,
* messagePriority [2] ENUMERATED {
* normal (0),
* urgent (1)
* },
* message [3] CharacterString
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fConfirmedTextMessageRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReinitializeDevice-Request ::= SEQUENCE {
* reinitializedStateOfDevice [0] ENUMERATED {
* coldstart (0),
* warmstart (1),
* startbackup (2),
* endbackup (3),
* startrestore (4),
* endrestore (5),
* abortrestor (6)
* },
* password [1] CharacterString (SIZE(1..20)) OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReinitializeDeviceRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* VTOpen-Request ::= SEQUENCE {
* vtClass BACnetVTClass,
* localVTSessionIdentifier Unsigned8
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fVtOpenRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* VTOpen-ACK ::= SEQUENCE {
* remoteVTSessionIdentifier Unsigned8
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fVtOpenAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* VTClose-Request ::= SEQUENCE {
* listOfRemoteVTSessionIdentifiers SEQUENCE OF Unsigned8
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fVtCloseRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* VTData-Request ::= SEQUENCE {
* vtSessionIdentifier Unsigned8,
* vtNewData OCTET STRING,
* vtDataFlag Unsigned (0..1)
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fVtDataRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* VTData-ACK ::= SEQUENCE {
* allNewDataAccepted [0] BOOLEAN,
* acceptedOctetCount [1] Unsigned OPTIONAL -- present only if allNewDataAccepted = FALSE
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fVtDataAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Authenticate-Request ::= SEQUENCE {
* pseudoRandomNumber [0] Unsigned32,
* excpectedInvokeID [1] Unsigned8 OPTIONAL,
* operatorName [2] CharacterString OPTIONAL,
* operatorPassword [3] CharacterString (SIZE(1..20)) OPTIONAL,
* startEncypheredSession [4] BOOLEAN OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAuthenticateRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Authenticate-ACK ::= SEQUENCE {
* modifiedRandomNumber Unsigned32,
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAuthenticateAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* RequestKey-Request ::= SEQUENCE {
* requestingDeviceIdentifier BACnetObjectIdentifier,
* requestingDeviceAddress BACnetAddress,
* remoteDeviceIdentifier BACnetObjectIdentifier,
* remoteDeviceAddress BACnetAddress
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fRequestKeyRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Unconfirmed-Service-Request ::= CHOICE {
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param service_choice the service choice
* @return modified offset
*/
static guint
fUnconfirmedServiceRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, gint service_choice);
/**
* UnconfirmedCOVNotification-Request ::= SEQUENCE {
* subscriberProcessIdentifier [0] Unsigned32,
* initiatingDeviceIdentifier [1] BACnetObjectIdentifer,
* monitoredObjectIdentifier [2] BACnetObjectIdentifer,
* timeRemaining [3] unsigned,
* listOfValues [4] SEQUENCE OF BACnetPropertyValues
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fUnconfirmedCOVNotificationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* UnconfirmedEventNotification-Request ::= SEQUENCE {
* ProcessIdentifier [0] Unsigned32,
* initiatingDeviceIdentifier [1] BACnetObjectIdentifer,
* eventObjectIdentifier [2] BACnetObjectIdentifer,
* timeStamp [3] BACnetTimeStamp,
* notificationClass [4] unsigned,
* priority [5] unsigned8,
* eventType [6] BACnetEventType,
* messageText [7] CharacterString OPTIONAL,
* notifyType [8] BACnetNotifyType,
* ackRequired [9] BOOLEAN OPTIONAL,
* fromState [10] BACnetEventState OPTIONAL,
* toState [11] BACnetEventState,
* eventValues [12] BACnetNotificationParameters OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fUnconfirmedEventNotificationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* I-Am-Request ::= SEQUENCE {
* aAmDeviceIdentifier BACnetObjectIdentifier,
* maxAPDULengthAccepted Unsigned,
* segmentationSupported BACnetSegmentation,
* vendorID Unsigned
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fIAmRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* I-Have-Request ::= SEQUENCE {
* deviceIdentifier BACnetObjectIdentifier,
* objectIdentifier BACnetObjectIdentifier,
* objectName CharacterString
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fIHaveRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* UnconfirmedPrivateTransfer-Request ::= SEQUENCE {
* vendorID [0] Unsigned,
* serviceNumber [1] Unsigned,
* serviceParameters [2] ABSTRACT-SYNTAX.&Type OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fUnconfirmedPrivateTransferRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* UnconfirmedTextMessage-Request ::= SEQUENCE {
* textMessageSourceDevice [0] BACnetObjectIdentifier,
* messageClass [1] CHOICE {
* numeric [0] Unsigned,
* character [1] CharacterString
* } OPTIONAL,
* messagePriority [2] ENUMERATED {
* normal (0),
* urgent (1)
* },
* message [3] CharacterString
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fUnconfirmedTextMessageRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* TimeSynchronization-Request ::= SEQUENCE {
* BACnetDateTime
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fTimeSynchronizationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* UTCTimeSynchronization-Request ::= SEQUENCE {
* BACnetDateTime
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fUTCTimeSynchronizationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Who-Has-Request ::= SEQUENCE {
* limits SEQUENCE {
* deviceInstanceRangeLowLimit [0] Unsigned (0..4194303),
* deviceInstanceRangeHighLimit [1] Unsigned (0..4194303)
* } OPTIONAL,
* object CHOICE {
* objectIdentifier [2] BACnetObjectIdentifier,
* objectName [3] CharacterString
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fWhoHas(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Who-Is-Request ::= SEQUENCE {
* deviceInstanceRangeLowLimit [0] Unsigned (0..4194303) OPTIONAL, -- must be used as a pair, see 16.9,
* deviceInstanceRangeHighLimit [0] Unsigned (0..4194303) OPTIONAL, -- must be used as a pair, see 16.9,
* }
* @param tvb the tv buffer of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fWhoIsRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnet-Error ::= CHOICE {
* addListElement [8] ChangeList-Error,
* removeListElement [9] ChangeList-Error,
* writePropertyMultiple [16] WritePropertyMultiple-Error,
* confirmedPrivatTransfer [18] ConfirmedPrivateTransfer-Error,
* vtClose [22] VTClose-Error,
* readRange [26] ObjectAccessService-Error
* [default] Error
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param service the service
* @return modified offset
*/
static guint
fBACnetError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint service);
/**
* Dissect a BACnetError in a context tag
*
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint fContextTaggedError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ChangeList-Error ::= SEQUENCE {
* errorType [0] Error,
* firstFailedElementNumber [1] Unsigned
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fChangeListError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* CreateObject-Error ::= SEQUENCE {
* errorType [0] Error,
* firstFailedElementNumber [1] Unsigned
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fCreateObjectError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ConfirmedPrivateTransfer-Error ::= SEQUENCE {
* errorType [0] Error,
* vendorID [1] Unsigned,
* serviceNumber [2] Unsigned,
* errorParameters [3] ABSTRACT-SYNTAX.&Type OPTIONAL
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fConfirmedPrivateTransferError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* WritePropertyMultiple-Error ::= SEQUENCE {
* errorType [0] Error,
* firstFailedWriteAttempt [1] Unsigned
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fWritePropertyMultipleError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* VTClose-Error ::= SEQUENCE {
* errorType [0] Error,
* listOfVTSessionIdentifiers [1] SEQUENCE OF Unsigned8 OPTIONAL
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fVTCloseError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnet Application Types chapter 20.2.1
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param label the label of this item
* @return modified offset
*/
static guint
fApplicationTypes(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* BACnetActionCommand ::= SEQUENCE {
* deviceIdentifier [0] BACnetObjectIdentifier OPTIONAL,
* objectIdentifier [1] BACnetObjectIdentifier,
* propertyIdentifier [2] BACnetPropertyIdentifier,
* propertyArrayIndex [3] Unsigned OPTIONAL, -- used only with array datatype
* propertyValue [4] ABSTRACT-SYNTAX.&Type,
* priority [5] Unsigned (1..16) OPTIONAL, -- used only when property is commandable
* postDelay [6] Unsigned OPTIONAL,
* quitOnFailure [7] BOOLEAN,
* writeSuccessful [8] BOOLEAN
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param tag_match the tag number
* @return modified offset
*/
static guint
fActionCommand(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 tag_match);
/**
* BACnetActionList ::= SEQUENCE {
* action [0] SEQUENCE of BACnetActionCommand
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fActionList(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/** BACnetAddress ::= SEQUENCE {
* network-number Unsigned16, -- A value 0 indicates the local network
* mac-address OCTET STRING -- A string of length 0 indicates a broadcast
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAddress(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetAddressBinding ::= SEQUENCE {
* deviceObjectID BACnetObjectIdentifier
* deviceAddress BacnetAddress
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fAddressBinding(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetCalendarEntry ::= CHOICE {
* date [0] Date,
* dateRange [1] BACnetDateRange,
* weekNDay [2] BacnetWeekNday
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fCalendarEntry(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetClientCOV ::= CHOICE {
* real-increment REAL,
* default-increment NULL
* }
* @param tvb the tv buffer of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fClientCOV(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetDailySchedule ::= SEQUENCE {
* day-schedule [0] SENQUENCE OF BACnetTimeValue
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fDailySchedule(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetWeeklySchedule ::= SEQUENCE {
* week-schedule SENQUENCE SIZE (7) OF BACnetDailySchedule
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fWeeklySchedule(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetDateRange ::= SEQUENCE {
* StartDate Date,
* EndDate Date
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fDateRange(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetDateTime ::= SEQUENCE {
* date Date,
* time Time
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param label the label of this item
* @return modified offset
*/
static guint
fDateTime(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* BACnetDestination ::= SEQUENCE {
* validDays BACnetDaysOfWeek,
* fromTime Time,
* toTime Time,
* recipient BACnetRecipient,
* processIdentifier Unsigned32,
* issueConfirmedNotifications BOOLEAN,
* transitions BACnetEventTransitionBits
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fDestination(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetDeviceObjectPropertyReference ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigend OPTIONAL,
* deviceIdentifier [3] BACnetObjectIdentifier OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fDeviceObjectPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetObjectPropertyReference ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigend OPTIONAL,
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fObjectPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetDeviceObjectReference ::= SEQUENCE {
* deviceIdentifier [0] BACnetObjectIdentifier OPTIONAL,
* objectIdentifier [1] BACnetObjectIdentifier
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fDeviceObjectReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetEventParameter ::= CHOICE {
* change-of-bitstring [0] SEQUENCE {
* time-delay [0] Unsigned,
* bitmask [1] BIT STRING,
* list-of-bitstring-values [2] SEQUENCE OF BIT STRING
* },
* change-of-state [1] SEQUENCE {
* time-delay [0] Unsigned,
* list-of-values [1] SEQUENCE OF BACnetPropertyStates
* },
* change-of-value [2] SEQUENCE {
* time-delay [0] Unsigned,
* cov-criteria [1] CHOICE {
* bitmask [0] BIT STRING,
* referenced-property-increment [1] REAL
* }
* },
* command-failure [3] SEQUENCE {
* time-delay [0] Unsigned,
* feedback-property-reference [1] BACnetDeviceObjectPropertyReference
* },
* floating-limit [4] SEQUENCE {
* time-delay [0] Unsigned,
* setpoint-reference [1] BACnetDeviceObjectPropertyReference,
* low-diff-limit [2] REAL,
* high-diff-limit [3] REAL,
* deadband [4] REAL
* },
* out-of-range [5] SEQUENCE {
* time-delay [0] Unsigned,
* low-limit [1] REAL,
* high-limit [2] REAL,
* deadband [3] REAL
* },
* -- context tag 7 is deprecated
* change-of-life-safety [8] SEQUENCE {
* time-delay [0] Unsigned,
* list-of-life-safety-alarm-values [1] SEQUENCE OF BACnetLifeSafetyState,
* list-of-alarm-values [2] SEQUENCE OF BACnetLifeSafetyState,
* mode-property-reference [3] BACnetDeviceObjectPropertyReference
* },
* extended [9] SEQUENCE {
* vendor-id [0] Unsigned16,
* extended-event-type [1] Unsigned,
* parameters [2] SEQUENCE OF CHOICE {
* null NULL,
* real REAL,
* integer Unsigned,
* boolean BOOLEAN,
* double Double,
* octet OCTET STRING,
* bitstring BIT STRING,
* enum ENUMERATED,
* reference [0] BACnetDeviceObjectPropertyReference
* }
* },
* buffer-ready [10] SEQUENCE {
* notification-threshold [0] Unsigned,
* previous-notification-count [1] Unsigned32
* },
* unsigned-range [11] SEQUENCE {
* time-delay [0] Unsigned,
* low-limit [1] Unsigned,
* high-limit [2] Unsigned,
* }
* -- context tag 12 is reserved for future addenda
* access-event [13] SEQUENCE {
* list-of-access-events [0] SEQUENCE OF BACnetAccessEvent,
* access-event-time-reference [1] BACnetDeviceObjectPropertyReference
* }
* double-out-of-range [14] SEQUENCE {
* time-delay [0] Unsigned,
* low-limit [1] Double,
* high-limit [2] Double,
* deadband [3] Double
* }
* signed-out-of-range [15] SEQUENCE {
* time-delay [0] Unsigned,
* low-limit [1] INTEGER,
* high-limit [2] INTEGER,
* deadband [3] Unsigned
* }
* unsigned-out-of-range [16] SEQUENCE {
* time-delay [0] Unsigned,
* low-limit [1] Unsigned,
* high-limit [2] Unsigned,
* deadband [3] Unsigned
* }
* change-of-characterstring [17] SEQUENCE {
* time-delay [0] Unsigned,
* list-of-alarm-values [1] SEQUENCE OF CharacterString,
* }
* change-of-status-flags [18] SEQUENCE {
* time-delay [0] Unsigned,
* selected-flags [1] BACnetStatusFlags
* }
* }
* @param tvb the tv buffer of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fEventParameter(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetLogRecord ::= SEQUENCE {
* timestamp [0] BACnetDateTime,
* logDatum [1] CHOICE {
* log-status [0] BACnetLogStatus,
* boolean-value [1] BOOLEAN,
* real-value [2] REAL,
* enum-value [3] ENUMERATED, -- Optionally limited to 32 bits
* unsigned-value [4] Unsigned, -- Optionally limited to 32 bits
* signed-value [5] INTEGER, -- Optionally limited to 32 bits
* bitstring-value [6] BIT STRING, -- Optionally limited to 32 bits
* null-value [7] NULL,
* failure [8] Error,
* time-change [9] REAL,
* any-value [10] ABSTRACT-SYNTAX.&Type -- Optional
* }
* statusFlags [2] BACnetStatusFlags OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fLogRecord(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetEventLogRecord ::= SEQUENCE {
* timestamp [0] BACnetDateTime,
* logDatum [1] CHOICE {
* log-status [0] BACnetLogStatus,
* notification [1] ConfirmedEventNotification-Request,
* time-change [2] REAL,
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fEventLogRecord(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
static guint
fLogMultipleRecord(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetNotificationParameters ::= CHOICE {
* change-of-bitstring [0] SEQUENCE {
* referenced-bitstring [0] BIT STRING,
* status-flags [1] BACnetStatusFlags
* },
* change-of-state [1] SEQUENCE {
* new-state [0] BACnetPropertyStatus,
* status-flags [1] BACnetStatusFlags
* },
* change-of-value [2] SEQUENCE {
* new-value [0] CHOICE {
* changed-bits [0] BIT STRING,
* changed-value [1] REAL
* },
* status-flags [1] BACnetStatusFlags
* },
* command-failure [3] SEQUENCE {
* command-value [0] ABSTRACT-SYNTAX.&Type, -- depends on ref property
* status-flags [1] BACnetStatusFlags
* feedback-value [2] ABSTRACT-SYNTAX.&Type -- depends on ref property
* },
* floating-limit [4] SEQUENCE {
* reference-value [0] REAL,
* status-flags [1] BACnetStatusFlags
* setpoint-value [2] REAL,
* error-limit [3] REAL
* },
* out-of-range [5] SEQUENCE {
* exceeding-value [0] REAL,
* status-flags [1] BACnetStatusFlags
* deadband [2] REAL,
* exceeded-limit [3] REAL
* },
* complex-event-type [6] SEQUENCE OF BACnetPropertyValue,
* -- complex tag 7 is deprecated
* change-of-life-safety [8] SEQUENCE {
* new-state [0] BACnetLifeSafetyState,
* new-mode [1] BACnetLifeSafetyState
* status-flags [2] BACnetStatusFlags,
* operation-expected [3] BACnetLifeSafetyOperation
* },
* extended [9] SEQUENCE {
* vendor-id [0] Unsigned16,
* extended-event-type [1] Unsigned,
* parameters [2] SEQUENCE OF CHOICE {
* null NULL,
* real REAL,
* integer Unsigned,
* boolean BOOLEAN,
* double Double,
* octet OCTET STRING,
* bitstring BIT STRING,
* enum ENUMERATED,
* propertyValue [0] BACnetDeviceObjectPropertyValue
* }
* },
* buffer-ready [10] SEQUENCE {
* buffer-property [0] BACnetDeviceObjectPropertyReference,
* previous-notification[1] Unsigned32,
* current-notification [2] BACneUnsigned32tDateTime
* },
* unsigned-range [11] SEQUENCE {
* exceeding-value [0] Unsigned,
* status-flags [1] BACnetStatusFlags,
* exceeded-limit [2] Unsigned
* },
* -- context tag 12 is reserved for future addenda
* access-event [13] SEQUENCE {
* access-event [0] BACnetAccessEvent,
* status-flags [1] BACnetStatusFlags,
* access-event-tag [2] Unsigned,
* access-event-time [3] BACnetTimeStamp,
* access-credential [4] BACnetDeviceObjectReference,
* authentication-factor [5] BACnetAuthenticationFactor OPTIONAL
* },
* double-out-of-range [14] SEQUENCE {
* exceeding-value [0] Double,
* status-flags [1] BACnetStatusFlags
* deadband [2] Double,
* exceeded-limit [3] Double
* },
* signed-out-of-range [15] SEQUENCE {
* exceeding-value [0] INTEGER,
* status-flags [1] BACnetStatusFlags
* deadband [2] Unsigned,
* exceeded-limit [3] INTEGER
* },
* unsigned-out-of-range [16] SEQUENCE {
* exceeding-value [0] Unsigned,
* status-flags [1] BACnetStatusFlags
* deadband [2] Unsigned,
* exceeded-limit [3] Unsigned
* },
* change-of-characterstring [17] SEQUENCE {
* changed-value [0] CharacterString,
* status-flags [1] BACnetStatusFlags
* alarm-value [2] CharacterString
* },
* change-of-status-flags [18] SEQUENCE {
* present-value [0] ABSTRACT-SYNTAX.&Type OPTIONAL,
* -- depends on referenced property
* referenced-flags [1] BACnetStatusFlags
* },
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fNotificationParameters(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetObjectPropertyReference ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fBACnetObjectPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
#if 0
/**
* BACnetObjectPropertyValue ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* propertyIdentifier [1] BACnetPropertyIdentifier,
* propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
* -- if omitted with an array the entire array is referenced
* value [3] ABSTRACT-SYNTAX.&Type, --any datatype appropriate for the specified property
* priority [4] Unsigned (1..16) OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fObjectPropertyValue(tvbuff_t *tvb, proto_tree *tree, guint offset);
#endif
/**
* BACnetPriorityArray ::= SEQUENCE SIZE (16) OF BACnetPriorityValue
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fPriorityArray(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
static guint
fPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 tagoffset, guint8 list);
/**
* BACnetPropertyReference ::= SEQUENCE {
* propertyIdentifier [0] BACnetPropertyIdentifier,
* propertyArrayIndex [1] Unsigned OPTIONAL, -- used only with array datatype
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fBACnetPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 list);
/* static guint
fBACnetObjectPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset); */
static guint
fLOPR(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
static guint
fRestartReason(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetPropertyValue ::= SEQUENCE {
* PropertyIdentifier [0] BACnetPropertyIdentifier,
* propertyArrayIndex [1] Unsigned OPTIONAL, -- used only with array datatypes
* -- if omitted with an array the entire array is referenced
* value [2] ABSTRACT-SYNTAX.&Type, -- any datatype appropriate for the specified property
* priority [3] Unsigned (1..16) OPTIONAL -- used only when property is commandable
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fBACnetPropertyValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
static guint
fPropertyValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 tagoffset);
/**
* BACnet Application PDUs chapter 21
* BACnetRecipient::= CHOICE {
* device [0] BACnetObjectIdentifier
* address [1] BACnetAddress
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fRecipient(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnet Application PDUs chapter 21
* BACnetRecipientProcess::= SEQUENCE {
* recipient [0] BACnetRecipient
* processID [1] Unsigned32
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fRecipientProcess(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
static guint
fCOVSubscription(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
#if 0
/**
* BACnetSessionKey ::= SEQUENCE {
* sessionKey OCTET STRING (SIZE(8)), -- 56 bits for key, 8 bits for checksum
* peerAddress BACnetAddress
* }
* @param tvb the tv buffer of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
* @todo check if checksum is displayed correctly
*/
static guint
fSessionKey(tvbuff_t *tvb, proto_tree *tree, guint offset);
#endif
/**
* BACnetSpecialEvent ::= SEQUENCE {
* period CHOICE {
* calendarEntry [0] BACnetCalendarEntry,
* calendarRefernce [1] BACnetObjectIdentifier
* },
* listOfTimeValues [2] SEQUENCE OF BACnetTimeValue,
* eventPriority [3] Unsigned (1..16)
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fSpecialEvent(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetTimeStamp ::= CHOICE {
* time [0] Time,
* sequenceNumber [1] Unsigned (0..65535),
* dateTime [2] BACnetDateTime
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @param label the label of this item
* @return modified offset
*/
static guint
fTimeStamp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
static guint
fEventTimeStamps(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnetTimeValue ::= SEQUENCE {
* time Time,
* value ABSTRACT-SYNTAX.&Type -- any primitive datatype, complex types cannot be decoded
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fTimeValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
#if 0
/**
* BACnetVTSession ::= SEQUENCE {
* local-vtSessionID Unsigned8,
* remote-vtSessionID Unsigned8,
* remote-vtAddress BACnetAddress
* }
* @param tvb the tv buffer of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fVTSession(tvbuff_t *tvb, proto_tree *tree, guint offset);
#endif
/**
* BACnetWeekNDay ::= OCTET STRING (SIZE (3))
* -- first octet month (1..12) January = 1, X'FF' = any month
* -- second octet weekOfMonth where: 1 = days numbered 1-7
* -- 2 = days numbered 8-14
* -- 3 = days numbered 15-21
* -- 4 = days numbered 22-28
* -- 5 = days numbered 29-31
* -- 6 = last 7 days of this month
* -- X'FF' = any week of this month
* -- third octet dayOfWeek (1..7) where 1 = Monday
* -- 7 = Sunday
* -- X'FF' = any day of week
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fWeekNDay(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReadAccessResult ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* listOfResults [1] SEQUENCE OF SEQUENCE {
* propertyIdentifier [2] BACnetPropertyIdentifier,
* propertyArrayIndex [3] Unsigned OPTIONAL, -- used only with array datatype if omitted with an array the entire array is referenced
* readResult CHOICE {
* propertyValue [4] ABSTRACT-SYNTAX.&Type,
* propertyAccessError [5] Error
* }
* } OPTIONAL
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReadAccessResult(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* ReadAccessSpecification ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* listOfPropertyReferences [1] SEQUENCE OF BACnetPropertyReference
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param subtree the subtree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fReadAccessSpecification(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset);
/**
* WriteAccessSpecification ::= SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* listOfProperty [1] SEQUENCE OF BACnetPropertyValue
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param subtree the sub tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fWriteAccessSpecification(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset);
/********************************************************* Helper functions *******************************************/
/**
* extracts the tag number from the tag header.
* @param tvb the tv buffer of the current data "TestyVirtualBuffer"
* @param offset the offset in the tvb in actual tvb
* @return Tag Number corresponding to BACnet 20.2.1.2 Tag Number
*/
static guint
fTagNo(tvbuff_t *tvb, guint offset);
/**
* splits Tag Header coresponding to 20.2.1 General Rules For BACnet Tags
* @param tvb the tv buffer of the current data = "TestyVirtualBuffer"
* @param pinfo the packet info of the current data = packet info
* @param offset the offset in the tvb = offset in actual tvb
* @return tag_no BACnet 20.2.1.2 Tag Number
* @return class_tag BACnet 20.2.1.1 Class
* @return lvt BACnet 20.2.1.3 Length/Value/Type
* @return offs = length of this header
*/
static guint
fTagHeader(tvbuff_t *tvb, packet_info *pinfo, guint offset, guint8 *tag_no, guint8* class_tag, guint32 *lvt);
/**
* adds processID with max 32Bit unsigned Integer Value to tree
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fProcessId(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* adds timeSpan with max 32Bit unsigned Integer Value to tree
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fTimeSpan(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* BACnet Application PDUs chapter 21
* BACnetPropertyIdentifier::= ENUMERATED {
* @see bacapp_property_identifier
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fPropertyIdentifier(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* BACnet Application PDUs chapter 21
* BACnetPropertyArrayIndex::= ENUMERATED {
* @see bacapp_property_array_index
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fPropertyArrayIndex(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* listOfEventSummaries ::= SEQUENCE OF SEQUENCE {
* objectIdentifier [0] BACnetObjectIdentifier,
* eventState [1] BACnetEventState,
* acknowledgedTransitions [2] BACnetEventTransitionBits,
* eventTimeStamps [3] SEQURNCE SIZE (3) OF BACnetTimeStamps,
* notifyType [4] BACnetNotifyType,
* eventEnable [5] BACnetEventTransitionBits,
* eventPriorities [6] SEQUENCE SIZE (3) OF Unsigned
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
flistOfEventSummaries(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* SelectionCriteria ::= SEQUENCE {
* propertyIdentifier [0] BACnetPropertyIdentifier,
* propertyArrayIndex [1] Unsigned OPTIONAL, -- used only with array datatype
* relationSpecifier [2] ENUMERATED { bacapp_relationSpecifier },
* comparisonValue [3] ABSTRACT-SYNTAX.&Type
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fSelectionCriteria(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* objectSelectionCriteria ::= SEQUENCE {
* selectionLogic [0] ENUMERATED { bacapp_selectionLogic },
* listOfSelectionCriteria [1] SelectionCriteria
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param subtree the sub tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fObjectSelectionCriteria(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset);
/**
* BACnet-Error ::= SEQUENCE {
* error-class ENUMERATED {},
* error-code ENUMERATED {}
* }
* }
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
*/
static guint
fError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
/**
* Generic handler for context tagged values. Mostly for handling
* vendor-defined properties and services.
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
* @todo beautify this ugly construct
*/
static guint
fContextTaggedValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label);
/**
* realizes some ABSTRACT-SYNTAX.&Type
* @param tvb the tv buffer of the current data
* @param pinfo the packet info of the current data
* @param tree the tree to append this item to
* @param offset the offset in the tvb
* @return modified offset
* @todo beautify this ugly construct
*/
static guint
fAbstractSyntaxNType(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset);
static guint
fBitStringTagVS(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label,
const value_string *src);
/**
* register_bacapp
*/
void
proto_register_bacapp(void);
/**
* proto_reg_handoff_bacapp
*/
void
proto_reg_handoff_bacapp(void);
/* <<<< formerly bacapp.h */
/* reassembly table for segmented messages */
static reassembly_table msg_reassembly_table;
/* some necessary forward function prototypes */
static guint
fApplicationTypesEnumerated(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset,
const gchar *label, const value_string *vs);
static const char *bacapp_unknown_service_str = "unknown service"; /* Usage: no format specifiers */
static const char ASHRAE_Reserved_Fmt[] = "(%d) Reserved for Use by ASHRAE";
static const char Vendor_Proprietary_Fmt[] = "(%d) Vendor Proprietary Value";
static const value_string
BACnetTypeName[] = {
{ 0, "Confirmed-REQ"},
{ 1, "Unconfirmed-REQ"},
{ 2, "Simple-ACK"},
{ 3, "Complex-ACK"},
{ 4, "Segment-ACK"},
{ 5, "Error"},
{ 6, "Reject"},
{ 7, "Abort"},
{ 0, NULL }
};
static const true_false_string segments_follow = {
"Segmented Request",
"Unsegmented Request"
};
static const true_false_string more_follow = {
"More Segments Follow",
"No More Segments Follow"
};
static const true_false_string segmented_accept = {
"Segmented Response accepted",
"Segmented Response not accepted"
};
static const true_false_string
BACnetTagClass = {
"Context Specific Tag",
"Application Tag"
};
static const value_string
BACnetMaxSegmentsAccepted [] = {
{ 0, "Unspecified"},
{ 1, "2 segments"},
{ 2, "4 segments"},
{ 3, "8 segments"},
{ 4, "16 segments"},
{ 5, "32 segments"},
{ 6, "64 segments"},
{ 7, "Greater than 64 segments"},
{ 0, NULL }
};
static const value_string
BACnetMaxAPDULengthAccepted [] = {
{ 0, "Up to MinimumMessageSize (50 octets)"},
{ 1, "Up to 128 octets"},
{ 2, "Up to 206 octets (fits in a LonTalk frame)"},
{ 3, "Up to 480 octets (fits in an ARCNET frame)"},
{ 4, "Up to 1024 octets"},
{ 5, "Up to 1476 octets (fits in an ISO 8802-3 frame)"},
{ 6, "reserved by ASHRAE"},
{ 7, "reserved by ASHRAE"},
{ 8, "reserved by ASHRAE"},
{ 9, "reserved by ASHRAE"},
{ 10, "reserved by ASHRAE"},
{ 11, "reserved by ASHRAE"},
{ 12, "reserved by ASHRAE"},
{ 13, "reserved by ASHRAE"},
{ 14, "reserved by ASHRAE"},
{ 15, "reserved by ASHRAE"},
{ 0, NULL}
};
static const value_string
BACnetRejectReason [] = {
{0, "other"},
{1, "buffer-overflow"},
{2, "inconsistent-parameters"},
{3, "invalid-parameter-data-type"},
{4, "invalid-tag"},
{5, "missing-required-parameter"},
{6, "parameter-out-of-range"},
{7, "too-many-arguments"},
{8, "undefined-enumeration"},
{9, "unrecognized-service"},
{0, NULL}
};
static const value_string
BACnetRestartReason [] = {
{ 0, "unknown"},
{ 1, "coldstart"},
{ 2, "warmstart"},
{ 3, "detected-power-lost"},
{ 4, "detected-powered-off"},
{ 5, "hardware-watchdog"},
{ 6, "software-watchdog"},
{ 7, "suspended"},
{ 0, NULL}
};
static const value_string
BACnetApplicationTagNumber [] = {
{ 0, "Null"},
{ 1, "Boolean"},
{ 2, "Unsigned Integer"},
{ 3, "Signed Integer (2's complement notation)"},
{ 4, "Real (ANSI/IEE-754 floating point)"},
{ 5, "Double (ANSI/IEE-754 double precision floating point)"},
{ 6, "Octet String"},
{ 7, "Character String"},
{ 8, "Bit String"},
{ 9, "Enumerated"},
{ 10, "Date"},
{ 11, "Time"},
{ 12, "BACnetObjectIdentifier"},
{ 13, "reserved by ASHRAE"},
{ 14, "reserved by ASHRAE"},
{ 15, "reserved by ASHRAE"},
{ 0, NULL}
};
static const value_string
BACnetAction [] = {
{ 0, "direct"},
{ 1, "reverse"},
{ 0, NULL}
};
static const value_string
BACnetAccessEvent [] = {
{ 0, "none"},
{ 1, "granted"},
{ 2, "muster"},
{ 3, "passback-detected"},
{ 4, "duress"},
{ 5, "trace"},
{ 6, "lockout-max-attempts"},
{ 7, "lockout-other"},
{ 8, "lockout-relinquished"},
{ 9, "lockout-by-higher-priority"},
{ 10, "out-of-service"},
{ 11, "out-of-service-relinquished"},
{ 12, "accompaniment-by"},
{ 13, "authentication-factor-read"},
{ 14, "authorization-delayed"},
{ 15, "verification-required"},
/* Enumerated values 128-511 are used for events
* which indicate that access has been denied. */
{ 128, "denied-deny-all"},
{ 129, "denied-unknown-credential"},
{ 130, "denied-authentication-unavailable"},
{ 131, "denied-authentication-factor-timeout"},
{ 132, "denied-incorrect-authentication-factor"},
{ 133, "denied-zone-no-access-rights"},
{ 134, "denied-point-no-access-rights"},
{ 135, "denied-no-access-rights"},
{ 136, "denied-out-of-time-range"},
{ 137, "denied-threat-level"},
{ 138, "denied-passback"},
{ 139, "denied-unexpected-location-usage"},
{ 140, "denied-max-attempts"},
{ 141, "denied-lower-occupancy-limit"},
{ 142, "denied-upper-occupancy-limit"},
{ 143, "denied-authentication-factor-lost"},
{ 144, "denied-authentication-factor-stolen"},
{ 145, "denied-authentication-factor-damaged"},
{ 146, "denied-authentication-factor-destroyed"},
{ 147, "denied-authentication-factor-disabled"},
{ 148, "denied-authentication-factor-error"},
{ 149, "denied-credential-unassigned"},
{ 150, "denied-credential-not-provisioned"},
{ 151, "denied-credential-not-yet-active"},
{ 152, "denied-credential-expired"},
{ 153, "denied-credential-manual-disable"},
{ 154, "denied-credential-lockout"},
{ 155, "denied-credential-max-days"},
{ 156, "denied-credential-max-uses"},
{ 157, "denied-credential-inactivity"},
{ 158, "denied-credential-disabled"},
{ 159, "denied-no-accompaniment"},
{ 160, "denied-incorrect-accompaniment"},
{ 161, "denied-lockout"},
{ 162, "denied-verification-failed"},
{ 163, "denied-verification-timeout"},
{ 164, "denied-other"},
{ 0, NULL}
/* Enumerated values 0-512 are reserved for definition by ASHRAE.
Enumerated values 512-65535 may be used by others subject to
procedures and constraints described in Clause 23. */
};
static const value_string
BACnetFileAccessMethod [] = {
{ 0, "record-access"},
{ 1, "stream-access"},
{ 0, NULL}
};
/* For some reason, BACnet defines the choice parameter
in the file read and write services backwards from the
BACnetFileAccessMethod enumeration.
*/
static const value_string
BACnetFileAccessOption [] = {
{ 0, "stream access"},
{ 1, "record access"},
{ 0, NULL}
};
static const value_string
BACnetFileStartOption [] = {
{ 0, "File Start Position: "},
{ 1, "File Start Record: "},
{ 0, NULL}
};
static const value_string
BACnetFileRequestCount [] = {
{ 0, "Requested Octet Count: "},
{ 1, "Requested Record Count: "},
{ 0, NULL}
};
static const value_string
BACnetFileWriteInfo [] = {
{ 0, "File Data: "},
{ 1, "Record Count: "},
{ 0, NULL}
};
static const value_string
BACnetAbortReason [] = {
{ 0, "other"},
{ 1, "buffer-overflow"},
{ 2, "invalid-apdu-in-this-state"},
{ 3, "preempted-by-higher-priority-task"},
{ 4, "segmentation-not-supported"},
{ 0, NULL}
};
static const value_string
BACnetLifeSafetyMode [] = {
{ 0, "off"},
{ 1, "on"},
{ 2, "test"},
{ 3, "manned"},
{ 4, "unmanned"},
{ 5, "armed"},
{ 6, "disarmed"},
{ 7, "prearmed"},
{ 8, "slow"},
{ 9, "fast"},
{ 10, "disconnected"},
{ 11, "enabled"},
{ 12, "disabled"},
{ 13, "atomic-release-disabled"},
{ 14, "default"},
{ 0, NULL}
/* Enumerated values 0-255 are reserved for definition by ASHRAE.
Enumerated values 256-65535 may be used by others subject to
procedures and constraints described in Clause 23. */
};
static const value_string
BACnetLifeSafetyOperation [] = {
{ 0, "none"},
{ 1, "silence"},
{ 2, "silence-audible"},
{ 3, "silence-visual"},
{ 4, "reset"},
{ 5, "reset-alarm"},
{ 6, "reset-fault"},
{ 7, "unsilence"},
{ 8, "unsilence-audible"},
{ 9, "unsilence-visual"},
{ 0, NULL}
/* Enumerated values 0-63 are reserved for definition by ASHRAE.
Enumerated values 64-65535 may be used by others subject to
procedures and constraints described in Clause 23. */
};
#if 0
static const value_string
BACnetLimitEnable [] = {
{ 0, "lowLimitEnable"},
{ 1, "highLimitEnable"},
{ 0, NULL}
};
#endif
static const value_string
BACnetLifeSafetyState [] = {
{ 0, "quiet"},
{ 1, "pre-alarm"},
{ 2, "alarm"},
{ 3, "fault"},
{ 4, "fault-pre-alarm"},
{ 5, "fault-alarm"},
{ 6, "not-ready"},
{ 7, "active"},
{ 8, "tamper"},
{ 9, "test-alarm"},
{ 10, "test-active"},
{ 11, "test-fault"},
{ 12, "test-fault-alarm"},
{ 13, "holdup"},
{ 14, "duress"},
{ 15, "tamper-alarm"},
{ 16, "abnormal"},
{ 17, "emergency-power"},
{ 18, "delayed"},
{ 19, "blocked"},
{ 20, "local-alarm"},
{ 21, "general-alarm"},
{ 22, "supervisory"},
{ 23, "test-supervisory"},
{ 0, NULL}
/* Enumerated values 0-255 are reserved for definition by ASHRAE.
Enumerated values 256-65535 may be used by others subject to
procedures and constraints described in Clause 23. */
};
static const value_string
BACnetConfirmedServiceChoice [] = {
{ 0, "acknowledgeAlarm"},
{ 1, "confirmedCOVNotification"},
{ 2, "confirmedEventNotification"},
{ 3, "getAlarmSummary"},
{ 4, "getEnrollmentSummary"},
{ 5, "subscribeCOV"},
{ 6, "atomicReadFile"},
{ 7, "atomicWriteFile"},
{ 8, "addListElement"},
{ 9, "removeListElement"},
{ 10, "createObject"},
{ 11, "deleteObject"},
{ 12, "readProperty"},
{ 13, "readPropertyConditional"},
{ 14, "readPropertyMultiple"},
{ 15, "writeProperty"},
{ 16, "writePropertyMultiple"},
{ 17, "deviceCommunicationControl"},
{ 18, "confirmedPrivateTransfer"},
{ 19, "confirmedTextMessage"},
{ 20, "reinitializeDevice"},
{ 21, "vtOpen"},
{ 22, "vtClose"},
{ 23, "vtData"},
{ 24, "authenticate"},
{ 25, "requestKey"},
{ 26, "readRange"},
{ 27, "lifeSafetyOperation"},
{ 28, "subscribeCOVProperty"},
{ 29, "getEventInformation"},
{ 30, "reserved by ASHRAE"},
{ 0, NULL}
};
static const value_string
BACnetReliability [] = {
{ 0, "no-fault-detected"},
{ 1, "no-sensor"},
{ 2, "over-range"},
{ 3, "under-range"},
{ 4, "open-loop"},
{ 5, "shorted-loop"},
{ 6, "no-output"},
{ 7, "unreliable-other"},
{ 8, "process-error"},
{ 9, "multi-state-fault"},
{ 10, "configuration-error"},
/* enumeration value 11 is reserved for a future addendum */
{ 12, "communication-failure"},
{ 13, "member-fault"},
{ 0, NULL}
};
static const value_string
BACnetUnconfirmedServiceChoice [] = {
{ 0, "i-Am"},
{ 1, "i-Have"},
{ 2, "unconfirmedCOVNotification"},
{ 3, "unconfirmedEventNotification"},
{ 4, "unconfirmedPrivateTransfer"},
{ 5, "unconfirmedTextMessage"},
{ 6, "timeSynchronization"},
{ 7, "who-Has"},
{ 8, "who-Is"},
{ 9, "utcTimeSynchronization"},
{ 0, NULL}
};
#if 0
static const value_string
BACnetUnconfirmedServiceRequest [] = {
{ 0, "i-Am-Request"},
{ 1, "i-Have-Request"},
{ 2, "unconfirmedCOVNotification-Request"},
{ 3, "unconfirmedEventNotification-Request"},
{ 4, "unconfirmedPrivateTransfer-Request"},
{ 5, "unconfirmedTextMessage-Request"},
{ 6, "timeSynchronization-Request"},
{ 7, "who-Has-Request"},
{ 8, "who-Is-Request"},
{ 9, "utcTimeSynchonization-Request"},
{ 0, NULL}
};
#endif
static const value_string
BACnetObjectType [] = {
{ 0, "analog-input"},
{ 1, "analog-output"},
{ 2, "analog-value"},
{ 3, "binary-input"},
{ 4, "binary-output"},
{ 5, "binary-value"},
{ 6, "calendar"},
{ 7, "command"},
{ 8, "device"},
{ 9, "event-enrollment"},
{ 10, "file"},
{ 11, "group"},
{ 12, "loop"},
{ 13, "multi-state-input"},
{ 14, "multi-state-output"},
{ 15, "notification-class"},
{ 16, "program"},
{ 17, "schedule"},
{ 18, "averaging"},
{ 19, "multi-state-value"},
{ 20, "trend-log"},
{ 21, "life-safety-point"},
{ 22, "life-safety-zone"},
{ 23, "accumulator"},
{ 24, "pulse-converter"},
{ 25, "event-log"},
{ 26, "global-group"},
{ 27, "trend-log-multiple"},
{ 28, "load-control"},
{ 29, "structured-view"},
{ 30, "access-door"}, /* 30-37 added with addanda 135-2008j */
/* value 31 is unassigned */
{ 32, "access-credential"},
{ 33, "access-point"},
{ 34, "access-rights"},
{ 35, "access-user"},
{ 36, "access-zone"},
{ 37, "credential-data-input"},
{ 38, "network-security"},
{ 39, "bitstring-value"}, /* 39-50 added with addenda 135-2008w */
{ 40, "characterstring-value"},
{ 41, "date-pattern-value"},
{ 42, "date-value"},
{ 43, "datetime-pattern-value"},
{ 44, "datetime-value"},
{ 45, "integer-value"},
{ 46, "large-analog-value"},
{ 47, "octetstring-value"},
{ 48, "positive-integer-value"},
{ 49, "time-pattern-value"},
{ 50, "time-value"},
{ 0, NULL}
/* Enumerated values 0-127 are reserved for definition by ASHRAE.
Enumerated values 128-1023 may be used by others subject to
the procedures and constraints described in Clause 23. */
};
static const value_string
BACnetEngineeringUnits [] = {
{ 0, "Sq Meters"},
{ 1, "Sq Feet"},
{ 2, "Milliamperes"},
{ 3, "Amperes"},
{ 4, "Ohms"},
{ 5, "Volts"},
{ 6, "Kilovolts"},
{ 7, "Megavolts"},
{ 8, "Volt Amperes"},
{ 9, "Kilovolt Amperes"},
{ 10, "Megavolt Amperes"},
{ 11, "Volt Amperes Reactive"},
{ 12, "Kilovolt Amperes Reactive"},
{ 13, "Megavolt Amperes Reactive"},
{ 14, "Degrees Phase"},
{ 15, "Power Factor"},
{ 16, "Joules"},
{ 17, "Kilojoules"},
{ 18, "Watt Hours"},
{ 19, "Kilowatt Hours"},
{ 20, "BTUs"},
{ 21, "Therms"},
{ 22, "Ton Hours"},
{ 23, "Joules Per Kg Dry Air"},
{ 24, "BTUs Per Pound Dry Air"},
{ 25, "Cycles Per Hour"},
{ 26, "Cycles Per Minute"},
{ 27, "Hertz"},
{ 28, "Grams Of Water Per Kilogram Dry Air"},
{ 29, "Relative Humidity"},
{ 30, "Millimeters"},
{ 31, "Meters"},
{ 32, "Inches"},
{ 33, "Feed"},
{ 34, "Watts Per Sq Foot"},
{ 35, "Watts Per Sq meter"},
{ 36, "Lumens"},
{ 37, "Lux"},
{ 38, "Foot Candles"},
{ 39, "Kilograms"},
{ 40, "Pounds Mass"},
{ 41, "Tons"},
{ 42, "Kgs per Second"},
{ 43, "Kgs Per Minute"},
{ 44, "Kgs Per Hour"},
{ 45, "Pounds Mass Per Minute"},
{ 46, "Pounds Mass Per Hour"},
{ 47, "Watt"},
{ 48, "Kilowatts"},
{ 49, "Megawatts"},
{ 50, "BTUs Per Hour"},
{ 51, "Horsepower"},
{ 52, "Tons Refrigeration"},
{ 53, "Pascals"},
{ 54, "Kilopascals"},
{ 55, "Bars"},
{ 56, "Pounds Force Per Square Inch"},
{ 57, "Centimeters Of Water"},
{ 58, "Inches Of Water"},
{ 59, "Millimeters Of Mercury"},
{ 60, "Centimeters Of Mercury"},
{ 61, "Inches Of Mercury"},
{ 62, "Degrees Celsius"},
{ 63, "Degrees Kelvin"},
{ 64, "Degrees Fahrenheit"},
{ 65, "Degree Days Celsius"},
{ 66, "Degree Days Fahrenheit"},
{ 67, "Years"},
{ 68, "Months"},
{ 69, "Weeks"},
{ 70, "Days"},
{ 71, "Hours"},
{ 72, "Minutes"},
{ 73, "Seconds"},
{ 74, "Meters Per Second"},
{ 75, "Kilometers Per Hour"},
{ 76, "Feed Per Second"},
{ 77, "Feet Per Minute"},
{ 78, "Miles Per Hour"},
{ 79, "Cubic Feet"},
{ 80, "Cubic Meters"},
{ 81, "Imperial Gallons"},
{ 82, "Liters"},
{ 83, "US Gallons"},
{ 84, "Cubic Feet Per Minute"},
{ 85, "Cubic Meters Per Second"},
{ 86, "Imperial Gallons Per Minute"},
{ 87, "Liters Per Second"},
{ 88, "Liters Per Minute"},
{ 89, "US Gallons Per Minute"},
{ 90, "Degrees Angular"},
{ 91, "Degrees Celsius Per Hour"},
{ 92, "Degrees Celsius Per Minute"},
{ 93, "Degrees Fahrenheit Per Hour"},
{ 94, "Degrees Fahrenheit Per Minute"},
{ 95, "No Units"},
{ 96, "Parts Per Million"},
{ 97, "Parts Per Billion"},
{ 98, "Percent"},
{ 99, "Pecent Per Second"},
{ 100, "Per Minute"},
{ 101, "Per Second"},
{ 102, "Psi Per Degree Fahrenheit"},
{ 103, "Radians"},
{ 104, "Revolutions Per Min"},
{ 105, "Currency1"},
{ 106, "Currency2"},
{ 107, "Currency3"},
{ 108, "Currency4"},
{ 109, "Currency5"},
{ 110, "Currency6"},
{ 111, "Currency7"},
{ 112, "Currency8"},
{ 113, "Currency9"},
{ 114, "Currency10"},
{ 115, "Sq Inches"},
{ 116, "Sq Centimeters"},
{ 117, "BTUs Per Pound"},
{ 118, "Centimeters"},
{ 119, "Pounds Mass Per Second"},
{ 120, "Delta Degrees Fahrenheit"},
{ 121, "Delta Degrees Kelvin"},
{ 122, "Kilohms"},
{ 123, "Megohms"},
{ 124, "Millivolts"},
{ 125, "Kilojoules Per Kg"},
{ 126, "Megajoules"},
{ 127, "Joules Per Degree Kelvin"},
{ 128, "Joules Per Kg Degree Kelvin"},
{ 129, "Kilohertz"},
{ 130, "Megahertz"},
{ 131, "Per Hour"},
{ 132, "Milliwatts"},
{ 133, "Hectopascals"},
{ 134, "Millibars"},
{ 135, "Cubic Meters Per Hour"},
{ 136, "Liters Per Hour"},
{ 137, "KWatt Hours Per Square Meter"},
{ 138, "KWatt Hours Per Square Foot"},
{ 139, "Megajoules Per Square Meter"},
{ 140, "Megajoules Per Square Foot"},
{ 141, "Watts Per Sq Meter Degree Kelvin"},
{ 142, "Cubic Feet Per Second"},
{ 143, "Percent Obstruction Per Foot"},
{ 144, "Percent Obstruction Per Meter"},
{ 145, "milliohms"},
{ 146, "megawatt-hours"},
{ 147, "kilo-btus"},
{ 148, "mega-btus"},
{ 149, "kilojoules-per-kilogram-dry-air"},
{ 150, "megajoules-per-kilogram-dry-air"},
{ 151, "kilojoules-per-degree-Kelvin"},
{ 152, "megajoules-per-degree-Kelvin"},
{ 153, "newton"},
{ 154, "grams-per-second"},
{ 155, "grams-per-minute"},
{ 156, "tons-per-hour"},
{ 157, "kilo-btus-per-hour"},
{ 158, "hundredths-seconds"},
{ 159, "milliseconds"},
{ 160, "newton-meters"},
{ 161, "millimeters-per-second"},
{ 162, "millimeters-per-minute"},
{ 163, "meters-per-minute"},
{ 164, "meters-per-hour"},
{ 165, "cubic-meters-per-minute"},
{ 166, "meters-per-second-per-second"},
{ 167, "amperes-per-meter"},
{ 168, "amperes-per-square-meter"},
{ 169, "ampere-square-meters"},
{ 170, "farads"},
{ 171, "henrys"},
{ 172, "ohm-meters"},
{ 173, "siemens"},
{ 174, "siemens-per-meter"},
{ 175, "teslas"},
{ 176, "volts-per-degree-Kelvin"},
{ 177, "volts-per-meter"},
{ 178, "webers"},
{ 179, "candelas"},
{ 180, "candelas-per-square-meter"},
{ 181, "degrees-Kelvin-per-hour"},
{ 182, "degrees-Kelvin-per-minute"},
{ 183, "joule-seconds"},
{ 184, "radians-per-second"},
{ 185, "square-meters-per-Newton"},
{ 186, "kilograms-per-cubic-meter"},
{ 187, "newton-seconds"},
{ 188, "newtons-per-meter"},
{ 189, "watts-per-meter-per-degree-Kelvin"},
{ 190, "micro-siemens"},
{ 191, "cubic-feet-per-hour"},
{ 192, "us-gallons-per-hour"},
{ 193, "kilometers"},
{ 194, "micrometers"},
{ 195, "grams"},
{ 196, "milligrams"},
{ 197, "milliliters"},
{ 198, "milliliters-per-second"},
{ 199, "decibels"},
{ 200, "decibels-millivolt"},
{ 201, "decibels-volt"},
{ 202, "millisiemens"},
{ 203, "watt-hours-reactive"},
{ 204, "kilowatt-hours-reactive"},
{ 205, "megawatt-hours-reactive"},
{ 206, "millimeters-of-water"},
{ 207, "per-mille"},
{ 208, "grams-per-gram"},
{ 209, "kilograms-per-kilogram"},
{ 210, "grams-per-kilogram"},
{ 211, "milligrams-per-gram"},
{ 212, "milligrams-per-kilogram"},
{ 213, "grams-per-milliliter"},
{ 214, "grams-per-liter"},
{ 215, "milligrams-per-liter"},
{ 216, "micrograms-per-liter"},
{ 217, "grams-per-cubic-meter"},
{ 218, "milligrams-per-cubic-meter"},
{ 219, "micrograms-per-cubic-meter"},
{ 220, "nanograms-per-cubic-meter"},
{ 221, "grams-per-cubic-centimeter"},
{ 222, "becquerels"},
{ 223, "kilobecquerels"},
{ 224, "megabecquerels"},
{ 225, "gray"},
{ 226, "milligray"},
{ 227, "microgray"},
{ 228, "sieverts"},
{ 229, "millisieverts"},
{ 230, "microsieverts"},
{ 231, "microsieverts-per-hour"},
{ 232, "decibels-a"},
{ 233, "nephelometric-turbidity-unit"},
{ 234, "pH"},
{ 235, "grams-per-square-meter"},
{ 236, "minutes-per-degree-kelvin"},
{ 0, NULL}
/* Enumerated values 0-255 are reserved for definition by ASHRAE.
Enumerated values 256-65535 may be used by others subject to
the procedures and constraints described in Clause 23. */
};
static const value_string
BACnetErrorCode [] = {
{ 0, "other"},
{ 1, "authentication-failed"},
{ 2, "configuration-in-progress"},
{ 3, "device-busy"},
{ 4, "dynamic-creation-not-supported"},
{ 5, "file-access-denied"},
{ 6, "incompatible-security-levels"},
{ 7, "inconsistent-parameters"},
{ 8, "inconsistent-selection-criterion"},
{ 9, "invalid-data-type"},
{ 10, "invalid-file-access-method"},
{ 11, "invalid-file-start-position"},
{ 12, "invalid-operator-name"},
{ 13, "invalid-parameter-data-type"},
{ 14, "invalid-time-stamp"},
{ 15, "key-generation-error"},
{ 16, "missing-required-parameter"},
{ 17, "no-objects-of-specified-type"},
{ 18, "no-space-for-object"},
{ 19, "no-space-to-add-list-element"},
{ 20, "no-space-to-write-property"},
{ 21, "no-vt-sessions-available"},
{ 22, "property-is-not-a-list"},
{ 23, "object-deletion-not-permitted"},
{ 24, "object-identifier-already-exists"},
{ 25, "operational-problem"},
{ 26, "password-failure"},
{ 27, "read-access-denied"},
{ 28, "security-not-supported"},
{ 29, "service-request-denied"},
{ 30, "timeout"},
{ 31, "unknown-object"},
{ 32, "unknown-property"},
{ 33, "removed enumeration"},
{ 34, "unknown-vt-class"},
{ 35, "unknown-vt-session"},
{ 36, "unsupported-object-type"},
{ 37, "value-out-of-range"},
{ 38, "vt-session-already-closed"},
{ 39, "vt-session-termination-failure"},
{ 40, "write-access-denied"},
{ 41, "character-set-not-supported"},
{ 42, "invalid-array-index"},
{ 43, "cov-subscription-failed"},
{ 44, "not-cov-property"},
{ 45, "optional-functionality-not-supported"},
{ 46, "invalid-configuration-data"},
{ 47, "datatype-not-supported"},
{ 48, "duplicate-name"},
{ 49, "duplicate-object-id"},
{ 50, "property-is-not-an-array"},
{ 73, "invalid-event-state"},
{ 74, "no-alarm-configured"},
{ 75, "log-buffer-full"},
{ 76, "logged-value-purged"},
{ 77, "no-property-specified"},
{ 78, "not-configured-for-triggered-logging"},
{ 79, "unknown-subscription"},
{ 80, "parameter-out-of-range"},
{ 81, "list-element-not-found"},
{ 82, "busy"},
{ 83, "communication-disabled"},
{ 84, "success"},
{ 85, "access-denied"},
{ 86, "bad-destination-address"},
{ 87, "bad-destination-device-id"},
{ 88, "bad-signature"},
{ 89, "bad-source-address"},
{ 90, "bad-timestamp"},
{ 91, "cannot-use-key"},
{ 92, "cannot-verify-message-id"},
{ 93, "correct-key-revision"},
{ 94, "destination-device-id-required"},
{ 95, "duplicate-message"},
{ 96, "encryption-not-configured"},
{ 97, "encryption-required"},
{ 98, "incorrect-key"},
{ 99, "invalid-key-data"},
{ 100, "key-update-in-progress"},
{ 101, "malformed-message"},
{ 102, "not-key-server"},
{ 103, "security-not-configured"},
{ 104, "source-security-required"},
{ 105, "too-many-keys"},
{ 106, "unknown-authentication-type"},
{ 107, "unknown-key"},
{ 108, "unknown-key-revision"},
{ 109, "unknown-source-message"},
{ 110, "not-router-to-dnet"},
{ 111, "router-busy"},
{ 112, "unknown-network-message"},
{ 113, "message-too-long"},
{ 114, "security-error"},
{ 115, "addressing-error"},
{ 116, "write-bdt-failed"},
{ 117, "read-bdt-failed"},
{ 118, "register-foreign-device-failed"},
{ 119, "read-fdt-failed"},
{ 120, "delete-fdt-entry-failed"},
{ 121, "distribute-broadcast-failed"},
{ 122, "unknown-file-size"},
{ 123, "abort-apdu-too-long"},
{ 124, "abort-application-exceeded-reply-time"},
{ 125, "abort-out-of-resources"},
{ 126, "abort-tsm-timeout"},
{ 127, "abort-window-size-out-of-range"},
{ 128, "file-full"},
{ 129, "inconsistent-configuration"},
{ 130, "inconsistent-object-type"},
{ 131, "internal-error"},
{ 132, "not-configured"},
{ 133, "out-of-memory"},
{ 134, "value-too-long"},
{ 135, "abort-insufficient-security"},
{ 136, "abort-security-error"},
{ 0, NULL}
/* Enumerated values 0-255 are reserved for definition by ASHRAE.
Enumerated values 256-65535 may be used by others subject to the
procedures and constraints described in Clause 23. */
};
static const value_string
BACnetPropertyIdentifier [] = {
{ 0, "acked-transition"},
{ 1, "ack-required"},
{ 2, "action"},
{ 3, "action-text"},
{ 4, "active-text"},
{ 5, "active-vt-session"},
{ 6, "alarm-value"},
{ 7, "alarm-values"},
{ 8, "all"},
{ 9, "all-write-successful"},
{ 10, "apdu-segment-timeout"},
{ 11, "apdu-timeout"},
{ 12, "application-software-version"},
{ 13, "archive"},
{ 14, "bias"},
{ 15, "change-of-state-count"},
{ 16, "change-of-state-time"},
{ 17, "notification-class"},
{ 18, "the property in this place was deleted"},
{ 19, "controlled-variable-reference"},
{ 20, "controlled-variable-units"},
{ 21, "controlled-variable-value"},
{ 22, "cov-increment"},
{ 23, "datelist"},
{ 24, "daylights-savings-status"},
{ 25, "deadband"},
{ 26, "derivative-constant"},
{ 27, "derivative-constant-units"},
{ 28, "description"},
{ 29, "description-of-halt"},
{ 30, "device-address-binding"},
{ 31, "device-type"},
{ 32, "effective-period"},
{ 33, "elapsed-active-time"},
{ 34, "error-limit"},
{ 35, "event-enable"},
{ 36, "event-state"},
{ 37, "event-type"},
{ 38, "exception-schedule"},
{ 39, "fault-values"},
{ 40, "feedback-value"},
{ 41, "file-access-method"},
{ 42, "file-size"},
{ 43, "file-type"},
{ 44, "firmware-revision"},
{ 45, "high-limit"},
{ 46, "inactive-text"},
{ 47, "in-progress"},
{ 48, "instance-of"},
{ 49, "integral-constant"},
{ 50, "integral-constant-units"},
{ 51, "issue-confirmed-notifications"},
{ 52, "limit-enable"},
{ 53, "list-of-group-members"},
{ 54, "list-of-object-property-references"},
{ 55, "list-of-session-keys"},
{ 56, "local-date"},
{ 57, "local-time"},
{ 58, "location"},
{ 59, "low-limit"},
{ 60, "manipulated-variable-reference"},
{ 61, "maximum-output"},
{ 62, "max-apdu-length-accepted"},
{ 63, "max-info-frames"},
{ 64, "max-master"},
{ 65, "max-pres-value"},
{ 66, "minimum-off-time"},
{ 67, "minimum-on-time"},
{ 68, "minimum-output"},
{ 69, "min-pres-value"},
{ 70, "model-name"},
{ 71, "modification-date"},
{ 72, "notify-type"},
{ 73, "number-of-APDU-retries"},
{ 74, "number-of-states"},
{ 75, "object-identifier"},
{ 76, "object-list"},
{ 77, "object-name"},
{ 78, "object-property-reference"},
{ 79, "object-type"},
{ 80, "optional"},
{ 81, "out-of-service"},
{ 82, "output-units"},
{ 83, "event-parameters"},
{ 84, "polarity"},
{ 85, "present-value"},
{ 86, "priority"},
{ 87, "priority-array"},
{ 88, "priority-for-writing"},
{ 89, "process-identifier"},
{ 90, "program-change"},
{ 91, "program-location"},
{ 92, "program-state"},
{ 93, "proportional-constant"},
{ 94, "proportional-constant-units"},
{ 95, "protocol-conformance-class"},
{ 96, "protocol-object-types-supported"},
{ 97, "protocol-services-supported"},
{ 98, "protocol-version"},
{ 99, "read-only"},
{ 100, "reason-for-halt"},
{ 101, "recipient"},
{ 102, "recipient-list"},
{ 103, "reliability"},
{ 104, "relinquish-default"},
{ 105, "required"},
{ 106, "resolution"},
{ 107, "segmentation-supported"},
{ 108, "setpoint"},
{ 109, "setpoint-reference"},
{ 110, "state-text"},
{ 111, "status-flags"},
{ 112, "system-status"},
{ 113, "time-delay"},
{ 114, "time-of-active-time-reset"},
{ 115, "time-of-state-count-reset"},
{ 116, "time-synchronization-recipients"},
{ 117, "units"},
{ 118, "update-interval"},
{ 119, "utc-offset"},
{ 120, "vendor-identifier"},
{ 121, "vendor-name"},
{ 122, "vt-class-supported"},
{ 123, "weekly-schedule"},
{ 124, "attempted-samples"},
{ 125, "average-value"},
{ 126, "buffer-size"},
{ 127, "client-cov-increment"},
{ 128, "cov-resubscription-interval"},
{ 129, "current-notify-time"},
{ 130, "event-time-stamp"},
{ 131, "log-buffer"},
{ 132, "log-device-object-property"},
{ 133, "enable"}, /* per ANSI/ASHRAE 135-2004 addendum B */
{ 134, "log-interval"},
{ 135, "maximum-value"},
{ 136, "minimum-value"},
{ 137, "notification-threshold"},
{ 138, "previous-notify-time"},
{ 139, "protocol-revision"},
{ 140, "records-since-notification"},
{ 141, "record-count"},
{ 142, "start-time"},
{ 143, "stop-time"},
{ 144, "stop-when-full"},
{ 145, "total-record-count"},
{ 146, "valid-samples"},
{ 147, "window-interval"},
{ 148, "window-samples"},
{ 149, "maximum-value-time-stamp"},
{ 150, "minimum-value-time-stamp"},
{ 151, "variance-value"},
{ 152, "active-cov-subscriptions"},
{ 153, "backup-failure-timeout"},
{ 154, "configuration-files"},
{ 155, "database-revision"},
{ 156, "direct-reading"},
{ 157, "last-restore-time"},
{ 158, "maintenance-required"},
{ 159, "member-of"},
{ 160, "mode"},
{ 161, "operation-expected"},
{ 162, "setting"},
{ 163, "silenced"},
{ 164, "tracking-value"},
{ 165, "zone-members"},
{ 166, "life-safety-alarm-values"},
{ 167, "max-segments-accepted"},
{ 168, "profile-name"},
{ 169, "auto-slave-discovery"},
{ 170, "manual-slave-address-binding"},
{ 171, "slave-address-binding"},
{ 172, "slave-proxy-enable"},
{ 173, "last-notify-record"}, /* bug 4117 */
{ 174, "schedule-default"},
{ 175, "accepted-modes"},
{ 176, "adjust-value"},
{ 177, "count"},
{ 178, "count-before-change"},
{ 179, "count-change-time"},
{ 180, "cov-period"},
{ 181, "input-reference"},
{ 182, "limit-monitoring-interval"},
{ 183, "logging-device"},
{ 184, "logging-record"},
{ 185, "prescale"},
{ 186, "pulse-rate"},
{ 187, "scale"},
{ 188, "scale-factor"},
{ 189, "update-time"},
{ 190, "value-before-change"},
{ 191, "value-set"},
{ 192, "value-change-time"},
{ 193, "align-intervals"},
{ 194, "group-member-names"},
{ 195, "interval-offset"},
{ 196, "last-restart-reason"},
{ 197, "logging-type"},
{ 198, "member-status-flags"},
{ 199, "notification-period"},
{ 200, "previous-notify-record"},
{ 201, "requested-update-interval"},
{ 202, "restart-notification-recipients"},
{ 203, "time-of-device-restart"},
{ 204, "time-synchronization-interval"},
{ 205, "trigger"},
{ 206, "UTC-time-synchronization-recipients"},
{ 207, "node-subtype"},
{ 208, "node-type"},
{ 209, "structured-object-list"},
{ 210, "subordinate-annotations"},
{ 211, "subordinate-list"},
{ 212, "actual-shed-level"},
{ 213, "duty-window"},
{ 214, "expected-shed-level"},
{ 215, "full-duty-baseline"},
{ 216, "node-subtype"},
{ 217, "node-type"},
{ 218, "requested-shed-level"},
{ 219, "shed-duration"},
{ 220, "shed-level-descriptions"},
{ 221, "shed-levels"},
{ 222, "state-description"},
/* enumeration values 223-225 are unassigned */
{ 226, "door-alarm-state"},
{ 227, "door-extended-pulse-time"},
{ 228, "door-members"},
{ 229, "door-open-too-long-time"},
{ 230, "door-pulse-time"},
{ 231, "door-status"},
{ 232, "door-unlock-delay-time"},
{ 233, "lock-status"},
{ 234, "masked-alarm-values"},
{ 235, "secured-status"},
/* enumeration values 236-243 are unassigned */
{ 244, "absentee-limit"}, /* added with addenda 135-2008j */
{ 245, "access-alarm-events"},
{ 246, "access-doors"},
{ 247, "access-event"},
{ 248, "access-event-authentication-factor"},
{ 249, "access-event-credential"},
{ 250, "access-event-time"},
{ 251, "access-transaction-events"},
{ 252, "accompaniment"},
{ 253, "accompaniment-time"},
{ 254, "activation-time"},
{ 255, "active-authentication-policy"},
{ 256, "assigned-access-rights"},
{ 257, "authentication-factors"},
{ 258, "authentication-policy-list"},
{ 259, "authentication-policy-names"},
{ 260, "authentication-status"},
{ 261, "authorization-mode"},
{ 262, "belongs-to"},
{ 263, "credential-disable"},
{ 264, "credential-status"},
{ 265, "credentials"},
{ 266, "credentials-in-zone"},
{ 267, "days-remaining"},
{ 268, "entry-points"},
{ 269, "exit-points"},
{ 270, "expiry-time"},
{ 271, "extended-time-enable"},
{ 272, "failed-attempt-events"},
{ 273, "failed-attempts"},
{ 274, "failed-attempts-time"},
{ 275, "last-access-event"},
{ 276, "last-access-point"},
{ 277, "last-credential-added"},
{ 278, "last-credential-added-time"},
{ 279, "last-credential-removed"},
{ 280, "last-credential-removed-time"},
{ 281, "last-use-time"},
{ 282, "lockout"},
{ 283, "lockout-relinquish-time"},
{ 284, "master-exemption"},
{ 285, "max-failed-attempts"},
{ 286, "members"},
{ 287, "muster-point"},
{ 288, "negative-access-rules"},
{ 289, "number-of-authentication-policies"},
{ 290, "occupancy-count"},
{ 291, "occupancy-count-adjust"},
{ 292, "occupancy-count-enable"},
{ 293, "occupancy-exemption"},
{ 294, "occupancy-lower-limit"},
{ 295, "occupancy-lower-limit-enforced"},
{ 296, "occupancy-state"},
{ 297, "occupancy-upper-limit"},
{ 298, "occupancy-upper-limit-enforced"},
{ 299, "passback-exemption"},
{ 300, "passback-mode"},
{ 301, "passback-timeout"},
{ 302, "positive-access-rules"},
{ 303, "reason-for-disable"},
{ 304, "supported-formats"},
{ 305, "supported-format-classes"},
{ 306, "threat-authority"},
{ 307, "threat-level"},
{ 308, "trace-flag"},
{ 309, "transaction-notification-class"},
{ 310, "user-external-identifier"},
{ 311, "user-information-reference"},
/* enumeration values 312-316 are unassigned */
{ 317, "user-name"},
{ 318, "user-type"},
{ 319, "uses-remaining"},
{ 320, "zone-from"},
{ 321, "zone-to"},
{ 322, "access-event-tag"},
{ 323, "global-identifier"},
/* enumeration values 324-325 reserved for future addenda */
{ 326, "verification-time"},
{ 327, "base-device-security-policy"},
{ 328, "distribution-key-revision"},
{ 329, "do-not-hide"},
{ 330, "key-sets"},
{ 331, "last-key-server"},
{ 332, "network-access-security-policies"},
{ 333, "packet-reorder-time"},
{ 334, "security-pdu-timeout"},
{ 335, "security-time-window"},
{ 336, "supported-security-algorithms"},
{ 337, "update-key-set-timeout"},
{ 338, "backup-and-restore-state"},
{ 339, "backup-preparation-time"},
{ 340, "restore-completion-time"},
{ 341, "restore-preparation-time"},
{ 342, "bit-mask"}, /* addenda 135-2008w */
{ 343, "bit-text"},
{ 344, "is-utc"},
{ 345, "group-members"},
{ 346, "group-member-names"},
{ 347, "member-status-flags"},
{ 348, "requested-update-interval"},
{ 349, "covu-period"},
{ 350, "covu-recipients"},
{ 351, "event-message-texts"},
{ 0, NULL}
/* Enumerated values 0-511 are reserved for definition by ASHRAE.
Enumerated values 512-4194303 may be used by others subject to
the procedures and constraints described in Clause 23. */
};
static const value_string
BACnetBinaryPV [] = {
{ 0, "inactive"},
{ 1, "active"},
{ 0, NULL}
};
#define ANSI_X3_4 0 /* ANSI X3.4, a/k/a "ASCII"; full UTF-8 since 2010 */
/* See, for example, ANSI/ASHRAE Addendum k to ANSI/ASHRAE Standard 135-2008 */
/* XXX - I've seen captures using this for ISO 8859-1 */
#define IBM_MS_DBCS 1 /* "IBM/Microsoft DBCS"; was there only one such DBCS? */
#define JIS_C_6226 2 /* JIS C 6226 */
#define ISO_10646_UCS4 3 /* ISO 10646 (UCS-4) - 4-byte Unicode */
#define ISO_10646_UCS2 4 /* ISO 10646 (UCS-2) - 2-byte Unicode Basic Multilingual Plane (not UTF-16, presumably) */
#define ISO_8859_1 5 /* ISO 8859-1 */
static const value_string
BACnetCharacterSet [] = {
{ ANSI_X3_4, "ANSI X3.4 / UTF-8 (since 2010)"},
{ IBM_MS_DBCS, "IBM/Microsoft DBCS"},
{ JIS_C_6226, "JIS C 6226"},
{ ISO_10646_UCS4, "ISO 10646 (UCS-4)"},
{ ISO_10646_UCS2, "ISO 10646 (UCS-2)"},
{ ISO_8859_1, "ISO 8859-1"},
{ 0, NULL}
};
static const value_string
BACnetStatusFlags [] = {
{ 0, "in-alarm"},
{ 1, "fault"},
{ 2, "overridden"},
{ 3, "out-of-service"},
{ 0, NULL}
};
static const value_string
BACnetMessagePriority [] = {
{ 0, "normal"},
{ 1, "urgent"},
{ 0, NULL}
};
static const value_string
BACnetAcknowledgementFilter [] = {
{ 0, "all"},
{ 1, "acked"},
{ 2, "not-acked"},
{ 0, NULL}
};
static const value_string
BACnetResultFlags [] = {
{ 0, "firstitem"},
{ 1, "lastitem"},
{ 2, "moreitems"},
{ 0, NULL}
};
static const value_string
BACnetRelationSpecifier [] = {
{ 0, "equal"},
{ 1, "not-equal"},
{ 2, "less-than"},
{ 3, "greater-than"},
{ 4, "less-than-or-equal"},
{ 5, "greater-than-or-equal"},
{ 0, NULL}
};
static const value_string
BACnetSelectionLogic [] = {
{ 0, "and"},
{ 1, "or"},
{ 2, "all"},
{ 0, NULL}
};
static const value_string
BACnetEventStateFilter [] = {
{ 0, "offnormal"},
{ 1, "fault"},
{ 2, "normal"},
{ 3, "all"},
{ 4, "active"},
{ 0, NULL}
};
static const value_string
BACnetEventTransitionBits [] = {
{ 0, "to-offnormal"},
{ 1, "to-fault"},
{ 2, "to-normal"},
{ 0, NULL}
};
static const value_string
BACnetSegmentation [] = {
{ 0, "segmented-both"},
{ 1, "segmented-transmit"},
{ 2, "segmented-receive"},
{ 3, "no-segmentation"},
{ 0, NULL}
};
static const value_string
BACnetSilencedState [] = {
{ 0, "unsilenced"},
{ 1, "audible-silenced"},
{ 2, "visible-silenced"},
{ 3, "all-silenced"},
{ 0, NULL}
};
static const value_string
BACnetDeviceStatus [] = {
{ 0, "operational"},
{ 1, "operational-read-only"},
{ 2, "download-required"},
{ 3, "download-in-progress"},
{ 4, "non-operational"},
{ 5, "backup-in-progress"},
{ 0, NULL}
};
static const value_string
BACnetEnableDisable [] = {
{ 0, "enable"},
{ 1, "disable"},
{ 2, "disable-initiation"},
{ 0, NULL}
};
static const value_string
months [] = {
{ 1, "January" },
{ 2, "February" },
{ 3, "March" },
{ 4, "April" },
{ 5, "May" },
{ 6, "June" },
{ 7, "July" },
{ 8, "August" },
{ 9, "September" },
{ 10, "October" },
{ 11, "November" },
{ 12, "December" },
{ 255, "any month" },
{ 0, NULL }
};
static const value_string
weekofmonth [] = {
{ 1, "days numbered 1-7" },
{ 2, "days numbered 8-14" },
{ 3, "days numbered 15-21" },
{ 4, "days numbered 22-28" },
{ 5, "days numbered 29-31" },
{ 6, "last 7 days of this month" },
{ 255, "any week of this month" },
{ 0, NULL }
};
/* note: notification class object recipient-list uses
different day-of-week enum */
static const value_string
day_of_week [] = {
{ 1, "Monday" },
{ 2, "Tuesday" },
{ 3, "Wednesday" },
{ 4, "Thursday" },
{ 5, "Friday" },
{ 6, "Saturday" },
{ 7, "Sunday" },
{ 255, "any day of week" },
{ 0, NULL }
};
static const value_string
BACnetErrorClass [] = {
{ 0, "device" },
{ 1, "object" },
{ 2, "property" },
{ 3, "resources" },
{ 4, "security" },
{ 5, "services" },
{ 6, "vt" },
{ 7, "communication" },
{ 0, NULL }
/* Enumerated values 0-63 are reserved for definition by ASHRAE.
Enumerated values64-65535 may be used by others subject to
the procedures and constraints described in Clause 23. */
};
static const value_string
BACnetVTClass [] = {
{ 0, "default-terminal" },
{ 1, "ansi-x3-64" },
{ 2, "dec-vt52" },
{ 3, "dec-vt100" },
{ 4, "dec-vt200" },
{ 5, "hp-700-94" },
{ 6, "ibm-3130" },
{ 0, NULL }
};
static const value_string
BACnetEventType [] = {
{ 0, "change-of-bitstring" },
{ 1, "change-of-state" },
{ 2, "change-of-value" },
{ 3, "command-failure" },
{ 4, "floating-limit" },
{ 5, "out-of-range" },
{ 6, "complex-event-type" },
{ 7, "(deprecated)buffer-ready" },
{ 8, "change-of-life-safety" },
{ 9, "extended" },
{ 10, "buffer-ready" },
{ 11, "unsigned-range" },
{ 14, "double-out-of-range"}, /* added with addenda 135-2008w */
{ 15, "signed-out-of-range"},
{ 16, "unsigned-out-of-range"},
{ 17, "change-of-characterstring"},
{ 18, "change-of-status-flags"},
{ 0, NULL }
/* Enumerated values 0-63 are reserved for definition by ASHRAE.
Enumerated values 64-65535 may be used by others subject to
the procedures and constraints described in Clause 23.
It is expected that these enumerated values will correspond
to the use of the complex-event-type CHOICE [6] of the
BACnetNotificationParameters production. */
};
static const value_string
BACnetEventState [] = {
{ 0, "normal" },
{ 1, "fault" },
{ 2, "offnormal" },
{ 3, "high-limit" },
{ 4, "low-limit" },
{ 5, "life-safety-alarm" },
{ 0, NULL }
/* Enumerated values 0-63 are reserved for definition by ASHRAE.
Enumerated values 64-65535 may be used by others subject to
the procedures and constraints described in Clause 23. */
};
static const value_string
BACnetLogStatus [] = {
{ 0, "log-disabled" },
{ 1, "buffer-purged" },
{ 2, "log-interrupted"},
{ 0, NULL }
};
static const value_string
BACnetMaintenance [] = {
{ 0, "none" },
{ 1, "periodic-test" },
{ 2, "need-service-operational" },
{ 3, "need-service-inoperative" },
{ 0, NULL }
};
static const value_string
BACnetNotifyType [] = {
{ 0, "alarm" },
{ 1, "event" },
{ 2, "ack-notification" },
{ 0, NULL }
};
static const value_string
BACnetServicesSupported [] = {
{ 0, "acknowledgeAlarm"},
{ 1, "confirmedCOVNotification"},
{ 2, "confirmedEventNotification"},
{ 3, "getAlarmSummary"},
{ 4, "getEnrollmentSummary"},
{ 5, "subscribeCOV"},
{ 6, "atomicReadFile"},
{ 7, "atomicWriteFile"},
{ 8, "addListElement"},
{ 9, "removeListElement"},
{ 10, "createObject"},
{ 11, "deleteObject"},
{ 12, "readProperty"},
{ 13, "readPropertyConditional"},
{ 14, "readPropertyMultiple"},
{ 15, "writeProperty"},
{ 16, "writePropertyMultiple"},
{ 17, "deviceCommunicationControl"},
{ 18, "confirmedPrivateTransfer"},
{ 19, "confirmedTextMessage"},
{ 20, "reinitializeDevice"},
{ 21, "vtOpen"},
{ 22, "vtClose"},
{ 23, "vtData"},
{ 24, "authenticate"},
{ 25, "requestKey"},
{ 26, "i-Am"},
{ 27, "i-Have"},
{ 28, "unconfirmedCOVNotification"},
{ 29, "unconfirmedEventNotification"},
{ 30, "unconfirmedPrivateTransfer"},
{ 31, "unconfirmedTextMessage"},
{ 32, "timeSynchronization"},
{ 33, "who-Has"},
{ 34, "who-Is"},
{ 35, "readRange"},
{ 36, "utcTimeSynchronization"},
{ 37, "lifeSafetyOperation"},
{ 38, "subscribeCOVProperty"},
{ 39, "getEventInformation"},
{ 0, NULL}
};
static const value_string
BACnetPropertyStates [] = {
{ 0, "boolean-value"},
{ 1, "binary-value"},
{ 2, "event-type"},
{ 3, "polarity"},
{ 4, "program-change"},
{ 5, "program-state"},
{ 6, "reason-for-halt"},
{ 7, "reliability"},
{ 8, "state"},
{ 9, "system-status"},
{ 10, "units"},
{ 11, "unsigned-value"},
{ 12, "life-safety-mode"},
{ 13, "life-safety-state"},
{ 14, "restart-reason"},
{ 15, "door-alarm-state"},
{ 16, "action"},
{ 17, "door-secured-status"},
{ 18, "door-status"},
{ 19, "door-value"},
{ 20, "file-access-method"},
{ 21, "lock-status"},
{ 22, "life-safety-operation"},
{ 23, "maintenance"},
{ 24, "node-type"},
{ 25, "notify-type"},
{ 26, "security-level"},
{ 27, "shed-state"},
{ 28, "silenced-state"},
/* context tag 29 reserved for future addenda */
{ 29, "unknown-29"},
{ 30, "access-event"},
{ 31, "zone-occupancy-state"},
{ 32, "access-credential-disable-reason"},
{ 33, "access-credential-disable"},
{ 34, "authentication-status"},
{ 35, "unknown-35"},
{ 36, "backup-state"},
{ 0, NULL}
/* Tag values 0-63 are reserved for definition by ASHRAE.
Tag values of 64-254 may be used by others to accommodate
vendor specific properties that have discrete or enumerated values,
subject to the constraints described in Clause 23. */
};
static const value_string
BACnetProgramError [] = {
{ 0, "normal"},
{ 1, "load-failed"},
{ 2, "internal"},
{ 3, "program"},
{ 4, "other"},
{ 0, NULL}
/* Enumerated values 0-63 are reserved for definition by ASHRAE.
Enumerated values 64-65535 may be used by others subject to
the procedures and constraints described in Clause 23. */
};
static const value_string
BACnetProgramRequest [] = {
{ 0, "ready"},
{ 1, "load"},
{ 2, "run"},
{ 3, "halt"},
{ 4, "restart"},
{ 4, "unload"},
{ 0, NULL}
};
static const value_string
BACnetProgramState [] = {
{ 0, "idle"},
{ 1, "loading"},
{ 2, "running"},
{ 3, "waiting"},
{ 4, "halted"},
{ 4, "unloading"},
{ 0, NULL}
};
static const value_string
BACnetReinitializedStateOfDevice [] = {
{ 0, "coldstart"},
{ 1, "warmstart"},
{ 2, "startbackup"},
{ 3, "endbackup"},
{ 4, "startrestore"},
{ 5, "endrestore"},
{ 6, "abortrestore"},
{ 0, NULL}
};
static const value_string
BACnetPolarity [] = {
{ 0, "normal"},
{ 1, "reverse"},
{ 0, NULL}
};
static const value_string
BACnetTagNames[] = {
{ 5, "Extended Value" },
{ 6, "Opening Tag" },
{ 7, "Closing Tag" },
{ 0, NULL }
};
static const value_string
BACnetReadRangeOptions[] = {
{ 3, "range byPosition" },
{ 4, "range byTime" },
{ 5, "range timeRange" },
{ 6, "range bySequenceNumber" },
{ 7, "range byTime" },
{ 0, NULL }
};
/* Present_Value for Load Control Object */
static const value_string
BACnetShedState[] = {
{ 0, "shed-inactive" },
{ 1, "shed-request-pending" },
{ 2, "shed-compliant" },
{ 3, "shed-non-compliant" },
{ 0, NULL }
};
static const value_string
BACnetNodeType [] = {
{ 0, "unknown" },
{ 1, "system" },
{ 2, "network" },
{ 3, "device" },
{ 4, "organizational" },
{ 5, "area" },
{ 6, "equipment" },
{ 7, "point" },
{ 8, "collection" },
{ 9, "property" },
{ 10, "functional" },
{ 11, "other" },
{ 0, NULL }
};
static const value_string
BACnetLoggingType [] = {
{ 0, "polled" },
{ 1, "cov" },
{ 2, "triggered" },
{ 0, NULL }
};
static const value_string
BACnetDoorStatus [] = {
{ 0, "closed" },
{ 1, "opened" },
{ 2, "unknown" },
{ 0, NULL }
};
static const value_string
BACnetLockStatus [] = {
{ 0, "locked" },
{ 1, "unlocked" },
{ 2, "fault" },
{ 3, "unknown" },
{ 0, NULL }
};
static const value_string
BACnetDoorSecuredStatus [] = {
{ 0, "secured" },
{ 1, "unsecured" },
{ 2, "unknown" },
{ 0, NULL }
};
static const value_string
BACnetDoorAlarmState [] = {
{ 0, "normal" },
{ 1, "alarm" },
{ 2, "door-open-too-long" },
{ 3, "forced-open" },
{ 4, "tamper" },
{ 5, "door-fault" },
{ 6, "lock-down" },
{ 7, "free-access" },
{ 8, "egress-open" },
{ 0, NULL }
};
static const value_string
BACnetAccumulatorStatus [] = {
{ 0, "normal" },
{ 1, "starting" },
{ 2, "recovered" },
{ 3, "abnormal" },
{ 4, "failed" },
{ 0, NULL }
};
/* These values are (manually) transferred from
* http://www.bacnet.org/VendorID/BACnet Vendor IDs.htm
* Version: "As of September 16, 2013"
*/
static const value_string
BACnetVendorIdentifiers [] = {
{ 0, "ASHRAE" },
{ 1, "NIST" },
{ 2, "The Trane Company" },
{ 3, "McQuay International" },
{ 4, "PolarSoft" },
{ 5, "Johnson Controls, Inc." },
{ 6, "American Auto-Matrix" },
{ 7, "Siemens Schweiz AG (Formerly: Landis & Staefa Division Europe)" },
{ 8, "Delta Controls" },
{ 9, "Siemens Schweiz AG" },
{ 10, "Schneider Electric" },
{ 11, "TAC" },
{ 12, "Orion Analysis Corporation" },
{ 13, "Teletrol Systems Inc." },
{ 14, "Cimetrics Technology" },
{ 15, "Cornell University" },
{ 16, "United Technologies Carrier" },
{ 17, "Honeywell Inc." },
{ 18, "Alerton / Honeywell" },
{ 19, "TAC AB" },
{ 20, "Hewlett-Packard Company" },
{ 21, "Dorsette's Inc." },
{ 22, "Siemens Schweiz AG (Formerly: Cerberus AG)" },
{ 23, "York Controls Group" },
{ 24, "Automated Logic Corporation" },
{ 25, "CSI Control Systems International" },
{ 26, "Phoenix Controls Corporation" },
{ 27, "Innovex Technologies, Inc." },
{ 28, "KMC Controls, Inc." },
{ 29, "Xn Technologies, Inc." },
{ 30, "Hyundai Information Technology Co., Ltd." },
{ 31, "Tokimec Inc." },
{ 32, "Simplex" },
{ 33, "North Building Technologies Limited" },
{ 34, "Notifier" },
{ 35, "Reliable Controls Corporation" },
{ 36, "Tridium Inc." },
{ 37, "Sierra Monitor Corporation/FieldServer Technologies" },
{ 38, "Silicon Energy" },
{ 39, "Kieback & Peter GmbH & Co KG" },
{ 40, "Anacon Systems, Inc." },
{ 41, "Systems Controls & Instruments, LLC" },
{ 42, "Lithonia Lighting" },
{ 43, "Micropower Manufacturing" },
{ 44, "Matrix Controls" },
{ 45, "METALAIRE" },
{ 46, "ESS Engineering" },
{ 47, "Sphere Systems Pty Ltd." },
{ 48, "Walker Technologies Corporation" },
{ 49, "H I Solutions, Inc." },
{ 50, "MBS GmbH" },
{ 51, "SAMSON AG" },
{ 52, "Badger Meter Inc." },
{ 53, "DAIKIN Industries Ltd." },
{ 54, "NARA Controls Inc." },
{ 55, "Mammoth Inc." },
{ 56, "Liebert Corporation" },
{ 57, "SEMCO Incorporated" },
{ 58, "Air Monitor Corporation" },
{ 59, "TRIATEK, LLC" },
{ 60, "NexLight" },
{ 61, "Multistack" },
{ 62, "TSI Incorporated" },
{ 63, "Weather-Rite, Inc." },
{ 64, "Dunham-Bush" },
{ 65, "Reliance Electric" },
{ 66, "LCS Inc." },
{ 67, "Regulator Australia PTY Ltd." },
{ 68, "Touch-Plate Lighting Controls" },
{ 69, "Amann GmbH" },
{ 70, "RLE Technologies" },
{ 71, "Cardkey Systems" },
{ 72, "SECOM Co., Ltd." },
{ 73, "ABB Gebaudetechnik AG Bereich NetServ" },
{ 74, "KNX Association cvba" },
{ 75, "Institute of Electrical Installation Engineers of Japan (IEIEJ)" },
{ 76, "Nohmi Bosai, Ltd." },
{ 77, "Carel S.p.A." },
{ 78, "AirSense Technology, Inc." },
{ 79, "Hochiki Corporation" },
{ 80, "Fr. Sauter AG" },
{ 81, "Matsushita Electric Works, Ltd." },
{ 82, "Mitsubishi Electric Corporation, Inazawa Works" },
{ 83, "Mitsubishi Heavy Industries, Ltd." },
{ 84, "ITT Bell & Gossett" },
{ 85, "Yamatake Building Systems Co., Ltd." },
{ 86, "The Watt Stopper, Inc." },
{ 87, "Aichi Tokei Denki Co., Ltd." },
{ 88, "Activation Technologies, LLC" },
{ 89, "Saia-Burgess Controls, Ltd." },
{ 90, "Hitachi, Ltd." },
{ 91, "Novar Corp./Trend Control Systems Ltd." },
{ 92, "Mitsubishi Electric Lighting Corporation" },
{ 93, "Argus Control Systems, Ltd." },
{ 94, "Kyuki Corporation" },
{ 95, "Richards-Zeta Building Intelligence, Inc." },
{ 96, "Scientech R&D, Inc." },
{ 97, "VCI Controls, Inc." },
{ 98, "Toshiba Corporation" },
{ 99, "Mitsubishi Electric Corporation Air Conditioning & Refrigeration Systems Works" },
{ 100, "Custom Mechanical Equipment, LLC" },
{ 101, "ClimateMaster" },
{ 102, "ICP Panel-Tec, Inc." },
{ 103, "D-Tek Controls" },
{ 104, "NEC Engineering, Ltd." },
{ 105, "PRIVA BV" },
{ 106, "Meidensha Corporation" },
{ 107, "JCI Systems Integration Services" },
{ 108, "Freedom Corporation" },
{ 109, "Neuberger Gebaudeautomation GmbH" },
{ 110, "Sitronix" },
{ 111, "Leviton Manufacturing" },
{ 112, "Fujitsu Limited" },
{ 113, "Emerson Network Power" },
{ 114, "S. A. Armstrong, Ltd." },
{ 115, "Visonet AG" },
{ 116, "M&M Systems, Inc." },
{ 117, "Custom Software Engineering" },
{ 118, "Nittan Company, Limited" },
{ 119, "Elutions Inc. (Wizcon Systems SAS)" },
{ 120, "Pacom Systems Pty., Ltd." },
{ 121, "Unico, Inc." },
{ 122, "Ebtron, Inc." },
{ 123, "Scada Engine" },
{ 124, "AC Technology Corporation" },
{ 125, "Eagle Technology" },
{ 126, "Data Aire, Inc." },
{ 127, "ABB, Inc." },
{ 128, "Transbit Sp. z o. o." },
{ 129, "Toshiba Carrier Corporation" },
{ 130, "Shenzhen Junzhi Hi-Tech Co., Ltd." },
{ 131, "Tokai Soft" },
{ 132, "Blue Ridge Technologies" },
{ 133, "Veris Industries" },
{ 134, "Centaurus Prime" },
{ 135, "Sand Network Systems" },
{ 136, "Regulvar, Inc." },
{ 137, "AFDtek Division of Fastek International Inc." },
{ 138, "PowerCold Comfort Air Solutions, Inc." },
{ 139, "I Controls" },
{ 140, "Viconics Electronics, Inc." },
{ 141, "Yaskawa America, Inc." },
{ 142, "DEOS control systems GmbH" },
{ 143, "Digitale Mess- und Steuersysteme AG" },
{ 144, "Fujitsu General Limited" },
{ 145, "Project Engineering S.r.l." },
{ 146, "Sanyo Electric Co., Ltd." },
{ 147, "Integrated Information Systems, Inc." },
{ 148, "Temco Controls, Ltd." },
{ 149, "Airtek International Inc." },
{ 150, "Advantech Corporation" },
{ 151, "Titan Products, Ltd." },
{ 152, "Regel Partners" },
{ 153, "National Environmental Product" },
{ 154, "Unitec Corporation" },
{ 155, "Kanden Engineering Company" },
{ 156, "Messner Gebaudetechnik GmbH" },
{ 157, "Integrated.CH" },
{ 158, "Price Industries" },
{ 159, "SE-Elektronic GmbH" },
{ 160, "Rockwell Automation" },
{ 161, "Enflex Corp." },
{ 162, "ASI Controls" },
{ 163, "SysMik GmbH Dresden" },
{ 164, "HSC Regelungstechnik GmbH" },
{ 165, "Smart Temp Australia Pty. Ltd." },
{ 166, "Cooper Controls" },
{ 167, "Duksan Mecasys Co., Ltd." },
{ 168, "Fuji IT Co., Ltd." },
{ 169, "Vacon Plc" },
{ 170, "Leader Controls" },
{ 171, "Cylon Controls, Ltd." },
{ 172, "Compas" },
{ 173, "Mitsubishi Electric Building Techno-Service Co., Ltd." },
{ 174, "Building Control Integrators" },
{ 175, "ITG Worldwide (M) Sdn Bhd" },
{ 176, "Lutron Electronics Co., Inc." },
{ 178, "LOYTEC Electronics GmbH" },
{ 179, "ProLon" },
{ 180, "Mega Controls Limited" },
{ 181, "Micro Control Systems, Inc." },
{ 182, "Kiyon, Inc." },
{ 183, "Dust Networks" },
{ 184, "Advanced Building Automation Systems" },
{ 185, "Hermos AG" },
{ 186, "CEZIM" },
{ 187, "Softing" },
{ 188, "Lynxspring" },
{ 189, "Schneider Toshiba Inverter Europe" },
{ 190, "Danfoss Drives A/S" },
{ 191, "Eaton Corporation" },
{ 192, "Matyca S.A." },
{ 193, "Botech AB" },
{ 194, "Noveo, Inc." },
{ 195, "AMEV" },
{ 196, "Yokogawa Electric Corporation" },
{ 197, "GFR Gesellschaft fur Regelungstechnik" },
{ 198, "Exact Logic" },
{ 199, "Mass Electronics Pty Ltd dba Innotech Control Systems Australia" },
{ 200, "Kandenko Co., Ltd." },
{ 201, "DTF, Daten-Technik Fries" },
{ 202, "Klimasoft, Ltd." },
{ 203, "Toshiba Schneider Inverter Corporation" },
{ 204, "Control Applications, Ltd." },
{ 205, "KDT Systems Co., Ltd." },
{ 206, "Onicon Incorporated" },
{ 207, "Automation Displays, Inc." },
{ 208, "Control Solutions, Inc." },
{ 209, "Remsdaq Limited" },
{ 210, "NTT Facilities, Inc." },
{ 211, "VIPA GmbH" },
{ 212, "TSC21 Association of Japan" },
{ 213, "Strato Automation" },
{ 214, "HRW Limited" },
{ 215, "Lighting Control & Design, Inc." },
{ 216, "Mercy Electronic and Electrical Industries" },
{ 217, "Samsung SDS Co., Ltd" },
{ 218, "Impact Facility Solutions, Inc." },
{ 219, "Aircuity" },
{ 220, "Control Techniques, Ltd." },
{ 221, "OpenGeneral Pty., Ltd." },
{ 222, "WAGO Kontakttechnik GmbH & Co. KG" },
{ 223, "Cerus Industrial" },
{ 224, "Chloride Power Protection Company" },
{ 225, "Computrols, Inc." },
{ 226, "Phoenix Contact GmbH & Co. KG" },
{ 227, "Grundfos Management A/S" },
{ 228, "Ridder Drive Systems" },
{ 229, "Soft Device SDN BHD" },
{ 230, "Integrated Control Technology Limited" },
{ 231, "AIRxpert Systems, Inc." },
{ 232, "Microtrol Limited" },
{ 233, "Red Lion Controls" },
{ 234, "Digital Electronics Corporation" },
{ 235, "Ennovatis GmbH" },
{ 236, "Serotonin Software Technologies, Inc." },
{ 237, "LS Industrial Systems Co., Ltd." },
{ 238, "Square D Company" },
{ 239, "S Squared Innovations, Inc." },
{ 240, "Aricent Ltd." },
{ 241, "EtherMetrics, LLC" },
{ 242, "Industrial Control Communications, Inc." },
{ 243, "Paragon Controls, Inc." },
{ 244, "A. O. Smith Corporation" },
{ 245, "Contemporary Control Systems, Inc." },
{ 246, "Intesis Software SL" },
{ 247, "Ingenieurgesellschaft N. Hartleb mbH" },
{ 248, "Heat-Timer Corporation" },
{ 249, "Ingrasys Technology, Inc." },
{ 250, "Costerm Building Automation" },
{ 251, "WILO SE" },
{ 252, "Embedia Technologies Corp." },
{ 253, "Technilog" },
{ 254, "HR Controls Ltd. & Co. KG" },
{ 255, "Lennox International, Inc." },
{ 256, "RK-Tec Rauchklappen-Steuerungssysteme GmbH & Co. KG" },
{ 257, "Thermomax, Ltd." },
{ 258, "ELCON Electronic Control, Ltd." },
{ 259, "Larmia Control AB" },
{ 260, "BACnet Stack at SourceForge" },
{ 261, "G4S Security Services A/S" },
{ 262, "Exor International S.p.A." },
{ 263, "Cristal Controles" },
{ 264, "Regin AB" },
{ 265, "Dimension Software, Inc." },
{ 266, "SynapSense Corporation" },
{ 267, "Beijing Nantree Electronic Co., Ltd." },
{ 268, "Camus Hydronics Ltd." },
{ 269, "Kawasaki Heavy Industries, Ltd." },
{ 270, "Critical Environment Technologies" },
{ 271, "ILSHIN IBS Co., Ltd." },
{ 272, "ELESTA Energy Control AG" },
{ 273, "KROPMAN Installatietechniek" },
{ 274, "Baldor Electric Company" },
{ 275, "INGA mbH" },
{ 276, "GE Consumer & Industrial" },
{ 277, "Functional Devices, Inc." },
{ 278, "ESAC" },
{ 279, "M-System Co., Ltd." },
{ 280, "Yokota Co., Ltd." },
{ 281, "Hitranse Technology Co., LTD" },
{ 282, "Federspiel Controls" },
{ 283, "Kele, Inc." },
{ 284, "Opera Electronics, Inc." },
{ 285, "Gentec" },
{ 286, "Embedded Science Labs, LLC" },
{ 287, "Parker Hannifin Corporation" },
{ 288, "MaCaPS International Limited" },
{ 289, "Link4 Corporation" },
{ 290, "Romutec Steuer-u. Regelsysteme GmbH" },
{ 291, "Pribusin, Inc." },
{ 292, "Advantage Controls" },
{ 293, "Critical Room Control" },
{ 294, "LEGRAND" },
{ 295, "Tongdy Control Technology Co., Ltd." },
{ 296, "ISSARO Integrierte Systemtechnik" },
{ 297, "Pro-Dev Industries" },
{ 298, "DRI-STEEM" },
{ 299, "Creative Electronic GmbH" },
{ 300, "Swegon AB" },
{ 301, "Jan Brachacek" },
{ 302, "Hitachi Appliances, Inc." },
{ 303, "Real Time Automation, Inc." },
{ 304, "ITEC Hankyu-Hanshin Co." },
{ 305, "Cyrus E&M Engineering Co., Ltd." },
{ 306, "Racine Federated, Inc." },
{ 307, "Cirrascale Corporation" },
{ 308, "Elesta GmbH Building Automation" },
{ 309, "Securiton" },
{ 310, "OSlsoft, Inc." },
{ 311, "Hanazeder Electronic GmbH" },
{ 312, "Honeywell Security Deutschland, Novar GmbH" },
{ 313, "Siemens Energy & Automation, Inc." },
{ 314, "ETM Professional Control GmbH" },
{ 315, "Meitav-tec, Ltd." },
{ 316, "Janitza Electronics GmbH" },
{ 317, "MKS Nordhausen" },
{ 318, "De Gier Drive Systems B.V." },
{ 319, "Cypress Envirosystems" },
{ 320, "SMARTron s.r.o." },
{ 321, "Verari Systems, Inc." },
{ 322, "K-W Electronic Service, Inc." },
{ 323, "ALFA-SMART Energy Management" },
{ 324, "Telkonet, Inc." },
{ 325, "Securiton GmbH" },
{ 326, "Cemtrex, Inc." },
{ 327, "Performance Technologies, Inc." },
{ 328, "Xtralis (Aust) Pty Ltd" },
{ 329, "TROX GmbH" },
{ 330, "Beijing Hysine Technology Co., Ltd" },
{ 331, "RCK Controls, Inc." },
{ 332, "Distech Controls SAS" },
{ 333, "Novar/Honeywell" },
{ 334, "The S4 Group, Inc." },
{ 335, "Schneider Electric" },
{ 336, "LHA Systems" },
{ 337, "GHM engineering Group, Inc." },
{ 338, "Cllimalux S.A." },
{ 339, "VAISALA Oyj" },
{ 340, "COMPLEX (Beijing) Technology, Co., LTD." },
{ 341, "SCADAmetrics" },
{ 342, "POWERPEG NSI Limited" },
{ 343, "BACnet Interoperability Testing Services, Inc." },
{ 344, "Teco a.s." },
{ 345, "Plexus Technology, Inc." },
{ 346, "Energy Focus, Inc." },
{ 347, "Powersmiths International Corp." },
{ 348, "Nichibei Co., Ltd." },
{ 349, "HKC Technology Ltd." },
{ 350, "Ovation Networks, Inc." },
{ 351, "Setra Systems" },
{ 352, "AVG Automation" },
{ 353, "ZXC Ltd." },
{ 354, "Byte Sphere" },
{ 355, "Generiton Co., Ltd." },
{ 356, "Holter Regelarmaturen GmbH & Co. KG" },
{ 357, "Bedford Instruments, LLC" },
{ 358, "Standair Inc." },
{ 359, "WEG Automation - R&D" },
{ 360, "Prolon Control Systems ApS" },
{ 361, "Inneasoft" },
{ 362, "ConneXSoft GmbH" },
{ 363, "CEAG Notlichtsysteme GmbH" },
{ 364, "Distech Controls Inc." },
{ 365, "Industrial Technology Research Institute" },
{ 366, "ICONICS, Inc." },
{ 367, "IQ Controls s.c." },
{ 368, "OJ Electronics A/S" },
{ 369, "Rolbit Ltd." },
{ 370, "Synapsys Solutions Ltd." },
{ 371, "ACME Engineering Prod. Ltd." },
{ 372, "Zener Electric Pty, Ltd." },
{ 373, "Selectronix, Inc." },
{ 374, "Gorbet & Banerjee, LLC." },
{ 375, "IME" },
{ 376, "Stephen H. Dawson Computer Service" },
{ 377, "Accutrol, LLC" },
{ 378, "Schneider Elektronik GmbH" },
{ 379, "Alpha-Inno Tec GmbH" },
{ 380, "ADMMicro, Inc." },
{ 381, "Greystone Energy Systems, Inc." },
{ 382, "CAP Technologie" },
{ 383, "KeRo Systems" },
{ 384, "Domat Control System s.r.o." },
{ 385, "Efektronics Pty. Ltd." },
{ 386, "Hekatron Vertriebs GmbH" },
{ 387, "Securiton AG" },
{ 388, "Carlo Gavazzi Controls SpA" },
{ 389, "Chipkin Automation Systems" },
{ 390, "Savant Systems, LLC" },
{ 391, "Simmtronic Lighting Controls" },
{ 392, "Abelko Innovation AB" },
{ 393, "Seresco Technologies Inc." },
{ 394, "IT Watchdogs" },
{ 395, "Automation Assist Japan Corp." },
{ 396, "Thermokon Sensortechnik GmbH" },
{ 397, "EGauge Systems, LLC" },
{ 398, "Quantum Automation (ASIA) PTE, Ltd." },
{ 399, "Toshiba Lighting & Technology Corp." },
{ 400, "SPIN Engenharia de Automaca Ltda." },
{ 401, "Logistics Systems & Software Services India PVT. Ltd." },
{ 402, "Delta Controls Integration Products" },
{ 403, "Focus Media" },
{ 404, "LUMEnergi Inc." },
{ 405, "Kara Systems" },
{ 406, "RF Code, Inc." },
{ 407, "Fatek Automation Corp." },
{ 408, "JANDA Software Company, LLC" },
{ 409, "Open System Solutions Limited" },
{ 410, "Intelec Systems PTY Ltd." },
{ 411, "Ecolodgix, LLC" },
{ 412, "Douglas Lighting Controls" },
{ 413, "iSAtech GmbH" },
{ 414, "AREAL" },
{ 415, "Beckhoff Automation GmbH" },
{ 416, "IPAS GmbH" },
{ 417, "KE2 Therm Solutions" },
{ 418, "Base2Products" },
{ 419, "DTL Controls, LLC" },
{ 420, "INNCOM International, Inc." },
{ 421, "BTR Netcom GmbH" },
{ 422, "Greentrol Automation, Inc" },
{ 423, "BELIMO Automation AG" },
{ 424, "Samsung Heavy Industries Co, Ltd" },
{ 425, "Triacta Power Technologies, Inc." },
{ 426, "Globestar Systems" },
{ 427, "MLB Advanced Media, LP" },
{ 428, "SWG Stuckmann Wirtschaftliche Gebaudesysteme GmbH" },
{ 429, "SensorSwitch" },
{ 430, "Multitek Power Limited" },
{ 431, "Aquametro AG" },
{ 432, "LG Electronics Inc." },
{ 433, "Electronic Theatre Controls, Inc." },
{ 434, "Mitsubishi Electric Corporation Nagoya Works" },
{ 435, "Delta Electronics, Inc." },
{ 436, "Elma Kurtalj, Ltd." },
{ 437, "ADT Fire and Security Sp. A.o.o." },
{ 438, "Nedap Security Management" },
{ 439, "ESC Automation Inc." },
{ 440, "DSP4YOU Ltd." },
{ 441, "GE Sensing and Inspection Technologies" },
{ 442, "Embedded Systems SIA" },
{ 443, "BEFEGA GmbH" },
{ 444, "Baseline Inc." },
{ 445, "M2M Systems Integrators" },
{ 446, "OEMCtrl" },
{ 447, "Clarkson Controls Limited" },
{ 448, "Rogerwell Control System Limited" },
{ 449, "SCL Elements" },
{ 450, "Hitachi Ltd." },
{ 451, "Newron System SA" },
{ 452, "BEVECO Gebouwautomatisering BV" },
{ 453, "Streamside Solutions" },
{ 454, "Yellowstone Soft" },
{ 455, "Oztech Intelligent Systems Pty Ltd." },
{ 456, "Novelan GmbH" },
{ 457, "Flexim Americas Corporation" },
{ 458, "ICP DAS Co., Ltd." },
{ 459, "CARMA Industries Inc." },
{ 460, "Log-One Ltd." },
{ 461, "TECO Electric & Machinery Co., Ltd." },
{ 462, "ConnectEx, Inc." },
{ 463, "Turbo DDC Sudwest" },
{ 464, "Quatrosense Environmental Ltd." },
{ 465, "Fifth Light Technology Ltd." },
{ 466, "Scientific Solutions, Ltd." },
{ 467, "Controller Area Network Solutions (M) Sdn Bhd" },
{ 468, "RESOL - Elektronische Regelungen GmbH" },
{ 469, "RPBUS LLC" },
{ 470, "BRS Sistemas Eletronicos" },
{ 471, "WindowMaster A/S" },
{ 472, "Sunlux Technologies Ltd." },
{ 473, "Measurlogic" },
{ 474, "Frimat GmbH" },
{ 475, "Spirax Sarco" },
{ 476, "Luxtron" },
{ 477, "Raypak Inc" },
{ 478, "Air Monitor Corporation" },
{ 479, "Regler Och Webbteknik Sverige (ROWS)" },
{ 480, "Intelligent Lighting Controls Inc." },
{ 481, "Sanyo Electric Industry Co., Ltd" },
{ 482, "E-Mon Energy Monitoring Products" },
{ 483, "Digital Control Systems" },
{ 484, "ATI Airtest Technologies, Inc." },
{ 485, "SCS SA" },
{ 486, "HMS Industrial Networks AB" },
{ 487, "Shenzhen Universal Intellisys Co Ltd" },
{ 488, "EK Intellisys Sdn Bhd" },
{ 489, "SysCom" },
{ 490, "Firecom, Inc." },
{ 491, "ESA Elektroschaltanlagen Grimma GmbH" },
{ 492, "Kumahira Co Ltd" },
{ 493, "Hotraco" },
{ 494, "SABO Elektronik GmbH" },
{ 495, "Equip'Trans" },
{ 496, "TCS Basys Controls" },
{ 497, "FlowCon International A/S" },
{ 498, "ThyssenKrupp Elevator Americas" },
{ 499, "Abatement Technologies" },
{ 500, "Continental Control Systems, LLC" },
{ 501, "WISAG Automatisierungstechnik GmbH & Co KG" },
{ 502, "EasyIO" },
{ 503, "EAP-Electric GmbH" },
{ 504, "Hardmeier" },
{ 505, "Mircom Group of Companies" },
{ 506, "Quest Controls" },
{ 507, "Mestek, Inc" },
{ 508, "Pulse Energy" },
{ 509, "Tachikawa Corporation" },
{ 510, "University of Nebraska-Lincoln" },
{ 511, "Redwood Systems" },
{ 512, "PASStec Industrie-Elektronik GmbH" },
{ 513, "NgEK, Inc." },
{ 514, "FAW Electronics Ltd" },
{ 515, "Jireh Energy Tech Co., Ltd." },
{ 516, "Enlighted Inc." },
{ 517, "El-Piast Sp. Z o.o" },
{ 518, "NetxAutomation Software GmbH" },
{ 519, "Invertek Drives" },
{ 520, "Deutschmann Automation GmbH & Co. KG" },
{ 521, "EMU Electronic AG" },
{ 522, "Phaedrus Limited" },
{ 523, "Sigmatek GmbH & Co KG" },
{ 524, "Marlin Controls" },
{ 525, "Circutor, SA" },
{ 526, "UTC Fire & Security" },
{ 527, "DENT Instruments, Inc." },
{ 528, "FHP Manufacturing Company - Bosch Group" },
{ 529, "GE Intelligent Platforms" },
{ 530, "Inner Range Pty Ltd" },
{ 531, "GLAS Energy Technology" },
{ 532, "MSR-Electronic-GmbH" },
{ 533, "Energy Control Systems, Inc." },
{ 534, "EMT Controls" },
{ 535, "Daintree Networks Inc." },
{ 536, "EURO ICC d.o.o" },
{ 537, "TE Connectivity Energy" },
{ 538, "GEZE GmbH" },
{ 539, "NEC Corporation" },
{ 540, "Ho Cheung International Company Limited" },
{ 541, "Sharp Manufacturing Systems Corporation" },
{ 542, "DOT CONTROLS a.s." },
{ 543, "BeaconMedaes" },
{ 544, "Midea Commercial Aircon" },
{ 545, "WattMaster Controls" },
{ 546, "Kamstrup A/S" },
{ 547, "CA Computer Automation GmbH" },
{ 548, "Laars Heating Systems Company" },
{ 549, "Hitachi Systems, Ltd." },
{ 550, "Fushan AKE Electronic Engineering Co., Ltd." },
{ 551, "Toshiba International Corporation" },
{ 552, "Starman Systems, LLC" },
{ 553, "Samsung Techwin Co., Ltd." },
{ 554, "ISAS-Integrated Switchgear and Systems P/L" },
{ 556, "Obvius" },
{ 557, "Marek Guzik" },
{ 558, "Vortek Instruments, LLC" },
{ 559, "Universal Lighting Technologies" },
{ 560, "Myers Power Products, Inc." },
{ 561, "Vector Controls GmbH" },
{ 562, "Crestron Electronics, Inc." },
{ 563, "A&E Controls Limited" },
{ 564, "Projektomontaza A.D." },
{ 565, "Freeaire Refrigeration" },
{ 566, "Aqua Cooler Pty Limited" },
{ 567, "Basic Controls" },
{ 568, "GE Measurement and Control Solutions Advanced Sensors" },
{ 569, "EQUAL Networks" },
{ 570, "Millennial Net" },
{ 571, "APLI Ltd" },
{ 572, "Electro Industries/GaugeTech" },
{ 573, "SangMyung University" },
{ 574, "Coppertree Analytics, Inc." },
{ 575, "CoreNetiX GmbH" },
{ 576, "Acutherm" },
{ 577, "Dr. Riedel Automatisierungstechnik GmbH" },
{ 578, "Shina System Co., Ltd" },
{ 579, "Iqapertus" },
{ 580, "PSE Technology" },
{ 581, "BA Systems" },
{ 582, "BTICINO" },
{ 583, "Monico, Inc." },
{ 584, "iCue" },
{ 585, "tekmar Control Systems Ltd." },
{ 586, "Control Technology Corporation" },
{ 587, "GFAE GmbH" },
{ 588, "BeKa Software GmbH" },
{ 589, "Isoil Industria SpA" },
{ 590, "Home Systems Consulting SpA" },
{ 591, "Socomec" },
{ 592, "Everex Communications, Inc." },
{ 593, "Ceiec Electric Technology" },
{ 594, "Atrila GmbH" },
{ 595, "WingTechs" },
{ 596, "Shenzhen Mek Intellisys Pte Ltd." },
{ 597, "Nestfield Co., Ltd." },
{ 598, "Swissphone Telecom AG" },
{ 599, "PNTECH JSC" },
{ 600, "Horner APG, LLC" },
{ 601, "PVI Industries, LLC" },
{ 602, "Ela-compil" },
{ 603, "Pegasus Automation International LLC" },
{ 604, "Wight Electronic Services Ltd." },
{ 605, "Marcom" },
{ 606, "Exhausto A/S" },
{ 607, "Dwyer Instruments, Inc." },
{ 608, "Link GmbH" },
{ 609, "Oppermann Regelgerate GmbH" },
{ 610, "NuAire, Inc." },
{ 611, "Nortec Humidity, Inc." },
{ 612, "Bigwood Systems, Inc." },
{ 613, "Enbala Power Networks" },
{ 614, "Inter Energy Co., Ltd." },
{ 615, "ETC" },
{ 616, "COMELEC S.A.R.L" },
{ 617, "Pythia Technologies" },
{ 618, "TrendPoint Systems, Inc." },
{ 619, "AWEX" },
{ 620, "Eurevia" },
{ 621, "Kongsberg E-lon AS" },
{ 622, "FlaktWoods" },
{ 623, "E + E Elektronik GES M.B.H." },
{ 624, "ARC Informatique" },
{ 625, "SKIDATA AG" },
{ 626, "WSW Solutions" },
{ 627, "Trefon Electronic GmbH" },
{ 628, "Dongseo System" },
{ 629, "Kanontec Intelligence Technology Co., Ltd." },
{ 630, "EVCO S.p.A." },
{ 631, "Accuenergy (CANADA) Inc." },
{ 632, "SoftDEL" },
{ 633, "Orion Energy Systems, Inc." },
{ 634, "Roboticsware" },
{ 635, "DOMIQ Sp. z o.o." },
{ 636, "Solidyne" },
{ 637, "Elecsys Corporation" },
{ 638, "Conditionaire International Pty. Limited" },
{ 639, "Quebec, Inc." },
{ 640, "Homerun Holdings" },
{ 641, "RFM, Inc." },
{ 642, "Comptek" },
{ 643, "Westco Systems, Inc." },
{ 644, "Advancis Software & Services GmbH" },
{ 645, "Intergrid, LLC" },
{ 646, "Markerr Controls, Inc." },
{ 647, "Toshiba Elevator and Building Systems Corporation" },
{ 648, "Spectrum Controls, Inc." },
{ 649, "Mkservice" },
{ 650, "Fox Thermal Instruments" },
{ 651, "SyxthSense Ltd" },
{ 652, "DUHA System S R.O." },
{ 653, "NIBE" },
{ 654, "Melink Corporation" },
{ 655, "Fritz-Haber-Institut" },
{ 656, "MTU Onsite Energy GmbH, Gas Power Systems" },
{ 657, "Omega Engineering, Inc." },
{ 658, "Avelon" },
{ 659, "Ywire Technologies, Inc." },
{ 660, "M.R. Engineering Co., Ltd." },
{ 661, "Lochinvar, LLC" },
{ 662, "Sontay Limited" },
{ 663, "GRUPA Slawomir Chelminski" },
{ 664, "Arch Meter Corporation" },
{ 665, "Senva, Inc." },
{ 667, "FM-Tec" },
{ 668, "Systems Specialists, Inc." },
{ 669, "SenseAir" },
{ 670, "AB IndustrieTechnik Srl" },
{ 671, "Cortland Research, LLC" },
{ 672, "MediaView" },
{ 673, "VDA Elettronica" },
{ 674, "CSS, Inc." },
{ 675, "Tek-Air Systems, Inc." },
{ 676, "ICDT" },
{ 677, "The Armstrong Monitoring Corporation" },
{ 678, "DIXELL S.r.l" },
{ 679, "Lead System, Inc." },
{ 680, "ISM EuroCenter S.A." },
{ 681, "TDIS" },
{ 682, "Trade FIDES" },
{ 683, "Knurr GmbH (Emerson Network Power)" },
{ 684, "Resource Data Management" },
{ 685, "Abies Technology, Inc." },
{ 686, "Amalva" },
{ 687, "MIRAE Electrical Mfg. Co., Ltd." },
{ 688, "HunterDouglas Architectural Projects Scandinavia ApS" },
{ 689, "RUNPAQ Group Co., Ltd" },
{ 690, "Unicard SA" },
{ 691, "IE Technologies" },
{ 692, "Ruskin Manufacturing" },
{ 693, "Calon Associates Limited" },
{ 694, "Contec Co., Ltd." },
{ 695, "iT GmbH"},
{ 696, "Autani Corporation"},
{ 697, "Christian Fortin"},
{ 698, "HDL"},
{ 699, "IPID Sp. Z.O.O Limited"},
{ 700, "Fuji Electric Co., Ltd"},
{ 701, "View, Inc."},
{ 702, "Samsung S1 Corporation"},
{ 703, "New Lift"},
{ 704, "VRT Systems"},
{ 0, NULL }
};
static value_string_ext BACnetVendorIdentifiers_ext = VALUE_STRING_EXT_INIT(BACnetVendorIdentifiers);
static int proto_bacapp = -1;
static int hf_bacapp_type = -1;
static int hf_bacapp_pduflags = -1;
static int hf_bacapp_SEG = -1;
static int hf_bacapp_MOR = -1;
static int hf_bacapp_SA = -1;
static int hf_bacapp_response_segments = -1;
static int hf_bacapp_max_adpu_size = -1;
static int hf_bacapp_invoke_id = -1;
static int hf_bacapp_objectType = -1;
static int hf_bacapp_instanceNumber = -1;
static int hf_bacapp_sequence_number = -1;
static int hf_bacapp_window_size = -1;
static int hf_bacapp_service = -1;
static int hf_bacapp_NAK = -1;
static int hf_bacapp_SRV = -1;
static int hf_Device_Instance_Range_Low_Limit = -1;
static int hf_Device_Instance_Range_High_Limit = -1;
static int hf_BACnetRejectReason = -1;
static int hf_BACnetAbortReason = -1;
static int hf_BACnetApplicationTagNumber = -1;
static int hf_BACnetContextTagNumber = -1;
static int hf_BACnetExtendedTagNumber = -1;
static int hf_BACnetNamedTag = -1;
static int hf_BACnetTagClass = -1;
static int hf_BACnetCharacterSet = -1;
static int hf_bacapp_tag_lvt = -1;
static int hf_bacapp_tag_ProcessId = -1;
static int hf_bacapp_uservice = -1;
static int hf_BACnetPropertyIdentifier = -1;
static int hf_BACnetVendorIdentifier = -1;
static int hf_BACnetRestartReason = -1;
static int hf_bacapp_tag_IPV4 = -1;
static int hf_bacapp_tag_IPV6 = -1;
static int hf_bacapp_tag_PORT = -1;
/* some more variables for segmented messages */
static int hf_msg_fragments = -1;
static int hf_msg_fragment = -1;
static int hf_msg_fragment_overlap = -1;
static int hf_msg_fragment_overlap_conflicts = -1;
static int hf_msg_fragment_multiple_tails = -1;
static int hf_msg_fragment_too_long_fragment = -1;
static int hf_msg_fragment_error = -1;
static int hf_msg_fragment_count = -1;
static int hf_msg_reassembled_in = -1;
static int hf_msg_reassembled_length = -1;
static gint ett_msg_fragment = -1;
static gint ett_msg_fragments = -1;
static gint ett_bacapp = -1;
static gint ett_bacapp_control = -1;
static gint ett_bacapp_tag = -1;
static gint ett_bacapp_list = -1;
static gint ett_bacapp_value = -1;
static expert_field ei_bacapp_bad_length = EI_INIT;
static gint32 propertyIdentifier = -1;
static gint32 propertyArrayIndex = -1;
static guint32 object_type = 4096;
static guint8 bacapp_flags = 0;
static guint8 bacapp_seq = 0;
/* Defined to allow vendor identifier registration of private transfer dissectors */
static dissector_table_t bacapp_dissector_table;
/* Stat: BACnet Packets sorted by IP */
bacapp_info_value_t bacinfo;
static const gchar* st_str_packets_by_ip = "BACnet Packets by IP";
static const gchar* st_str_packets_by_ip_dst = "By Destination";
static const gchar* st_str_packets_by_ip_src = "By Source";
static int st_node_packets_by_ip = -1;
static int st_node_packets_by_ip_dst = -1;
static int st_node_packets_by_ip_src = -1;
static void
bacapp_packet_stats_tree_init(stats_tree* st)
{
st_node_packets_by_ip = stats_tree_create_pivot(st, st_str_packets_by_ip, 0);
st_node_packets_by_ip_src = stats_tree_create_node(st, st_str_packets_by_ip_src, st_node_packets_by_ip, TRUE);
st_node_packets_by_ip_dst = stats_tree_create_node(st, st_str_packets_by_ip_dst, st_node_packets_by_ip, TRUE);
}
static gchar *
bacapp_get_address_label(const char *tag, address *addr)
{
gchar *addr_str, *label_str;
addr_str = address_to_str(NULL, addr);
label_str = wmem_strconcat(NULL, tag, addr_str, NULL);
wmem_free(NULL, addr_str);
return label_str;
}
static int
bacapp_stats_tree_packet(stats_tree* st, packet_info* pinfo, epan_dissect_t* edt _U_, const void* p)
{
int packets_for_this_dst;
int packets_for_this_src;
int service_for_this_dst;
int service_for_this_src;
int src_for_this_dst;
int dst_for_this_src;
int objectid_for_this_dst;
int objectid_for_this_src;
int instanceid_for_this_dst;
int instanceid_for_this_src;
gchar *dststr;
gchar *srcstr;
const bacapp_info_value_t *binfo = (const bacapp_info_value_t *)p;
srcstr = bacapp_get_address_label("Src: ", &pinfo->src);
dststr = bacapp_get_address_label("Dst: ", &pinfo->dst);
tick_stat_node(st, st_str_packets_by_ip, 0, TRUE);
packets_for_this_dst = tick_stat_node(st, st_str_packets_by_ip_dst, st_node_packets_by_ip, TRUE);
packets_for_this_src = tick_stat_node(st, st_str_packets_by_ip_src, st_node_packets_by_ip, TRUE);
src_for_this_dst = tick_stat_node(st, dststr, packets_for_this_dst, TRUE);
dst_for_this_src = tick_stat_node(st, srcstr, packets_for_this_src, TRUE);
service_for_this_src = tick_stat_node(st, dststr, dst_for_this_src, TRUE);
service_for_this_dst = tick_stat_node(st, srcstr, src_for_this_dst, TRUE);
if (binfo->service_type) {
objectid_for_this_dst = tick_stat_node(st, binfo->service_type, service_for_this_dst, TRUE);
objectid_for_this_src = tick_stat_node(st, binfo->service_type, service_for_this_src, TRUE);
if (binfo->object_ident) {
instanceid_for_this_dst = tick_stat_node(st, binfo->object_ident, objectid_for_this_dst, TRUE);
tick_stat_node(st, binfo->instance_ident, instanceid_for_this_dst, FALSE);
instanceid_for_this_src = tick_stat_node(st, binfo->object_ident, objectid_for_this_src, TRUE);
tick_stat_node(st, binfo->instance_ident, instanceid_for_this_src, FALSE);
}
}
wmem_free(NULL, srcstr);
wmem_free(NULL, dststr);
return 1;
}
/* Stat: BACnet Packets sorted by Service */
static const gchar* st_str_packets_by_service = "BACnet Packets by Service";
static int st_node_packets_by_service = -1;
static void
bacapp_service_stats_tree_init(stats_tree* st)
{
st_node_packets_by_service = stats_tree_create_pivot(st, st_str_packets_by_service, 0);
}
static int
bacapp_stats_tree_service(stats_tree* st, packet_info* pinfo, epan_dissect_t* edt _U_, const void* p)
{
int servicetype;
int src, dst;
int objectid;
gchar *dststr;
gchar *srcstr;
const bacapp_info_value_t *binfo = (const bacapp_info_value_t *)p;
srcstr = bacapp_get_address_label("Src: ", &pinfo->src);
dststr = bacapp_get_address_label("Dst: ", &pinfo->dst);
tick_stat_node(st, st_str_packets_by_service, 0, TRUE);
if (binfo->service_type) {
servicetype = tick_stat_node(st, binfo->service_type, st_node_packets_by_service, TRUE);
src = tick_stat_node(st, srcstr, servicetype, TRUE);
dst = tick_stat_node(st, dststr, src, TRUE);
if (binfo->object_ident) {
objectid = tick_stat_node(st, binfo->object_ident, dst, TRUE);
tick_stat_node(st, binfo->instance_ident, objectid, FALSE);
}
}
wmem_free(NULL, srcstr);
wmem_free(NULL, dststr);
return 1;
}
/* Stat: BACnet Packets sorted by Object Type */
static const gchar* st_str_packets_by_objectid = "BACnet Packets by Object Type";
static int st_node_packets_by_objectid = -1;
static void
bacapp_objectid_stats_tree_init(stats_tree* st)
{
st_node_packets_by_objectid = stats_tree_create_pivot(st, st_str_packets_by_objectid, 0);
}
static int
bacapp_stats_tree_objectid(stats_tree* st, packet_info* pinfo, epan_dissect_t* edt _U_, const void* p)
{
int servicetype;
int src, dst;
int objectid;
gchar *dststr;
gchar *srcstr;
const bacapp_info_value_t *binfo = (const bacapp_info_value_t *)p;
srcstr = bacapp_get_address_label("Src: ", &pinfo->src);
dststr = bacapp_get_address_label("Dst: ", &pinfo->dst);
tick_stat_node(st, st_str_packets_by_objectid, 0, TRUE);
if (binfo->object_ident) {
objectid = tick_stat_node(st, binfo->object_ident, st_node_packets_by_objectid, TRUE);
src = tick_stat_node(st, srcstr, objectid, TRUE);
dst = tick_stat_node(st, dststr, src, TRUE);
if (binfo->service_type) {
servicetype = tick_stat_node(st, binfo->service_type, dst, TRUE);
tick_stat_node(st, binfo->instance_ident, servicetype, FALSE);
}
}
wmem_free(NULL, srcstr);
wmem_free(NULL, dststr);
return 1;
}
/* Stat: BACnet Packets sorted by Instance No */
static const gchar* st_str_packets_by_instanceid = "BACnet Packets by Instance ID";
static int st_node_packets_by_instanceid = -1;
static void
bacapp_instanceid_stats_tree_init(stats_tree* st)
{
st_node_packets_by_instanceid = stats_tree_create_pivot(st, st_str_packets_by_instanceid, 0);
}
static int
bacapp_stats_tree_instanceid(stats_tree* st, packet_info* pinfo, epan_dissect_t* edt _U_, const void* p)
{
int servicetype;
int src, dst;
int instanceid;
gchar *dststr;
gchar *srcstr;
const bacapp_info_value_t *binfo = (const bacapp_info_value_t *)p;
srcstr = bacapp_get_address_label("Src: ", &pinfo->src);
dststr = bacapp_get_address_label("Dst: ", &pinfo->dst);
tick_stat_node(st, st_str_packets_by_instanceid, 0, TRUE);
if (binfo->object_ident) {
instanceid = tick_stat_node(st, binfo->instance_ident, st_node_packets_by_instanceid, TRUE);
src = tick_stat_node(st, srcstr, instanceid, TRUE);
dst = tick_stat_node(st, dststr, src, TRUE);
if (binfo->service_type) {
servicetype = tick_stat_node(st, binfo->service_type, dst, TRUE);
tick_stat_node(st, binfo->object_ident, servicetype, FALSE);
}
}
wmem_free(NULL, srcstr);
wmem_free(NULL, dststr);
return 1;
}
/* register all BACnet Ststistic trees */
static void
register_bacapp_stat_trees(void)
{
stats_tree_register("bacapp", "bacapp_ip", "BACnet/Packets sorted by IP", 0,
bacapp_stats_tree_packet, bacapp_packet_stats_tree_init, NULL);
stats_tree_register("bacapp", "bacapp_service", "BACnet/Packets sorted by Service", 0,
bacapp_stats_tree_service, bacapp_service_stats_tree_init, NULL);
stats_tree_register("bacapp", "bacapp_objectid", "BACnet/Packets sorted by Object Type", 0,
bacapp_stats_tree_objectid, bacapp_objectid_stats_tree_init, NULL);
stats_tree_register("bacapp", "bacapp_instanceid", "BACnet/Packets sorted by Instance ID", 0,
bacapp_stats_tree_instanceid, bacapp_instanceid_stats_tree_init, NULL);
}
/* 'data' must be ep_ allocated */
static gint
updateBacnetInfoValue(gint whichval, const gchar *data)
{
if (whichval == BACINFO_SERVICE) {
bacinfo.service_type = data;
return 0;
}
if (whichval == BACINFO_INVOKEID) {
bacinfo.invoke_id = data;
return 0;
}
if (whichval == BACINFO_OBJECTID) {
bacinfo.object_ident = data;
return 0;
}
if (whichval == BACINFO_INSTANCEID) {
bacinfo.instance_ident = data;
return 0;
}
return -1;
}
static const fragment_items msg_frag_items = {
/* Fragment subtrees */
&ett_msg_fragment,
&ett_msg_fragments,
/* Fragment fields */
&hf_msg_fragments,
&hf_msg_fragment,
&hf_msg_fragment_overlap,
&hf_msg_fragment_overlap_conflicts,
&hf_msg_fragment_multiple_tails,
&hf_msg_fragment_too_long_fragment,
&hf_msg_fragment_error,
&hf_msg_fragment_count,
/* Reassembled in field */
&hf_msg_reassembled_in,
/* Reassembled length field */
&hf_msg_reassembled_length,
/* Reassembled data field */
NULL,
/* Tag */
"Message fragments"
};
#if 0
/* if BACnet uses the reserved values, then patch the corresponding values here, maximum 16 values are defined */
/* FIXME: fGetMaxAPDUSize is commented out, as it is not used. It was used to set variables which were not later used. */
static const guint MaxAPDUSize [] = { 50, 128, 206, 480, 1024, 1476 };
static guint
fGetMaxAPDUSize(guint8 idx)
{
/* only 16 values are defined, so use & 0x0f */
/* check the size of the Array, deliver either the entry
or the first entry if idx is outside of the array (bug 3736 comment#7) */
if ((idx & 0x0f) >= (gint)(sizeof(MaxAPDUSize)/sizeof(guint)))
return MaxAPDUSize[0];
else
return MaxAPDUSize[idx & 0x0f];
}
#endif
static const char*
val_to_split_str(guint32 val, guint32 split_val, const value_string *vs,
const char *fmt, const char *split_fmt)
G_GNUC_PRINTF(4, 0)
G_GNUC_PRINTF(5, 0);
/* Used when there are ranges of reserved and proprietary enumerations */
static const char*
val_to_split_str(guint32 val, guint32 split_val, const value_string *vs,
const char *fmt, const char *split_fmt)
{
if (val < split_val)
return val_to_str(val, vs, fmt);
else
return val_to_str(val, vs, split_fmt);
}
/* from clause 20.2.1.3.2 Constructed Data */
/* returns true if the extended value is used */
static gboolean
tag_is_extended_value(guint8 tag)
{
return (tag & 0x07) == 5;
}
static gboolean
tag_is_opening(guint8 tag)
{
return (tag & 0x07) == 6;
}
static gboolean
tag_is_closing(guint8 tag)
{
return (tag & 0x07) == 7;
}
/* from clause 20.2.1.1 Class
class bit shall be one for context specific tags */
/* returns true if the tag is context specific */
static gboolean
tag_is_context_specific(guint8 tag)
{
return (tag & 0x08) != 0;
}
static gboolean
tag_is_extended_tag_number(guint8 tag)
{
return ((tag & 0xF0) == 0xF0);
}
static guint32
object_id_type(guint32 object_identifier)
{
return ((object_identifier >> 22) & 0x3FF);
}
static guint32
object_id_instance(guint32 object_identifier)
{
return (object_identifier & 0x3FFFFF);
}
static guint
fTagNo(tvbuff_t *tvb, guint offset)
{
return (guint)(tvb_get_guint8(tvb, offset) >> 4);
}
static gboolean
fUnsigned32(tvbuff_t *tvb, guint offset, guint32 lvt, guint32 *val)
{
gboolean valid = TRUE;
switch (lvt) {
case 1:
*val = tvb_get_guint8(tvb, offset);
break;
case 2:
*val = tvb_get_ntohs(tvb, offset);
break;
case 3:
*val = tvb_get_ntoh24(tvb, offset);
break;
case 4:
*val = tvb_get_ntohl(tvb, offset);
break;
default:
valid = FALSE;
break;
}
return valid;
}
static gboolean
fUnsigned64(tvbuff_t *tvb, guint offset, guint32 lvt, guint64 *val)
{
gboolean valid = FALSE;
gint64 value = 0;
guint8 data, i;
if (lvt && (lvt <= 8)) {
valid = TRUE;
for (i = 0; i < lvt; i++) {
data = tvb_get_guint8(tvb, offset+i);
value = (value << 8) + data;
}
*val = value;
}
return valid;
}
/* BACnet Signed Value uses 2's complement notation, but with a twist:
All signed integers shall be encoded in the smallest number of octets
possible. That is, the first octet of any multi-octet encoded value
shall not be X'00' if the most significant bit (bit 7) of the second
octet is 0, and the first octet shall not be X'FF' if the most
significant bit of the second octet is 1. ASHRAE-135-2004-20.2.5 */
static gboolean
fSigned64(tvbuff_t *tvb, guint offset, guint32 lvt, gint64 *val)
{
gboolean valid = FALSE;
gint64 value = 0;
guint8 data;
guint32 i;
/* we can only handle 7 bytes for a 64-bit value due to signed-ness */
if (lvt && (lvt <= 7)) {
valid = TRUE;
data = tvb_get_guint8(tvb, offset);
if ((data & 0x80) != 0)
value = (-1 << 8) | data;
else
value = data;
for (i = 1; i < lvt; i++) {
data = tvb_get_guint8(tvb, offset+i);
value = (value << 8) + data;
}
*val = value;
}
return valid;
}
static guint
fTagHeaderTree(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
guint offset, guint8 *tag_no, guint8* tag_info, guint32 *lvt)
{
proto_item *ti = NULL;
guint8 tag;
guint8 value;
guint tag_len = 1;
guint lvt_len = 1; /* used for tree display of lvt */
guint lvt_offset; /* used for tree display of lvt */
lvt_offset = offset;
tag = tvb_get_guint8(tvb, offset);
*tag_info = 0;
*lvt = tag & 0x07;
/* To solve the problem of lvt values of 6/7 being indeterminate - it */
/* can mean open/close tag or length of 6/7 after the length is */
/* computed below - store whole tag info, not just context bit. */
if (tag_is_context_specific(tag)) *tag_info = tag & 0x0F;
*tag_no = tag >> 4;
if (tag_is_extended_tag_number(tag)) {
*tag_no = tvb_get_guint8(tvb, offset + tag_len++);
}
if (tag_is_extended_value(tag)) { /* length is more than 4 Bytes */
lvt_offset += tag_len;
value = tvb_get_guint8(tvb, lvt_offset);
tag_len++;
if (value == 254) { /* length is encoded with 16 Bits */
*lvt = tvb_get_ntohs(tvb, lvt_offset+1);
tag_len += 2;
lvt_len += 2;
} else if (value == 255) { /* length is encoded with 32 Bits */
*lvt = tvb_get_ntohl(tvb, lvt_offset+1);
tag_len += 4;
lvt_len += 4;
} else
*lvt = value;
}
if (tree) {
proto_tree *subtree;
if (tag_is_opening(tag))
ti = proto_tree_add_text(tree, tvb, offset, tag_len, "{[%u]", *tag_no );
else if (tag_is_closing(tag))
ti = proto_tree_add_text(tree, tvb, offset, tag_len, "}[%u]", *tag_no );
else if (tag_is_context_specific(tag)) {
ti = proto_tree_add_text(tree, tvb, offset, tag_len,
"Context Tag: %u, Length/Value/Type: %u",
*tag_no, *lvt);
} else
ti = proto_tree_add_text(tree, tvb, offset, tag_len,
"Application Tag: %s, Length/Value/Type: %u",
val_to_str(*tag_no,
BACnetApplicationTagNumber,
ASHRAE_Reserved_Fmt),
*lvt);
/* details if needed */
subtree = proto_item_add_subtree(ti, ett_bacapp_tag);
proto_tree_add_item(subtree, hf_BACnetTagClass, tvb, offset, 1, ENC_BIG_ENDIAN);
if (tag_is_extended_tag_number(tag)) {
proto_tree_add_uint_format(subtree,
hf_BACnetContextTagNumber,
tvb, offset, 1, tag,
"Extended Tag Number");
proto_tree_add_item(subtree,
hf_BACnetExtendedTagNumber,
tvb, offset + 1, 1, ENC_BIG_ENDIAN);
} else {
if (tag_is_context_specific(tag))
proto_tree_add_item(subtree,
hf_BACnetContextTagNumber,
tvb, offset, 1, ENC_BIG_ENDIAN);
else
proto_tree_add_item(subtree,
hf_BACnetApplicationTagNumber,
tvb, offset, 1, ENC_BIG_ENDIAN);
}
if (tag_is_closing(tag) || tag_is_opening(tag))
proto_tree_add_item(subtree,
hf_BACnetNamedTag,
tvb, offset, 1, ENC_BIG_ENDIAN);
else if (tag_is_extended_value(tag)) {
proto_tree_add_item(subtree,
hf_BACnetNamedTag,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_uint(subtree, hf_bacapp_tag_lvt,
tvb, lvt_offset, lvt_len, *lvt);
} else
proto_tree_add_uint(subtree, hf_bacapp_tag_lvt,
tvb, lvt_offset, lvt_len, *lvt);
} /* if (tree) */
if (*lvt > tvb_length(tvb)) {
expert_add_info_format(pinfo, ti, &ei_bacapp_bad_length,
"LVT length too long: %d > %d", *lvt,
tvb_length(tvb));
*lvt = 1;
}
return tag_len;
}
static guint
fTagHeader(tvbuff_t *tvb, packet_info *pinfo, guint offset, guint8 *tag_no, guint8* tag_info,
guint32 *lvt)
{
return fTagHeaderTree(tvb, pinfo, NULL, offset, tag_no, tag_info, lvt);
}
static guint
fNullTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree;
subtree = proto_tree_add_subtree_format(tree, tvb, offset, 1, ett_bacapp_tag, NULL, "%sNULL", label);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset + 1;
}
static guint
fBooleanTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint8 tag_no, tag_info;
guint32 lvt = 0;
proto_tree *subtree;
guint bool_len = 1;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_info && lvt == 1) {
lvt = tvb_get_guint8(tvb, offset+1);
++bool_len;
}
subtree = proto_tree_add_subtree_format(tree, tvb, offset, bool_len,
ett_bacapp_tag, NULL, "%s%s", label, lvt == 0 ? "FALSE" : "TRUE");
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset + bool_len;
}
static guint
fUnsignedTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint64 val = 0;
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* only support up to an 8 byte (64-bit) integer */
if (fUnsigned64(tvb, offset + tag_len, lvt, &val))
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "%s(Unsigned) %" G_GINT64_MODIFIER "u", label, val);
else
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "%s - %u octets (Unsigned)", label, lvt);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
static guint
fDevice_Instance(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, int hf)
{
guint8 tag_no, tag_info;
guint32 lvt, safe_lvt;
guint tag_len;
proto_item *ti;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (lvt > 4)
safe_lvt = 4;
else
safe_lvt = lvt;
ti = proto_tree_add_item(tree, hf, tvb, offset+tag_len, safe_lvt, ENC_BIG_ENDIAN);
if (lvt != safe_lvt)
expert_add_info_format(pinfo, ti, &ei_bacapp_bad_length,
"This field claims to be an impossible %u bytes, while the max is %u", lvt, safe_lvt);
subtree = proto_item_add_subtree(ti, ett_bacapp_tag);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
/* set split_val to zero when not needed */
static guint
fEnumeratedTagSplit(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
guint offset, const gchar *label, const value_string *vs, guint32 split_val)
{
guint32 val = 0;
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* only support up to a 4 byte (32-bit) enumeration */
if (fUnsigned32(tvb, offset+tag_len, lvt, &val)) {
if (vs)
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "%s %s", label, val_to_split_str(val, split_val, vs,
ASHRAE_Reserved_Fmt, Vendor_Proprietary_Fmt));
else
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "%s %u", label, val);
} else {
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "%s - %u octets (enumeration)", label, lvt);
}
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
static guint
fEnumeratedTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
guint offset, const gchar *label, const value_string *vs)
{
return fEnumeratedTagSplit(tvb, pinfo, tree, offset, label, vs, 0);
}
static guint
fSignedTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
gint64 val = 0;
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (fSigned64(tvb, offset + tag_len, lvt, &val))
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "%s(Signed) %" G_GINT64_MODIFIER "d", label, val);
else
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "%s - %u octets (Signed)", label, lvt);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
static guint
fRealTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
gfloat f_val;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
f_val = tvb_get_ntohieee_float(tvb, offset+tag_len);
subtree = proto_tree_add_subtree_format(tree, tvb, offset, 4+tag_len,
ett_bacapp_tag, NULL, "%s%f (Real)", label, f_val);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+4;
}
static guint
fDoubleTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
gdouble d_val;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
d_val = tvb_get_ntohieee_double(tvb, offset+tag_len);
subtree = proto_tree_add_subtree_format(tree, tvb, offset, 8+tag_len,
ett_bacapp_tag, NULL, "%s%f (Double)", label, d_val);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+8;
}
static guint
fProcessId(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint32 val = 0, lvt;
guint8 tag_no, tag_info;
proto_item *ti;
proto_tree *subtree;
guint tag_len;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (fUnsigned32(tvb, offset+tag_len, lvt, &val))
{
ti = proto_tree_add_uint(tree, hf_bacapp_tag_ProcessId,
tvb, offset, lvt+tag_len, val);
subtree = proto_item_add_subtree(ti, ett_bacapp_tag);
}
else
{
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "Process Identifier - %u octets (Signed)", lvt);
}
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset += tag_len + lvt;
return offset;
}
static guint
fTimeSpan(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint32 val = 0, lvt;
guint8 tag_no, tag_info;
proto_tree *subtree;
guint tag_len;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (fUnsigned32(tvb, offset+tag_len, lvt, &val))
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL,
"%s (hh.mm.ss): %d.%02d.%02d%s",
label,
(val / 3600), ((val % 3600) / 60), (val % 60),
val == 0 ? " (indefinite)" : "");
else
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL,
"%s - %u octets (Signed)", label, lvt);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
static guint
fWeekNDay(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint32 month, weekOfMonth, dayOfWeek;
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
month = tvb_get_guint8(tvb, offset+tag_len);
weekOfMonth = tvb_get_guint8(tvb, offset+tag_len+1);
dayOfWeek = tvb_get_guint8(tvb, offset+tag_len+2);
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "%s %s, %s",
val_to_str(month, months, "month (%d) not found"),
val_to_str(weekOfMonth, weekofmonth, "week of month (%d) not found"),
val_to_str(dayOfWeek, day_of_week, "day of week (%d) not found"));
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
static guint
fDate(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint32 year, month, day, weekday;
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
year = tvb_get_guint8(tvb, offset+tag_len);
month = tvb_get_guint8(tvb, offset+tag_len+1);
day = tvb_get_guint8(tvb, offset+tag_len+2);
weekday = tvb_get_guint8(tvb, offset+tag_len+3);
if ((year == 255) && (day == 255) && (month == 255) && (weekday == 255)) {
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL,
"%sany", label);
}
else if (year != 255) {
year += 1900;
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL,
"%s%s %d, %d, (Day of Week = %s)",
label, val_to_str(month,
months,
"month (%d) not found"),
day, year, val_to_str(weekday,
day_of_week,
"(%d) not found"));
} else {
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL,
"%s%s %d, any year, (Day of Week = %s)",
label, val_to_str(month, months, "month (%d) not found"),
day, val_to_str(weekday, day_of_week, "(%d) not found"));
}
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
static guint
fTime(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint32 hour, minute, second, msec, lvt;
guint8 tag_no, tag_info;
guint tag_len;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
hour = tvb_get_guint8(tvb, offset+tag_len);
minute = tvb_get_guint8(tvb, offset+tag_len+1);
second = tvb_get_guint8(tvb, offset+tag_len+2);
msec = tvb_get_guint8(tvb, offset+tag_len+3);
if ((hour == 255) && (minute == 255) && (second == 255) && (msec == 255))
subtree = proto_tree_add_subtree_format(tree, tvb, offset,
lvt+tag_len, ett_bacapp_tag, NULL,
"%sany", label);
else
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL,
"%s%d:%02d:%02d.%d %s = %02d:%02d:%02d.%d",
label,
hour > 12 ? hour - 12 : hour,
minute, second, msec,
hour >= 12 ? "P.M." : "A.M.",
hour, minute, second, msec);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
static guint
fDateTime(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
proto_tree *subtree = tree;
if (label != NULL) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 10, ett_bacapp_value, NULL, label);
}
offset = fDate(tvb, pinfo, subtree, offset, "Date: ");
return fTime(tvb, pinfo, subtree, offset, "Time: ");
}
static guint
fTimeValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) { /* closing Tag, but not for me */
return offset;
}
offset = fTime(tvb, pinfo, tree, offset, "Time: ");
offset = fApplicationTypes(tvb, pinfo, tree, offset, "Value: ");
if (offset == lastoffset) break; /* exit loop if nothing happens inside */
}
return offset;
}
static guint
fCalendarEntry(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
switch (fTagNo(tvb, offset)) {
case 0: /* Date */
offset = fDate(tvb, pinfo, tree, offset, "Date: ");
break;
case 1: /* dateRange */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fDateRange(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 2: /* BACnetWeekNDay */
offset = fWeekNDay(tvb, pinfo, tree, offset);
break;
default:
return offset;
}
return offset;
}
static guint
fEventTimeStamps( tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint offset)
{
guint32 lvt = 0;
proto_tree* subtree = tree;
if (tvb_reported_length_remaining(tvb, offset) > 0) {
subtree = proto_tree_add_subtree(tree, tvb, offset, lvt, ett_bacapp_tag, NULL, "eventTimeStamps");
offset = fTimeStamp(tvb, pinfo, subtree, offset, "TO-OFFNORMAL timestamp: ");
offset = fTimeStamp(tvb, pinfo, subtree, offset, "TO-FAULT timestamp: ");
offset = fTimeStamp(tvb, pinfo, subtree, offset, "TO-NORMAL timestamp: ");
}
return offset;
}
static guint
fTimeStamp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint8 tag_no = 0, tag_info = 0;
guint32 lvt = 0;
if (tvb_reported_length_remaining(tvb, offset) > 0) { /* don't loop, it's a CHOICE */
switch (fTagNo(tvb, offset)) {
case 0: /* time */
offset = fTime(tvb, pinfo, tree, offset, label?label:"time: ");
break;
case 1: /* sequenceNumber */
offset = fUnsignedTag(tvb, pinfo, tree, offset,
label?label:"sequence number: ");
break;
case 2: /* dateTime */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fDateTime(tvb, pinfo, tree, offset, label?label:"date time: ");
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
}
return offset;
}
static guint
fClientCOV(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
if (tvb_reported_length_remaining(tvb, offset) > 0) {
offset = fApplicationTypes(tvb, pinfo, tree, offset, "increment: ");
}
return offset;
}
static const value_string
BACnetDaysOfWeek [] = {
{ 0, "Monday" },
{ 1, "Tuesday" },
{ 2, "Wednesday" },
{ 3, "Thursday" },
{ 4, "Friday" },
{ 5, "Saturday" },
{ 6, "Sunday" },
{ 0, NULL }
};
static guint
fDestination(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
if (tvb_reported_length_remaining(tvb, offset) > 0) {
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset,
"valid Days: ", BACnetDaysOfWeek);
offset = fTime(tvb, pinfo, tree, offset, "from time: ");
offset = fTime(tvb, pinfo, tree, offset, "to time: ");
offset = fRecipient(tvb, pinfo, tree, offset);
offset = fProcessId(tvb, pinfo, tree, offset);
offset = fApplicationTypes(tvb, pinfo, tree, offset,
"issue confirmed notifications: ");
offset = fBitStringTagVS(tvb, pinfo, tree, offset,
"transitions: ", BACnetEventTransitionBits);
}
return offset;
}
static guint
fOctetString(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label, guint32 lvt)
{
gchar *tmp;
guint start = offset;
guint8 tag_no, tag_info;
proto_tree *subtree = tree;
offset += fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (lvt > 0) {
tmp = tvb_bytes_to_ep_str(tvb, offset, lvt);
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt,
ett_bacapp_tag, NULL, "%s %s", label, tmp);
offset += lvt;
}
fTagHeaderTree(tvb, pinfo, subtree, start, &tag_no, &tag_info, &lvt);
return offset;
}
static guint
fMacAddress(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label, guint32 lvt)
{
guint start = offset;
guint8 tag_no, tag_info;
proto_tree* subtree = tree;
offset += fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
subtree = proto_tree_add_subtree(tree, tvb, offset, 6, ett_bacapp_tag, NULL, label); /* just add the label, with the tagHeader information in its subtree */
if (lvt > 0) {
if (lvt == 6) { /* we have 6 Byte IP Address with 4 Octets IPv4 and 2 Octets Port Information */
proto_tree_add_item(tree, hf_bacapp_tag_IPV4, tvb, offset, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_bacapp_tag_PORT, tvb, offset+4, 2, ENC_BIG_ENDIAN);
} else {
if (lvt == 18) { /* we have 18 Byte IP Address with 16 Octets IPv6 and 2 Octets Port Information */
proto_tree_add_item(tree, hf_bacapp_tag_IPV6, tvb, offset, 16, ENC_NA);
proto_tree_add_item(tree, hf_bacapp_tag_PORT, tvb, offset+16, 2, ENC_BIG_ENDIAN);
} else { /* we have 1 Byte MS/TP Address or anything else interpreted as an address */
subtree = proto_tree_add_subtree(tree, tvb, offset, lvt,
ett_bacapp_tag, NULL, tvb_bytes_to_ep_str(tvb, offset, lvt));
}
}
offset += lvt;
}
fTagHeaderTree(tvb, pinfo, subtree, start, &tag_no, &tag_info, &lvt);
return offset;
}
static guint
fAddress(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint offs;
offset = fUnsignedTag(tvb, pinfo, tree, offset, "network-number");
offs = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (lvt == 0) {
proto_tree_add_text(tree, tvb, offset, offs, "MAC-address: broadcast");
offset += offs;
} else
offset = fMacAddress(tvb, pinfo, tree, offset, "MAC-address: ", lvt);
return offset;
}
static guint
fSessionKey(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
offset = fOctetString(tvb, pinfo, tree, offset, "session key: ", 8);
return fAddress(tvb, pinfo, tree, offset);
}
static guint
fObjectIdentifier(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_length;
proto_tree *subtree;
guint32 object_id;
tag_length = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
object_id = tvb_get_ntohl(tvb, offset+tag_length);
object_type = object_id_type(object_id);
subtree = proto_tree_add_subtree_format(tree, tvb, offset, tag_length + 4,
ett_bacapp_tag, NULL, "ObjectIdentifier: %s, %u",
val_to_split_str(object_type,
128,
BACnetObjectType,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt),
object_id_instance(object_id));
if (col_get_writable(pinfo->cinfo))
col_append_fstr(pinfo->cinfo, COL_INFO, "%s,%u ",
val_to_split_str(object_type,
128,
BACnetObjectType,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt),
object_id_instance(object_id));
/* update BACnet Statistics */
updateBacnetInfoValue(BACINFO_OBJECTID,
wmem_strdup(wmem_packet_scope(),
val_to_split_str(object_type, 128,
BACnetObjectType, ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt)));
updateBacnetInfoValue(BACINFO_INSTANCEID,
wmem_strdup_printf(wmem_packet_scope(),
"Instance ID: %u",
object_id_instance(object_id)));
/* here are the details of how we arrived at the above text */
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset += tag_length;
proto_tree_add_item(subtree, hf_bacapp_objectType, tvb, offset, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(subtree, hf_bacapp_instanceNumber, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
return offset;
}
static guint
fRecipient(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_no < 2) {
if (tag_no == 0) { /* device */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
}
else { /* address */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fAddress(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
}
}
return offset;
}
static guint
fRecipientProcess(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *orgtree = tree;
proto_tree *subtree;
/* beginning of new item - indent and label */
tree = proto_tree_add_subtree(orgtree, tvb, offset, 1, ett_bacapp_value, NULL, "Recipient Process" );
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* recipient */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt); /* show context open */
subtree = proto_tree_add_subtree(tree, tvb, offset, 1, ett_bacapp_value, NULL, "Recipient"); /* add tree label and indent */
offset = fRecipient(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt); /* show context close */
break;
case 1: /* processId */
offset = fProcessId(tvb, pinfo, tree, offset);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fCOVSubscription(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree;
proto_tree *orgtree = tree;
guint itemno = 1;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info) ) {
return offset;
}
switch (tag_no) {
case 0: /* recipient */
/* beginning of new item in list */
tree = proto_tree_add_subtree_format(orgtree, tvb, offset, 1,
ett_bacapp_value, NULL, "Subscription %d",itemno); /* add tree label and indent */
itemno = itemno + 1;
subtree = proto_tree_add_subtree(tree, tvb, offset, 1,
ett_bacapp_value, NULL, "Recipient"); /* add tree label and indent */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt); /* show context open */
offset = fRecipientProcess(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt); /* show context close */
break;
case 1: /* MonitoredPropertyReference */
subtree = proto_tree_add_subtree(tree, tvb, offset, 1,
ett_bacapp_value, NULL, "Monitored Property Reference");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fBACnetObjectPropertyReference(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 2: /* IssueConfirmedNotifications - boolean */
offset = fBooleanTag(tvb, pinfo, tree, offset, "Issue Confirmed Notifications: ");
break;
case 3: /* TimeRemaining */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Time Remaining: ");
break;
case 4: /* COVIncrement */
offset = fRealTag(tvb, pinfo, tree, offset, "COV Increment: ");
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fAddressBinding(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
return fAddress(tvb, pinfo, tree, offset);
}
static guint
fActionCommand(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 tag_match)
{
guint lastoffset = 0, len;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
/* set the optional global properties to indicate not-used */
propertyArrayIndex = -1;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info) ) {
if (tag_no == tag_match) {
return offset;
}
offset += len;
subtree = tree;
continue;
}
switch (tag_no) {
case 0: /* deviceIdentifier */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 1: /* objectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 2: /* propertyIdentifier */
offset = fPropertyIdentifier(tvb, pinfo, subtree, offset);
break;
case 3: /* propertyArrayIndex */
offset = fPropertyArrayIndex(tvb, pinfo, subtree, offset);
break;
case 4: /* propertyValue */
offset = fPropertyValue(tvb, pinfo, subtree, offset, tag_info);
break;
case 5: /* priority */
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "Priority: ");
break;
case 6: /* postDelay */
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "Post Delay: ");
break;
case 7: /* quitOnFailure */
offset = fBooleanTag(tvb, pinfo, subtree, offset,
"Quit On Failure: ");
break;
case 8: /* writeSuccessful */
offset = fBooleanTag(tvb, pinfo, subtree, offset,
"Write Successful: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
/* BACnetActionList ::= SEQUENCE{
action [0] SEQUENCE OF BACnetActionCommand
}
*/
static guint
fActionList(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0, len;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
while (tvb_reported_length_remaining(tvb, offset) > 0) {
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
subtree = tree;
if ( tag_no != 0 ) /* don't eat the closing property tag, just return */
return offset;
offset += len;
continue;
}
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(tree, tvb, offset, 1, ett_bacapp_tag, NULL, "Action List");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset,
&tag_no, &tag_info, &lvt);
}
switch (tag_no) {
case 0: /* BACnetActionCommand */
offset = fActionCommand(tvb, pinfo, subtree, offset, tag_no);
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fPropertyIdentifier(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_tree *subtree;
const gchar *label = "Property Identifier";
propertyIdentifier = 0; /* global Variable */
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* can we decode this value? */
if (fUnsigned32(tvb, offset+tag_len, lvt, (guint32 *)&propertyIdentifier)) {
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL,
"%s: %s (%u)", label,
val_to_split_str(propertyIdentifier, 512,
BACnetPropertyIdentifier,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt), propertyIdentifier);
if (col_get_writable(pinfo->cinfo))
col_append_fstr(pinfo->cinfo, COL_INFO, "%s ",
val_to_split_str(propertyIdentifier, 512,
BACnetPropertyIdentifier,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt));
} else {
/* property identifiers cannot be larger than 22-bits */
return offset;
}
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
proto_tree_add_item(subtree, hf_BACnetPropertyIdentifier, tvb,
offset+tag_len, lvt, ENC_BIG_ENDIAN);
return offset+tag_len+lvt;
}
static guint
fPropertyArrayIndex(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_tree *subtree;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (fUnsigned32(tvb, offset + tag_len, lvt, (guint32 *)&propertyArrayIndex))
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "property Array Index (Unsigned) %u", propertyArrayIndex);
else
subtree = proto_tree_add_subtree_format(tree, tvb, offset, lvt+tag_len,
ett_bacapp_tag, NULL, "property Array Index - %u octets (Unsigned)", lvt);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset+tag_len+lvt;
}
static guint
fCharacterString(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint8 tag_no, tag_info, character_set;
guint32 lvt, l;
guint offs, extra = 1;
const char *coding;
guint8 *out;
proto_tree *subtree;
guint start = offset;
if (tvb_reported_length_remaining(tvb, offset) > 0) {
offs = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
character_set = tvb_get_guint8(tvb, offset+offs);
/* Account for code page if DBCS */
if (character_set == 1) {
extra = 3;
}
offset += (offs+extra);
lvt -= (extra);
do {
l = MIN(lvt, 256);
/*
* XXX - are we guaranteed that these encoding
* names correspond, on *all* platforms with
* iconv(), to the encodings we want?
* If not (and perhaps even if so), we should
* perhaps have our own iconv() implementation,
* with a different name, so that we control the
* encodings it supports and the names of those
* encodings.
*
* We should also handle that in the general
* string handling code, rather than making it
* specific to the BACAPP dissector, as many
* other dissectors need to handle various
* character encodings.
*/
/** this decoding may be not correct for multi-byte characters, Lka */
switch (character_set) {
case ANSI_X3_4:
out = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, l, ENC_UTF_8);
coding = "UTF-8";
break;
case IBM_MS_DBCS:
out = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, l, ENC_ASCII);
coding = "IBM MS DBCS";
break;
case JIS_C_6226:
out = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, l, ENC_ASCII);
coding = "JIS C 6226";
break;
case ISO_10646_UCS4:
out = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, l, ENC_UCS_4|ENC_BIG_ENDIAN);
coding = "ISO 10646 UCS-4";
break;
case ISO_10646_UCS2:
out = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, l, ENC_UCS_2|ENC_BIG_ENDIAN);
coding = "ISO 10646 UCS-2";
break;
case ISO_8859_1:
out = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, l, ENC_ISO_8859_1);
coding = "ISO 8859-1";
break;
default:
/* Assume this is some form of extended ASCII, with one-byte code points for ASCII characters */
out = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, l, ENC_ASCII);
coding = "unknown";
break;
}
subtree = proto_tree_add_subtree_format(tree, tvb, offset, l, ett_bacapp_tag, NULL,
"%s%s '%s'", label, coding, out);
lvt -= l;
offset += l;
} while (lvt > 0);
fTagHeaderTree(tvb, pinfo, subtree, start, &tag_no, &tag_info, &lvt);
proto_tree_add_item(subtree, hf_BACnetCharacterSet, tvb, start+offs, 1, ENC_BIG_ENDIAN);
if (character_set == 1) {
proto_tree_add_text(subtree, tvb, start+offs+1, 2, "Code Page: %d", tvb_get_ntohs(tvb, start+offs+1));
}
/* XXX - put the string value here */
}
return offset;
}
static guint
fBitStringTagVS(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label,
const value_string *src)
{
guint8 tag_no, tag_info, tmp;
gint j, unused, skip;
guint start = offset;
guint offs;
guint32 lvt, i, numberOfBytes;
guint8 bf_arr[256];
proto_tree* subtree = tree;
offs = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
numberOfBytes = lvt-1; /* Ignore byte for unused bit count */
offset += offs;
unused = tvb_get_guint8(tvb, offset); /* get the unused Bits */
subtree = proto_tree_add_subtree_format(tree, tvb, start, offs+lvt,
ett_bacapp_tag, NULL,
"%s(Bit String)", label);
fTagHeaderTree(tvb, pinfo, subtree, start, &tag_no, &tag_info, &lvt);
proto_tree_add_text(subtree, tvb, offset, 1,
"Unused bits: %u", unused);
memset(bf_arr, 0, 256);
skip = 0;
for (i = 0; i < numberOfBytes; i++) {
tmp = tvb_get_guint8(tvb, (offset)+i+1);
if (i == numberOfBytes-1) { skip = unused; }
for (j = 0; j < 8-skip; j++) {
if (src != NULL) {
if (tmp & (1 << (7 - j)))
proto_tree_add_text(subtree, tvb,
offset+i+1, 1,
"%s = TRUE",
val_to_str((guint) (i*8 +j),
src,
ASHRAE_Reserved_Fmt));
else
proto_tree_add_text(subtree, tvb,
offset+i+1, 1,
"%s = FALSE",
val_to_str((guint) (i*8 +j),
src,
ASHRAE_Reserved_Fmt));
} else {
bf_arr[MIN(255, (i*8)+j)] = tmp & (1 << (7 - j)) ? '1' : '0';
}
}
}
if (src == NULL) {
bf_arr[MIN(255, numberOfBytes*8-unused)] = 0;
proto_tree_add_text(subtree, tvb, offset, lvt, "B'%s'", bf_arr);
}
offset += lvt;
return offset;
}
static guint
fBitStringTag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
return fBitStringTagVS(tvb, pinfo, tree, offset, label, NULL);
}
/* handles generic application types, as well as enumerated and enumerations
with reserved and proprietarty ranges (split) */
static guint
fApplicationTypesEnumeratedSplit(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset,
const gchar *label, const value_string *src, guint32 split_val)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
if (tvb_reported_length_remaining(tvb, offset) > 0) {
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (!tag_is_context_specific(tag_info)) {
switch (tag_no) {
case 0: /** NULL 20.2.2 */
offset = fNullTag(tvb, pinfo, tree, offset, label);
break;
case 1: /** BOOLEAN 20.2.3 */
offset = fBooleanTag(tvb, pinfo, tree, offset, label);
break;
case 2: /** Unsigned Integer 20.2.4 */
offset = fUnsignedTag(tvb, pinfo, tree, offset, label);
break;
case 3: /** Signed Integer 20.2.5 */
offset = fSignedTag(tvb, pinfo, tree, offset, label);
break;
case 4: /** Real 20.2.6 */
offset = fRealTag(tvb, pinfo, tree, offset, label);
break;
case 5: /** Double 20.2.7 */
offset = fDoubleTag(tvb, pinfo, tree, offset, label);
break;
case 6: /** Octet String 20.2.8 */
offset = fOctetString(tvb, pinfo, tree, offset, label, lvt);
break;
case 7: /** Character String 20.2.9 */
offset = fCharacterString(tvb, pinfo, tree, offset, label);
break;
case 8: /** Bit String 20.2.10 */
offset = fBitStringTagVS(tvb, pinfo, tree, offset, label, src);
break;
case 9: /** Enumerated 20.2.11 */
offset = fEnumeratedTagSplit(tvb, pinfo, tree, offset, label, src, split_val);
break;
case 10: /** Date 20.2.12 */
offset = fDate(tvb, pinfo, tree, offset, label);
break;
case 11: /** Time 20.2.13 */
offset = fTime(tvb, pinfo, tree, offset, label);
break;
case 12: /** BACnetObjectIdentifier 20.2.14 */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 13: /* reserved for ASHRAE */
case 14:
case 15:
proto_tree_add_text(tree, tvb, offset, lvt+tag_len, "%s'reserved for ASHRAE'", label);
offset += lvt + tag_len;
break;
default:
break;
}
}
}
return offset;
}
static guint
fShedLevel(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* percent */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "shed percent: ");
break;
case 1: /* level */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "shed level: ");
break;
case 2: /* amount */
offset = fRealTag(tvb, pinfo, tree, offset, "shed amount: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fApplicationTypesEnumerated(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset,
const gchar *label, const value_string *vs)
{
return fApplicationTypesEnumeratedSplit(tvb, pinfo, tree, offset, label, vs, 0);
}
static guint
fApplicationTypes(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset,
const gchar *label)
{
return fApplicationTypesEnumeratedSplit(tvb, pinfo, tree, offset, label, NULL, 0);
}
static guint
fContextTaggedValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_tree *subtree;
gint tvb_len;
(void)label;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* cap the the suggested length in case of bad data */
tvb_len = tvb_reported_length_remaining(tvb, offset+tag_len);
if ((tvb_len >= 0) && ((guint32)tvb_len < lvt)) {
lvt = tvb_len;
}
subtree = proto_tree_add_subtree_format(tree, tvb, offset+tag_len, lvt,
ett_bacapp_tag, NULL, "Context Value (as %u DATA octets)", lvt);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset + tag_len + lvt;
}
/*
BACnetPrescale ::= SEQUENCE {
multiplier [0] Unsigned,
moduloDivide [1] Unsigned
}
*/
static guint
fPrescale(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info) ) {
return offset;
}
switch (tag_no) {
case 0: /* multiplier */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Multiplier: ");
break;
case 1: /* moduloDivide */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Modulo Divide: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
/*
BACnetScale ::= CHOICE {
floatScale [0] REAL,
integerScale [1] INTEGER
}
*/
static guint
fScale(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info) ) {
return offset;
}
switch (tag_no) {
case 0: /* floatScale */
offset = fRealTag(tvb, pinfo, tree, offset, "Float Scale: ");
break;
case 1: /* integerScale */
offset = fSignedTag(tvb, pinfo, tree, offset, "Integer Scale: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
/*
BACnetAccumulatorRecord ::= SEQUENCE {
timestamp [0] BACnetDateTime,
presentValue [1] Unsigned,
accumulatedValue [2] Unsigned,
accumulatortStatus [3] ENUMERATED {
normal (0),
starting (1),
recovered (2),
abnormal (3),
failed (4)
}
}
*/
static guint
fLoggingRecord(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info) ) {
return offset;
}
switch (tag_no) {
case 0: /* timestamp */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fDateTime(tvb, pinfo, tree, offset, "Timestamp: ");
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 1: /* presentValue */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Present Value: ");
break;
case 2: /* accumulatedValue */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Accumulated Value: ");
break;
case 3: /* accumulatorStatus */
offset = fEnumeratedTag(tvb, pinfo, tree, offset, "Accumulator Status: ", BACnetAccumulatorStatus);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
/*
SEQ OF Any enumeration (current usage is SEQ OF BACnetDoorAlarmState
*/
static guint
fSequenceOfEnums(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label, const value_string *vs)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info) ) {
return offset;
}
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, label, vs);
if ( offset == lastoffset ) break;
}
return offset;
}
/*
SEQ OF BACnetDeviceObjectReference (accessed as an array)
}
*/
static guint
fDoorMembers(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info) ) {
return offset;
}
offset = fDeviceObjectReference(tvb, pinfo, tree, offset);
if (offset == lastoffset) break;
}
return offset;
}
/*
SEQ OF ReadAccessSpecification
*/
static guint
fListOfGroupMembers(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info) ) {
return offset;
}
offset = fReadAccessSpecification(tvb, pinfo, tree, offset);
if ( offset == lastoffset ) break;
}
return offset;
}
static guint
fAbstractSyntaxNType(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint lastoffset = 0, depth = 0;
char ar[256];
guint32 save_object_type;
if (propertyIdentifier >= 0) {
g_snprintf(ar, sizeof(ar), "%s: ",
val_to_split_str(propertyIdentifier, 512,
BACnetPropertyIdentifier,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt));
} else {
g_snprintf(ar, sizeof(ar), "Abstract Type: ");
}
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) { /* closing tag, but not for me */
if (depth <= 0) return offset;
}
/* Application Tags */
switch (propertyIdentifier) {
case 2: /* action */
/* loop object is application tagged,
command object is context tagged */
if (tag_is_context_specific(tag_info)) {
/* BACnetActionList */
offset = fActionList(tvb, pinfo, tree, offset);
} else {
/* BACnetAction */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar,
BACnetAction);
}
break;
case 30: /* BACnetAddressBinding */
offset = fAddressBinding(tvb, pinfo, tree, offset);
break;
case 54: /* list of object property reference */
offset = fLOPR(tvb, pinfo, tree, offset);
break;
case 55: /* list-of-session-keys */
fSessionKey(tvb, pinfo, tree, offset);
break;
case 79: /* object-type */
case 96: /* protocol-object-types-supported */
offset = fApplicationTypesEnumeratedSplit(tvb, pinfo, tree, offset, ar,
BACnetObjectType, 128);
break;
case 97: /* Protocol-Services-Supported */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar,
BACnetServicesSupported);
break;
case 102: /* recipient-list */
offset = fDestination(tvb, pinfo, tree, offset);
break;
case 107: /* segmentation-supported */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar,
BACnetSegmentation);
break;
case 111: /* Status-Flags */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar,
BACnetStatusFlags);
break;
case 112: /* System-Status */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar,
BACnetDeviceStatus);
break;
case 117: /* units */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar,
BACnetEngineeringUnits);
break;
case 87: /* priority-array -- accessed as a BACnetARRAY */
if (propertyArrayIndex == 0) {
/* BACnetARRAY index 0 refers to the length
of the array, not the elements of the array */
offset = fApplicationTypes(tvb, pinfo, tree, offset, ar);
} else {
offset = fPriorityArray(tvb, pinfo, tree, offset);
}
break;
case 38: /* exception-schedule */
if (object_type < 128) {
if (propertyArrayIndex == 0) {
/* BACnetARRAY index 0 refers to the length
of the array, not the elements of the array */
offset = fApplicationTypes(tvb, pinfo, tree, offset, ar);
} else {
offset = fSpecialEvent(tvb, pinfo, tree, offset);
}
}
break;
case 19: /* controlled-variable-reference */
case 60: /* manipulated-variable-reference */
case 132: /* log-device-object-property */
offset = fDeviceObjectPropertyReference(tvb, pinfo, tree, offset);
break;
case 109: /* Setpoint-Reference */
/* setpoint-Reference is actually BACnetSetpointReference which is a SEQ of [0] */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fBACnetObjectPropertyReference(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 123: /* weekly-schedule -- accessed as a BACnetARRAY */
if (object_type < 128) {
if (propertyArrayIndex == 0) {
/* BACnetARRAY index 0 refers to the length
of the array, not the elements of the array */
offset = fApplicationTypes(tvb, pinfo, tree, offset, ar);
} else {
offset = fWeeklySchedule(tvb, pinfo, tree, offset);
}
}
break;
case 127: /* client COV increment */
offset = fClientCOV(tvb, pinfo, tree, offset);
break;
case 131: /* log-buffer */
if ( object_type == 25 )
offset = fEventLogRecord(tvb, pinfo, tree, offset);
else if ( object_type == 27 )
offset = fLogMultipleRecord(tvb, pinfo, tree, offset);
else
offset = fLogRecord(tvb, pinfo, tree, offset);
break;
case 159: /* member-of */
case 165: /* zone-members */
offset = fDeviceObjectReference(tvb, pinfo, tree, offset);
break;
case 196: /* last-restart-reason */
offset = fRestartReason(tvb, pinfo, tree, offset);
break;
case 212: /* actual-shed-level */
case 214: /* expected-shed-level */
case 218: /* requested-shed-level */
offset = fShedLevel(tvb, pinfo, tree, offset);
break;
case 152: /* active-cov-subscriptions */
offset = fCOVSubscription(tvb, pinfo, tree, offset);
break;
case 23: /* date-list */
offset = fCalendarEntry(tvb, pinfo, tree, offset);
break;
case 116: /* time-sychronization-recipients */
offset = fRecipient(tvb, pinfo, tree, offset);
break;
case 83: /* event-parameters */
offset = fEventParameter(tvb, pinfo, tree, offset);
break;
case 211: /* subordinate-list */
offset = fDeviceObjectReference(tvb, pinfo, tree, offset);
break;
case 130: /* event-time-stamp */
offset = fEventTimeStamps(tvb, pinfo, tree, offset);
break;
case 197: /* logging-type */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetLoggingType);
break;
case 36: /* event-state */
offset = fApplicationTypesEnumeratedSplit(tvb, pinfo, tree, offset, ar, BACnetEventState, 64);
break;
case 103: /* reliability */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetReliability);
break;
case 72: /* notify-type */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetNotifyType);
break;
case 208: /* node-type */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetNodeType);
break;
case 231: /* door-status */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetDoorStatus);
break;
case 233: /* lock-status */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetLockStatus);
break;
case 235: /* secured-status */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetDoorSecuredStatus);
break;
case 158: /* maintenance-required */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetMaintenance);
break;
case 92: /* program-state */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetProgramState);
break;
case 90: /* program-change */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetProgramRequest);
break;
case 100: /* reason-for-halt */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetProgramError);
break;
case 160: /* mode */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetLifeSafetyMode);
break;
case 163: /* silenced */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetSilencedState);
break;
case 161: /* operation-expected */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetLifeSafetyOperation);
break;
case 164: /* tracking-value */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetLifeSafetyState);
break;
case 41: /* file-access-method */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset, ar, BACnetFileAccessMethod);
break;
case 185: /* prescale */
offset = fPrescale(tvb, pinfo, tree, offset);
break;
case 187: /* scale */
offset = fScale(tvb, pinfo, tree, offset);
break;
case 184: /* logging-record */
offset = fLoggingRecord(tvb, pinfo, tree, offset);
break;
case 228: /* door-members */
offset = fDoorMembers(tvb, pinfo, tree, offset);
break;
case 181: /* input-reference */
offset = fObjectPropertyReference(tvb, pinfo, tree, offset);
break;
case 78: /* object-property-reference */
offset = fObjectPropertyReference(tvb, pinfo, tree, offset);
break;
case 234: /* masked-alarm-values */
offset = fSequenceOfEnums(tvb, pinfo, tree, offset, "masked-alarm-value: ", BACnetDoorAlarmState);
break;
case 53: /* list-of-group-members */
save_object_type = object_type;
offset = fListOfGroupMembers(tvb, pinfo, tree, offset);
object_type = save_object_type;
break;
case 85: /* present-value */
if ( object_type == 11 ) /* group object handling of present-value */
{
offset = fReadAccessResult(tvb, pinfo, tree, offset);
break;
}
/* intentially fall through here so don't reorder this case statement */
default:
if (tag_info) {
if (tag_is_opening(tag_info)) {
++depth;
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
} else if (tag_is_closing(tag_info)) {
--depth;
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
} else {
offset = fContextTaggedValue(tvb, pinfo, tree, offset, ar);
}
} else {
offset = fApplicationTypes(tvb, pinfo, tree, offset, ar);
}
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fPropertyValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 tag_info)
{
guint8 tag_no;
guint32 lvt;
if (tag_is_opening(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, tree, offset,
&tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, tree, offset);
if (tvb_length_remaining(tvb, offset) > 0) {
offset += fTagHeaderTree(tvb, pinfo, tree, offset,
&tag_no, &tag_info, &lvt);
}
} else {
proto_tree_add_text(tree, tvb, offset, tvb_length(tvb) - offset,
"expected Opening Tag!");
offset = tvb_length(tvb);
}
return offset;
}
static guint
fPropertyIdentifierValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 tagoffset)
{
guint lastoffset = offset;
guint8 tag_no, tag_info;
guint32 lvt;
offset = fPropertyReference(tvb, pinfo, tree, offset, tagoffset, 0);
if (offset > lastoffset) {
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_no == tagoffset+2) { /* Value - might not be present in ReadAccessResult */
offset = fPropertyValue(tvb, pinfo, tree, offset, tag_info);
}
}
return offset;
}
static guint
fBACnetPropertyValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
offset = fPropertyIdentifierValue(tvb, pinfo, tree, offset, 0);
if (offset > lastoffset) {
/* detect optional priority
by looking to see if the next tag is context tag number 3 */
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_context_specific(tag_info) && (tag_no == 3))
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Priority: ");
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fSubscribeCOVPropertyRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0, len;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
offset += len;
subtree = tree;
continue;
}
switch (tag_no) {
case 0: /* ProcessId */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "subscriber Process Id: ");
break;
case 1: /* monitored ObjectId */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 2: /* issueConfirmedNotifications */
offset = fBooleanTag(tvb, pinfo, tree, offset, "issue Confirmed Notifications: ");
break;
case 3: /* life time */
offset = fTimeSpan(tvb, pinfo, tree, offset, "life time");
break;
case 4: /* monitoredPropertyIdentifier */
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL, "monitoredPropertyIdentifier");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fBACnetPropertyReference(tvb, pinfo, subtree, offset, 1);
break;
}
FAULT;
break;
case 5: /* covIncrement */
offset = fRealTag(tvb, pinfo, tree, offset, "COV Increment: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fSubscribeCOVRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fSubscribeCOVPropertyRequest(tvb, pinfo, tree, offset);
}
static guint
fWhoHas(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* deviceInstanceLowLimit */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "device Instance Low Limit: ");
break;
case 1: /* deviceInstanceHighLimit */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "device Instance High Limit: ");
break;
case 2: /* BACnetObjectId */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 3: /* messageText */
offset = fCharacterString(tvb, pinfo, tree, offset, "Object Name: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fDailySchedule(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_opening(tag_info) && tag_no == 0) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt); /* opening context tag 0 */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
/* should be closing context tag 0 */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset;
}
offset = fTimeValue(tvb, pinfo, subtree, offset);
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
} else if ((tag_no == 0) && (lvt == 0)) {
/* not sure null (empty array element) is legal */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
}
return offset;
}
static guint
fWeeklySchedule(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
guint i = 1; /* day of week array index */
proto_tree *subtree = tree;
if (propertyArrayIndex > 0) {
/* BACnetARRAY index 0 refers to the length
of the array, not the elements of the array.
BACnetARRAY index -1 is our internal flag that
the optional index was not used.
BACnetARRAY refers to this as all elements of the array.
If the optional index is specified for a BACnetARRAY,
then that specific array element is referenced. */
i = propertyArrayIndex;
}
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
return offset; /* outer encoding will print out closing tag */
}
subtree = proto_tree_add_subtree(tree, tvb, offset, 0, ett_bacapp_value, NULL,
val_to_str(i++, day_of_week, "day of week (%d) not found"));
offset = fDailySchedule(tvb, pinfo, subtree, offset);
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fUTCTimeSynchronizationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
if (tvb_reported_length_remaining(tvb, offset) <= 0)
return offset;
return fDateTime(tvb, pinfo, tree, offset, "UTC-Time: ");
}
static guint
fTimeSynchronizationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
if (tvb_reported_length_remaining(tvb, offset) <= 0)
return offset;
return fDateTime(tvb, pinfo, tree, offset, NULL);
}
static guint
fDateRange(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
if (tvb_reported_length_remaining(tvb, offset) <= 0)
return offset;
offset = fDate(tvb, pinfo, tree, offset, "Start Date: ");
return fDate(tvb, pinfo, tree, offset, "End Date: ");
}
static guint
fVendorIdentifier(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint32 val = 0;
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_item *ti;
proto_tree *subtree;
const gchar *label = "Vendor ID";
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (fUnsigned32(tvb, offset + tag_len, lvt, &val))
ti = proto_tree_add_text(tree, tvb, offset, lvt+tag_len,
"%s: %s (%u)",
label,
val_to_str_ext_const(val, &BACnetVendorIdentifiers_ext, "Unknown Vendor"),
val);
else
ti = proto_tree_add_text(tree, tvb, offset, lvt+tag_len,
"%s - %u octets (Unsigned)", label, lvt);
subtree = proto_item_add_subtree(ti, ett_bacapp_tag);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
if ((lvt < 1) || (lvt > 2)) { /* vendorIDs >= 1 and <= 2 are supported */
proto_tree_add_expert_format(tree, pinfo, &ei_bacapp_bad_length, tvb, 0, lvt,
"Wrong length indicated. Expected 1 or 2, got %u", lvt);
return offset+tag_len+lvt;
}
proto_tree_add_item(subtree, hf_BACnetVendorIdentifier, tvb,
offset+tag_len, lvt, ENC_BIG_ENDIAN);
return offset+tag_len+lvt;
}
static guint
fRestartReason(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint32 val = 0;
guint8 tag_no, tag_info;
guint32 lvt;
guint tag_len;
proto_item *ti;
proto_tree *subtree;
const gchar *label = "Restart Reason";
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (fUnsigned32(tvb, offset + tag_len, lvt, &val))
ti = proto_tree_add_text(tree, tvb, offset, lvt+tag_len,
"%s: %s (%u)", label,
val_to_str_const(val, BACnetRestartReason, "Unknown reason"), val);
else
ti = proto_tree_add_text(tree, tvb, offset, lvt+tag_len,
"%s - %u octets (Unsigned)", label, lvt);
subtree = proto_item_add_subtree(ti, ett_bacapp_tag);
fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
if (lvt != 1) {
proto_tree_add_expert_format(tree, pinfo, &ei_bacapp_bad_length, tvb, 0, lvt,
"Wrong length indicated. Expected 1, got %u", lvt);
return offset+tag_len+lvt;
}
proto_tree_add_item(subtree, hf_BACnetRestartReason, tvb,
offset+tag_len, lvt, ENC_BIG_ENDIAN);
return offset+tag_len+lvt;
}
static guint
fConfirmedTextMessageRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* textMessageSourceDevice */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* messageClass */
switch (fTagNo(tvb, offset)) {
case 0: /* numeric */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "message Class: ");
break;
case 1: /* character */
offset = fCharacterString(tvb, pinfo, tree, offset, "message Class: ");
break;
}
break;
case 2: /* messagePriority */
offset = fEnumeratedTag(tvb, pinfo, tree, offset, "message Priority: ",
BACnetMessagePriority);
break;
case 3: /* message */
offset = fCharacterString(tvb, pinfo, tree, offset, "message: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fUnconfirmedTextMessageRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fConfirmedTextMessageRequest(tvb, pinfo, tree, offset);
}
static guint
fConfirmedPrivateTransferRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset, len;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
tvbuff_t *next_tvb;
guint vendor_identifier = 0;
guint service_number = 0;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
fUnsigned32(tvb, offset+len, lvt, &vendor_identifier);
if (col_get_writable(pinfo->cinfo))
col_append_fstr(pinfo->cinfo, COL_INFO, "V=%u ", vendor_identifier);
offset = fVendorIdentifier(tvb, pinfo, subtree, offset);
next_tvb = tvb_new_subset_remaining(tvb, offset);
if (dissector_try_uint(bacapp_dissector_table,
vendor_identifier, next_tvb, pinfo, tree)) {
/* we parsed it so skip over length and we are done */
offset += tvb_length(next_tvb);
return offset;
}
/* Not handled by vendor dissector */
/* exit loop if nothing happens inside */
while (tvb_reported_length_remaining(tvb, offset) > 0) {
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
if (tag_no == 2) { /* Make sure it's the expected tag */
offset += len;
subtree = tree;
continue;
} else {
break; /* End loop if incorrect closing tag */
}
}
switch (tag_no) {
/* vendorID is now parsed above */
case 1: /* serviceNumber */
fUnsigned32(tvb, offset+len, lvt, &service_number);
if (col_get_writable(pinfo->cinfo))
col_append_fstr(pinfo->cinfo, COL_INFO, "SN=%u ", service_number);
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "service Number: ");
break;
case 2: /*serviceParameters */
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1,
ett_bacapp_value, NULL, "service Parameters");
propertyIdentifier = -1;
offset = fAbstractSyntaxNType(tvb, pinfo, subtree, offset);
break;
}
FAULT;
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fUnconfirmedPrivateTransferRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fConfirmedPrivateTransferRequest(tvb, pinfo, tree, offset);
}
static guint
fConfirmedPrivateTransferAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fConfirmedPrivateTransferRequest(tvb, pinfo, tree, offset);
}
static guint
fLifeSafetyOperationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const gchar *label)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
if (label != NULL) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL, label);
}
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 0: /* subscriberProcessId */
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "requesting Process Id: ");
break;
case 1: /* requestingSource */
offset = fCharacterString(tvb, pinfo, tree, offset, "requesting Source: ");
break;
case 2: /* request */
offset = fEnumeratedTagSplit(tvb, pinfo, tree, offset,
"request: ", BACnetLifeSafetyOperation, 64);
break;
case 3: /* objectId */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
typedef struct _value_string_enum {
const value_string *valstr;
} value_string_enum;
static const value_string_enum
BACnetPropertyStatesEnums[] = {
{ NULL },
{BACnetBinaryPV },
{BACnetEventType },
{BACnetPolarity },
{BACnetProgramRequest },
{BACnetProgramState },
{BACnetProgramError },
{BACnetReliability },
{BACnetEventState },
{BACnetDeviceStatus },
{BACnetEngineeringUnits },
{ NULL },
{BACnetLifeSafetyMode },
{BACnetLifeSafetyState },
{BACnetRestartReason },
{BACnetDoorAlarmState },
{BACnetAction },
{BACnetDoorSecuredStatus },
{BACnetDoorStatus },
{ NULL }, /* {BACnetDoorValue }, */
{BACnetFileAccessMethod },
{BACnetLockStatus },
{BACnetLifeSafetyOperation },
{BACnetMaintenance },
{BACnetNodeType },
{BACnetNotifyType },
{ NULL }, /* {BACnetSecurityLevel }, */
{BACnetShedState },
{BACnetSilencedState },
{ NULL },
{ NULL }, /* {BACnetAccessEvent }, */
{ NULL }, /* {BACnetZoneOccupancyState }, */
{ NULL }, /* {BACnetAccessCredentialDisableReason }, */
{ NULL }, /* {BACnetAccessCredentialDisable }, */
{ NULL }, /* {BACnetAuthenticationStatus }, */
{ NULL },
{ NULL }, /* {BACnetBackupState }, */
};
#define BACnetPropertyStatesEnums_Size 36
static guint
fBACnetPropertyStates(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
const gchar* label;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
label = wmem_strdup_printf(wmem_packet_scope(), "%s: ",
val_to_str_const( tag_no, VALS(BACnetPropertyStates), "Unknown State" ));
switch (tag_no) {
case 0:
offset = fBooleanTag(tvb, pinfo, tree, offset, label);
break;
case 11:
offset = fUnsignedTag(tvb, pinfo, tree, offset, label);
break;
default:
if ( (tag_no > BACnetPropertyStatesEnums_Size) ||
VALS(BACnetPropertyStatesEnums[tag_no].valstr) == NULL)
{
offset = fEnumeratedTag(tvb, pinfo, tree, offset, label, NULL);
/* don't use Abstract type here because it is context tagged and therefore we don't know app type */
}
else
{
offset = fEnumeratedTagSplit(tvb, pinfo, tree, offset, label,
VALS(BACnetPropertyStatesEnums[tag_no].valstr), 64);
}
break;
}
return offset;
}
/*
BACnetDeviceObjectPropertyValue ::= SEQUENCE {
deviceIdentifier [0] BACnetObjectIdentifier,
objectIdentifier [1] BACnetObjectIdentifier,
propertyIdentifier [2] BACnetPropertyIdentifier,
arrayIndex [3] Unsigned OPTIONAL,
value [4] ABSTRACT-SYNTAX.&Type
}
*/
static guint
fDeviceObjectPropertyValue(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) {
lastoffset = offset;
/* check the tag. A closing tag means we are done */
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
return offset;
}
switch (tag_no) {
case 0: /* deviceIdentifier */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* objectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 2: /* propertyIdentifier */
offset = fPropertyIdentifier(tvb, pinfo, tree, offset);
break;
case 3: /* arrayIndex - OPTIONAL */
offset = fUnsignedTag(tvb, pinfo, tree, offset,
"arrayIndex: ");
break;
case 4: /* value */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
/*
BACnetDeviceObjectPropertyReference ::= SEQUENCE {
objectIdentifier [0] BACnetObjectIdentifier,
propertyIdentifier [1] BACnetPropertyIdentifier,
propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
-- if omitted with an array then
-- the entire array is referenced
deviceIdentifier [3] BACnetObjectIdentifier OPTIONAL
}
*/
static guint
fObjectPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fDeviceObjectPropertyReference(tvb, pinfo, tree, offset);
}
/*
BACnetDeviceObjectPropertyReference ::= SEQUENCE {
objectIdentifier [0] BACnetObjectIdentifier,
propertyIdentifier [1] BACnetPropertyIdentifier,
propertyArrayIndex [2] Unsigned OPTIONAL, -- used only with array datatype
-- if omitted with an array then
-- the entire array is referenced
deviceIdentifier [3] BACnetObjectIdentifier OPTIONAL
}
*/
static guint
fDeviceObjectPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) {
lastoffset = offset;
/* check the tag. A closing tag means we are done */
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
return offset;
}
switch (tag_no) {
case 0: /* objectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* propertyIdentifier */
offset = fPropertyIdentifier(tvb, pinfo, tree, offset);
break;
case 2: /* arrayIndex - OPTIONAL */
offset = fUnsignedTag(tvb, pinfo, tree, offset,
"arrayIndex: ");
break;
case 3: /* deviceIdentifier - OPTIONAL */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fNotificationParameters(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = offset;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
subtree = proto_tree_add_subtree_format(subtree, tvb, offset, 0,
ett_bacapp_value, NULL, "notification parameters (%d) %s",
tag_no, val_to_str_const(tag_no, BACnetEventType, "invalid type"));
/* Opening tag for parameter choice */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 0: /* change-of-bitstring */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fBitStringTag(tvb, pinfo, subtree, offset,
"referenced-bitstring: ");
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 1: /* change-of-state */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fBACnetPropertyStates(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 2: /* change-of-value */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
switch (fTagNo(tvb, offset)) {
case 0:
offset = fBitStringTag(tvb, pinfo, subtree, offset,
"changed-bits: ");
break;
case 1:
offset = fRealTag(tvb, pinfo, subtree, offset,
"changed-value: ");
break;
default:
break;
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 3: /* command-failure */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* "command-value: " */
/* from BACnet Table 13-3,
Standard Object Property Values Returned in Notifications */
propertyIdentifier = 85; /* PRESENT_VALUE */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
break;
case 2: /* "feedback-value: " */
propertyIdentifier = 40; /* FEEDBACK_VALUE */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 4: /* floating-limit */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fRealTag(tvb, pinfo, subtree, offset, "reference-value: ");
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
break;
case 2:
offset = fRealTag(tvb, pinfo, subtree, offset, "setpoint-value: ");
break;
case 3:
offset = fRealTag(tvb, pinfo, subtree, offset, "error-limit: ");
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 5: /* out-of-range */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fRealTag(tvb, pinfo, subtree, offset, "exceeding-value: ");
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
break;
case 2:
offset = fRealTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
case 3:
offset = fRealTag(tvb, pinfo, subtree, offset, "exceeded-limit: ");
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 6:
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
offset =fBACnetPropertyValue(tvb, pinfo, subtree, offset);
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 7: /* deprecated (was 'buffer-ready', changed and moved to [10]) */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fObjectIdentifier(tvb, pinfo, subtree, offset); /* buffer-device */
break;
case 1:
offset = fObjectIdentifier(tvb, pinfo, subtree, offset); /* buffer-object */
break;
case 2:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fDateTime(tvb, pinfo, subtree, offset, "previous-notification: ");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 3:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fDateTime(tvb, pinfo, subtree, offset, "current-notification: ");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 8: /* change-of-life-safety */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fEnumeratedTagSplit(tvb, pinfo, subtree, offset,
"new-state: ", BACnetLifeSafetyState, 256);
break;
case 1:
offset = fEnumeratedTagSplit(tvb, pinfo, subtree, offset,
"new-mode: ", BACnetLifeSafetyMode, 256);
break;
case 2:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
break;
case 3:
offset = fEnumeratedTagSplit(tvb, pinfo, subtree, offset,
"operation-expected: ", BACnetLifeSafetyOperation, 64);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 9: /* extended */
while (tvb_reported_length_remaining(tvb, offset) > 0) {
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fVendorIdentifier(tvb, pinfo, subtree, offset);
break;
case 1:
offset = fUnsignedTag(tvb, pinfo, subtree, offset,
"extended-event-type: ");
break;
case 2: /* parameters */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fApplicationTypes(tvb, pinfo, subtree, offset, "parameters: ");
offset = fDeviceObjectPropertyValue(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 10: /* buffer ready */
while (tvb_reported_length_remaining(tvb, offset) > 0) {
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* buffer-property */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fDeviceObjectPropertyReference(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 1:
offset = fUnsignedTag(tvb, pinfo, subtree, offset,
"previous-notification: ");
break;
case 2:
offset = fUnsignedTag(tvb, pinfo, subtree, offset,
"current-notification: ");
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 11: /* unsigned range */
while (tvb_reported_length_remaining(tvb, offset) > 0) {
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fUnsignedTag(tvb, pinfo, subtree, offset,
"exceeding-value: ");
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
break;
case 2:
offset = fUnsignedTag(tvb, pinfo, subtree, offset,
"exceeded-limit: ");
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
/* 12 reserved */
case 13: /* access-event */
break;
case 14: /* double-out-of-range */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fDoubleTag(tvb, pinfo, subtree, offset, "exceeding-value: ");
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
break;
case 2:
offset = fDoubleTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
case 3:
offset = fDoubleTag(tvb, pinfo, subtree, offset, "exceeded-limit: ");
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 15: /* signed-out-of-range */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fSignedTag(tvb, pinfo, subtree, offset, "exceeding-value: ");
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
break;
case 2:
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
case 3:
offset = fSignedTag(tvb, pinfo, subtree, offset, "exceeded-limit: ");
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 16: /* unsigned-out-of-range */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "exceeding-value: ");
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"status-flags: ", BACnetStatusFlags);
break;
case 2:
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
case 3:
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "exceeded-limit: ");
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 17: /* change-of-characterstring */
break;
case 18: /* change-of-status-flags */
break;
/* todo: add new parameters here ... */
default:
offset = fAbstractSyntaxNType(tvb, pinfo, subtree, offset);
break;
}
/* Closing tag for parameter choice */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset;
}
static guint
fEventParameter(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = offset;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
subtree = proto_tree_add_subtree_format(subtree, tvb, offset, 0,
ett_bacapp_value, NULL, "event parameters (%d) %s",
tag_no, val_to_str_const(tag_no, BACnetEventType, "invalid type"));
/* Opening tag for parameter choice */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 0: /* change-of-bitstring */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
switch (tag_no) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset = fBitStringTag(tvb, pinfo, subtree, offset, "bitmask: ");
break;
case 2: /* SEQUENCE OF BIT STRING */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
offset = fBitStringTag(tvb, pinfo, subtree, offset,
"bitstring value: ");
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
default:
break;
}
}
break;
case 1: /* change-of-state */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
switch (tag_no) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1: /* SEQUENCE OF BACnetPropertyStates */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
offset = fBACnetPropertyStates(tvb, pinfo, subtree, offset);
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
default:
break;
}
}
break;
case 2: /* change-of-value */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1: /* don't loop it, it's a CHOICE */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
switch (fTagNo(tvb, offset)) {
case 0:
offset = fBitStringTag(tvb, pinfo, subtree, offset, "bitmask: ");
break;
case 1:
offset = fRealTag(tvb, pinfo, subtree, offset,
"referenced Property Increment: ");
break;
default:
break;
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
default:
break;
}
}
break;
case 3: /* command-failure */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
tag_no = fTagNo(tvb, offset);
switch (tag_no) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fDeviceObjectPropertyReference(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
default:
break;
}
}
break;
case 4: /* floating-limit */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
switch (tag_no) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fDeviceObjectPropertyReference(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 2:
offset = fRealTag(tvb, pinfo, subtree, offset, "low diff limit: ");
break;
case 3:
offset = fRealTag(tvb, pinfo, subtree, offset, "high diff limit: ");
break;
case 4:
offset = fRealTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
default:
break;
}
}
break;
case 5: /* out-of-range */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset = fRealTag(tvb, pinfo, subtree, offset, "low limit: ");
break;
case 2:
offset = fRealTag(tvb, pinfo, subtree, offset, "high limit: ");
break;
case 3:
offset = fRealTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
default:
break;
}
}
break;
/* deprectated
case 6:
offset = fBACnetPropertyValue (tvb, pinfo, tree, offset);
break;
*/
case 7: /* buffer-ready */
#if 0
/* deprecated */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) {
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fUnsignedTag(tvb, pinfo, tree, offset, "notification threshold");
break;
case 1:
offset = fUnsignedTag(tvb, pinfo, tree, offset,
"previous notification count: ");
break;
default:
return offset;
}
}
#endif
break;
case 8: /* change-of-life-safety */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
offset = fEnumeratedTagSplit(tvb, pinfo, subtree, offset,
"life safety alarm value: ", BACnetLifeSafetyState, 256);
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 2:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
offset = fEnumeratedTagSplit(tvb, pinfo, subtree, offset,
"alarm value: ", BACnetLifeSafetyState, 256);
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 3:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fDeviceObjectPropertyReference(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
default:
break;
}
}
break;
case 9: /* extended */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fVendorIdentifier(tvb, pinfo, tree, offset);
break;
case 1:
offset = fUnsignedTag(tvb, pinfo, tree, offset,
"extended-event-type: ");
break;
case 2: /* parameters */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fApplicationTypes(tvb, pinfo, tree, offset, "parameters: ");
offset = fDeviceObjectPropertyValue(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
lastoffset = offset;
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
break;
case 10: /* buffer-ready */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fUnsignedTag(tvb, pinfo, subtree, offset,
"notification-threshold: ");
break;
case 1:
offset = fUnsignedTag(tvb, pinfo, subtree, offset,
"previous-notification-count: ");
break;
default:
break;
}
}
break;
case 11: /* unsigned-range */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, tree, offset, "Time Delay");
break;
case 1:
offset = fUnsignedTag(tvb, pinfo, tree, offset,
"low-limit: ");
break;
case 2:
offset = fUnsignedTag(tvb, pinfo, tree, offset,
"high-limit: ");
break;
default:
break;
}
}
break;
case 13: /* access-event */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
/* TODO: [0] SEQUENCE OF BACnetAccessEvent */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
offset = fEnumeratedTagSplit(tvb, pinfo, subtree, offset,
"access event: ", BACnetAccessEvent, 512);
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 1:
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fDeviceObjectPropertyReference(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
default:
break;
}
}
break;
case 14: /* double-out-of-range */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset = fDoubleTag(tvb, pinfo, subtree, offset, "low limit: ");
break;
case 2:
offset = fDoubleTag(tvb, pinfo, subtree, offset, "high limit: ");
break;
case 3:
offset = fDoubleTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
default:
break;
}
}
break;
case 15: /* signed-out-of-range */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset = fSignedTag(tvb, pinfo, subtree, offset, "low limit: ");
break;
case 2:
offset = fSignedTag(tvb, pinfo, subtree, offset, "high limit: ");
break;
case 3:
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
default:
break;
}
}
break;
case 16: /* unsigned-out-of-range */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "low limit: ");
break;
case 2:
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "high limit: ");
break;
case 3:
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "deadband: ");
break;
default:
break;
}
}
break;
case 17: /* change-of-characterstring */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1: /* SEQUENCE OF CharacterString */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
offset = fCharacterString(tvb, pinfo, tree, offset, "alarm value: ");
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
default:
break;
}
}
break;
case 18: /* change-of-status-flags */
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0:
offset = fTimeSpan(tvb, pinfo, subtree, offset, "Time Delay");
break;
case 1:
offset = fBitStringTagVS(tvb, pinfo, subtree, offset,
"selected flags: ", BACnetStatusFlags);
break;
default:
break;
}
}
break;
/* todo: add new event-parameter cases here */
default:
break;
}
/* Closing tag for parameter choice */
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
return offset;
}
static guint
fEventLogRecord(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* timestamp */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fDate(tvb, pinfo, tree, offset, "Date: ");
offset = fTime(tvb, pinfo, tree, offset, "Time: ");
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 1: /* logDatum: don't loop, it's a CHOICE */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
switch (fTagNo(tvb, offset)) {
case 0: /* logStatus */ /* Changed this to BitString per BACnet Spec. */
offset = fBitStringTagVS(tvb, pinfo, tree, offset, "log status:", BACnetLogStatus);
break;
case 1: /* todo: move this to new method fConfirmedEventNotificationRequestTag... */
subtree = proto_tree_add_subtree(tree, tvb, offset, 1, ett_bacapp_value, NULL, "notification: ");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fConfirmedEventNotificationRequest(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 2:
offset = fRealTag(tvb, pinfo, tree, offset, "time-change: ");
break;
default:
return offset;
}
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fLogRecord(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* timestamp */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fDate(tvb, pinfo, tree, offset, "Date: ");
offset = fTime(tvb, pinfo, tree, offset, "Time: ");
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 1: /* logDatum: don't loop, it's a CHOICE */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
switch (fTagNo(tvb, offset)) {
case 0: /* logStatus */ /* Changed this to BitString per BACnet Spec. */
offset = fBitStringTagVS(tvb, pinfo, tree, offset, "log status:", BACnetLogStatus);
break;
case 1:
offset = fBooleanTag(tvb, pinfo, tree, offset, "boolean-value: ");
break;
case 2:
offset = fRealTag(tvb, pinfo, tree, offset, "real value: ");
break;
case 3:
offset = fUnsignedTag(tvb, pinfo, tree, offset, "enum value: ");
break;
case 4:
offset = fUnsignedTag(tvb, pinfo, tree, offset, "unsigned value: ");
break;
case 5:
offset = fSignedTag(tvb, pinfo, tree, offset, "signed value: ");
break;
case 6:
offset = fBitStringTag(tvb, pinfo, tree, offset, "bitstring value: ");
break;
case 7:
offset = fNullTag(tvb, pinfo, tree, offset, "null value: ");
break;
case 8:
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fError(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 9:
offset = fRealTag(tvb, pinfo, tree, offset, "time change: ");
break;
case 10: /* any Value */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 2:
/* Changed this to BitString per BACnet Spec. */
offset = fBitStringTagVS(tvb, pinfo, tree, offset, "Status Flags:", BACnetStatusFlags);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fLogMultipleRecord(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* timestamp */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fDate(tvb, pinfo, tree, offset, "Date: ");
offset = fTime(tvb, pinfo, tree, offset, "Time: ");
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 1: /* logData: don't loop, it's a CHOICE */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
switch (fTagNo(tvb, offset)) {
case 0: /* logStatus */ /* Changed this to BitString per BACnet Spec. */
offset = fBitStringTagVS(tvb, pinfo, tree, offset, "log status:", BACnetLogStatus);
break;
case 1: /* log-data: SEQUENCE OF CHOICE */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
while ((tvb_reported_length_remaining(tvb, offset) > 0) && (offset != lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
lastoffset = offset;
break;
}
switch (tag_no) {
case 0:
offset = fBooleanTag(tvb, pinfo, tree, offset, "boolean-value: ");
break;
case 1:
offset = fRealTag(tvb, pinfo, tree, offset, "real value: ");
break;
case 2:
offset = fUnsignedTag(tvb, pinfo, tree, offset, "enum value: ");
break;
case 3:
offset = fUnsignedTag(tvb, pinfo, tree, offset, "unsigned value: ");
break;
case 4:
offset = fSignedTag(tvb, pinfo, tree, offset, "signed value: ");
break;
case 5:
offset = fBitStringTag(tvb, pinfo, tree, offset, "bitstring value: ");
break;
case 6:
offset = fNullTag(tvb, pinfo, tree, offset, "null value: ");
break;
case 7:
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fError(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 8: /* any Value */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
}
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 2:
offset = fRealTag(tvb, pinfo, tree, offset, "time-change: ");
break;
default:
return offset;
}
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fConfirmedEventNotificationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
break;
}
switch (tag_no) {
case 0: /* ProcessId */
offset = fProcessId(tvb, pinfo, tree, offset);
break;
case 1: /* initiating ObjectId */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 2: /* event ObjectId */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 3: /* time stamp */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fTimeStamp(tvb, pinfo, tree, offset, NULL);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 4: /* notificationClass */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Notification Class: ");
break;
case 5: /* Priority */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Priority: ");
break;
case 6: /* EventType */
offset = fEnumeratedTagSplit(tvb, pinfo, tree, offset,
"Event Type: ", BACnetEventType, 64);
break;
case 7: /* messageText */
offset = fCharacterString(tvb, pinfo, tree, offset, "message Text: ");
break;
case 8: /* NotifyType */
offset = fEnumeratedTag(tvb, pinfo, tree, offset,
"Notify Type: ", BACnetNotifyType);
break;
case 9: /* ackRequired */
offset = fBooleanTag(tvb, pinfo, tree, offset, "ack Required: ");
break;
case 10: /* fromState */
offset = fEnumeratedTagSplit(tvb, pinfo, tree, offset,
"from State: ", BACnetEventState, 64);
break;
case 11: /* toState */
offset = fEnumeratedTagSplit(tvb, pinfo, tree, offset,
"to State: ", BACnetEventState, 64);
break;
case 12: /* NotificationParameters */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fNotificationParameters(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fUnconfirmedEventNotificationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fConfirmedEventNotificationRequest(tvb, pinfo, tree, offset);
}
static guint
fConfirmedCOVNotificationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0, len;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
offset += len;
subtree = tree;
continue;
}
switch (tag_no) {
case 0: /* ProcessId */
offset = fProcessId(tvb, pinfo, tree, offset);
break;
case 1: /* initiating DeviceId */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 2: /* monitored ObjectId */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 3: /* time remaining */
offset = fTimeSpan(tvb, pinfo, tree, offset, "Time remaining");
break;
case 4: /* List of Values */
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL, "list of Values");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fBACnetPropertyValue(tvb, pinfo, subtree, offset);
break;
}
FAULT;
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fUnconfirmedCOVNotificationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fConfirmedCOVNotificationRequest(tvb, pinfo, tree, offset);
}
static guint
fAcknowledgeAlarmRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no = 0, tag_info = 0;
guint32 lvt = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* acknowledgingProcessId */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "acknowledging Process Id: ");
break;
case 1: /* eventObjectId */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 2: /* eventStateAcknowledged */
offset = fEnumeratedTagSplit(tvb, pinfo, tree, offset,
"event State Acknowledged: ", BACnetEventState, 64);
break;
case 3: /* timeStamp */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fTimeStamp(tvb, pinfo, tree, offset, NULL);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 4: /* acknowledgementSource */
offset = fCharacterString(tvb, pinfo, tree, offset, "acknowledgement Source: ");
break;
case 5: /* timeOfAcknowledgement */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fTimeStamp(tvb, pinfo, tree, offset, "acknowledgement timestamp: ");
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fGetAlarmSummaryAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
offset = fApplicationTypes(tvb, pinfo, tree, offset, "Object Identifier: ");
offset = fApplicationTypesEnumeratedSplit(tvb, pinfo, tree, offset,
"alarm State: ", BACnetEventState, 64);
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset,
"acknowledged Transitions: ", BACnetEventTransitionBits);
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fGetEnrollmentSummaryRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* acknowledgmentFilter */
offset = fEnumeratedTag(tvb, pinfo, tree, offset,
"acknowledgment Filter: ", BACnetAcknowledgementFilter);
break;
case 1: /* eventObjectId - OPTIONAL */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fRecipientProcess(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 2: /* eventStateFilter */
offset = fEnumeratedTag(tvb, pinfo, tree, offset,
"event State Filter: ", BACnetEventStateFilter);
break;
case 3: /* eventTypeFilter - OPTIONAL */
offset = fEnumeratedTag(tvb, pinfo, tree, offset,
"event Type Filter: ", BACnetEventType);
break;
case 4: /* priorityFilter */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fUnsignedTag(tvb, pinfo, tree, offset, "min Priority: ");
offset = fUnsignedTag(tvb, pinfo, tree, offset, "max Priority: ");
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 5: /* notificationClassFilter - OPTIONAL */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "notification Class Filter: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fGetEnrollmentSummaryAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
offset = fApplicationTypes(tvb, pinfo, tree, offset, "Object Identifier: ");
offset = fApplicationTypesEnumeratedSplit(tvb, pinfo, tree, offset,
"event Type: ", BACnetEventType, 64);
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset,
"event State: ", BACnetEventState);
offset = fApplicationTypes(tvb, pinfo, tree, offset, "Priority: ");
if (tvb_reported_length_remaining(tvb, offset) > 0 && fTagNo(tvb, offset) == 2) /* Notification Class - OPTIONAL */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "Notification Class: ");
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fGetEventInformationRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
if (tvb_reported_length_remaining(tvb, offset) > 0) {
if (fTagNo(tvb, offset) == 0) {
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
}
}
return offset;
}
static guint
flistOfEventSummaries(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree* subtree = tree;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* we are finished here if we spot a closing tag */
if (tag_is_closing(tag_info)) {
break;
}
switch (tag_no) {
case 0: /* ObjectId */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* eventState */
offset = fEnumeratedTag(tvb, pinfo, tree, offset,
"event State: ", BACnetEventState);
break;
case 2: /* acknowledgedTransitions */
offset = fBitStringTagVS(tvb, pinfo, tree, offset,
"acknowledged Transitions: ", BACnetEventTransitionBits);
break;
case 3: /* eventTimeStamps */
subtree = proto_tree_add_subtree(tree, tvb, offset, lvt, ett_bacapp_tag, NULL, "eventTimeStamps");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fTimeStamp(tvb, pinfo, subtree, offset, "TO-OFFNORMAL timestamp: ");
offset = fTimeStamp(tvb, pinfo, subtree, offset, "TO-FAULT timestamp: ");
offset = fTimeStamp(tvb, pinfo, subtree, offset, "TO-NORMAL timestamp: ");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
case 4: /* notifyType */
offset = fEnumeratedTag(tvb, pinfo, tree, offset,
"Notify Type: ", BACnetNotifyType);
break;
case 5: /* eventEnable */
offset = fBitStringTagVS(tvb, pinfo, tree, offset,
"event Enable: ", BACnetEventTransitionBits);
break;
case 6: /* eventPriorities */
subtree = proto_tree_add_subtree(tree, tvb, offset, lvt, ett_bacapp_tag, NULL, "eventPriorities");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "TO-OFFNORMAL Priority: ");
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "TO-FAULT Priority: ");
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "TO-NORMAL Priority: ");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fLOPR(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* we are finished here if we spot a closing tag */
if (tag_is_closing(tag_info)) {
break;
}
offset = fDeviceObjectPropertyReference(tvb, pinfo, tree, offset);
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fGetEventInformationACK(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* listOfEventSummaries */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = flistOfEventSummaries(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
case 1: /* moreEvents */
offset = fBooleanTag(tvb, pinfo, tree, offset, "more Events: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fAddListElementRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0, len;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
offset += len;
subtree = tree;
continue;
}
switch (tag_no) {
case 0: /* ObjectId */
offset = fBACnetObjectPropertyReference(tvb, pinfo, subtree, offset);
break;
case 3: /* listOfElements */
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL, "listOfElements");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, subtree, offset);
break;
}
FAULT;
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fDeleteObjectRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fObjectIdentifier(tvb, pinfo, tree, offset);
}
static guint
fDeviceCommunicationControlRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* timeDuration */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "time Duration: ");
break;
case 1: /* enable-disable */
offset = fEnumeratedTag(tvb, pinfo, tree, offset, "enable-disable: ",
BACnetEnableDisable);
break;
case 2: /* password - OPTIONAL */
offset = fCharacterString(tvb, pinfo, tree, offset, "Password: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fReinitializeDeviceRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* reinitializedStateOfDevice */
offset = fEnumeratedTag(tvb, pinfo, tree, offset,
"reinitialized State Of Device: ",
BACnetReinitializedStateOfDevice);
break;
case 1: /* password - OPTIONAL */
offset = fCharacterString(tvb, pinfo, tree, offset, "Password: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fVtOpenRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset,
"vtClass: ", BACnetVTClass);
return fApplicationTypes(tvb, pinfo, tree, offset, "local VT Session ID: ");
}
static guint
fVtOpenAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fApplicationTypes(tvb, pinfo, tree, offset, "remote VT Session ID: ");
}
static guint
fVtCloseRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
offset= fApplicationTypes(tvb, pinfo, tree, offset, "remote VT Session ID: ");
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fVtDataRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
offset= fApplicationTypes(tvb, pinfo, tree, offset, "VT Session ID: ");
offset = fApplicationTypes(tvb, pinfo, tree, offset, "VT New Data: ");
return fApplicationTypes(tvb, pinfo, tree, offset, "VT Data Flag: ");
}
static guint
fVtDataAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* BOOLEAN */
offset = fBooleanTag(tvb, pinfo, tree, offset, "all New Data Accepted: ");
break;
case 1: /* Unsigned OPTIONAL */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "accepted Octet Count: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fAuthenticateRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* Unsigned32 */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "pseudo Random Number: ");
break;
case 1: /* expected Invoke ID Unsigned8 OPTIONAL */
proto_tree_add_item(tree, hf_bacapp_invoke_id, tvb, offset++, 1, ENC_BIG_ENDIAN);
break;
case 2: /* Chararacter String OPTIONAL */
offset = fCharacterString(tvb, pinfo, tree, offset, "operator Name: ");
break;
case 3: /* Chararacter String OPTIONAL */
offset = fCharacterString(tvb, pinfo, tree, offset, "operator Password: ");
break;
case 4: /* Boolean OPTIONAL */
offset = fBooleanTag(tvb, pinfo, tree, offset, "start Encyphered Session: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fAuthenticateAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fApplicationTypes(tvb, pinfo, tree, offset, "modified Random Number: ");
}
static guint
fRequestKeyRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
offset = fObjectIdentifier(tvb, pinfo, tree, offset); /* Requesting Device Identifier */
offset = fAddress(tvb, pinfo, tree, offset);
offset = fObjectIdentifier(tvb, pinfo, tree, offset); /* Remote Device Identifier */
return fAddress(tvb, pinfo, tree, offset);
}
static guint
fRemoveListElementRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
/* Same as AddListElement request after service choice */
return fAddListElementRequest(tvb, pinfo, tree, offset);
}
static guint
fReadPropertyRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fBACnetObjectPropertyReference(tvb, pinfo, tree, offset);
}
static guint
fReadPropertyAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0, len;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
/* set the optional global properties to indicate not-used */
propertyArrayIndex = -1;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
offset += len;
subtree = tree;
continue;
}
switch (tag_no) {
case 0: /* objectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 1: /* propertyIdentifier */
offset = fPropertyIdentifier(tvb, pinfo, subtree, offset);
break;
case 2: /* propertyArrayIndex */
offset = fPropertyArrayIndex(tvb, pinfo, subtree, offset);
break;
case 3: /* propertyValue */
offset = fPropertyValue(tvb, pinfo, subtree, offset, tag_info);
break;
default:
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fWritePropertyRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
/* set the optional global properties to indicate not-used */
propertyArrayIndex = -1;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* quit loop if we spot a closing tag */
if (tag_is_closing(tag_info)) {
break;
}
switch (tag_no) {
case 0: /* objectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 1: /* propertyIdentifier */
offset = fPropertyIdentifier(tvb, pinfo, subtree, offset);
break;
case 2: /* propertyArrayIndex */
offset = fPropertyArrayIndex(tvb, pinfo, subtree, offset);
break;
case 3: /* propertyValue */
offset = fPropertyValue(tvb, pinfo, subtree, offset, tag_info);
break;
case 4: /* Priority (only used for write) */
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "Priority: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fWriteAccessSpecification(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset)
{
guint lastoffset = 0, len;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* maybe a listOfwriteAccessSpecifications if we spot a closing tag */
if (tag_is_closing(tag_info)) {
offset += len;
continue;
}
switch (tag_no) {
case 0: /* objectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 1: /* listOfPropertyValues */
if (tag_is_opening(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fBACnetPropertyValue(tvb, pinfo, subtree, offset);
break;
}
FAULT;
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fWritePropertyMultipleRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
if (offset >= tvb_reported_length(tvb))
return offset;
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
return fWriteAccessSpecification(tvb, pinfo, tree, offset);
}
static guint
fPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 tagoffset, guint8 list)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
/* set the optional global properties to indicate not-used */
propertyArrayIndex = -1;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) { /* closing Tag, but not for me */
return offset;
} else if (tag_is_opening(tag_info)) { /* opening Tag, but not for me */
return offset;
}
switch (tag_no-tagoffset) {
case 0: /* PropertyIdentifier */
offset = fPropertyIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* propertyArrayIndex */
offset = fPropertyArrayIndex(tvb, pinfo, tree, offset);
if (list != 0) break; /* Continue decoding if this may be a list */
default:
lastoffset = offset; /* Set loop end condition */
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fBACnetPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint8 list)
{
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
return fPropertyReference(tvb, pinfo, tree, offset, 0, list);
}
static guint
fBACnetObjectPropertyReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* ObjectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* PropertyIdentifier and propertyArrayIndex */
offset = fPropertyReference(tvb, pinfo, tree, offset, 1, 0);
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
default:
lastoffset = offset; /* Set loop end condition */
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
#if 0
static guint
fObjectPropertyValue(tvbuff_t *tvb, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree* subtree = tree;
proto_item* tt;
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset,
&tag_no, &tag_info, &lvt);
continue;
}
switch (tag_no) {
case 0: /* ObjectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 1: /* PropertyIdentifier */
offset = fPropertyIdentifier(tvb, pinfo, subtree, offset);
break;
case 2: /* propertyArrayIndex */
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "property Array Index: ");
break;
case 3: /* Value */
offset = fPropertyValue(tvb, pinfo, subtree, offset, tag_info);
break;
case 4: /* Priority */
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "Priority: ");
break;
default:
break;
}
}
return offset;
}
#endif
static guint
fPriorityArray(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
char i = 1, ar[256];
guint lastoffset = 0;
if (propertyArrayIndex > 0) {
/* BACnetARRAY index 0 refers to the length
of the array, not the elements of the array.
BACnetARRAY index -1 is our internal flag that
the optional index was not used.
BACnetARRAY refers to this as all elements of the array.
If the optional index is specified for a BACnetARRAY,
then that specific array element is referenced. */
i = propertyArrayIndex;
}
while (tvb_reported_length_remaining(tvb, offset) > 0) {
/* exit loop if nothing happens inside */
lastoffset = offset;
g_snprintf(ar, sizeof(ar), "%s[%d]: ",
val_to_split_str(87 , 512,
BACnetPropertyIdentifier,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt),
i++);
/* DMR Should be fAbstractNSyntax, but that's where we came from! */
offset = fApplicationTypes(tvb, pinfo, tree, offset, ar);
/* there are only 16 priority array elements */
if (i > 16) {
break;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fDeviceObjectReference(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* deviceIdentifier - OPTIONAL */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* ObjectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fSpecialEvent(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
guint lastoffset = 0, len;
gboolean closing_found = FALSE; /* tracks when we are done decoding the fSpecialEvent entries */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* maybe a SEQUENCE of SpecialEvents if we spot a closing tag */
if (tag_is_closing(tag_info)) {
/* if we find 2 closing tags in succession we need to exit without incrementing the offset again */
/* This handles the special case where we have a special event entry in an RPM-ACK msg */
if ( closing_found == TRUE )
break;
offset += len;
closing_found = TRUE;
continue;
}
switch (tag_no) {
case 0: /* calendarEntry */
if (tag_is_opening(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fCalendarEntry(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
}
break;
case 1: /* calendarReference */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 2: /* list of BACnetTimeValue */
if (tag_is_opening(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fTimeValue(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
}
FAULT;
break;
case 3: /* eventPriority */
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "event priority: ");
break;
default:
return offset;
}
closing_found = FALSE; /* reset our closing tag status, we processed another open tag */
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fSelectionCriteria(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0, len;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* maybe a listOfSelectionCriteria if we spot a closing tag */
if (tag_is_closing(tag_info)) {
offset += len;
continue;
}
switch (fTagNo(tvb, offset)) {
case 0: /* propertyIdentifier */
offset = fPropertyIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* propertyArrayIndex */
offset = fPropertyArrayIndex(tvb, pinfo, tree, offset);
break;
case 2: /* relationSpecifier */
offset = fEnumeratedTag(tvb, pinfo, tree, offset,
"relation Specifier: ", BACnetRelationSpecifier);
break;
case 3: /* comparisonValue */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fObjectSelectionCriteria(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* quit loop if we spot a closing tag */
if (tag_is_closing(tag_info)) {
break;
}
switch (tag_no) {
case 0: /* selectionLogic */
offset = fEnumeratedTag(tvb, pinfo, subtree, offset,
"selection Logic: ", BACnetSelectionLogic);
break;
case 1: /* listOfSelectionCriteria */
if (tag_is_opening(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fSelectionCriteria(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
}
FAULT;
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fReadPropertyConditionalRequest(tvbuff_t *tvb, packet_info* pinfo, proto_tree *subtree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader (tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_opening(tag_info) && tag_no < 2) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 0: /* objectSelectionCriteria */
offset = fObjectSelectionCriteria(tvb, pinfo, subtree, offset);
break;
case 1: /* listOfPropertyReferences */
offset = fBACnetPropertyReference(tvb, pinfo, subtree, offset, 1);
break;
default:
return offset;
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fReadAccessSpecification(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 0: /* objectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
case 1: /* listOfPropertyReferences */
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL, "listOfPropertyReferences");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fBACnetPropertyReference(tvb, pinfo, subtree, offset, 1);
} else if (tag_is_closing(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset,
&tag_no, &tag_info, &lvt);
subtree = tree;
} else {
/* error condition: let caller handle */
return offset;
}
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fReadAccessResult(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0, len;
guint8 tag_no;
guint8 tag_info;
guint32 lvt;
proto_tree *subtree = tree;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
/* maybe a listOfReadAccessResults if we spot a closing tag here */
if (tag_is_closing(tag_info)) {
offset += len;
if ((tag_no == 4 || tag_no == 5) && (subtree != tree)) subtree = subtree->parent; /* Value and error have extra subtree */
continue;
}
switch (tag_no) {
case 0: /* objectSpecifier */
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
break;
case 1: /* list of Results */
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(tree, tvb, offset, 1, ett_bacapp_value, NULL, "listOfResults");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
break;
}
FAULT;
break;
case 2: /* propertyIdentifier */
offset = fPropertyIdentifierValue(tvb, pinfo, subtree, offset, 2);
break;
case 5: /* propertyAccessError */
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL, "propertyAccessError");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
/* Error Code follows */
offset = fError(tvb, pinfo, subtree, offset);
break;
}
FAULT;
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fReadPropertyConditionalAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
/* listOfReadAccessResults */
return fReadAccessResult(tvb, pinfo, tree, offset);
}
static guint
fCreateObjectRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_no < 2) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 0: /* objectSpecifier */
switch (fTagNo(tvb, offset)) { /* choice of objectType or objectIdentifier */
case 0: /* objectType */
offset = fEnumeratedTagSplit(tvb, pinfo, subtree, offset, "Object Type: ", BACnetObjectType, 128);
break;
case 1: /* objectIdentifier */
offset = fObjectIdentifier(tvb, pinfo, subtree, offset);
break;
default:
break;
}
break;
case 1: /* propertyValue */
if (tag_is_opening(tag_info)) {
offset = fBACnetPropertyValue(tvb, pinfo, subtree, offset);
break;
}
FAULT;
break;
default:
break;
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fCreateObjectAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
return fObjectIdentifier(tvb, pinfo, tree, offset);
}
static guint
fReadRangeRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
offset = fBACnetObjectPropertyReference(tvb, pinfo, subtree, offset);
if (tvb_reported_length_remaining(tvb, offset) > 0) {
/* optional range choice */
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL,
val_to_str_const(tag_no, BACnetReadRangeOptions, "unknown range option"));
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 3: /* range byPosition */
case 6: /* range bySequenceNumber, 2004 spec */
offset = fApplicationTypes(tvb, pinfo, subtree, offset, "reference Index: ");
offset = fApplicationTypes(tvb, pinfo, subtree, offset, "reference Count: ");
break;
case 4: /* range byTime - deprecated in 2004 */
case 7: /* 2004 spec */
offset = fDateTime(tvb, pinfo, subtree, offset, "reference Date/Time: ");
offset = fApplicationTypes(tvb, pinfo, subtree, offset, "reference Count: ");
break;
case 5: /* range timeRange - deprecated in 2004 */
offset = fDateTime(tvb, pinfo, subtree, offset, "beginning Time: ");
offset = fDateTime(tvb, pinfo, subtree, offset, "ending Time: ");
break;
default:
break;
}
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
}
}
return offset;
}
static guint
fReadRangeAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
/* set the optional global properties to indicate not-used */
propertyArrayIndex = -1;
/* objectIdentifier, propertyIdentifier, and
OPTIONAL propertyArrayIndex */
offset = fBACnetObjectPropertyReference(tvb, pinfo, subtree, offset);
/* resultFlags => BACnetResultFlags ::= BIT STRING */
offset = fBitStringTagVS(tvb, pinfo, tree, offset,
"resultFlags: ",
BACnetResultFlags);
/* itemCount */
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "item Count: ");
/* itemData */
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_opening(tag_info)) {
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL, "itemData");
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, subtree, offset);
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
}
/* firstSequenceNumber - OPTIONAL */
if (tvb_reported_length_remaining(tvb, offset) > 0) {
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "first Sequence Number: ");
}
return offset;
}
static guint
fAccessMethod(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint32 lvt;
guint8 tag_no, tag_info;
proto_tree* subtree = NULL;
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(tree, tvb, offset, 1, ett_bacapp_value, NULL,
val_to_str_const(tag_no, BACnetFileAccessOption, "invalid access method"));
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fApplicationTypes(tvb, pinfo, subtree, offset, val_to_str_const(tag_no, BACnetFileStartOption, "invalid option"));
offset = fApplicationTypes(tvb, pinfo, subtree, offset, val_to_str_const(tag_no, BACnetFileWriteInfo, "unknown option"));
if (tag_no == 1) {
while ((tvb_reported_length_remaining(tvb, offset) > 0)&&(offset>lastoffset)) {
/* exit loop if nothing happens inside */
lastoffset = offset;
offset = fApplicationTypes(tvb, pinfo, subtree, offset, "Record Data: ");
}
}
if ((bacapp_flags & BACAPP_MORE_SEGMENTS) == 0) {
/* More Flag is not set, so we can look for closing tag in this segment */
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_closing(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
}
}
}
return offset;
}
static guint
fAtomicReadFileRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no, tag_info;
guint32 lvt;
proto_tree *subtree = tree;
offset = fObjectIdentifier(tvb, pinfo, tree, offset);
fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1, ett_bacapp_value, NULL,
val_to_str_const(tag_no, BACnetFileAccessOption, "unknown access method"));
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fSignedTag(tvb, pinfo, subtree, offset, val_to_str_const(tag_no, BACnetFileStartOption, "unknown option"));
offset = fUnsignedTag(tvb, pinfo, subtree, offset, val_to_str_const(tag_no, BACnetFileRequestCount, "unknown option"));
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
}
return offset;
}
static guint
fAtomicWriteFileRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
offset = fObjectIdentifier(tvb, pinfo, tree, offset); /* file Identifier */
offset = fAccessMethod(tvb, pinfo, tree, offset);
return offset;
}
static guint
fAtomicWriteFileAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint tag_no = fTagNo(tvb, offset);
return fSignedTag(tvb, pinfo, tree, offset, val_to_str_const(tag_no, BACnetFileStartOption, "unknown option"));
}
static guint
fAtomicReadFileAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
offset = fApplicationTypes(tvb, pinfo, tree, offset, "End Of File: ");
offset = fAccessMethod(tvb, pinfo, tree, offset);
return offset;
}
static guint
fReadPropertyMultipleRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *subtree, guint offset)
{
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
return fReadAccessSpecification(tvb, pinfo, subtree, offset);
}
static guint
fReadPropertyMultipleAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
return fReadAccessResult(tvb, pinfo, tree, offset);
}
static guint
fConfirmedServiceRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, gint service_choice)
{
if (tvb_reported_length_remaining(tvb, offset) <= 0)
return offset;
switch (service_choice) {
case 0: /* acknowledgeAlarm */
offset = fAcknowledgeAlarmRequest(tvb, pinfo, tree, offset);
break;
case 1: /* confirmedCOVNotification */
offset = fConfirmedCOVNotificationRequest(tvb, pinfo, tree, offset);
break;
case 2: /* confirmedEventNotification */
offset = fConfirmedEventNotificationRequest(tvb, pinfo, tree, offset);
break;
case 3: /* confirmedGetAlarmSummary conveys no parameters */
break;
case 4: /* getEnrollmentSummaryRequest */
offset = fGetEnrollmentSummaryRequest(tvb, pinfo, tree, offset);
break;
case 5: /* subscribeCOVRequest */
offset = fSubscribeCOVRequest(tvb, pinfo, tree, offset);
break;
case 6: /* atomicReadFile-Request */
offset = fAtomicReadFileRequest(tvb, pinfo, tree, offset);
break;
case 7: /* atomicWriteFile-Request */
offset = fAtomicWriteFileRequest(tvb, pinfo, tree, offset);
break;
case 8: /* AddListElement-Request */
offset = fAddListElementRequest(tvb, pinfo, tree, offset);
break;
case 9: /* removeListElement-Request */
offset = fRemoveListElementRequest(tvb, pinfo, tree, offset);
break;
case 10: /* createObjectRequest */
offset = fCreateObjectRequest(tvb, pinfo, tree, offset);
break;
case 11: /* deleteObject */
offset = fDeleteObjectRequest(tvb, pinfo, tree, offset);
break;
case 12:
offset = fReadPropertyRequest(tvb, pinfo, tree, offset);
break;
case 13:
offset = fReadPropertyConditionalRequest(tvb, pinfo, tree, offset);
break;
case 14:
offset = fReadPropertyMultipleRequest(tvb, pinfo, tree, offset);
break;
case 15:
offset = fWritePropertyRequest(tvb, pinfo, tree, offset);
break;
case 16:
offset = fWritePropertyMultipleRequest(tvb, pinfo, tree, offset);
break;
case 17:
offset = fDeviceCommunicationControlRequest(tvb, pinfo, tree, offset);
break;
case 18:
offset = fConfirmedPrivateTransferRequest(tvb, pinfo, tree, offset);
break;
case 19:
offset = fConfirmedTextMessageRequest(tvb, pinfo, tree, offset);
break;
case 20:
offset = fReinitializeDeviceRequest(tvb, pinfo, tree, offset);
break;
case 21:
offset = fVtOpenRequest(tvb, pinfo, tree, offset);
break;
case 22:
offset = fVtCloseRequest(tvb, pinfo, tree, offset);
break;
case 23:
offset = fVtDataRequest(tvb, pinfo, tree, offset);
break;
case 24:
offset = fAuthenticateRequest(tvb, pinfo, tree, offset);
break;
case 25:
offset = fRequestKeyRequest(tvb, pinfo, tree, offset);
break;
case 26:
offset = fReadRangeRequest(tvb, pinfo, tree, offset);
break;
case 27:
offset = fLifeSafetyOperationRequest(tvb, pinfo, tree, offset, NULL);
break;
case 28:
offset = fSubscribeCOVPropertyRequest(tvb, pinfo, tree, offset);
break;
case 29:
offset = fGetEventInformationRequest(tvb, pinfo, tree, offset);
break;
default:
return offset;
}
return offset;
}
static guint
fConfirmedServiceAck(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, gint service_choice)
{
if (tvb_reported_length_remaining(tvb, offset) <= 0)
return offset;
switch (service_choice) {
case 3: /* confirmedEventNotificationAck */
offset = fGetAlarmSummaryAck(tvb, pinfo, tree, offset);
break;
case 4: /* getEnrollmentSummaryAck */
offset = fGetEnrollmentSummaryAck(tvb, pinfo, tree, offset);
break;
case 6: /* atomicReadFile */
offset = fAtomicReadFileAck(tvb, pinfo, tree, offset);
break;
case 7: /* atomicReadFileAck */
offset = fAtomicWriteFileAck(tvb, pinfo, tree, offset);
break;
case 10: /* createObject */
offset = fCreateObjectAck(tvb, pinfo, tree, offset);
break;
case 12:
offset = fReadPropertyAck(tvb, pinfo, tree, offset);
break;
case 13:
offset = fReadPropertyConditionalAck(tvb, pinfo, tree, offset);
break;
case 14:
offset = fReadPropertyMultipleAck(tvb, pinfo, tree, offset);
break;
case 18:
offset = fConfirmedPrivateTransferAck(tvb, pinfo, tree, offset);
break;
case 21:
offset = fVtOpenAck(tvb, pinfo, tree, offset);
break;
case 23:
offset = fVtDataAck(tvb, pinfo, tree, offset);
break;
case 24:
offset = fAuthenticateAck(tvb, pinfo, tree, offset);
break;
case 26:
offset = fReadRangeAck(tvb, pinfo, tree, offset);
break;
case 29:
offset = fGetEventInformationACK(tvb, pinfo, tree, offset);
break;
default:
return offset;
}
return offset;
}
static guint
fIAmRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
/* BACnetObjectIdentifier */
offset = fApplicationTypes(tvb, pinfo, tree, offset, "BACnet Object Identifier: ");
/* MaxAPDULengthAccepted */
offset = fApplicationTypes(tvb, pinfo, tree, offset, "Maximum ADPU Length Accepted: ");
/* segmentationSupported */
offset = fApplicationTypesEnumerated(tvb, pinfo, tree, offset,
"Segmentation Supported: ", BACnetSegmentation);
/* vendor ID */
return fVendorIdentifier(tvb, pinfo, tree, offset);
}
static guint
fIHaveRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
/* BACnetDeviceIdentifier */
offset = fApplicationTypes(tvb, pinfo, tree, offset, "Device Identifier: ");
/* BACnetObjectIdentifier */
offset = fApplicationTypes(tvb, pinfo, tree, offset, "Object Identifier: ");
/* ObjectName */
return fApplicationTypes(tvb, pinfo, tree, offset, "Object Name: ");
}
static guint
fWhoIsRequest(tvbuff_t *tvb, packet_info* pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint val;
guint8 tag_len;
guint8 tag_no, tag_info;
guint32 lvt;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 0:
/* DeviceInstanceRangeLowLimit Optional */
if (col_get_writable(pinfo->cinfo) && fUnsigned32(tvb, offset+tag_len, lvt, &val))
col_append_fstr(pinfo->cinfo, COL_INFO, "%d ", val);
offset = fDevice_Instance(tvb, pinfo, tree, offset,
hf_Device_Instance_Range_Low_Limit);
break;
case 1:
/* DeviceInstanceRangeHighLimit Optional but
required if DeviceInstanceRangeLowLimit is there */
if (col_get_writable(pinfo->cinfo) && fUnsigned32(tvb, offset+tag_len, lvt, &val))
col_append_fstr(pinfo->cinfo, COL_INFO, "%d ", val);
offset = fDevice_Instance(tvb, pinfo, tree, offset,
hf_Device_Instance_Range_High_Limit);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fUnconfirmedServiceRequest(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, gint service_choice)
{
if (tvb_reported_length_remaining(tvb, offset) <= 0)
return offset;
switch (service_choice) {
case 0: /* I-Am-Request */
offset = fIAmRequest(tvb, pinfo, tree, offset);
break;
case 1: /* i-Have Request */
offset = fIHaveRequest(tvb, pinfo, tree, offset);
break;
case 2: /* unconfirmedCOVNotification */
offset = fUnconfirmedCOVNotificationRequest(tvb, pinfo, tree, offset);
break;
case 3: /* unconfirmedEventNotification */
offset = fUnconfirmedEventNotificationRequest(tvb, pinfo, tree, offset);
break;
case 4: /* unconfirmedPrivateTransfer */
offset = fUnconfirmedPrivateTransferRequest(tvb, pinfo, tree, offset);
break;
case 5: /* unconfirmedTextMessage */
offset = fUnconfirmedTextMessageRequest(tvb, pinfo, tree, offset);
break;
case 206: /* utc-time-synchronization-recipients */
case 6: /* timeSynchronization */
offset = fTimeSynchronizationRequest(tvb, pinfo, tree, offset);
break;
case 7: /* who-Has */
offset = fWhoHas(tvb, pinfo, tree, offset);
break;
case 8: /* who-Is */
offset = fWhoIsRequest(tvb, pinfo, tree, offset);
break;
case 9: /* utcTimeSynchronization */
offset = fUTCTimeSynchronizationRequest(tvb, pinfo, tree, offset);
break;
default:
break;
}
return offset;
}
static guint
fStartConfirmed(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *bacapp_tree, guint offset, guint8 ack,
gint *svc, proto_item **tt)
{
proto_item *tc;
proto_tree *bacapp_tree_control;
gint tmp;
guint extra = 2;
bacapp_seq = 0;
tmp = (gint) tvb_get_guint8(tvb, offset);
bacapp_flags = tmp & 0x0f;
if (ack == 0) {
extra = 3;
}
*svc = (gint) tvb_get_guint8(tvb, offset+extra);
if (bacapp_flags & 0x08)
*svc = (gint) tvb_get_guint8(tvb, offset+extra+2);
proto_tree_add_item(bacapp_tree, hf_bacapp_type, tvb, offset, 1, ENC_BIG_ENDIAN);
tc = proto_tree_add_item(bacapp_tree, hf_bacapp_pduflags, tvb, offset, 1, ENC_BIG_ENDIAN);
bacapp_tree_control = proto_item_add_subtree(tc, ett_bacapp_control);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_SEG, tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_MOR, tvb, offset, 1, ENC_BIG_ENDIAN);
if (ack == 0) { /* The following are for ConfirmedRequest, not Complex ack */
proto_tree_add_item(bacapp_tree_control, hf_bacapp_SA, tvb, offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree, hf_bacapp_response_segments, tvb,
offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree, hf_bacapp_max_adpu_size, tvb,
offset, 1, ENC_BIG_ENDIAN);
}
offset++;
proto_tree_add_item(bacapp_tree, hf_bacapp_invoke_id, tvb, offset++, 1, ENC_BIG_ENDIAN);
if (bacapp_flags & 0x08) {
bacapp_seq = tvb_get_guint8(tvb, offset);
proto_tree_add_item(bacapp_tree, hf_bacapp_sequence_number, tvb,
offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree, hf_bacapp_window_size, tvb,
offset++, 1, ENC_BIG_ENDIAN);
}
*tt = proto_tree_add_item(bacapp_tree, hf_bacapp_service, tvb,
offset++, 1, ENC_BIG_ENDIAN);
return offset;
}
static guint
fContinueConfirmedRequestPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *bacapp_tree, guint offset, gint svc)
{ /* BACnet-Confirmed-Request */
/* ASHRAE 135-2001 20.1.2 */
return fConfirmedServiceRequest(tvb, pinfo, bacapp_tree, offset, svc);
}
static guint
fConfirmedRequestPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *bacapp_tree, guint offset)
{ /* BACnet-Confirmed-Request */
/* ASHRAE 135-2001 20.1.2 */
gint svc;
proto_item *tt = 0;
offset = fStartConfirmed(tvb, pinfo, bacapp_tree, offset, 0, &svc, &tt);
return fContinueConfirmedRequestPDU(tvb, pinfo, bacapp_tree, offset, svc);
}
static guint
fUnconfirmedRequestPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *bacapp_tree, guint offset)
{ /* BACnet-Unconfirmed-Request-PDU */
/* ASHRAE 135-2001 20.1.3 */
gint tmp;
proto_tree_add_item(bacapp_tree, hf_bacapp_type, tvb, offset++, 1, ENC_BIG_ENDIAN);
tmp = tvb_get_guint8(tvb, offset);
proto_tree_add_item(bacapp_tree, hf_bacapp_uservice, tvb,
offset++, 1, ENC_BIG_ENDIAN);
/* Service Request follows... Variable Encoding 20.2ff */
return fUnconfirmedServiceRequest(tvb, pinfo, bacapp_tree, offset, tmp);
}
static guint
fSimpleAckPDU(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *bacapp_tree, guint offset)
{ /* BACnet-Simple-Ack-PDU */
/* ASHRAE 135-2001 20.1.4 */
proto_tree_add_item(bacapp_tree, hf_bacapp_type, tvb, offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree, hf_bacapp_invoke_id, tvb,
offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree, hf_bacapp_service, tvb,
offset++, 1, ENC_BIG_ENDIAN);
return offset;
}
static guint
fContinueComplexAckPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *bacapp_tree, guint offset, gint svc)
{ /* BACnet-Complex-Ack-PDU */
/* ASHRAE 135-2001 20.1.5 */
/* Service ACK follows... */
return fConfirmedServiceAck(tvb, pinfo, bacapp_tree, offset, svc);
}
static guint
fComplexAckPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *bacapp_tree, guint offset)
{ /* BACnet-Complex-Ack-PDU */
/* ASHRAE 135-2001 20.1.5 */
gint svc;
proto_item *tt = 0;
offset = fStartConfirmed(tvb, pinfo, bacapp_tree, offset, 1, &svc, &tt);
return fContinueComplexAckPDU(tvb, pinfo, bacapp_tree, offset, svc);
}
static guint
fSegmentAckPDU(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *bacapp_tree, guint offset)
{ /* BACnet-SegmentAck-PDU */
/* ASHRAE 135-2001 20.1.6 */
proto_item *tc;
proto_tree *bacapp_tree_control;
tc = proto_tree_add_item(bacapp_tree, hf_bacapp_type, tvb, offset, 1, ENC_BIG_ENDIAN);
bacapp_tree_control = proto_item_add_subtree(tc, ett_bacapp);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_NAK, tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_SRV, tvb, offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_invoke_id, tvb,
offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_sequence_number, tvb,
offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_window_size, tvb,
offset++, 1, ENC_BIG_ENDIAN);
return offset;
}
static guint
fContextTaggedError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_info = 0;
guint8 parsed_tag = 0;
guint32 lvt = 0;
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &parsed_tag, &tag_info, &lvt);
offset = fError(tvb, pinfo, tree, offset);
return offset + fTagHeaderTree(tvb, pinfo, tree, offset, &parsed_tag, &tag_info, &lvt);
}
static guint
fConfirmedPrivateTransferError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no = 0, tag_info = 0;
guint32 lvt = 0;
proto_tree *subtree = tree;
guint vendor_identifier = 0;
guint service_number = 0;
guint8 tag_len = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) {
/* exit loop if nothing happens inside */
lastoffset = offset;
tag_len = fTagHeader(tvb, pinfo, offset, &tag_no, &tag_info, &lvt);
switch (tag_no) {
case 0: /* errorType */
offset = fContextTaggedError(tvb, pinfo, subtree, offset);
break;
case 1: /* vendorID */
fUnsigned32(tvb, offset+tag_len, lvt, &vendor_identifier);
if (col_get_writable(pinfo->cinfo))
col_append_fstr(pinfo->cinfo, COL_INFO, "V=%u ", vendor_identifier);
offset = fVendorIdentifier(tvb, pinfo, subtree, offset);
break;
case 2: /* serviceNumber */
fUnsigned32(tvb, offset+tag_len, lvt, &service_number);
if (col_get_writable(pinfo->cinfo))
col_append_fstr(pinfo->cinfo, COL_INFO, "SN=%u ", service_number);
offset = fUnsignedTag(tvb, pinfo, subtree, offset, "service Number: ");
break;
case 3: /* errorParameters */
if (tag_is_opening(tag_info)) {
subtree = proto_tree_add_subtree(subtree, tvb, offset, 1,
ett_bacapp_value, NULL, "error Parameters");
propertyIdentifier = -1;
offset += fTagHeaderTree(tvb, pinfo, subtree, offset, &tag_no, &tag_info, &lvt);
offset = fAbstractSyntaxNType(tvb, pinfo, subtree, offset);
} else if (tag_is_closing(tag_info)) {
offset += fTagHeaderTree(tvb, pinfo, subtree, offset,
&tag_no, &tag_info, &lvt);
subtree = tree;
} else {
/* error condition: let caller handle */
return offset;
}
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fCreateObjectError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* errorType */
offset = fContextTaggedError(tvb, pinfo, tree, offset);
break;
case 1: /* firstFailedElementNumber */
offset = fUnsignedTag(tvb, pinfo, tree, offset, "first failed element number: ");
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fChangeListError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
/* Identical to CreateObjectError */
return fCreateObjectError(tvb, pinfo, tree, offset);
}
static guint
fVTCloseError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint8 tag_no = 0, tag_info = 0;
guint32 lvt = 0;
if (fTagNo(tvb, offset) == 0) {
/* errorType */
offset = fContextTaggedError(tvb, pinfo, tree, offset);
if (fTagNo(tvb, offset) == 1) {
/* listOfVTSessionIdentifiers [OPTIONAL] */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fVtCloseRequest(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
}
}
/* should report bad packet if initial tag wasn't 0 */
return offset;
}
static guint
fWritePropertyMultipleError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
guint lastoffset = 0;
guint8 tag_no = 0, tag_info = 0;
guint32 lvt = 0;
col_set_writable(pinfo->cinfo, FALSE); /* don't set all infos into INFO column */
while (tvb_reported_length_remaining(tvb, offset) > 0) { /* exit loop if nothing happens inside */
lastoffset = offset;
switch (fTagNo(tvb, offset)) {
case 0: /* errorType */
offset = fContextTaggedError(tvb, pinfo, tree, offset);
break;
case 1: /* firstFailedWriteAttempt */
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
offset = fBACnetObjectPropertyReference(tvb, pinfo, tree, offset);
offset += fTagHeaderTree(tvb, pinfo, tree, offset, &tag_no, &tag_info, &lvt);
break;
default:
return offset;
}
if (offset == lastoffset) break; /* nothing happened, exit loop */
}
return offset;
}
static guint
fError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset)
{
offset = fApplicationTypesEnumeratedSplit(tvb, pinfo, tree, offset,
"error Class: ", BACnetErrorClass, 64);
return fApplicationTypesEnumeratedSplit(tvb, pinfo, tree, offset,
"error Code: ", BACnetErrorCode, 256);
}
static guint
fBACnetError(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint service)
{
switch (service) {
case 8: /* no break here !!!! */
case 9:
offset = fChangeListError(tvb, pinfo, tree, offset);
break;
case 10:
offset = fCreateObjectError(tvb, pinfo, tree, offset);
break;
case 16:
offset = fWritePropertyMultipleError(tvb, pinfo, tree, offset);
break;
case 18:
offset = fConfirmedPrivateTransferError(tvb, pinfo, tree, offset);
break;
case 22:
offset = fVTCloseError(tvb, pinfo, tree, offset);
break;
default:
return fError(tvb, pinfo, tree, offset);
}
return offset;
}
static guint
fErrorPDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *bacapp_tree, guint offset)
{ /* BACnet-Error-PDU */
/* ASHRAE 135-2001 20.1.7 */
proto_item *tc;
proto_tree *bacapp_tree_control;
guint8 tmp;
tc = proto_tree_add_item(bacapp_tree, hf_bacapp_type, tvb, offset++, 1, ENC_BIG_ENDIAN);
bacapp_tree_control = proto_item_add_subtree(tc, ett_bacapp);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_invoke_id, tvb,
offset++, 1, ENC_BIG_ENDIAN);
tmp = tvb_get_guint8(tvb, offset);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_service, tvb,
offset++, 1, ENC_BIG_ENDIAN);
/* Error Handling follows... */
return fBACnetError(tvb, pinfo, bacapp_tree, offset, tmp);
}
static guint
fRejectPDU(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *bacapp_tree, guint offset)
{ /* BACnet-Reject-PDU */
/* ASHRAE 135-2001 20.1.8 */
proto_item *tc;
proto_tree *bacapp_tree_control;
tc = proto_tree_add_item(bacapp_tree, hf_bacapp_type, tvb, offset++, 1, ENC_BIG_ENDIAN);
bacapp_tree_control = proto_item_add_subtree(tc, ett_bacapp);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_invoke_id, tvb,
offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree_control, hf_BACnetRejectReason, tvb,
offset++, 1, ENC_BIG_ENDIAN);
return offset;
}
static guint
fAbortPDU(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *bacapp_tree, guint offset)
{ /* BACnet-Abort-PDU */
/* ASHRAE 135-2001 20.1.9 */
proto_item *tc;
proto_tree *bacapp_tree_control;
tc = proto_tree_add_item(bacapp_tree, hf_bacapp_type, tvb, offset, 1, ENC_BIG_ENDIAN);
bacapp_tree_control = proto_item_add_subtree(tc, ett_bacapp);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_SRV, tvb, offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree_control, hf_bacapp_invoke_id, tvb,
offset++, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(bacapp_tree_control, hf_BACnetAbortReason, tvb,
offset++, 1, ENC_BIG_ENDIAN);
return offset;
}
static guint
do_the_dissection(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
guint8 flag, bacapp_type;
guint offset = 0;
flag = (gint) tvb_get_guint8(tvb, 0);
bacapp_type = (flag >> 4) & 0x0f;
if (tvb == NULL) {
return 0;
}
/* ASHRAE 135-2001 20.1.1 */
switch (bacapp_type) {
case BACAPP_TYPE_CONFIRMED_SERVICE_REQUEST: /* BACnet-Confirmed-Service-Request */
offset = fConfirmedRequestPDU(tvb, pinfo, tree, offset);
break;
case BACAPP_TYPE_UNCONFIRMED_SERVICE_REQUEST: /* BACnet-Unconfirmed-Request-PDU */
offset = fUnconfirmedRequestPDU(tvb, pinfo, tree, offset);
break;
case BACAPP_TYPE_SIMPLE_ACK: /* BACnet-Simple-Ack-PDU */
offset = fSimpleAckPDU(tvb, pinfo, tree, offset);
break;
case BACAPP_TYPE_COMPLEX_ACK: /* BACnet-Complex-Ack-PDU */
offset = fComplexAckPDU(tvb, pinfo, tree, offset);
break;
case BACAPP_TYPE_SEGMENT_ACK: /* BACnet-SegmentAck-PDU */
offset = fSegmentAckPDU(tvb, pinfo, tree, offset);
break;
case BACAPP_TYPE_ERROR: /* BACnet-Error-PDU */
offset = fErrorPDU(tvb, pinfo, tree, offset);
break;
case BACAPP_TYPE_REJECT: /* BACnet-Reject-PDU */
offset = fRejectPDU(tvb, pinfo, tree, offset);
break;
case BACAPP_TYPE_ABORT: /* BACnet-Abort-PDU */
offset = fAbortPDU(tvb, pinfo, tree, offset);
break;
}
return offset;
}
static void
dissect_bacapp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
guint8 flag, bacapp_type;
guint save_fragmented = FALSE, data_offset = 0, /*bacapp_apdu_size,*/ fragment = FALSE;
tvbuff_t *new_tvb = NULL;
guint offset = 0;
guint8 bacapp_seqno = 0;
guint8 bacapp_service, bacapp_reason/*, bacapp_prop_win_size*/;
guint8 bacapp_invoke_id = 0;
proto_item *ti;
proto_tree *bacapp_tree = NULL;
gint svc = 0;
proto_item *tt = 0;
gint8 ack = 0;
/* Strings for BACnet Statistics */
const gchar errstr[] = "ERROR: ";
const gchar rejstr[] = "REJECTED: ";
const gchar abortstr[] = "ABORTED: ";
const gchar sackstr[] = " (SimpleAck)";
const gchar cackstr[] = " (ComplexAck)";
const gchar uconfsreqstr[] = " (Unconfirmed Service Request)";
const gchar confsreqstr[] = " (Confirmed Service Request)";
col_set_str(pinfo->cinfo, COL_PROTOCOL, "BACnet-APDU");
col_clear(pinfo->cinfo, COL_INFO);
flag = tvb_get_guint8(tvb, 0);
bacapp_type = (flag >> 4) & 0x0f;
/* show some descriptive text in the INFO column */
col_add_fstr(pinfo->cinfo, COL_INFO, "%-16s",
val_to_str_const(bacapp_type, BACnetTypeName, "# unknown APDU #"));
bacinfo.service_type = NULL;
bacinfo.invoke_id = NULL;
bacinfo.instance_ident = NULL;
bacinfo.object_ident = NULL;
switch (bacapp_type) {
case BACAPP_TYPE_CONFIRMED_SERVICE_REQUEST:
/* segmented messages have 2 additional bytes */
if (flag & BACAPP_SEGMENTED_REQUEST) {
fragment = TRUE;
ack = 0;
/* bacapp_apdu_size = fGetMaxAPDUSize(tvb_get_guint8(tvb, offset + 1)); */ /* has 16 values, reserved are 50 Bytes */
bacapp_invoke_id = tvb_get_guint8(tvb, offset + 2);
bacapp_seqno = tvb_get_guint8(tvb, offset + 3);
/* bacapp_prop_win_size = tvb_get_guint8(tvb, offset + 4); */
bacapp_service = tvb_get_guint8(tvb, offset + 5);
data_offset = 6;
} else {
bacapp_invoke_id = tvb_get_guint8(tvb, offset + 2);
bacapp_service = tvb_get_guint8(tvb, offset + 3);
}
col_append_fstr(pinfo->cinfo, COL_INFO, "%s[%3u] ",
val_to_str_const(bacapp_service,
BACnetConfirmedServiceChoice,
bacapp_unknown_service_str),
bacapp_invoke_id);
updateBacnetInfoValue(BACINFO_INVOKEID,
wmem_strdup_printf(wmem_packet_scope(), "Invoke ID: %d", bacapp_invoke_id));
updateBacnetInfoValue(BACINFO_SERVICE,
wmem_strconcat(wmem_packet_scope(),
val_to_str_const(bacapp_service,
BACnetConfirmedServiceChoice,
bacapp_unknown_service_str),
confsreqstr, NULL));
break;
case BACAPP_TYPE_UNCONFIRMED_SERVICE_REQUEST:
bacapp_service = tvb_get_guint8(tvb, offset + 1);
col_append_fstr(pinfo->cinfo, COL_INFO, "%s ",
val_to_str_const(bacapp_service,
BACnetUnconfirmedServiceChoice,
bacapp_unknown_service_str));
updateBacnetInfoValue(BACINFO_SERVICE,
wmem_strconcat(wmem_packet_scope(),
val_to_str_const(bacapp_service,
BACnetUnconfirmedServiceChoice,
bacapp_unknown_service_str),
uconfsreqstr, NULL));
break;
case BACAPP_TYPE_SIMPLE_ACK:
bacapp_invoke_id = tvb_get_guint8(tvb, offset + 1);
bacapp_service = tvb_get_guint8(tvb, offset + 2);
col_append_fstr(pinfo->cinfo, COL_INFO, "%s[%3u] ", /* "original-invokeID" replaced */
val_to_str_const(bacapp_service,
BACnetConfirmedServiceChoice,
bacapp_unknown_service_str),
bacapp_invoke_id);
updateBacnetInfoValue(BACINFO_INVOKEID,
wmem_strdup_printf(wmem_packet_scope(),
"Invoke ID: %d", bacapp_invoke_id));
updateBacnetInfoValue(BACINFO_SERVICE,
wmem_strconcat(wmem_packet_scope(),
val_to_str_const(bacapp_service,
BACnetConfirmedServiceChoice,
bacapp_unknown_service_str),
sackstr, NULL));
break;
case BACAPP_TYPE_COMPLEX_ACK:
/* segmented messages have 2 additional bytes */
if (flag & BACAPP_SEGMENTED_REQUEST) {
fragment = TRUE;
ack = 1;
/* bacapp_apdu_size = fGetMaxAPDUSize(0); */ /* has minimum of 50 Bytes */
bacapp_invoke_id = tvb_get_guint8(tvb, offset + 1);
bacapp_seqno = tvb_get_guint8(tvb, offset + 2);
/* bacapp_prop_win_size = tvb_get_guint8(tvb, offset + 3); */
bacapp_service = tvb_get_guint8(tvb, offset + 4);
data_offset = 5;
} else {
bacapp_invoke_id = tvb_get_guint8(tvb, offset + 1);
bacapp_service = tvb_get_guint8(tvb, offset + 2);
}
col_append_fstr(pinfo->cinfo, COL_INFO, "%s[%3u] ", /* "original-invokeID" replaced */
val_to_str_const(bacapp_service,
BACnetConfirmedServiceChoice,
bacapp_unknown_service_str),
bacapp_invoke_id);
updateBacnetInfoValue(BACINFO_INVOKEID,
wmem_strdup_printf(wmem_packet_scope(), "Invoke ID: %d", bacapp_invoke_id));
updateBacnetInfoValue(BACINFO_SERVICE,
wmem_strconcat(wmem_packet_scope(),
val_to_str_const(bacapp_service,
BACnetConfirmedServiceChoice,
bacapp_unknown_service_str),
cackstr, NULL));
break;
case BACAPP_TYPE_SEGMENT_ACK:
/* nothing more to add */
break;
case BACAPP_TYPE_ERROR:
bacapp_invoke_id = tvb_get_guint8(tvb, offset + 1);
bacapp_service = tvb_get_guint8(tvb, offset + 2);
col_append_fstr(pinfo->cinfo, COL_INFO, "%s[%3u] ", /* "original-invokeID" replaced */
val_to_str_const(bacapp_service,
BACnetConfirmedServiceChoice,
bacapp_unknown_service_str),
bacapp_invoke_id);
updateBacnetInfoValue(BACINFO_INVOKEID,
wmem_strdup_printf(wmem_packet_scope(), "Invoke ID: %d", bacapp_invoke_id));
updateBacnetInfoValue(BACINFO_SERVICE,
wmem_strconcat(wmem_packet_scope(),
errstr,
val_to_str_const(bacapp_service,
BACnetConfirmedServiceChoice,
bacapp_unknown_service_str),
NULL));
break;
case BACAPP_TYPE_REJECT:
bacapp_invoke_id = tvb_get_guint8(tvb, offset + 1);
bacapp_reason = tvb_get_guint8(tvb, offset + 2);
col_append_fstr(pinfo->cinfo, COL_INFO, "%s[%3u] ", /* "original-invokeID" replaced */
val_to_split_str(bacapp_reason,
64,
BACnetRejectReason,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt), bacapp_invoke_id);
updateBacnetInfoValue(BACINFO_INVOKEID,
wmem_strdup_printf(wmem_packet_scope(), "Invoke ID: %d", bacapp_invoke_id));
updateBacnetInfoValue(BACINFO_SERVICE,
wmem_strconcat(wmem_packet_scope(), rejstr,
val_to_split_str(bacapp_reason, 64,
BACnetRejectReason,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt),
NULL));
break;
case BACAPP_TYPE_ABORT:
bacapp_invoke_id = tvb_get_guint8(tvb, offset + 1);
bacapp_reason = tvb_get_guint8(tvb, offset + 2);
col_append_fstr(pinfo->cinfo, COL_INFO, "%s[%3u] ", /* "original-invokeID" replaced */
val_to_split_str(bacapp_reason,
64,
BACnetAbortReason,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt), bacapp_invoke_id);
updateBacnetInfoValue(BACINFO_INVOKEID,
wmem_strdup_printf(wmem_packet_scope(), "Invoke ID: %d", bacapp_invoke_id));
updateBacnetInfoValue(BACINFO_SERVICE,
wmem_strconcat(wmem_packet_scope(), abortstr,
val_to_split_str(bacapp_reason,
64,
BACnetAbortReason,
ASHRAE_Reserved_Fmt,
Vendor_Proprietary_Fmt),
NULL));
break;
/* UNKNOWN */
default:
/* nothing more to add */
break;
}
save_fragmented = pinfo->fragmented;
ti = proto_tree_add_item(tree, proto_bacapp, tvb, offset, -1, ENC_NA);
bacapp_tree = proto_item_add_subtree(ti, ett_bacapp);
if (!fragment)
do_the_dissection(tvb, pinfo, bacapp_tree);
else
fStartConfirmed(tvb, pinfo, bacapp_tree, offset, ack, &svc, &tt);
/* not resetting the offset so the remaining can be done */
if (fragment) { /* fragmented */
fragment_head *frag_msg;
pinfo->fragmented = TRUE;
frag_msg = fragment_add_seq_check(&msg_reassembly_table,
tvb, data_offset,
pinfo,
bacapp_invoke_id, /* ID for fragments belonging together */
NULL,
bacapp_seqno, /* fragment sequence number */
tvb_reported_length_remaining(tvb, data_offset), /* fragment length - to the end */
flag & BACAPP_MORE_SEGMENTS); /* Last fragment reached? */
new_tvb = process_reassembled_data(tvb, data_offset, pinfo,
"Reassembled BACapp", frag_msg, &msg_frag_items,
NULL, tree);
if (new_tvb) { /* Reassembled */
col_append_str(pinfo->cinfo, COL_INFO,
" (Message Reassembled)");
} else { /* Not last packet of reassembled Short Message */
col_append_fstr(pinfo->cinfo, COL_INFO,
" (Message fragment %u)", bacapp_seqno);
}
if (new_tvb) { /* take it all */
switch (bacapp_type) {
case BACAPP_TYPE_CONFIRMED_SERVICE_REQUEST:
fContinueConfirmedRequestPDU(new_tvb, pinfo, bacapp_tree, 0, svc);
break;
case BACAPP_TYPE_COMPLEX_ACK:
fContinueComplexAckPDU(new_tvb, pinfo, bacapp_tree, 0, svc);
break;
default:
/* do nothing */
break;
}
}
}
pinfo->fragmented = save_fragmented;
/* tapping */
tap_queue_packet(bacapp_tap, pinfo, &bacinfo);
}
static void
bacapp_init_routine(void)
{
reassembly_table_init(&msg_reassembly_table,
&addresses_reassembly_table_functions);
}
void
proto_register_bacapp(void)
{
static hf_register_info hf[] = {
{ &hf_bacapp_type,
{ "APDU Type", "bacapp.type",
FT_UINT8, BASE_DEC, VALS(BACnetTypeName), 0xf0, NULL, HFILL }
},
{ &hf_bacapp_pduflags,
{ "PDU Flags", "bacapp.pduflags",
FT_UINT8, BASE_HEX, NULL, 0x0f, NULL, HFILL }
},
{ &hf_bacapp_SEG,
{ "Segmented Request", "bacapp.segmented_request",
FT_BOOLEAN, 8, TFS(&segments_follow), 0x08, NULL, HFILL }
},
{ &hf_bacapp_MOR,
{ "More Segments", "bacapp.more_segments",
FT_BOOLEAN, 8, TFS(&more_follow), 0x04, "More Segments Follow", HFILL }
},
{ &hf_bacapp_SA,
{ "SA", "bacapp.SA",
FT_BOOLEAN, 8, TFS(&segmented_accept), 0x02, "Segmented Response accepted", HFILL }
},
{ &hf_bacapp_max_adpu_size,
{ "Size of Maximum ADPU accepted", "bacapp.max_adpu_size",
FT_UINT8, BASE_DEC, VALS(BACnetMaxAPDULengthAccepted), 0x0f, NULL, HFILL }
},
{ &hf_bacapp_response_segments,
{ "Max Response Segments accepted", "bacapp.response_segments",
FT_UINT8, BASE_DEC, VALS(BACnetMaxSegmentsAccepted), 0x70, NULL, HFILL }
},
{ &hf_bacapp_objectType,
{ "Object Type", "bacapp.objectType",
FT_UINT32, BASE_DEC, VALS(BACnetObjectType), 0xffc00000, NULL, HFILL }
},
{ &hf_bacapp_instanceNumber,
{ "Instance Number", "bacapp.instance_number",
FT_UINT32, BASE_DEC, NULL, 0x003fffff, NULL, HFILL }
},
{ &hf_BACnetPropertyIdentifier,
{ "Property Identifier", "bacapp.property_identifier",
FT_UINT32, BASE_DEC, VALS(BACnetPropertyIdentifier), 0, NULL, HFILL }
},
{ &hf_BACnetVendorIdentifier,
{ "Vendor Identifier", "bacapp.vendor_identifier",
FT_UINT16, BASE_DEC|BASE_EXT_STRING, &BACnetVendorIdentifiers_ext, 0, NULL, HFILL }
},
{ &hf_BACnetRestartReason,
{ "Restart Reason", "bacapp.restart_reason",
FT_UINT8, BASE_DEC, VALS(BACnetRestartReason), 0, NULL, HFILL }
},
{ &hf_bacapp_invoke_id,
{ "Invoke ID", "bacapp.invoke_id",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_bacapp_sequence_number,
{ "Sequence Number", "bacapp.sequence_number",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_bacapp_window_size,
{ "Proposed Window Size", "bacapp.window_size",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_bacapp_service,
{ "Service Choice", "bacapp.confirmed_service",
FT_UINT8, BASE_DEC, VALS(BACnetConfirmedServiceChoice), 0x00, NULL, HFILL }
},
{ &hf_bacapp_uservice,
{ "Unconfirmed Service Choice", "bacapp.unconfirmed_service",
FT_UINT8, BASE_DEC, VALS(BACnetUnconfirmedServiceChoice), 0x00, NULL, HFILL }
},
{ &hf_bacapp_NAK,
{ "NAK", "bacapp.NAK",
FT_BOOLEAN, 8, NULL, 0x02, "negative ACK", HFILL }
},
{ &hf_bacapp_SRV,
{ "SRV", "bacapp.SRV",
FT_BOOLEAN, 8, NULL, 0x01, "Server", HFILL }
},
{ &hf_Device_Instance_Range_Low_Limit,
{ "Device Instance Range Low Limit", "bacapp.who_is.low_limit",
FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_Device_Instance_Range_High_Limit,
{ "Device Instance Range High Limit", "bacapp.who_is.high_limit",
FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_BACnetRejectReason,
{ "Reject Reason", "bacapp.reject_reason",
FT_UINT8, BASE_DEC, VALS(BACnetRejectReason), 0x00, NULL, HFILL }
},
{ &hf_BACnetAbortReason,
{ "Abort Reason", "bacapp.abort_reason",
FT_UINT8, BASE_DEC, VALS(BACnetAbortReason), 0x00, NULL, HFILL }
},
{ &hf_BACnetApplicationTagNumber,
{ "Application Tag Number",
"bacapp.application_tag_number",
FT_UINT8, BASE_DEC, VALS(BACnetApplicationTagNumber), 0xF0,
NULL, HFILL }
},
{ &hf_BACnetContextTagNumber,
{ "Context Tag Number",
"bacapp.context_tag_number",
FT_UINT8, BASE_DEC, NULL, 0xF0,
NULL, HFILL }
},
{ &hf_BACnetExtendedTagNumber,
{ "Extended Tag Number",
"bacapp.extended_tag_number",
FT_UINT8, BASE_DEC, NULL, 0,
NULL, HFILL }
},
{ &hf_BACnetNamedTag,
{ "Named Tag",
"bacapp.named_tag",
FT_UINT8, BASE_DEC, VALS(BACnetTagNames), 0x07,
NULL, HFILL }
},
{ &hf_BACnetCharacterSet,
{ "String Character Set",
"bacapp.string_character_set",
FT_UINT8, BASE_DEC, VALS(BACnetCharacterSet), 0,
NULL, HFILL }
},
{ &hf_BACnetTagClass,
{ "Tag Class", "bacapp.tag_class",
FT_BOOLEAN, 8, TFS(&BACnetTagClass), 0x08, NULL, HFILL }
},
{ &hf_bacapp_tag_lvt,
{ "Length Value Type",
"bacapp.LVT",
FT_UINT8, BASE_DEC, NULL, 0,
NULL, HFILL }
},
{ &hf_bacapp_tag_ProcessId,
{ "ProcessIdentifier", "bacapp.processId",
FT_UINT32, BASE_DEC, NULL, 0, "Process Identifier", HFILL }
},
{ &hf_bacapp_tag_IPV4,
{ "IPV4", "bacapp.IPV4",
FT_IPv4, BASE_NONE, NULL, 0, "IP-Address", HFILL }
},
{ &hf_bacapp_tag_IPV6,
{ "IPV6", "bacapp.IPV6",
FT_IPv6, BASE_NONE, NULL, 0, "IP-Address", HFILL }
},
{ &hf_bacapp_tag_PORT,
{ "Port", "bacapp.Port",
FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
},
{&hf_msg_fragments,
{"Message fragments", "bacapp.fragments",
FT_NONE, BASE_NONE, NULL, 0x00, NULL, HFILL } },
{&hf_msg_fragment,
{"Message fragment", "bacapp.fragment",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL } },
{&hf_msg_fragment_overlap,
{"Message fragment overlap", "bacapp.fragment.overlap",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL } },
{&hf_msg_fragment_overlap_conflicts,
{"Message fragment overlapping with conflicting data",
"bacapp.fragment.overlap.conflicts",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL } },
{&hf_msg_fragment_multiple_tails,
{"Message has multiple tail fragments",
"bacapp.fragment.multiple_tails",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL } },
{&hf_msg_fragment_too_long_fragment,
{"Message fragment too long", "bacapp.fragment.too_long_fragment",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL } },
{&hf_msg_fragment_error,
{"Message defragmentation error", "bacapp.fragment.error",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL } },
{&hf_msg_fragment_count,
{"Message fragment count", "bacapp.fragment.count",
FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL } },
{&hf_msg_reassembled_in,
{"Reassembled in", "bacapp.reassembled.in",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL } },
{&hf_msg_reassembled_length,
{"Reassembled BACapp length", "bacapp.reassembled.length",
FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL } }
};
static gint *ett[] = {
&ett_bacapp,
&ett_bacapp_control,
&ett_bacapp_tag,
&ett_bacapp_list,
&ett_bacapp_value,
&ett_msg_fragment,
&ett_msg_fragments
};
static ei_register_info ei[] = {
{ &ei_bacapp_bad_length, { "bacapp.bad_length", PI_MALFORMED, PI_ERROR, "Wrong length indicated", EXPFILL }},
};
expert_module_t* expert_bacapp;
proto_bacapp = proto_register_protocol("Building Automation and Control Network APDU",
"BACapp", "bacapp");
proto_register_field_array(proto_bacapp, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_bacapp = expert_register_protocol(proto_bacapp);
expert_register_field_array(expert_bacapp, ei, array_length(ei));
register_dissector("bacapp", dissect_bacapp, proto_bacapp);
register_init_routine(&bacapp_init_routine);
bacapp_dissector_table = register_dissector_table("bacapp.vendor_identifier",
"BACapp Vendor Identifier",
FT_UINT8, BASE_HEX);
/* Register BACnet Statistic trees */
register_bacapp_stat_trees();
bacapp_tap = register_tap("bacapp"); /* BACnet statistics tap */
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| gpl-2.0 |
Exitare/TrinityCore | src/server/scripts/Kalimdor/RazorfenDowns/boss_tuten_kash.cpp | 4 | 3304 | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "razorfen_downs.h"
enum Spells
{
SPELL_THRASH = 8876,
SPELL_WEB_SPRAY = 12252,
SPELL_VIRULENT_POISON = 12254,
SPELL_CURSE_OF_TUTENKASH = 12255
};
enum Events
{
EVENT_WEB_SPRAY = 1,
EVENT_CURSE_OF_TUTENKASH = 2
};
class boss_tuten_kash : public CreatureScript
{
public:
boss_tuten_kash() : CreatureScript("boss_tuten_kash") { }
struct boss_tuten_kashAI : public BossAI
{
boss_tuten_kashAI(Creature* creature) : BossAI(creature, DATA_TUTEN_KASH) { }
void Reset() override
{
_Reset();
if (!me->HasAura(SPELL_THRASH))
DoCast(me, SPELL_THRASH);
if (!me->HasAura(SPELL_VIRULENT_POISON))
DoCast(me, SPELL_VIRULENT_POISON);
}
void JustEngagedWith(Unit* who) override
{
BossAI::JustEngagedWith(who);
events.ScheduleEvent(EVENT_WEB_SPRAY, 3s, 5s);
events.ScheduleEvent(EVENT_CURSE_OF_TUTENKASH, 9s, 14s);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_WEB_SPRAY:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, false))
{
if (!target->HasAura(SPELL_WEB_SPRAY))
DoCast(target, SPELL_WEB_SPRAY);
}
events.ScheduleEvent(EVENT_WEB_SPRAY, 6s, 8s);
break;
case EVENT_CURSE_OF_TUTENKASH:
DoCast(me, SPELL_CURSE_OF_TUTENKASH);
events.ScheduleEvent(EVENT_CURSE_OF_TUTENKASH, 15s, 25s);
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetRazorfenDownsAI<boss_tuten_kashAI>(creature);
}
};
void AddSC_boss_tuten_kash()
{
new boss_tuten_kash();
}
| gpl-2.0 |
rickgaiser/linux-2.2.1-ps2 | fs/coda/symlink.c | 4 | 3017 | /*
* Symlink inode operations for Coda filesystem
* Original version: (C) 1996 P. Braam and M. Callahan
* Rewritten for Linux 2.1. (C) 1997 Carnegie Mellon University
*
* Carnegie Mellon encourages users to contribute improvements to
* the Coda project. Contact Peter Braam (coda@cs.cmu.edu).
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/stat.h>
#include <linux/errno.h>
#include <linux/locks.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/string.h>
#include <linux/coda.h>
#include <linux/coda_linux.h>
#include <linux/coda_psdev.h>
#include <linux/coda_fs_i.h>
#include <linux/coda_cache.h>
#include <linux/coda_proc.h>
static int coda_readlink(struct dentry *de, char *buffer, int length);
static struct dentry *coda_follow_link(struct dentry *, struct dentry *,
unsigned int);
struct inode_operations coda_symlink_inode_operations = {
NULL, /* no file-operations */
NULL, /* create */
NULL, /* lookup */
NULL, /* link */
NULL, /* unlink */
NULL, /* symlink */
NULL, /* mkdir */
NULL, /* rmdir */
NULL, /* mknod */
NULL, /* rename */
coda_readlink, /* readlink */
coda_follow_link, /* follow_link */
NULL, /* readpage */
NULL, /* writepage */
NULL, /* bmap */
NULL, /* truncate */
NULL, /* permission */
NULL, /* smap */
NULL, /* update page */
NULL /* revalidate */
};
static int coda_readlink(struct dentry *de, char *buffer, int length)
{
struct inode *inode = de->d_inode;
int len;
int error;
char *buf;
struct coda_inode_info *cp;
ENTRY;
cp = ITOC(inode);
coda_vfs_stat.readlink++;
/* the maximum length we receive is len */
if ( length > CODA_MAXPATHLEN )
len = CODA_MAXPATHLEN;
else
len = length;
CODA_ALLOC(buf, char *, len);
if ( !buf )
return -ENOMEM;
error = venus_readlink(inode->i_sb, &(cp->c_fid), buf, &len);
CDEBUG(D_INODE, "result %s\n", buf);
if (! error) {
copy_to_user(buffer, buf, len);
put_user('\0', buffer + len);
error = len;
}
if ( buf )
CODA_FREE(buf, len);
return error;
}
static struct dentry *coda_follow_link(struct dentry *de, struct dentry *base,
unsigned int follow)
{
struct inode *inode = de->d_inode;
int error;
struct coda_inode_info *cnp;
unsigned int len;
char mem[CODA_MAXPATHLEN];
char *path;
ENTRY;
CDEBUG(D_INODE, "(%x/%ld)\n", inode->i_dev, inode->i_ino);
cnp = ITOC(inode);
coda_vfs_stat.follow_link++;
len = CODA_MAXPATHLEN;
error = venus_readlink(inode->i_sb, &(cnp->c_fid), mem, &len);
if (error) {
dput(base);
return ERR_PTR(error);
}
len = strlen(mem);
path = kmalloc(len + 1, GFP_KERNEL);
if (!path) {
dput(base);
return ERR_PTR(-ENOMEM);
}
memcpy(path, mem, len);
path[len] = 0;
base = lookup_dentry(path, base, follow);
kfree(path);
return base;
}
| gpl-2.0 |
bq-vegetalte/stock_vegetalte | fs/namespace.c | 4 | 71382 | /*
* linux/fs/namespace.c
*
* (C) Copyright Al Viro 2000, 2001
* Released under GPL v2.
*
* Based on code from fs/super.c, copyright Linus Torvalds and others.
* Heavily rewritten.
*/
#include <linux/syscalls.h>
#include <linux/export.h>
#include <linux/capability.h>
#include <linux/mnt_namespace.h>
#include <linux/user_namespace.h>
#include <linux/namei.h>
#include <linux/security.h>
#include <linux/idr.h>
#include <linux/acct.h> /* acct_auto_close_mnt */
#include <linux/ramfs.h> /* init_rootfs */
#include <linux/fs_struct.h> /* get_fs_root et.al. */
#include <linux/fsnotify.h> /* fsnotify_vfsmount_delete */
#include <linux/uaccess.h>
#include <linux/proc_ns.h>
#include <linux/magic.h>
#include "pnode.h"
#include "internal.h"
#define HASH_SHIFT ilog2(PAGE_SIZE / sizeof(struct list_head))
#define HASH_SIZE (1UL << HASH_SHIFT)
static int event;
static DEFINE_IDA(mnt_id_ida);
static DEFINE_IDA(mnt_group_ida);
static DEFINE_SPINLOCK(mnt_id_lock);
static int mnt_id_start = 0;
static int mnt_group_start = 1;
static struct list_head *mount_hashtable __read_mostly;
static struct list_head *mountpoint_hashtable __read_mostly;
static struct kmem_cache *mnt_cache __read_mostly;
static struct rw_semaphore namespace_sem;
/* /sys/fs */
struct kobject *fs_kobj;
EXPORT_SYMBOL_GPL(fs_kobj);
/*
* vfsmount lock may be taken for read to prevent changes to the
* vfsmount hash, ie. during mountpoint lookups or walking back
* up the tree.
*
* It should be taken for write in all cases where the vfsmount
* tree or hash is modified or when a vfsmount structure is modified.
*/
DEFINE_BRLOCK(vfsmount_lock);
static inline unsigned long hash(struct vfsmount *mnt, struct dentry *dentry)
{
unsigned long tmp = ((unsigned long)mnt / L1_CACHE_BYTES);
tmp += ((unsigned long)dentry / L1_CACHE_BYTES);
tmp = tmp + (tmp >> HASH_SHIFT);
return tmp & (HASH_SIZE - 1);
}
#define MNT_WRITER_UNDERFLOW_LIMIT -(1<<16)
/*
* allocation is serialized by namespace_sem, but we need the spinlock to
* serialize with freeing.
*/
static int mnt_alloc_id(struct mount *mnt)
{
int res;
retry:
ida_pre_get(&mnt_id_ida, GFP_KERNEL);
spin_lock(&mnt_id_lock);
res = ida_get_new_above(&mnt_id_ida, mnt_id_start, &mnt->mnt_id);
if (!res)
mnt_id_start = mnt->mnt_id + 1;
spin_unlock(&mnt_id_lock);
if (res == -EAGAIN)
goto retry;
return res;
}
static void mnt_free_id(struct mount *mnt)
{
int id = mnt->mnt_id;
spin_lock(&mnt_id_lock);
ida_remove(&mnt_id_ida, id);
if (mnt_id_start > id)
mnt_id_start = id;
spin_unlock(&mnt_id_lock);
}
/*
* Allocate a new peer group ID
*
* mnt_group_ida is protected by namespace_sem
*/
static int mnt_alloc_group_id(struct mount *mnt)
{
int res;
if (!ida_pre_get(&mnt_group_ida, GFP_KERNEL))
return -ENOMEM;
res = ida_get_new_above(&mnt_group_ida,
mnt_group_start,
&mnt->mnt_group_id);
if (!res)
mnt_group_start = mnt->mnt_group_id + 1;
return res;
}
/*
* Release a peer group ID
*/
void mnt_release_group_id(struct mount *mnt)
{
int id = mnt->mnt_group_id;
ida_remove(&mnt_group_ida, id);
if (mnt_group_start > id)
mnt_group_start = id;
mnt->mnt_group_id = 0;
}
/*
* vfsmount lock must be held for read
*/
static inline void mnt_add_count(struct mount *mnt, int n)
{
#ifdef CONFIG_SMP
this_cpu_add(mnt->mnt_pcp->mnt_count, n);
#else
preempt_disable();
mnt->mnt_count += n;
preempt_enable();
#endif
}
/*
* vfsmount lock must be held for write
*/
unsigned int mnt_get_count(struct mount *mnt)
{
#ifdef CONFIG_SMP
unsigned int count = 0;
int cpu;
for_each_possible_cpu(cpu) {
count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count;
}
return count;
#else
return mnt->mnt_count;
#endif
}
static struct mount *alloc_vfsmnt(const char *name)
{
struct mount *mnt = kmem_cache_zalloc(mnt_cache, GFP_KERNEL);
if (mnt) {
int err;
err = mnt_alloc_id(mnt);
if (err)
goto out_free_cache;
if (name) {
mnt->mnt_devname = kstrdup(name, GFP_KERNEL);
if (!mnt->mnt_devname)
goto out_free_id;
}
#ifdef CONFIG_SMP
mnt->mnt_pcp = alloc_percpu(struct mnt_pcp);
if (!mnt->mnt_pcp)
goto out_free_devname;
this_cpu_add(mnt->mnt_pcp->mnt_count, 1);
#else
mnt->mnt_count = 1;
mnt->mnt_writers = 0;
#endif
INIT_LIST_HEAD(&mnt->mnt_hash);
INIT_LIST_HEAD(&mnt->mnt_child);
INIT_LIST_HEAD(&mnt->mnt_mounts);
INIT_LIST_HEAD(&mnt->mnt_list);
INIT_LIST_HEAD(&mnt->mnt_expire);
INIT_LIST_HEAD(&mnt->mnt_share);
INIT_LIST_HEAD(&mnt->mnt_slave_list);
INIT_LIST_HEAD(&mnt->mnt_slave);
#ifdef CONFIG_FSNOTIFY
INIT_HLIST_HEAD(&mnt->mnt_fsnotify_marks);
#endif
}
return mnt;
#ifdef CONFIG_SMP
out_free_devname:
kfree(mnt->mnt_devname);
#endif
out_free_id:
mnt_free_id(mnt);
out_free_cache:
kmem_cache_free(mnt_cache, mnt);
return NULL;
}
/*
* Most r/o checks on a fs are for operations that take
* discrete amounts of time, like a write() or unlink().
* We must keep track of when those operations start
* (for permission checks) and when they end, so that
* we can determine when writes are able to occur to
* a filesystem.
*/
/*
* __mnt_is_readonly: check whether a mount is read-only
* @mnt: the mount to check for its write status
*
* This shouldn't be used directly ouside of the VFS.
* It does not guarantee that the filesystem will stay
* r/w, just that it is right *now*. This can not and
* should not be used in place of IS_RDONLY(inode).
* mnt_want/drop_write() will _keep_ the filesystem
* r/w.
*/
int __mnt_is_readonly(struct vfsmount *mnt)
{
if (mnt->mnt_flags & MNT_READONLY)
return 1;
if (mnt->mnt_sb->s_flags & MS_RDONLY)
return 1;
return 0;
}
EXPORT_SYMBOL_GPL(__mnt_is_readonly);
static inline void mnt_inc_writers(struct mount *mnt)
{
#ifdef CONFIG_SMP
this_cpu_inc(mnt->mnt_pcp->mnt_writers);
#else
mnt->mnt_writers++;
#endif
}
static inline void mnt_dec_writers(struct mount *mnt)
{
#ifdef CONFIG_SMP
this_cpu_dec(mnt->mnt_pcp->mnt_writers);
#else
mnt->mnt_writers--;
#endif
}
static unsigned int mnt_get_writers(struct mount *mnt)
{
#ifdef CONFIG_SMP
unsigned int count = 0;
int cpu;
for_each_possible_cpu(cpu) {
count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_writers;
}
return count;
#else
return mnt->mnt_writers;
#endif
}
static int mnt_is_readonly(struct vfsmount *mnt)
{
if (mnt->mnt_sb->s_readonly_remount)
return 1;
/* Order wrt setting s_flags/s_readonly_remount in do_remount() */
smp_rmb();
return __mnt_is_readonly(mnt);
}
/*
* Most r/o & frozen checks on a fs are for operations that take discrete
* amounts of time, like a write() or unlink(). We must keep track of when
* those operations start (for permission checks) and when they end, so that we
* can determine when writes are able to occur to a filesystem.
*/
/**
* __mnt_want_write - get write access to a mount without freeze protection
* @m: the mount on which to take a write
*
* This tells the low-level filesystem that a write is about to be performed to
* it, and makes sure that writes are allowed (mnt it read-write) before
* returning success. This operation does not protect against filesystem being
* frozen. When the write operation is finished, __mnt_drop_write() must be
* called. This is effectively a refcount.
*/
int __mnt_want_write(struct vfsmount *m)
{
struct mount *mnt = real_mount(m);
int ret = 0;
preempt_disable();
mnt_inc_writers(mnt);
/*
* The store to mnt_inc_writers must be visible before we pass
* MNT_WRITE_HOLD loop below, so that the slowpath can see our
* incremented count after it has set MNT_WRITE_HOLD.
*/
smp_mb();
while (ACCESS_ONCE(mnt->mnt.mnt_flags) & MNT_WRITE_HOLD)
cpu_relax();
/*
* After the slowpath clears MNT_WRITE_HOLD, mnt_is_readonly will
* be set to match its requirements. So we must not load that until
* MNT_WRITE_HOLD is cleared.
*/
smp_rmb();
if (mnt_is_readonly(m)) {
mnt_dec_writers(mnt);
ret = -EROFS;
}
preempt_enable();
return ret;
}
/**
* mnt_want_write - get write access to a mount
* @m: the mount on which to take a write
*
* This tells the low-level filesystem that a write is about to be performed to
* it, and makes sure that writes are allowed (mount is read-write, filesystem
* is not frozen) before returning success. When the write operation is
* finished, mnt_drop_write() must be called. This is effectively a refcount.
*/
int mnt_want_write(struct vfsmount *m)
{
int ret;
sb_start_write(m->mnt_sb);
ret = __mnt_want_write(m);
if (ret)
sb_end_write(m->mnt_sb);
return ret;
}
EXPORT_SYMBOL_GPL(mnt_want_write);
/**
* mnt_clone_write - get write access to a mount
* @mnt: the mount on which to take a write
*
* This is effectively like mnt_want_write, except
* it must only be used to take an extra write reference
* on a mountpoint that we already know has a write reference
* on it. This allows some optimisation.
*
* After finished, mnt_drop_write must be called as usual to
* drop the reference.
*/
int mnt_clone_write(struct vfsmount *mnt)
{
/* superblock may be r/o */
if (__mnt_is_readonly(mnt))
return -EROFS;
preempt_disable();
mnt_inc_writers(real_mount(mnt));
preempt_enable();
return 0;
}
EXPORT_SYMBOL_GPL(mnt_clone_write);
/**
* __mnt_want_write_file - get write access to a file's mount
* @file: the file who's mount on which to take a write
*
* This is like __mnt_want_write, but it takes a file and can
* do some optimisations if the file is open for write already
*/
int __mnt_want_write_file(struct file *file)
{
struct inode *inode = file_inode(file);
if (!(file->f_mode & FMODE_WRITE) || special_file(inode->i_mode))
return __mnt_want_write(file->f_path.mnt);
else
return mnt_clone_write(file->f_path.mnt);
}
/**
* mnt_want_write_file - get write access to a file's mount
* @file: the file who's mount on which to take a write
*
* This is like mnt_want_write, but it takes a file and can
* do some optimisations if the file is open for write already
*/
int mnt_want_write_file(struct file *file)
{
int ret;
sb_start_write(file->f_path.mnt->mnt_sb);
ret = __mnt_want_write_file(file);
if (ret)
sb_end_write(file->f_path.mnt->mnt_sb);
return ret;
}
EXPORT_SYMBOL_GPL(mnt_want_write_file);
/**
* __mnt_drop_write - give up write access to a mount
* @mnt: the mount on which to give up write access
*
* Tells the low-level filesystem that we are done
* performing writes to it. Must be matched with
* __mnt_want_write() call above.
*/
void __mnt_drop_write(struct vfsmount *mnt)
{
preempt_disable();
mnt_dec_writers(real_mount(mnt));
preempt_enable();
}
/**
* mnt_drop_write - give up write access to a mount
* @mnt: the mount on which to give up write access
*
* Tells the low-level filesystem that we are done performing writes to it and
* also allows filesystem to be frozen again. Must be matched with
* mnt_want_write() call above.
*/
void mnt_drop_write(struct vfsmount *mnt)
{
__mnt_drop_write(mnt);
sb_end_write(mnt->mnt_sb);
}
EXPORT_SYMBOL_GPL(mnt_drop_write);
void __mnt_drop_write_file(struct file *file)
{
__mnt_drop_write(file->f_path.mnt);
}
void mnt_drop_write_file(struct file *file)
{
mnt_drop_write(file->f_path.mnt);
}
EXPORT_SYMBOL(mnt_drop_write_file);
static int mnt_make_readonly(struct mount *mnt)
{
int ret = 0;
br_write_lock(&vfsmount_lock);
mnt->mnt.mnt_flags |= MNT_WRITE_HOLD;
/*
* After storing MNT_WRITE_HOLD, we'll read the counters. This store
* should be visible before we do.
*/
smp_mb();
/*
* With writers on hold, if this value is zero, then there are
* definitely no active writers (although held writers may subsequently
* increment the count, they'll have to wait, and decrement it after
* seeing MNT_READONLY).
*
* It is OK to have counter incremented on one CPU and decremented on
* another: the sum will add up correctly. The danger would be when we
* sum up each counter, if we read a counter before it is incremented,
* but then read another CPU's count which it has been subsequently
* decremented from -- we would see more decrements than we should.
* MNT_WRITE_HOLD protects against this scenario, because
* mnt_want_write first increments count, then smp_mb, then spins on
* MNT_WRITE_HOLD, so it can't be decremented by another CPU while
* we're counting up here.
*/
if (mnt_get_writers(mnt) > 0)
ret = -EBUSY;
else
mnt->mnt.mnt_flags |= MNT_READONLY;
/*
* MNT_READONLY must become visible before ~MNT_WRITE_HOLD, so writers
* that become unheld will see MNT_READONLY.
*/
smp_wmb();
mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD;
br_write_unlock(&vfsmount_lock);
return ret;
}
static void __mnt_unmake_readonly(struct mount *mnt)
{
br_write_lock(&vfsmount_lock);
mnt->mnt.mnt_flags &= ~MNT_READONLY;
br_write_unlock(&vfsmount_lock);
}
int sb_prepare_remount_readonly(struct super_block *sb)
{
struct mount *mnt;
int err = 0;
/* Racy optimization. Recheck the counter under MNT_WRITE_HOLD */
if (atomic_long_read(&sb->s_remove_count))
return -EBUSY;
br_write_lock(&vfsmount_lock);
list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) {
if (!(mnt->mnt.mnt_flags & MNT_READONLY)) {
mnt->mnt.mnt_flags |= MNT_WRITE_HOLD;
smp_mb();
if (mnt_get_writers(mnt) > 0) {
err = -EBUSY;
break;
}
}
}
if (!err && atomic_long_read(&sb->s_remove_count))
err = -EBUSY;
if (!err) {
sb->s_readonly_remount = 1;
smp_wmb();
}
list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) {
if (mnt->mnt.mnt_flags & MNT_WRITE_HOLD)
mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD;
}
br_write_unlock(&vfsmount_lock);
return err;
}
static void free_vfsmnt(struct mount *mnt)
{
kfree(mnt->mnt_devname);
mnt_free_id(mnt);
#ifdef CONFIG_SMP
free_percpu(mnt->mnt_pcp);
#endif
kmem_cache_free(mnt_cache, mnt);
}
/*
* find the first or last mount at @dentry on vfsmount @mnt depending on
* @dir. If @dir is set return the first mount else return the last mount.
* vfsmount_lock must be held for read or write.
*/
struct mount *__lookup_mnt(struct vfsmount *mnt, struct dentry *dentry,
int dir)
{
struct list_head *head = mount_hashtable + hash(mnt, dentry);
struct list_head *tmp = head;
struct mount *p, *found = NULL;
for (;;) {
tmp = dir ? tmp->next : tmp->prev;
p = NULL;
if (tmp == head)
break;
p = list_entry(tmp, struct mount, mnt_hash);
if (&p->mnt_parent->mnt == mnt && p->mnt_mountpoint == dentry) {
found = p;
break;
}
}
return found;
}
/*
* lookup_mnt - Return the first child mount mounted at path
*
* "First" means first mounted chronologically. If you create the
* following mounts:
*
* mount /dev/sda1 /mnt
* mount /dev/sda2 /mnt
* mount /dev/sda3 /mnt
*
* Then lookup_mnt() on the base /mnt dentry in the root mount will
* return successively the root dentry and vfsmount of /dev/sda1, then
* /dev/sda2, then /dev/sda3, then NULL.
*
* lookup_mnt takes a reference to the found vfsmount.
*/
struct vfsmount *lookup_mnt(struct path *path)
{
struct mount *child_mnt;
br_read_lock(&vfsmount_lock);
child_mnt = __lookup_mnt(path->mnt, path->dentry, 1);
if (child_mnt) {
mnt_add_count(child_mnt, 1);
br_read_unlock(&vfsmount_lock);
return &child_mnt->mnt;
} else {
br_read_unlock(&vfsmount_lock);
return NULL;
}
}
static struct mountpoint *new_mountpoint(struct dentry *dentry)
{
struct list_head *chain = mountpoint_hashtable + hash(NULL, dentry);
struct mountpoint *mp;
list_for_each_entry(mp, chain, m_hash) {
if (mp->m_dentry == dentry) {
/* might be worth a WARN_ON() */
if (d_unlinked(dentry))
return ERR_PTR(-ENOENT);
mp->m_count++;
return mp;
}
}
mp = kmalloc(sizeof(struct mountpoint), GFP_KERNEL);
if (!mp)
return ERR_PTR(-ENOMEM);
spin_lock(&dentry->d_lock);
if (d_unlinked(dentry)) {
spin_unlock(&dentry->d_lock);
kfree(mp);
return ERR_PTR(-ENOENT);
}
dentry->d_flags |= DCACHE_MOUNTED;
spin_unlock(&dentry->d_lock);
mp->m_dentry = dentry;
mp->m_count = 1;
list_add(&mp->m_hash, chain);
return mp;
}
static void put_mountpoint(struct mountpoint *mp)
{
if (!--mp->m_count) {
struct dentry *dentry = mp->m_dentry;
spin_lock(&dentry->d_lock);
dentry->d_flags &= ~DCACHE_MOUNTED;
spin_unlock(&dentry->d_lock);
list_del(&mp->m_hash);
kfree(mp);
}
}
static inline int check_mnt(struct mount *mnt)
{
return mnt->mnt_ns == current->nsproxy->mnt_ns;
}
/*
* vfsmount lock must be held for write
*/
static void touch_mnt_namespace(struct mnt_namespace *ns)
{
if (ns) {
ns->event = ++event;
wake_up_interruptible(&ns->poll);
}
}
/*
* vfsmount lock must be held for write
*/
static void __touch_mnt_namespace(struct mnt_namespace *ns)
{
if (ns && ns->event != event) {
ns->event = event;
wake_up_interruptible(&ns->poll);
}
}
/*
* vfsmount lock must be held for write
*/
static void detach_mnt(struct mount *mnt, struct path *old_path)
{
old_path->dentry = mnt->mnt_mountpoint;
old_path->mnt = &mnt->mnt_parent->mnt;
mnt->mnt_parent = mnt;
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
list_del_init(&mnt->mnt_child);
list_del_init(&mnt->mnt_hash);
put_mountpoint(mnt->mnt_mp);
mnt->mnt_mp = NULL;
}
/*
* vfsmount lock must be held for write
*/
void mnt_set_mountpoint(struct mount *mnt,
struct mountpoint *mp,
struct mount *child_mnt)
{
mp->m_count++;
mnt_add_count(mnt, 1); /* essentially, that's mntget */
child_mnt->mnt_mountpoint = dget(mp->m_dentry);
child_mnt->mnt_parent = mnt;
child_mnt->mnt_mp = mp;
}
/*
* vfsmount lock must be held for write
*/
static void attach_mnt(struct mount *mnt,
struct mount *parent,
struct mountpoint *mp)
{
mnt_set_mountpoint(parent, mp, mnt);
list_add_tail(&mnt->mnt_hash, mount_hashtable +
hash(&parent->mnt, mp->m_dentry));
list_add_tail(&mnt->mnt_child, &parent->mnt_mounts);
}
/*
* vfsmount lock must be held for write
*/
static void commit_tree(struct mount *mnt)
{
struct mount *parent = mnt->mnt_parent;
struct mount *m;
LIST_HEAD(head);
struct mnt_namespace *n = parent->mnt_ns;
BUG_ON(parent == mnt);
list_add_tail(&head, &mnt->mnt_list);
list_for_each_entry(m, &head, mnt_list)
m->mnt_ns = n;
list_splice(&head, n->list.prev);
list_add_tail(&mnt->mnt_hash, mount_hashtable +
hash(&parent->mnt, mnt->mnt_mountpoint));
list_add_tail(&mnt->mnt_child, &parent->mnt_mounts);
touch_mnt_namespace(n);
}
static struct mount *next_mnt(struct mount *p, struct mount *root)
{
struct list_head *next = p->mnt_mounts.next;
if (next == &p->mnt_mounts) {
while (1) {
if (p == root)
return NULL;
next = p->mnt_child.next;
if (next != &p->mnt_parent->mnt_mounts)
break;
p = p->mnt_parent;
}
}
return list_entry(next, struct mount, mnt_child);
}
static struct mount *skip_mnt_tree(struct mount *p)
{
struct list_head *prev = p->mnt_mounts.prev;
while (prev != &p->mnt_mounts) {
p = list_entry(prev, struct mount, mnt_child);
prev = p->mnt_mounts.prev;
}
return p;
}
struct vfsmount *
vfs_kern_mount(struct file_system_type *type, int flags, const char *name, void *data)
{
struct mount *mnt;
struct dentry *root;
if (!type)
return ERR_PTR(-ENODEV);
mnt = alloc_vfsmnt(name);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flags & MS_KERNMOUNT)
mnt->mnt.mnt_flags = MNT_INTERNAL;
root = mount_fs(type, flags, name, data);
if (IS_ERR(root)) {
free_vfsmnt(mnt);
return ERR_CAST(root);
}
mnt->mnt.mnt_root = root;
mnt->mnt.mnt_sb = root->d_sb;
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
br_write_lock(&vfsmount_lock);
list_add_tail(&mnt->mnt_instance, &root->d_sb->s_mounts);
br_write_unlock(&vfsmount_lock);
return &mnt->mnt;
}
EXPORT_SYMBOL_GPL(vfs_kern_mount);
static struct mount *clone_mnt(struct mount *old, struct dentry *root,
int flag)
{
struct super_block *sb = old->mnt.mnt_sb;
struct mount *mnt;
int err;
mnt = alloc_vfsmnt(old->mnt_devname);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
mnt->mnt_group_id = 0; /* not a peer of original */
else
mnt->mnt_group_id = old->mnt_group_id;
if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
err = mnt_alloc_group_id(mnt);
if (err)
goto out_free;
}
mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~MNT_WRITE_HOLD;
/* Don't allow unprivileged users to change mount flags */
if ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY))
mnt->mnt.mnt_flags |= MNT_LOCK_READONLY;
atomic_inc(&sb->s_active);
mnt->mnt.mnt_sb = sb;
mnt->mnt.mnt_root = dget(root);
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
br_write_lock(&vfsmount_lock);
list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
br_write_unlock(&vfsmount_lock);
if ((flag & CL_SLAVE) ||
((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
list_add(&mnt->mnt_slave, &old->mnt_slave_list);
mnt->mnt_master = old;
CLEAR_MNT_SHARED(mnt);
} else if (!(flag & CL_PRIVATE)) {
if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
list_add(&mnt->mnt_share, &old->mnt_share);
if (IS_MNT_SLAVE(old))
list_add(&mnt->mnt_slave, &old->mnt_slave);
mnt->mnt_master = old->mnt_master;
}
if (flag & CL_MAKE_SHARED)
set_mnt_shared(mnt);
/* stick the duplicate mount on the same expiry list
* as the original if that was on one */
if (flag & CL_EXPIRE) {
if (!list_empty(&old->mnt_expire))
list_add(&mnt->mnt_expire, &old->mnt_expire);
}
return mnt;
out_free:
free_vfsmnt(mnt);
return ERR_PTR(err);
}
static inline void mntfree(struct mount *mnt)
{
struct vfsmount *m = &mnt->mnt;
struct super_block *sb = m->mnt_sb;
/*
* This probably indicates that somebody messed
* up a mnt_want/drop_write() pair. If this
* happens, the filesystem was probably unable
* to make r/w->r/o transitions.
*/
/*
* The locking used to deal with mnt_count decrement provides barriers,
* so mnt_get_writers() below is safe.
*/
WARN_ON(mnt_get_writers(mnt));
fsnotify_vfsmount_delete(m);
dput(m->mnt_root);
free_vfsmnt(mnt);
deactivate_super(sb);
}
static void mntput_no_expire(struct mount *mnt)
{
put_again:
#ifdef CONFIG_SMP
br_read_lock(&vfsmount_lock);
if (likely(mnt->mnt_ns)) {
/* shouldn't be the last one */
mnt_add_count(mnt, -1);
br_read_unlock(&vfsmount_lock);
return;
}
br_read_unlock(&vfsmount_lock);
br_write_lock(&vfsmount_lock);
mnt_add_count(mnt, -1);
if (mnt_get_count(mnt)) {
br_write_unlock(&vfsmount_lock);
return;
}
#else
mnt_add_count(mnt, -1);
if (likely(mnt_get_count(mnt)))
return;
br_write_lock(&vfsmount_lock);
#endif
if (unlikely(mnt->mnt_pinned)) {
mnt_add_count(mnt, mnt->mnt_pinned + 1);
mnt->mnt_pinned = 0;
br_write_unlock(&vfsmount_lock);
acct_auto_close_mnt(&mnt->mnt);
goto put_again;
}
list_del(&mnt->mnt_instance);
br_write_unlock(&vfsmount_lock);
mntfree(mnt);
}
void mntput(struct vfsmount *mnt)
{
if (mnt) {
struct mount *m = real_mount(mnt);
/* avoid cacheline pingpong, hope gcc doesn't get "smart" */
if (unlikely(m->mnt_expiry_mark))
m->mnt_expiry_mark = 0;
mntput_no_expire(m);
}
}
EXPORT_SYMBOL(mntput);
struct vfsmount *mntget(struct vfsmount *mnt)
{
if (mnt)
mnt_add_count(real_mount(mnt), 1);
return mnt;
}
EXPORT_SYMBOL(mntget);
void mnt_pin(struct vfsmount *mnt)
{
br_write_lock(&vfsmount_lock);
real_mount(mnt)->mnt_pinned++;
br_write_unlock(&vfsmount_lock);
}
EXPORT_SYMBOL(mnt_pin);
void mnt_unpin(struct vfsmount *m)
{
struct mount *mnt = real_mount(m);
br_write_lock(&vfsmount_lock);
if (mnt->mnt_pinned) {
mnt_add_count(mnt, 1);
mnt->mnt_pinned--;
}
br_write_unlock(&vfsmount_lock);
}
EXPORT_SYMBOL(mnt_unpin);
static inline void mangle(struct seq_file *m, const char *s)
{
seq_escape(m, s, " \t\n\\");
}
/*
* Simple .show_options callback for filesystems which don't want to
* implement more complex mount option showing.
*
* See also save_mount_options().
*/
int generic_show_options(struct seq_file *m, struct dentry *root)
{
const char *options;
rcu_read_lock();
options = rcu_dereference(root->d_sb->s_options);
if (options != NULL && options[0]) {
seq_putc(m, ',');
mangle(m, options);
}
rcu_read_unlock();
return 0;
}
EXPORT_SYMBOL(generic_show_options);
/*
* If filesystem uses generic_show_options(), this function should be
* called from the fill_super() callback.
*
* The .remount_fs callback usually needs to be handled in a special
* way, to make sure, that previous options are not overwritten if the
* remount fails.
*
* Also note, that if the filesystem's .remount_fs function doesn't
* reset all options to their default value, but changes only newly
* given options, then the displayed options will not reflect reality
* any more.
*/
void save_mount_options(struct super_block *sb, char *options)
{
BUG_ON(sb->s_options);
rcu_assign_pointer(sb->s_options, kstrdup(options, GFP_KERNEL));
}
EXPORT_SYMBOL(save_mount_options);
void replace_mount_options(struct super_block *sb, char *options)
{
char *old = sb->s_options;
rcu_assign_pointer(sb->s_options, options);
if (old) {
synchronize_rcu();
kfree(old);
}
}
EXPORT_SYMBOL(replace_mount_options);
#ifdef CONFIG_PROC_FS
/* iterator; we want it to have access to namespace_sem, thus here... */
static void *m_start(struct seq_file *m, loff_t *pos)
{
struct proc_mounts *p = proc_mounts(m);
down_read(&namespace_sem);
return seq_list_start(&p->ns->list, *pos);
}
static void *m_next(struct seq_file *m, void *v, loff_t *pos)
{
struct proc_mounts *p = proc_mounts(m);
return seq_list_next(v, &p->ns->list, pos);
}
static void m_stop(struct seq_file *m, void *v)
{
up_read(&namespace_sem);
}
static int m_show(struct seq_file *m, void *v)
{
struct proc_mounts *p = proc_mounts(m);
struct mount *r = list_entry(v, struct mount, mnt_list);
return p->show(m, &r->mnt);
}
const struct seq_operations mounts_op = {
.start = m_start,
.next = m_next,
.stop = m_stop,
.show = m_show,
};
#endif /* CONFIG_PROC_FS */
/**
* may_umount_tree - check if a mount tree is busy
* @mnt: root of mount tree
*
* This is called to check if a tree of mounts has any
* open files, pwds, chroots or sub mounts that are
* busy.
*/
int may_umount_tree(struct vfsmount *m)
{
struct mount *mnt = real_mount(m);
int actual_refs = 0;
int minimum_refs = 0;
struct mount *p;
BUG_ON(!m);
/* write lock needed for mnt_get_count */
br_write_lock(&vfsmount_lock);
for (p = mnt; p; p = next_mnt(p, mnt)) {
actual_refs += mnt_get_count(p);
minimum_refs += 2;
}
br_write_unlock(&vfsmount_lock);
if (actual_refs > minimum_refs)
return 0;
return 1;
}
EXPORT_SYMBOL(may_umount_tree);
/**
* may_umount - check if a mount point is busy
* @mnt: root of mount
*
* This is called to check if a mount point has any
* open files, pwds, chroots or sub mounts. If the
* mount has sub mounts this will return busy
* regardless of whether the sub mounts are busy.
*
* Doesn't take quota and stuff into account. IOW, in some cases it will
* give false negatives. The main reason why it's here is that we need
* a non-destructive way to look for easily umountable filesystems.
*/
int may_umount(struct vfsmount *mnt)
{
int ret = 1;
down_read(&namespace_sem);
br_write_lock(&vfsmount_lock);
if (propagate_mount_busy(real_mount(mnt), 2))
ret = 0;
br_write_unlock(&vfsmount_lock);
up_read(&namespace_sem);
return ret;
}
EXPORT_SYMBOL(may_umount);
static LIST_HEAD(unmounted); /* protected by namespace_sem */
static void namespace_unlock(void)
{
struct mount *mnt;
LIST_HEAD(head);
if (likely(list_empty(&unmounted))) {
up_write(&namespace_sem);
return;
}
list_splice_init(&unmounted, &head);
up_write(&namespace_sem);
while (!list_empty(&head)) {
mnt = list_first_entry(&head, struct mount, mnt_hash);
list_del_init(&mnt->mnt_hash);
if (mnt_has_parent(mnt)) {
struct dentry *dentry;
struct mount *m;
br_write_lock(&vfsmount_lock);
dentry = mnt->mnt_mountpoint;
m = mnt->mnt_parent;
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
m->mnt_ghosts--;
br_write_unlock(&vfsmount_lock);
dput(dentry);
mntput(&m->mnt);
}
mntput(&mnt->mnt);
}
}
static inline void namespace_lock(void)
{
down_write(&namespace_sem);
}
/*
* vfsmount lock must be held for write
* namespace_sem must be held for write
*/
void umount_tree(struct mount *mnt, int propagate)
{
LIST_HEAD(tmp_list);
struct mount *p;
for (p = mnt; p; p = next_mnt(p, mnt))
list_move(&p->mnt_hash, &tmp_list);
if (propagate)
propagate_umount(&tmp_list);
list_for_each_entry(p, &tmp_list, mnt_hash) {
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
list_del_init(&p->mnt_child);
if (mnt_has_parent(p)) {
p->mnt_parent->mnt_ghosts++;
put_mountpoint(p->mnt_mp);
p->mnt_mp = NULL;
}
change_mnt_propagation(p, MS_PRIVATE);
}
list_splice(&tmp_list, &unmounted);
}
static void shrink_submounts(struct mount *mnt);
static int do_umount(struct mount *mnt, int flags)
{
struct super_block *sb = mnt->mnt.mnt_sb;
int retval;
retval = security_sb_umount(&mnt->mnt, flags);
if (retval)
return retval;
/*
* Allow userspace to request a mountpoint be expired rather than
* unmounting unconditionally. Unmount only happens if:
* (1) the mark is already set (the mark is cleared by mntput())
* (2) the usage count == 1 [parent vfsmount] + 1 [sys_umount]
*/
if (flags & MNT_EXPIRE) {
if (&mnt->mnt == current->fs->root.mnt ||
flags & (MNT_FORCE | MNT_DETACH))
return -EINVAL;
/*
* probably don't strictly need the lock here if we examined
* all race cases, but it's a slowpath.
*/
br_write_lock(&vfsmount_lock);
if (mnt_get_count(mnt) != 2) {
br_write_unlock(&vfsmount_lock);
return -EBUSY;
}
br_write_unlock(&vfsmount_lock);
if (!xchg(&mnt->mnt_expiry_mark, 1))
return -EAGAIN;
}
/*
* If we may have to abort operations to get out of this
* mount, and they will themselves hold resources we must
* allow the fs to do things. In the Unix tradition of
* 'Gee thats tricky lets do it in userspace' the umount_begin
* might fail to complete on the first run through as other tasks
* must return, and the like. Thats for the mount program to worry
* about for the moment.
*/
if (flags & MNT_FORCE && sb->s_op->umount_begin) {
sb->s_op->umount_begin(sb);
}
/*
* No sense to grab the lock for this test, but test itself looks
* somewhat bogus. Suggestions for better replacement?
* Ho-hum... In principle, we might treat that as umount + switch
* to rootfs. GC would eventually take care of the old vfsmount.
* Actually it makes sense, especially if rootfs would contain a
* /reboot - static binary that would close all descriptors and
* call reboot(9). Then init(8) could umount root and exec /reboot.
*/
if (&mnt->mnt == current->fs->root.mnt && !(flags & MNT_DETACH)) {
/*
* Special case for "unmounting" root ...
* we just try to remount it readonly.
*/
down_write(&sb->s_umount);
if (!(sb->s_flags & MS_RDONLY))
retval = do_remount_sb(sb, MS_RDONLY, NULL, 0);
up_write(&sb->s_umount);
return retval;
}
namespace_lock();
br_write_lock(&vfsmount_lock);
event++;
if (!(flags & MNT_DETACH))
shrink_submounts(mnt);
retval = -EBUSY;
if (flags & MNT_DETACH || !propagate_mount_busy(mnt, 2)) {
if (!list_empty(&mnt->mnt_list))
umount_tree(mnt, 1);
retval = 0;
}
br_write_unlock(&vfsmount_lock);
namespace_unlock();
return retval;
}
/*
* Is the caller allowed to modify his namespace?
*/
static inline bool may_mount(void)
{
return ns_capable(current->nsproxy->mnt_ns->user_ns, CAP_SYS_ADMIN);
}
/*
* Now umount can handle mount points as well as block devices.
* This is important for filesystems which use unnamed block devices.
*
* We now support a flag for forced unmount like the other 'big iron'
* unixes. Our API is identical to OSF/1 to avoid making a mess of AMD
*/
SYSCALL_DEFINE2(umount, char __user *, name, int, flags)
{
struct path path;
struct mount *mnt;
int retval;
int lookup_flags = 0;
if (flags & ~(MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW))
return -EINVAL;
if (!may_mount())
return -EPERM;
if (!(flags & UMOUNT_NOFOLLOW))
lookup_flags |= LOOKUP_FOLLOW;
retval = user_path_at(AT_FDCWD, name, lookup_flags, &path);
if (retval)
goto out;
mnt = real_mount(path.mnt);
retval = -EINVAL;
if (path.dentry != path.mnt->mnt_root)
goto dput_and_out;
if (!check_mnt(mnt))
goto dput_and_out;
retval = do_umount(mnt, flags);
dput_and_out:
/* we mustn't call path_put() as that would clear mnt_expiry_mark */
dput(path.dentry);
mntput_no_expire(mnt);
out:
return retval;
}
#ifdef __ARCH_WANT_SYS_OLDUMOUNT
/*
* The 2.0 compatible umount. No flags.
*/
SYSCALL_DEFINE1(oldumount, char __user *, name)
{
return sys_umount(name, 0);
}
#endif
static bool mnt_ns_loop(struct path *path)
{
/* Could bind mounting the mount namespace inode cause a
* mount namespace loop?
*/
struct inode *inode = path->dentry->d_inode;
struct proc_ns *ei;
struct mnt_namespace *mnt_ns;
if (!proc_ns_inode(inode))
return false;
ei = get_proc_ns(inode);
if (ei->ns_ops != &mntns_operations)
return false;
mnt_ns = ei->ns;
return current->nsproxy->mnt_ns->seq >= mnt_ns->seq;
}
struct mount *copy_tree(struct mount *mnt, struct dentry *dentry,
int flag)
{
struct mount *res, *p, *q, *r, *parent;
if (!(flag & CL_COPY_ALL) && IS_MNT_UNBINDABLE(mnt))
return ERR_PTR(-EINVAL);
res = q = clone_mnt(mnt, dentry, flag);
if (IS_ERR(q))
return q;
q->mnt_mountpoint = mnt->mnt_mountpoint;
p = mnt;
list_for_each_entry(r, &mnt->mnt_mounts, mnt_child) {
struct mount *s;
if (!is_subdir(r->mnt_mountpoint, dentry))
continue;
for (s = r; s; s = next_mnt(s, r)) {
if (!(flag & CL_COPY_ALL) && IS_MNT_UNBINDABLE(s)) {
s = skip_mnt_tree(s);
continue;
}
while (p != s->mnt_parent) {
p = p->mnt_parent;
q = q->mnt_parent;
}
p = s;
parent = q;
q = clone_mnt(p, p->mnt.mnt_root, flag);
if (IS_ERR(q))
goto out;
br_write_lock(&vfsmount_lock);
list_add_tail(&q->mnt_list, &res->mnt_list);
attach_mnt(q, parent, p->mnt_mp);
br_write_unlock(&vfsmount_lock);
}
}
return res;
out:
if (res) {
br_write_lock(&vfsmount_lock);
umount_tree(res, 0);
br_write_unlock(&vfsmount_lock);
}
return q;
}
/* Caller should check returned pointer for errors */
struct vfsmount *collect_mounts(struct path *path)
{
struct mount *tree;
namespace_lock();
tree = copy_tree(real_mount(path->mnt), path->dentry,
CL_COPY_ALL | CL_PRIVATE);
namespace_unlock();
if (IS_ERR(tree))
return ERR_CAST(tree);
return &tree->mnt;
}
void drop_collected_mounts(struct vfsmount *mnt)
{
namespace_lock();
br_write_lock(&vfsmount_lock);
umount_tree(real_mount(mnt), 0);
br_write_unlock(&vfsmount_lock);
namespace_unlock();
}
int iterate_mounts(int (*f)(struct vfsmount *, void *), void *arg,
struct vfsmount *root)
{
struct mount *mnt;
int res = f(root, arg);
if (res)
return res;
list_for_each_entry(mnt, &real_mount(root)->mnt_list, mnt_list) {
res = f(&mnt->mnt, arg);
if (res)
return res;
}
return 0;
}
static void cleanup_group_ids(struct mount *mnt, struct mount *end)
{
struct mount *p;
for (p = mnt; p != end; p = next_mnt(p, mnt)) {
if (p->mnt_group_id && !IS_MNT_SHARED(p))
mnt_release_group_id(p);
}
}
static int invent_group_ids(struct mount *mnt, bool recurse)
{
struct mount *p;
for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) {
if (!p->mnt_group_id && !IS_MNT_SHARED(p)) {
int err = mnt_alloc_group_id(p);
if (err) {
cleanup_group_ids(mnt, p);
return err;
}
}
}
return 0;
}
/*
* @source_mnt : mount tree to be attached
* @nd : place the mount tree @source_mnt is attached
* @parent_nd : if non-null, detach the source_mnt from its parent and
* store the parent mount and mountpoint dentry.
* (done when source_mnt is moved)
*
* NOTE: in the table below explains the semantics when a source mount
* of a given type is attached to a destination mount of a given type.
* ---------------------------------------------------------------------------
* | BIND MOUNT OPERATION |
* |**************************************************************************
* | source-->| shared | private | slave | unbindable |
* | dest | | | | |
* | | | | | | |
* | v | | | | |
* |**************************************************************************
* | shared | shared (++) | shared (+) | shared(+++)| invalid |
* | | | | | |
* |non-shared| shared (+) | private | slave (*) | invalid |
* ***************************************************************************
* A bind operation clones the source mount and mounts the clone on the
* destination mount.
*
* (++) the cloned mount is propagated to all the mounts in the propagation
* tree of the destination mount and the cloned mount is added to
* the peer group of the source mount.
* (+) the cloned mount is created under the destination mount and is marked
* as shared. The cloned mount is added to the peer group of the source
* mount.
* (+++) the mount is propagated to all the mounts in the propagation tree
* of the destination mount and the cloned mount is made slave
* of the same master as that of the source mount. The cloned mount
* is marked as 'shared and slave'.
* (*) the cloned mount is made a slave of the same master as that of the
* source mount.
*
* ---------------------------------------------------------------------------
* | MOVE MOUNT OPERATION |
* |**************************************************************************
* | source-->| shared | private | slave | unbindable |
* | dest | | | | |
* | | | | | | |
* | v | | | | |
* |**************************************************************************
* | shared | shared (+) | shared (+) | shared(+++) | invalid |
* | | | | | |
* |non-shared| shared (+*) | private | slave (*) | unbindable |
* ***************************************************************************
*
* (+) the mount is moved to the destination. And is then propagated to
* all the mounts in the propagation tree of the destination mount.
* (+*) the mount is moved to the destination.
* (+++) the mount is moved to the destination and is then propagated to
* all the mounts belonging to the destination mount's propagation tree.
* the mount is marked as 'shared and slave'.
* (*) the mount continues to be a slave at the new location.
*
* if the source mount is a tree, the operations explained above is
* applied to each mount in the tree.
* Must be called without spinlocks held, since this function can sleep
* in allocations.
*/
static int attach_recursive_mnt(struct mount *source_mnt,
struct mount *dest_mnt,
struct mountpoint *dest_mp,
struct path *parent_path)
{
LIST_HEAD(tree_list);
struct mount *child, *p;
int err;
if (IS_MNT_SHARED(dest_mnt)) {
err = invent_group_ids(source_mnt, true);
if (err)
goto out;
}
err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list);
if (err)
goto out_cleanup_ids;
br_write_lock(&vfsmount_lock);
if (IS_MNT_SHARED(dest_mnt)) {
for (p = source_mnt; p; p = next_mnt(p, source_mnt))
set_mnt_shared(p);
}
if (parent_path) {
detach_mnt(source_mnt, parent_path);
attach_mnt(source_mnt, dest_mnt, dest_mp);
touch_mnt_namespace(source_mnt->mnt_ns);
} else {
mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt);
commit_tree(source_mnt);
}
list_for_each_entry_safe(child, p, &tree_list, mnt_hash) {
list_del_init(&child->mnt_hash);
commit_tree(child);
}
br_write_unlock(&vfsmount_lock);
return 0;
out_cleanup_ids:
if (IS_MNT_SHARED(dest_mnt))
cleanup_group_ids(source_mnt, NULL);
out:
return err;
}
static struct mountpoint *lock_mount(struct path *path)
{
struct vfsmount *mnt;
struct dentry *dentry = path->dentry;
retry:
mutex_lock(&dentry->d_inode->i_mutex);
if (unlikely(cant_mount(dentry))) {
mutex_unlock(&dentry->d_inode->i_mutex);
return ERR_PTR(-ENOENT);
}
namespace_lock();
mnt = lookup_mnt(path);
if (likely(!mnt)) {
struct mountpoint *mp = new_mountpoint(dentry);
if (IS_ERR(mp)) {
namespace_unlock();
mutex_unlock(&dentry->d_inode->i_mutex);
return mp;
}
return mp;
}
namespace_unlock();
mutex_unlock(&path->dentry->d_inode->i_mutex);
path_put(path);
path->mnt = mnt;
dentry = path->dentry = dget(mnt->mnt_root);
goto retry;
}
static void unlock_mount(struct mountpoint *where)
{
struct dentry *dentry = where->m_dentry;
put_mountpoint(where);
namespace_unlock();
mutex_unlock(&dentry->d_inode->i_mutex);
}
static int graft_tree(struct mount *mnt, struct mount *p, struct mountpoint *mp)
{
if (mnt->mnt.mnt_sb->s_flags & MS_NOUSER)
return -EINVAL;
if (S_ISDIR(mp->m_dentry->d_inode->i_mode) !=
S_ISDIR(mnt->mnt.mnt_root->d_inode->i_mode))
return -ENOTDIR;
return attach_recursive_mnt(mnt, p, mp, NULL);
}
/*
* Sanity check the flags to change_mnt_propagation.
*/
static int flags_to_propagation_type(int flags)
{
int type = flags & ~(MS_REC | MS_SILENT);
/* Fail if any non-propagation flags are set */
if (type & ~(MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
return 0;
/* Only one propagation flag should be set */
if (!is_power_of_2(type))
return 0;
return type;
}
/*
* recursively change the type of the mountpoint.
*/
static int do_change_type(struct path *path, int flag)
{
struct mount *m;
struct mount *mnt = real_mount(path->mnt);
int recurse = flag & MS_REC;
int type;
int err = 0;
if (path->dentry != path->mnt->mnt_root)
return -EINVAL;
type = flags_to_propagation_type(flag);
if (!type)
return -EINVAL;
namespace_lock();
if (type == MS_SHARED) {
err = invent_group_ids(mnt, recurse);
if (err)
goto out_unlock;
}
br_write_lock(&vfsmount_lock);
for (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL))
change_mnt_propagation(m, type);
br_write_unlock(&vfsmount_lock);
out_unlock:
namespace_unlock();
return err;
}
/*
* do loopback mount.
*/
static int do_loopback(struct path *path, const char *old_name,
int recurse)
{
struct path old_path;
struct mount *mnt = NULL, *old, *parent;
struct mountpoint *mp;
int err;
if (!old_name || !*old_name)
return -EINVAL;
err = kern_path(old_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path);
if (err)
return err;
err = -EINVAL;
if (mnt_ns_loop(&old_path))
goto out;
mp = lock_mount(path);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto out;
old = real_mount(old_path.mnt);
parent = real_mount(path->mnt);
err = -EINVAL;
if (IS_MNT_UNBINDABLE(old))
goto out2;
if (!check_mnt(parent) || !check_mnt(old))
goto out2;
if (recurse)
mnt = copy_tree(old, old_path.dentry, 0);
else
mnt = clone_mnt(old, old_path.dentry, 0);
if (IS_ERR(mnt)) {
err = PTR_ERR(mnt);
goto out2;
}
err = graft_tree(mnt, parent, mp);
if (err) {
br_write_lock(&vfsmount_lock);
umount_tree(mnt, 0);
br_write_unlock(&vfsmount_lock);
}
out2:
unlock_mount(mp);
out:
path_put(&old_path);
return err;
}
static int change_mount_flags(struct vfsmount *mnt, int ms_flags)
{
int error = 0;
int readonly_request = 0;
if (ms_flags & MS_RDONLY)
readonly_request = 1;
if (readonly_request == __mnt_is_readonly(mnt))
return 0;
if (mnt->mnt_flags & MNT_LOCK_READONLY)
return -EPERM;
if (readonly_request)
error = mnt_make_readonly(real_mount(mnt));
else
__mnt_unmake_readonly(real_mount(mnt));
return error;
}
/*
* change filesystem flags. dir should be a physical root of filesystem.
* If you've mounted a non-root directory somewhere and want to do remount
* on it - tough luck.
*/
static int do_remount(struct path *path, int flags, int mnt_flags,
void *data)
{
int err;
struct super_block *sb = path->mnt->mnt_sb;
struct mount *mnt = real_mount(path->mnt);
if (!check_mnt(mnt))
return -EINVAL;
if (path->dentry != path->mnt->mnt_root)
return -EINVAL;
err = security_sb_remount(sb, data);
if (err)
return err;
down_write(&sb->s_umount);
if (flags & MS_BIND)
err = change_mount_flags(path->mnt, flags);
else if (!capable(CAP_SYS_ADMIN))
err = -EPERM;
else
err = do_remount_sb(sb, flags, data, 0);
if (!err) {
br_write_lock(&vfsmount_lock);
mnt_flags |= mnt->mnt.mnt_flags & MNT_PROPAGATION_MASK;
mnt->mnt.mnt_flags = mnt_flags;
br_write_unlock(&vfsmount_lock);
}
up_write(&sb->s_umount);
if (!err) {
br_write_lock(&vfsmount_lock);
touch_mnt_namespace(mnt->mnt_ns);
br_write_unlock(&vfsmount_lock);
}
return err;
}
static inline int tree_contains_unbindable(struct mount *mnt)
{
struct mount *p;
for (p = mnt; p; p = next_mnt(p, mnt)) {
if (IS_MNT_UNBINDABLE(p))
return 1;
}
return 0;
}
static int do_move_mount(struct path *path, const char *old_name)
{
struct path old_path, parent_path;
struct mount *p;
struct mount *old;
struct mountpoint *mp;
int err;
if (!old_name || !*old_name)
return -EINVAL;
err = kern_path(old_name, LOOKUP_FOLLOW, &old_path);
if (err)
return err;
mp = lock_mount(path);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto out;
old = real_mount(old_path.mnt);
p = real_mount(path->mnt);
err = -EINVAL;
if (!check_mnt(p) || !check_mnt(old))
goto out1;
err = -EINVAL;
if (old_path.dentry != old_path.mnt->mnt_root)
goto out1;
if (!mnt_has_parent(old))
goto out1;
if (S_ISDIR(path->dentry->d_inode->i_mode) !=
S_ISDIR(old_path.dentry->d_inode->i_mode))
goto out1;
/*
* Don't move a mount residing in a shared parent.
*/
if (IS_MNT_SHARED(old->mnt_parent))
goto out1;
/*
* Don't move a mount tree containing unbindable mounts to a destination
* mount which is shared.
*/
if (IS_MNT_SHARED(p) && tree_contains_unbindable(old))
goto out1;
err = -ELOOP;
for (; mnt_has_parent(p); p = p->mnt_parent)
if (p == old)
goto out1;
err = attach_recursive_mnt(old, real_mount(path->mnt), mp, &parent_path);
if (err)
goto out1;
/* if the mount is moved, it should no longer be expire
* automatically */
list_del_init(&old->mnt_expire);
out1:
unlock_mount(mp);
out:
if (!err)
path_put(&parent_path);
path_put(&old_path);
return err;
}
static struct vfsmount *fs_set_subtype(struct vfsmount *mnt, const char *fstype)
{
int err;
const char *subtype = strchr(fstype, '.');
if (subtype) {
subtype++;
err = -EINVAL;
if (!subtype[0])
goto err;
} else
subtype = "";
mnt->mnt_sb->s_subtype = kstrdup(subtype, GFP_KERNEL);
err = -ENOMEM;
if (!mnt->mnt_sb->s_subtype)
goto err;
return mnt;
err:
mntput(mnt);
return ERR_PTR(err);
}
/*
* add a mount into a namespace's mount tree
*/
static int do_add_mount(struct mount *newmnt, struct path *path, int mnt_flags)
{
struct mountpoint *mp;
struct mount *parent;
int err;
mnt_flags &= ~(MNT_SHARED | MNT_WRITE_HOLD | MNT_INTERNAL);
mp = lock_mount(path);
if (IS_ERR(mp))
return PTR_ERR(mp);
parent = real_mount(path->mnt);
err = -EINVAL;
if (unlikely(!check_mnt(parent))) {
/* that's acceptable only for automounts done in private ns */
if (!(mnt_flags & MNT_SHRINKABLE))
goto unlock;
/* ... and for those we'd better have mountpoint still alive */
if (!parent->mnt_ns)
goto unlock;
}
/* Refuse the same filesystem on the same mount point */
err = -EBUSY;
if (path->mnt->mnt_sb == newmnt->mnt.mnt_sb &&
path->mnt->mnt_root == path->dentry)
goto unlock;
err = -EINVAL;
if (S_ISLNK(newmnt->mnt.mnt_root->d_inode->i_mode))
goto unlock;
newmnt->mnt.mnt_flags = mnt_flags;
err = graft_tree(newmnt, parent, mp);
unlock:
unlock_mount(mp);
return err;
}
/*
* create a new mount for userspace and request it to be added into the
* namespace's tree
*/
static int do_new_mount(struct path *path, const char *fstype, int flags,
int mnt_flags, const char *name, void *data)
{
struct file_system_type *type;
struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
struct vfsmount *mnt;
int err;
if (!fstype)
return -EINVAL;
type = get_fs_type(fstype);
if (!type)
return -ENODEV;
if (user_ns != &init_user_ns) {
if (!(type->fs_flags & FS_USERNS_MOUNT)) {
put_filesystem(type);
return -EPERM;
}
/* Only in special cases allow devices from mounts
* created outside the initial user namespace.
*/
if (!(type->fs_flags & FS_USERNS_DEV_MOUNT)) {
flags |= MS_NODEV;
mnt_flags |= MNT_NODEV;
}
}
mnt = vfs_kern_mount(type, flags, name, data);
if (!IS_ERR(mnt) && (type->fs_flags & FS_HAS_SUBTYPE) &&
!mnt->mnt_sb->s_subtype)
mnt = fs_set_subtype(mnt, fstype);
put_filesystem(type);
if (IS_ERR(mnt))
return PTR_ERR(mnt);
err = do_add_mount(real_mount(mnt), path, mnt_flags);
if (err)
mntput(mnt);
return err;
}
int finish_automount(struct vfsmount *m, struct path *path)
{
struct mount *mnt = real_mount(m);
int err;
/* The new mount record should have at least 2 refs to prevent it being
* expired before we get a chance to add it
*/
BUG_ON(mnt_get_count(mnt) < 2);
if (m->mnt_sb == path->mnt->mnt_sb &&
m->mnt_root == path->dentry) {
err = -ELOOP;
goto fail;
}
err = do_add_mount(mnt, path, path->mnt->mnt_flags | MNT_SHRINKABLE);
if (!err)
return 0;
fail:
/* remove m from any expiration list it may be on */
if (!list_empty(&mnt->mnt_expire)) {
namespace_lock();
br_write_lock(&vfsmount_lock);
list_del_init(&mnt->mnt_expire);
br_write_unlock(&vfsmount_lock);
namespace_unlock();
}
mntput(m);
mntput(m);
return err;
}
/**
* mnt_set_expiry - Put a mount on an expiration list
* @mnt: The mount to list.
* @expiry_list: The list to add the mount to.
*/
void mnt_set_expiry(struct vfsmount *mnt, struct list_head *expiry_list)
{
namespace_lock();
br_write_lock(&vfsmount_lock);
list_add_tail(&real_mount(mnt)->mnt_expire, expiry_list);
br_write_unlock(&vfsmount_lock);
namespace_unlock();
}
EXPORT_SYMBOL(mnt_set_expiry);
/*
* process a list of expirable mountpoints with the intent of discarding any
* mountpoints that aren't in use and haven't been touched since last we came
* here
*/
void mark_mounts_for_expiry(struct list_head *mounts)
{
struct mount *mnt, *next;
LIST_HEAD(graveyard);
if (list_empty(mounts))
return;
namespace_lock();
br_write_lock(&vfsmount_lock);
/* extract from the expiration list every vfsmount that matches the
* following criteria:
* - only referenced by its parent vfsmount
* - still marked for expiry (marked on the last call here; marks are
* cleared by mntput())
*/
list_for_each_entry_safe(mnt, next, mounts, mnt_expire) {
if (!xchg(&mnt->mnt_expiry_mark, 1) ||
propagate_mount_busy(mnt, 1))
continue;
list_move(&mnt->mnt_expire, &graveyard);
}
while (!list_empty(&graveyard)) {
mnt = list_first_entry(&graveyard, struct mount, mnt_expire);
touch_mnt_namespace(mnt->mnt_ns);
umount_tree(mnt, 1);
}
br_write_unlock(&vfsmount_lock);
namespace_unlock();
}
EXPORT_SYMBOL_GPL(mark_mounts_for_expiry);
/*
* Ripoff of 'select_parent()'
*
* search the list of submounts for a given mountpoint, and move any
* shrinkable submounts to the 'graveyard' list.
*/
static int select_submounts(struct mount *parent, struct list_head *graveyard)
{
struct mount *this_parent = parent;
struct list_head *next;
int found = 0;
repeat:
next = this_parent->mnt_mounts.next;
resume:
while (next != &this_parent->mnt_mounts) {
struct list_head *tmp = next;
struct mount *mnt = list_entry(tmp, struct mount, mnt_child);
next = tmp->next;
if (!(mnt->mnt.mnt_flags & MNT_SHRINKABLE))
continue;
/*
* Descend a level if the d_mounts list is non-empty.
*/
if (!list_empty(&mnt->mnt_mounts)) {
this_parent = mnt;
goto repeat;
}
if (!propagate_mount_busy(mnt, 1)) {
list_move_tail(&mnt->mnt_expire, graveyard);
found++;
}
}
/*
* All done at this level ... ascend and resume the search
*/
if (this_parent != parent) {
next = this_parent->mnt_child.next;
this_parent = this_parent->mnt_parent;
goto resume;
}
return found;
}
/*
* process a list of expirable mountpoints with the intent of discarding any
* submounts of a specific parent mountpoint
*
* vfsmount_lock must be held for write
*/
static void shrink_submounts(struct mount *mnt)
{
LIST_HEAD(graveyard);
struct mount *m;
/* extract submounts of 'mountpoint' from the expiration list */
while (select_submounts(mnt, &graveyard)) {
while (!list_empty(&graveyard)) {
m = list_first_entry(&graveyard, struct mount,
mnt_expire);
touch_mnt_namespace(m->mnt_ns);
umount_tree(m, 1);
}
}
}
/*
* Some copy_from_user() implementations do not return the exact number of
* bytes remaining to copy on a fault. But copy_mount_options() requires that.
* Note that this function differs from copy_from_user() in that it will oops
* on bad values of `to', rather than returning a short copy.
*/
static long exact_copy_from_user(void *to, const void __user * from,
unsigned long n)
{
char *t = to;
const char __user *f = from;
char c;
if (!access_ok(VERIFY_READ, from, n))
return n;
while (n) {
if (__get_user(c, f)) {
memset(t, 0, n);
break;
}
*t++ = c;
f++;
n--;
}
return n;
}
int copy_mount_options(const void __user * data, unsigned long *where)
{
int i;
unsigned long page;
unsigned long size;
*where = 0;
if (!data)
return 0;
if (!(page = __get_free_page(GFP_KERNEL)))
return -ENOMEM;
/* We only care that *some* data at the address the user
* gave us is valid. Just in case, we'll zero
* the remainder of the page.
*/
/* copy_from_user cannot cross TASK_SIZE ! */
size = TASK_SIZE - (unsigned long)data;
if (size > PAGE_SIZE)
size = PAGE_SIZE;
i = size - exact_copy_from_user((void *)page, data, size);
if (!i) {
free_page(page);
return -EFAULT;
}
if (i != PAGE_SIZE)
memset((char *)page + i, 0, PAGE_SIZE - i);
*where = page;
return 0;
}
int copy_mount_string(const void __user *data, char **where)
{
char *tmp;
if (!data) {
*where = NULL;
return 0;
}
tmp = strndup_user(data, PAGE_SIZE);
if (IS_ERR(tmp))
return PTR_ERR(tmp);
*where = tmp;
return 0;
}
/*
* Flags is a 32-bit value that allows up to 31 non-fs dependent flags to
* be given to the mount() call (ie: read-only, no-dev, no-suid etc).
*
* data is a (void *) that can point to any structure up to
* PAGE_SIZE-1 bytes, which can contain arbitrary fs-dependent
* information (or be NULL).
*
* Pre-0.97 versions of mount() didn't have a flags word.
* When the flags word was introduced its top half was required
* to have the magic value 0xC0ED, and this remained so until 2.4.0-test9.
* Therefore, if this magic number is present, it carries no information
* and must be discarded.
*/
long do_mount(const char *dev_name, const char *dir_name,
const char *type_page, unsigned long flags, void *data_page)
{
struct path path;
int retval = 0;
int mnt_flags = 0;
/* Discard magic */
if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
flags &= ~MS_MGC_MSK;
/* Basic sanity checks */
if (!dir_name || !*dir_name || !memchr(dir_name, 0, PAGE_SIZE))
return -EINVAL;
if (data_page)
((char *)data_page)[PAGE_SIZE - 1] = 0;
/* ... and get the mountpoint */
retval = kern_path(dir_name, LOOKUP_FOLLOW, &path);
if (retval)
return retval;
retval = security_sb_mount(dev_name, &path,
type_page, flags, data_page);
if (!retval && !may_mount())
retval = -EPERM;
if (retval)
goto dput_out;
/* Default to relatime unless overriden */
if (!(flags & MS_NOATIME))
mnt_flags |= MNT_RELATIME;
/* Separate the per-mountpoint flags */
if (flags & MS_NOSUID)
mnt_flags |= MNT_NOSUID;
if (flags & MS_NODEV)
mnt_flags |= MNT_NODEV;
if (flags & MS_NOEXEC)
mnt_flags |= MNT_NOEXEC;
if (flags & MS_NOATIME)
mnt_flags |= MNT_NOATIME;
if (flags & MS_NODIRATIME)
mnt_flags |= MNT_NODIRATIME;
if (flags & MS_STRICTATIME)
mnt_flags &= ~(MNT_RELATIME | MNT_NOATIME);
if (flags & MS_RDONLY)
mnt_flags |= MNT_READONLY;
flags &= ~(MS_NOSUID | MS_NOEXEC | MS_NODEV | MS_ACTIVE | MS_BORN |
MS_NOATIME | MS_NODIRATIME | MS_RELATIME| MS_KERNMOUNT |
MS_STRICTATIME);
if (flags & MS_REMOUNT)
retval = do_remount(&path, flags & ~MS_REMOUNT, mnt_flags,
data_page);
else if (flags & MS_BIND)
retval = do_loopback(&path, dev_name, flags & MS_REC);
else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
retval = do_change_type(&path, flags);
else if (flags & MS_MOVE)
retval = do_move_mount(&path, dev_name);
else
retval = do_new_mount(&path, type_page, flags, mnt_flags,
dev_name, data_page);
dput_out:
path_put(&path);
return retval;
}
static void free_mnt_ns(struct mnt_namespace *ns)
{
proc_free_inum(ns->proc_inum);
put_user_ns(ns->user_ns);
kfree(ns);
}
/*
* Assign a sequence number so we can detect when we attempt to bind
* mount a reference to an older mount namespace into the current
* mount namespace, preventing reference counting loops. A 64bit
* number incrementing at 10Ghz will take 12,427 years to wrap which
* is effectively never, so we can ignore the possibility.
*/
static atomic64_t mnt_ns_seq = ATOMIC64_INIT(1);
static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns)
{
struct mnt_namespace *new_ns;
int ret;
new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL);
if (!new_ns)
return ERR_PTR(-ENOMEM);
ret = proc_alloc_inum(&new_ns->proc_inum);
if (ret) {
kfree(new_ns);
return ERR_PTR(ret);
}
new_ns->seq = atomic64_add_return(1, &mnt_ns_seq);
atomic_set(&new_ns->count, 1);
new_ns->root = NULL;
INIT_LIST_HEAD(&new_ns->list);
init_waitqueue_head(&new_ns->poll);
new_ns->event = 0;
new_ns->user_ns = get_user_ns(user_ns);
return new_ns;
}
/*
* Allocate a new namespace structure and populate it with contents
* copied from the namespace of the passed in task structure.
*/
static struct mnt_namespace *dup_mnt_ns(struct mnt_namespace *mnt_ns,
struct user_namespace *user_ns, struct fs_struct *fs)
{
struct mnt_namespace *new_ns;
struct vfsmount *rootmnt = NULL, *pwdmnt = NULL;
struct mount *p, *q;
struct mount *old = mnt_ns->root;
struct mount *new;
int copy_flags;
new_ns = alloc_mnt_ns(user_ns);
if (IS_ERR(new_ns))
return new_ns;
namespace_lock();
/* First pass: copy the tree topology */
copy_flags = CL_COPY_ALL | CL_EXPIRE;
if (user_ns != mnt_ns->user_ns)
copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED;
new = copy_tree(old, old->mnt.mnt_root, copy_flags);
if (IS_ERR(new)) {
namespace_unlock();
free_mnt_ns(new_ns);
return ERR_CAST(new);
}
new_ns->root = new;
br_write_lock(&vfsmount_lock);
list_add_tail(&new_ns->list, &new->mnt_list);
br_write_unlock(&vfsmount_lock);
/*
* Second pass: switch the tsk->fs->* elements and mark new vfsmounts
* as belonging to new namespace. We have already acquired a private
* fs_struct, so tsk->fs->lock is not needed.
*/
p = old;
q = new;
while (p) {
q->mnt_ns = new_ns;
if (fs) {
if (&p->mnt == fs->root.mnt) {
fs->root.mnt = mntget(&q->mnt);
rootmnt = &p->mnt;
}
if (&p->mnt == fs->pwd.mnt) {
fs->pwd.mnt = mntget(&q->mnt);
pwdmnt = &p->mnt;
}
}
p = next_mnt(p, old);
q = next_mnt(q, new);
}
namespace_unlock();
if (rootmnt)
mntput(rootmnt);
if (pwdmnt)
mntput(pwdmnt);
return new_ns;
}
struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns,
struct user_namespace *user_ns, struct fs_struct *new_fs)
{
struct mnt_namespace *new_ns;
BUG_ON(!ns);
get_mnt_ns(ns);
if (!(flags & CLONE_NEWNS))
return ns;
new_ns = dup_mnt_ns(ns, user_ns, new_fs);
put_mnt_ns(ns);
return new_ns;
}
/**
* create_mnt_ns - creates a private namespace and adds a root filesystem
* @mnt: pointer to the new root filesystem mountpoint
*/
static struct mnt_namespace *create_mnt_ns(struct vfsmount *m)
{
struct mnt_namespace *new_ns = alloc_mnt_ns(&init_user_ns);
if (!IS_ERR(new_ns)) {
struct mount *mnt = real_mount(m);
mnt->mnt_ns = new_ns;
new_ns->root = mnt;
list_add(&mnt->mnt_list, &new_ns->list);
} else {
mntput(m);
}
return new_ns;
}
struct dentry *mount_subtree(struct vfsmount *mnt, const char *name)
{
struct mnt_namespace *ns;
struct super_block *s;
struct path path;
int err;
ns = create_mnt_ns(mnt);
if (IS_ERR(ns))
return ERR_CAST(ns);
err = vfs_path_lookup(mnt->mnt_root, mnt,
name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path);
put_mnt_ns(ns);
if (err)
return ERR_PTR(err);
/* trade a vfsmount reference for active sb one */
s = path.mnt->mnt_sb;
atomic_inc(&s->s_active);
mntput(path.mnt);
/* lock the sucker */
down_write(&s->s_umount);
/* ... and return the root of (sub)tree on it */
return path.dentry;
}
EXPORT_SYMBOL(mount_subtree);
SYSCALL_DEFINE5(mount, char __user *, dev_name, char __user *, dir_name,
char __user *, type, unsigned long, flags, void __user *, data)
{
int ret;
char *kernel_type = NULL;
struct filename *kernel_dir;
char *kernel_dev = NULL;
unsigned long data_page;
ret = copy_mount_string(type, &kernel_type);
if (ret < 0)
goto out_type;
kernel_dir = getname(dir_name);
if (IS_ERR(kernel_dir)) {
ret = PTR_ERR(kernel_dir);
goto out_dir;
}
ret = copy_mount_string(dev_name, &kernel_dev);
if (ret < 0)
goto out_dev;
ret = copy_mount_options(data, &data_page);
if (ret < 0)
goto out_data;
ret = do_mount(kernel_dev, kernel_dir->name, kernel_type, flags,
(void *) data_page);
free_page(data_page);
out_data:
kfree(kernel_dev);
out_dev:
putname(kernel_dir);
out_dir:
kfree(kernel_type);
out_type:
return ret;
}
/*
* Return true if path is reachable from root
*
* namespace_sem or vfsmount_lock is held
*/
bool is_path_reachable(struct mount *mnt, struct dentry *dentry,
const struct path *root)
{
while (&mnt->mnt != root->mnt && mnt_has_parent(mnt)) {
dentry = mnt->mnt_mountpoint;
mnt = mnt->mnt_parent;
}
return &mnt->mnt == root->mnt && is_subdir(dentry, root->dentry);
}
int path_is_under(struct path *path1, struct path *path2)
{
int res;
br_read_lock(&vfsmount_lock);
res = is_path_reachable(real_mount(path1->mnt), path1->dentry, path2);
br_read_unlock(&vfsmount_lock);
return res;
}
EXPORT_SYMBOL(path_is_under);
/*
* pivot_root Semantics:
* Moves the root file system of the current process to the directory put_old,
* makes new_root as the new root file system of the current process, and sets
* root/cwd of all processes which had them on the current root to new_root.
*
* Restrictions:
* The new_root and put_old must be directories, and must not be on the
* same file system as the current process root. The put_old must be
* underneath new_root, i.e. adding a non-zero number of /.. to the string
* pointed to by put_old must yield the same directory as new_root. No other
* file system may be mounted on put_old. After all, new_root is a mountpoint.
*
* Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
* See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
* in this situation.
*
* Notes:
* - we don't move root/cwd if they are not at the root (reason: if something
* cared enough to change them, it's probably wrong to force them elsewhere)
* - it's okay to pick a root that isn't the root of a file system, e.g.
* /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
* though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
* first.
*/
SYSCALL_DEFINE2(pivot_root, const char __user *, new_root,
const char __user *, put_old)
{
struct path new, old, parent_path, root_parent, root;
struct mount *new_mnt, *root_mnt, *old_mnt;
struct mountpoint *old_mp, *root_mp;
int error;
if (!may_mount())
return -EPERM;
error = user_path_dir(new_root, &new);
if (error)
goto out0;
error = user_path_dir(put_old, &old);
if (error)
goto out1;
error = security_sb_pivotroot(&old, &new);
if (error)
goto out2;
get_fs_root(current->fs, &root);
old_mp = lock_mount(&old);
error = PTR_ERR(old_mp);
if (IS_ERR(old_mp))
goto out3;
error = -EINVAL;
new_mnt = real_mount(new.mnt);
root_mnt = real_mount(root.mnt);
old_mnt = real_mount(old.mnt);
if (IS_MNT_SHARED(old_mnt) ||
IS_MNT_SHARED(new_mnt->mnt_parent) ||
IS_MNT_SHARED(root_mnt->mnt_parent))
goto out4;
if (!check_mnt(root_mnt) || !check_mnt(new_mnt))
goto out4;
error = -ENOENT;
if (d_unlinked(new.dentry))
goto out4;
error = -EBUSY;
if (new_mnt == root_mnt || old_mnt == root_mnt)
goto out4; /* loop, on the same file system */
error = -EINVAL;
if (root.mnt->mnt_root != root.dentry)
goto out4; /* not a mountpoint */
if (!mnt_has_parent(root_mnt))
goto out4; /* not attached */
root_mp = root_mnt->mnt_mp;
if (new.mnt->mnt_root != new.dentry)
goto out4; /* not a mountpoint */
if (!mnt_has_parent(new_mnt))
goto out4; /* not attached */
/* make sure we can reach put_old from new_root */
if (!is_path_reachable(old_mnt, old.dentry, &new))
goto out4;
root_mp->m_count++; /* pin it so it won't go away */
br_write_lock(&vfsmount_lock);
detach_mnt(new_mnt, &parent_path);
detach_mnt(root_mnt, &root_parent);
/* mount old root on put_old */
attach_mnt(root_mnt, old_mnt, old_mp);
/* mount new_root on / */
attach_mnt(new_mnt, real_mount(root_parent.mnt), root_mp);
touch_mnt_namespace(current->nsproxy->mnt_ns);
br_write_unlock(&vfsmount_lock);
chroot_fs_refs(&root, &new);
put_mountpoint(root_mp);
error = 0;
out4:
unlock_mount(old_mp);
if (!error) {
path_put(&root_parent);
path_put(&parent_path);
}
out3:
path_put(&root);
out2:
path_put(&old);
out1:
path_put(&new);
out0:
return error;
}
static void __init init_mount_tree(void)
{
struct vfsmount *mnt;
struct mnt_namespace *ns;
struct path root;
struct file_system_type *type;
type = get_fs_type("rootfs");
if (!type)
panic("Can't find rootfs type");
mnt = vfs_kern_mount(type, 0, "rootfs", NULL);
put_filesystem(type);
if (IS_ERR(mnt))
panic("Can't create rootfs");
ns = create_mnt_ns(mnt);
if (IS_ERR(ns))
panic("Can't allocate initial namespace");
init_task.nsproxy->mnt_ns = ns;
get_mnt_ns(ns);
root.mnt = mnt;
root.dentry = mnt->mnt_root;
set_fs_pwd(current->fs, &root);
set_fs_root(current->fs, &root);
}
void __init mnt_init(void)
{
unsigned u;
int err;
init_rwsem(&namespace_sem);
mnt_cache = kmem_cache_create("mnt_cache", sizeof(struct mount),
0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
mount_hashtable = (struct list_head *)__get_free_page(GFP_ATOMIC);
mountpoint_hashtable = (struct list_head *)__get_free_page(GFP_ATOMIC);
if (!mount_hashtable || !mountpoint_hashtable)
panic("Failed to allocate mount hash table\n");
printk(KERN_INFO "Mount-cache hash table entries: %lu\n", HASH_SIZE);
for (u = 0; u < HASH_SIZE; u++)
INIT_LIST_HEAD(&mount_hashtable[u]);
for (u = 0; u < HASH_SIZE; u++)
INIT_LIST_HEAD(&mountpoint_hashtable[u]);
br_lock_init(&vfsmount_lock);
err = sysfs_init();
if (err)
printk(KERN_WARNING "%s: sysfs_init error: %d\n",
__func__, err);
fs_kobj = kobject_create_and_add("fs", NULL);
if (!fs_kobj)
printk(KERN_WARNING "%s: kobj create error\n", __func__);
init_rootfs();
init_mount_tree();
}
void put_mnt_ns(struct mnt_namespace *ns)
{
if (!atomic_dec_and_test(&ns->count))
return;
namespace_lock();
br_write_lock(&vfsmount_lock);
umount_tree(ns->root, 0);
br_write_unlock(&vfsmount_lock);
namespace_unlock();
free_mnt_ns(ns);
}
struct vfsmount *kern_mount_data(struct file_system_type *type, void *data)
{
struct vfsmount *mnt;
mnt = vfs_kern_mount(type, MS_KERNMOUNT, type->name, data);
if (!IS_ERR(mnt)) {
/*
* it is a longterm mount, don't release mnt until
* we unmount before file sys is unregistered
*/
real_mount(mnt)->mnt_ns = MNT_NS_INTERNAL;
}
return mnt;
}
EXPORT_SYMBOL_GPL(kern_mount_data);
void kern_unmount(struct vfsmount *mnt)
{
/* release long term mount so mount point can be released */
if (!IS_ERR_OR_NULL(mnt)) {
br_write_lock(&vfsmount_lock);
real_mount(mnt)->mnt_ns = NULL;
br_write_unlock(&vfsmount_lock);
mntput(mnt);
}
}
EXPORT_SYMBOL(kern_unmount);
bool our_mnt(struct vfsmount *mnt)
{
return check_mnt(real_mount(mnt));
}
bool current_chrooted(void)
{
/* Does the current process have a non-standard root */
struct path ns_root;
struct path fs_root;
bool chrooted;
/* Find the namespace root */
ns_root.mnt = ¤t->nsproxy->mnt_ns->root->mnt;
ns_root.dentry = ns_root.mnt->mnt_root;
path_get(&ns_root);
while (d_mountpoint(ns_root.dentry) && follow_down_one(&ns_root))
;
get_fs_root(current->fs, &fs_root);
chrooted = !path_equal(&fs_root, &ns_root);
path_put(&fs_root);
path_put(&ns_root);
return chrooted;
}
void update_mnt_policy(struct user_namespace *userns)
{
struct mnt_namespace *ns = current->nsproxy->mnt_ns;
struct mount *mnt;
down_read(&namespace_sem);
list_for_each_entry(mnt, &ns->list, mnt_list) {
switch (mnt->mnt.mnt_sb->s_magic) {
case SYSFS_MAGIC:
userns->may_mount_sysfs = true;
break;
case PROC_SUPER_MAGIC:
userns->may_mount_proc = true;
break;
}
if (userns->may_mount_sysfs && userns->may_mount_proc)
break;
}
up_read(&namespace_sem);
}
static void *mntns_get(struct task_struct *task)
{
struct mnt_namespace *ns = NULL;
struct nsproxy *nsproxy;
rcu_read_lock();
nsproxy = task_nsproxy(task);
if (nsproxy) {
ns = nsproxy->mnt_ns;
get_mnt_ns(ns);
}
rcu_read_unlock();
return ns;
}
static void mntns_put(void *ns)
{
put_mnt_ns(ns);
}
static int mntns_install(struct nsproxy *nsproxy, void *ns)
{
struct fs_struct *fs = current->fs;
struct mnt_namespace *mnt_ns = ns;
struct path root;
if (!ns_capable(mnt_ns->user_ns, CAP_SYS_ADMIN) ||
!nsown_capable(CAP_SYS_CHROOT) ||
!nsown_capable(CAP_SYS_ADMIN))
return -EPERM;
if (fs->users != 1)
return -EINVAL;
get_mnt_ns(mnt_ns);
put_mnt_ns(nsproxy->mnt_ns);
nsproxy->mnt_ns = mnt_ns;
/* Find the root */
root.mnt = &mnt_ns->root->mnt;
root.dentry = mnt_ns->root->mnt.mnt_root;
path_get(&root);
while(d_mountpoint(root.dentry) && follow_down_one(&root))
;
/* Update the pwd and root */
set_fs_pwd(fs, &root);
set_fs_root(fs, &root);
path_put(&root);
return 0;
}
static unsigned int mntns_inum(void *ns)
{
struct mnt_namespace *mnt_ns = ns;
return mnt_ns->proc_inum;
}
const struct proc_ns_operations mntns_operations = {
.name = "mnt",
.type = CLONE_NEWNS,
.get = mntns_get,
.put = mntns_put,
.install = mntns_install,
.inum = mntns_inum,
};
| gpl-2.0 |
evaautomation/glibc-linaro | sysdeps/powerpc/powerpc64/multiarch/wcschr.c | 4 | 1514 | /* Multiple versions of wcschr
Copyright (C) 2013-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#if IS_IN (libc)
# define wcschr __redirect_wcschr
# define __wcschr __redirect___wcschr
# include <wchar.h>
# include <shlib-compat.h>
# include "init-arch.h"
extern __typeof (wcschr) __wcschr_ppc attribute_hidden;
extern __typeof (wcschr) __wcschr_power6 attribute_hidden;
extern __typeof (wcschr) __wcschr_power7 attribute_hidden;
# undef wcschr
# undef __wcschr
libc_ifunc_redirected (__redirect___wcschr, __wcschr,
(hwcap & PPC_FEATURE_HAS_VSX)
? __wcschr_power7
: (hwcap & PPC_FEATURE_ARCH_2_05)
? __wcschr_power6
: __wcschr_ppc);
weak_alias (__wcschr, wcschr)
#else
#undef libc_hidden_def
#define libc_hidden_def(a)
#include <wcsmbs/wcschr.c>
#endif
| gpl-2.0 |
waddlesplash/DolphinQt | Source/Core/VideoBackends/Software/Clipper.cpp | 4 | 12217 | // Copyright 2013 Dolphin Emulator Project
// Licensed under GPLv2
// Refer to the license.txt file included.
/*
Portions of this file are based off work by Markus Trenkwalder.
Copyright (c) 2007, 2008 Markus Trenkwalder
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the library's copyright owner nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Clipper.h"
#include "Rasterizer.h"
#include "NativeVertexFormat.h"
#include "XFMemLoader.h"
#include "BPMemLoader.h"
#include "SWStatistics.h"
namespace Clipper
{
enum { NUM_CLIPPED_VERTICES = 33, NUM_INDICES = NUM_CLIPPED_VERTICES + 3 };
float m_ViewOffset[2];
OutputVertexData ClippedVertices[NUM_CLIPPED_VERTICES];
OutputVertexData *Vertices[NUM_INDICES];
void DoState(PointerWrap &p)
{
p.DoArray(m_ViewOffset,2);
for (auto& ClippedVertice : ClippedVertices)
ClippedVertice.DoState(p);
}
void Init()
{
for (int i = 0; i < NUM_CLIPPED_VERTICES; ++i)
Vertices[i+3] = &ClippedVertices[i];
}
void SetViewOffset()
{
m_ViewOffset[0] = swxfregs.viewport.xOrig - 342;
m_ViewOffset[1] = swxfregs.viewport.yOrig - 342;
}
enum {
SKIP_FLAG = -1,
CLIP_POS_X_BIT = 0x01,
CLIP_NEG_X_BIT = 0x02,
CLIP_POS_Y_BIT = 0x04,
CLIP_NEG_Y_BIT = 0x08,
CLIP_POS_Z_BIT = 0x10,
CLIP_NEG_Z_BIT = 0x20
};
static inline int CalcClipMask(OutputVertexData *v)
{
int cmask = 0;
Vec4 pos = v->projectedPosition;
if (pos.w - pos.x < 0) cmask |= CLIP_POS_X_BIT;
if (pos.x + pos.w < 0) cmask |= CLIP_NEG_X_BIT;
if (pos.w - pos.y < 0) cmask |= CLIP_POS_Y_BIT;
if (pos.y + pos.w < 0) cmask |= CLIP_NEG_Y_BIT;
if (pos.w * pos.z > 0) cmask |= CLIP_POS_Z_BIT;
if (pos.z + pos.w < 0) cmask |= CLIP_NEG_Z_BIT;
return cmask;
}
static inline void AddInterpolatedVertex(float t, int out, int in, int& numVertices)
{
Vertices[numVertices]->Lerp(t, Vertices[out], Vertices[in]);
numVertices++;
}
#define DIFFERENT_SIGNS(x,y) ((x <= 0 && y > 0) || (x > 0 && y <= 0))
#define CLIP_DOTPROD(I, A, B, C, D) \
(Vertices[I]->projectedPosition.x * A + Vertices[I]->projectedPosition.y * B + Vertices[I]->projectedPosition.z * C + Vertices[I]->projectedPosition.w * D)
#define POLY_CLIP( PLANE_BIT, A, B, C, D ) \
{ \
if (mask & PLANE_BIT) { \
int idxPrev = inlist[0]; \
float dpPrev = CLIP_DOTPROD(idxPrev, A, B, C, D ); \
int outcount = 0; \
\
inlist[n] = inlist[0]; \
for (int j = 1; j <= n; j++) { \
int idx = inlist[j]; \
float dp = CLIP_DOTPROD(idx, A, B, C, D ); \
if (dpPrev >= 0) { \
outlist[outcount++] = idxPrev; \
} \
\
if (DIFFERENT_SIGNS(dp, dpPrev)) { \
if (dp < 0) { \
float t = dp / (dp - dpPrev); \
AddInterpolatedVertex(t, idx, idxPrev, numVertices); \
} else { \
float t = dpPrev / (dpPrev - dp); \
AddInterpolatedVertex(t, idxPrev, idx, numVertices); \
} \
outlist[outcount++] = numVertices - 1; \
} \
\
idxPrev = idx; \
dpPrev = dp; \
} \
\
if (outcount < 3) \
continue; \
\
{ \
int *tmp = inlist; \
inlist = outlist; \
outlist = tmp; \
n = outcount; \
} \
} \
}
#define LINE_CLIP(PLANE_BIT, A, B, C, D ) \
{ \
if (mask & PLANE_BIT) { \
const float dp0 = CLIP_DOTPROD( 0, A, B, C, D ); \
const float dp1 = CLIP_DOTPROD( 1, A, B, C, D ); \
const bool neg_dp0 = dp0 < 0; \
const bool neg_dp1 = dp1 < 0; \
\
if (neg_dp0 && neg_dp1) \
return; \
\
if (neg_dp1) { \
float t = dp1 / (dp1 - dp0); \
if (t > t1) t1 = t; \
} else if (neg_dp0) { \
float t = dp0 / (dp0 - dp1); \
if (t > t0) t0 = t; \
} \
} \
}
void ClipTriangle(int *indices, int &numIndices)
{
int mask = 0;
mask |= CalcClipMask(Vertices[0]);
mask |= CalcClipMask(Vertices[1]);
mask |= CalcClipMask(Vertices[2]);
if (mask != 0)
{
for(int i = 0; i < 3; i += 3)
{
int vlist[2][2*6+1];
int *inlist = vlist[0], *outlist = vlist[1];
int n = 3;
int numVertices = 3;
inlist[0] = 0;
inlist[1] = 1;
inlist[2] = 2;
// mark this triangle as unused in case it should be completely
// clipped
indices[0] = SKIP_FLAG;
indices[1] = SKIP_FLAG;
indices[2] = SKIP_FLAG;
POLY_CLIP(CLIP_POS_X_BIT, -1, 0, 0, 1);
POLY_CLIP(CLIP_NEG_X_BIT, 1, 0, 0, 1);
POLY_CLIP(CLIP_POS_Y_BIT, 0, -1, 0, 1);
POLY_CLIP(CLIP_NEG_Y_BIT, 0, 1, 0, 1);
POLY_CLIP(CLIP_POS_Z_BIT, 0, 0, 0, 1);
POLY_CLIP(CLIP_NEG_Z_BIT, 0, 0, 1, 1);
INCSTAT(swstats.thisFrame.numTrianglesClipped);
// transform the poly in inlist into triangles
indices[0] = inlist[0];
indices[1] = inlist[1];
indices[2] = inlist[2];
for (int j = 3; j < n; ++j) {
indices[numIndices++] = inlist[0];
indices[numIndices++] = inlist[j - 1];
indices[numIndices++] = inlist[j];
}
}
}
}
void ClipLine(int *indices)
{
int mask = 0;
int clip_mask[2] = { 0, 0 };
for (int i = 0; i < 2; ++i)
{
clip_mask[i] = CalcClipMask(Vertices[i]);
mask |= clip_mask[i];
}
if (mask == 0)
return;
float t0 = 0;
float t1 = 0;
// Mark unused in case of early termination
// of the macros below. (When fully clipped)
indices[0] = SKIP_FLAG;
indices[1] = SKIP_FLAG;
LINE_CLIP(CLIP_POS_X_BIT, -1, 0, 0, 1);
LINE_CLIP(CLIP_NEG_X_BIT, 1, 0, 0, 1);
LINE_CLIP(CLIP_POS_Y_BIT, 0, -1, 0, 1);
LINE_CLIP(CLIP_NEG_Y_BIT, 0, 1, 0, 1);
LINE_CLIP(CLIP_POS_Z_BIT, 0, 0, -1, 1);
LINE_CLIP(CLIP_NEG_Z_BIT, 0, 0, 1, 1);
// Restore the old values as this line
// was not fully clipped.
indices[0] = 0;
indices[1] = 1;
int numVertices = 2;
if (clip_mask[0])
{
indices[0] = numVertices;
AddInterpolatedVertex(t0, 0, 1, numVertices);
}
if (clip_mask[1])
{
indices[1] = numVertices;
AddInterpolatedVertex(t1, 1, 0, numVertices);
}
}
void ProcessTriangle(OutputVertexData *v0, OutputVertexData *v1, OutputVertexData *v2)
{
INCSTAT(swstats.thisFrame.numTrianglesIn)
bool backface;
if(!CullTest(v0, v1, v2, backface))
return;
int indices[NUM_INDICES] = { 0, 1, 2, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG,
SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG,
SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG };
int numIndices = 3;
if (backface)
{
Vertices[0] = v0;
Vertices[1] = v2;
Vertices[2] = v1;
}
else
{
Vertices[0] = v0;
Vertices[1] = v1;
Vertices[2] = v2;
}
ClipTriangle(indices, numIndices);
for(int i = 0; i+3 <= numIndices; i+=3)
{
_assert_(i < NUM_INDICES);
if(indices[i] != SKIP_FLAG)
{
PerspectiveDivide(Vertices[indices[i]]);
PerspectiveDivide(Vertices[indices[i+1]]);
PerspectiveDivide(Vertices[indices[i+2]]);
Rasterizer::DrawTriangleFrontFace(Vertices[indices[i]], Vertices[indices[i+1]], Vertices[indices[i+2]]);
}
}
}
void CopyVertex(OutputVertexData *dst, OutputVertexData *src, float dx, float dy, unsigned int sOffset)
{
dst->screenPosition.x = src->screenPosition.x + dx;
dst->screenPosition.y = src->screenPosition.y + dy;
dst->screenPosition.z = src->screenPosition.z;
for (int i = 0; i < 3; ++i)
dst->normal[i] = src->normal[i];
for (int i = 0; i < 4; ++i)
dst->color[0][i] = src->color[0][i];
// todo - s offset
for (int i = 0; i < 8; ++i)
dst->texCoords[i] = src->texCoords[i];
}
void ProcessLine(OutputVertexData *lineV0, OutputVertexData *lineV1)
{
int indices[4] = { 0, 1, SKIP_FLAG, SKIP_FLAG };
Vertices[0] = lineV0;
Vertices[1] = lineV1;
// point to a valid vertex to store to when clipping
Vertices[2] = &ClippedVertices[17];
ClipLine(indices);
if(indices[0] != SKIP_FLAG)
{
OutputVertexData *v0 = Vertices[indices[0]];
OutputVertexData *v1 = Vertices[indices[1]];
PerspectiveDivide(v0);
PerspectiveDivide(v1);
float dx = v1->screenPosition.x - v0->screenPosition.x;
float dy = v1->screenPosition.y - v0->screenPosition.y;
float screenDx = 0;
float screenDy = 0;
if(fabsf(dx) > fabsf(dy))
{
if(dx > 0)
screenDy = bpmem.lineptwidth.linesize / -12.0f;
else
screenDy = bpmem.lineptwidth.linesize / 12.0f;
}
else
{
if(dy > 0)
screenDx = bpmem.lineptwidth.linesize / 12.0f;
else
screenDx = bpmem.lineptwidth.linesize / -12.0f;
}
OutputVertexData triangle[3];
CopyVertex(&triangle[0], v0, screenDx, screenDy, 0);
CopyVertex(&triangle[1], v1, screenDx, screenDy, 0);
CopyVertex(&triangle[2], v1, -screenDx, -screenDy, bpmem.lineptwidth.lineoff);
// ccw winding
Rasterizer::DrawTriangleFrontFace(&triangle[2], &triangle[1], &triangle[0]);
CopyVertex(&triangle[1], v0, -screenDx, -screenDy, bpmem.lineptwidth.lineoff);
Rasterizer::DrawTriangleFrontFace(&triangle[0], &triangle[1], &triangle[2]);
}
}
bool CullTest(OutputVertexData *v0, OutputVertexData *v1, OutputVertexData *v2, bool &backface)
{
int mask = CalcClipMask(v0);
mask &= CalcClipMask(v1);
mask &= CalcClipMask(v2);
if(mask)
{
INCSTAT(swstats.thisFrame.numTrianglesRejected)
return false;
}
float x0 = v0->projectedPosition.x;
float x1 = v1->projectedPosition.x;
float x2 = v2->projectedPosition.x;
float y1 = v1->projectedPosition.y;
float y0 = v0->projectedPosition.y;
float y2 = v2->projectedPosition.y;
float w0 = v0->projectedPosition.w;
float w1 = v1->projectedPosition.w;
float w2 = v2->projectedPosition.w;
float normalZDir = (x0*w2 - x2*w0)*y1 + (x2*y0 - x0*y2)*w1 + (y2*w0 - y0*w2)*x1;
backface = normalZDir <= 0.0f;
if ((bpmem.genMode.cullmode & 1) && !backface) // cull frontfacing
{
INCSTAT(swstats.thisFrame.numTrianglesCulled)
return false;
}
if ((bpmem.genMode.cullmode & 2) && backface) // cull backfacing
{
INCSTAT(swstats.thisFrame.numTrianglesCulled)
return false;
}
return true;
}
void PerspectiveDivide(OutputVertexData *vertex)
{
Vec4 &projected = vertex->projectedPosition;
Vec3 &screen = vertex->screenPosition;
float wInverse = 1.0f/projected.w;
screen.x = projected.x * wInverse * swxfregs.viewport.wd + m_ViewOffset[0];
screen.y = projected.y * wInverse * swxfregs.viewport.ht + m_ViewOffset[1];
screen.z = projected.z * wInverse * swxfregs.viewport.zRange + swxfregs.viewport.farZ;
}
}
| gpl-2.0 |
pinskia/glibc-ilp32 | sysdeps/unix/bsd/getpt.c | 4 | 2290 | /* Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Zack Weinberg <zack@rabi.phys.columbia.edu>, 1998.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
/* Prefix for master pseudo terminal nodes. */
#define _PATH_PTY "/dev/pty"
/* Letters indicating a series of pseudo terminals. */
#ifndef PTYNAME1
#define PTYNAME1 "pqrsPQRS"
#endif
const char __libc_ptyname1[] attribute_hidden = PTYNAME1;
/* Letters indicating the position within a series. */
#ifndef PTYNAME2
#define PTYNAME2 "0123456789abcdefghijklmnopqrstuv";
#endif
const char __libc_ptyname2[] attribute_hidden = PTYNAME2;
/* Open a master pseudo terminal and return its file descriptor. */
int
__getpt (void)
{
char buf[sizeof (_PATH_PTY) + 2];
const char *p, *q;
char *s;
s = __mempcpy (buf, _PATH_PTY, sizeof (_PATH_PTY) - 1);
/* s[0] and s[1] will be filled in the loop. */
s[2] = '\0';
for (p = __libc_ptyname1; *p != '\0'; ++p)
{
s[0] = *p;
for (q = __libc_ptyname2; *q != '\0'; ++q)
{
int fd;
s[1] = *q;
fd = __open (buf, O_RDWR);
if (fd != -1)
return fd;
if (errno == ENOENT)
return -1;
}
}
__set_errno (ENOENT);
return -1;
}
#undef __getpt
weak_alias (__getpt, getpt)
#ifndef HAVE_POSIX_OPENPT
/* We cannot define posix_openpt in general for BSD systems. */
int
__posix_openpt (int oflag)
{
__set_errno (ENOSYS);
return -1;
}
weak_alias (__posix_openpt, posix_openpt)
stub_warning (posix_openpt)
# include <stub-tag.h>
#endif
| gpl-2.0 |
bigzz/ltp | testcases/kernel/syscalls/setdomainname/setdomainname01.c | 4 | 3828 | /*
* Copyright (c) Wipro Technologies Ltd, 2002. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
/**********************************************************
*
* TEST IDENTIFIER : setdomainname01
*
* EXECUTED BY : root / superuser
*
* TEST TITLE : Basic test for setdomainame(2)
*
* TEST CASE TOTAL : 1
*
* AUTHOR : Saji Kumar.V.R <saji.kumar@wipro.com>
*
* SIGNALS
* Uses SIGUSR1 to pause before test if option set.
* (See the parse_opts(3) man page).
*
* DESCRIPTION
* This is a Phase I test for the setdomainname(2) system call.
* It is intended to provide a limited exposure of the system call.
*
* Setup:
* Setup signal handling.
* Pause for SIGUSR1 if option specified.
* Save the current domainname.
*
* Test:
* Loop if the proper options are given.
* Execute system call
* Check return code, if system call failed (return=-1)
* Log the errno and Issue a FAIL message.
* Otherwise, Issue a PASS message.
*
* Cleanup:
* Restore old domain name.
* Print errno log and/or timing stats if options given
*
* USAGE: <for command-line>
* setdomainname01 [-c n] [-e] [-i n] [-I x] [-P x] [-t] [-h] [-f] [-p]
* where, -c n : Run n copies concurrently.
* -e : Turn on errno logging.
* -h : Show help screen
* -f : Turn off functional testing
* -i n : Execute test n times.
* -I x : Execute test for x seconds.
* -p : Pause for SIGUSR1 before starting
* -P x : Pause for x seconds between iterations.
* -t : Turn on syscall timing.
*
****************************************************************/
#include <errno.h>
#include <string.h>
#include <sys/utsname.h>
#include "test.h"
#define MAX_NAME_LEN _UTSNAME_DOMAIN_LENGTH
static void setup();
static void cleanup();
char *TCID = "setdomainname01";
int TST_TOTAL = 1;
static char *test_domain_name = "test_dom";
static char old_domain_name[MAX_NAME_LEN];
int main(int ac, char **av)
{
int lc;
tst_parse_opts(ac, av, NULL, NULL);
setup();
for (lc = 0; TEST_LOOPING(lc); lc++) {
tst_count = 0;
/*
* Call setdomainname(2)
*/
TEST(setdomainname(test_domain_name, sizeof(test_domain_name)));
/* check return code */
if (TEST_RETURN == -1) {
tst_resm(TFAIL, "setdomainname() Failed, errno = %d :"
" %s", TEST_ERRNO, strerror(TEST_ERRNO));
} else {
tst_resm(TPASS, "setdomainname() returned %ld, "
"Domain name set to \"%s\"", TEST_RETURN,
test_domain_name);
}
}
/* cleanup and exit */
cleanup();
tst_exit();
}
/* setup() - performs all ONE TIME setup for this test */
void setup(void)
{
tst_require_root(NULL);
tst_sig(NOFORK, DEF_HANDLER, cleanup);
/* Save current domain name */
if ((getdomainname(old_domain_name, sizeof(old_domain_name))) < 0) {
tst_brkm(TBROK, NULL, "getdomainname() failed while"
" getting current domain name");
}
TEST_PAUSE;
}
/*
*cleanup() - performs all ONE TIME cleanup for this test at
* completion or premature exit.
*/
void cleanup(void)
{
/* Restore domain name */
if ((setdomainname(old_domain_name, strlen(old_domain_name))) < 0) {
tst_resm(TWARN, "setdomainname() failed while restoring"
" domainname to \"%s\"", old_domain_name);
}
}
| gpl-2.0 |
maz-1/firefly-rk3288-kernel | drivers/gpu/rogue/services/server/env/linux/pvr_bridge_k.c | 4 | 15888 | /*************************************************************************/ /*!
@File
@Title PVR Bridge Module (kernel side)
@Copyright Copyright (c) Imagination Technologies Ltd. All Rights Reserved
@Description Receives calls from the user portion of services and
despatches them to functions in the kernel portion.
@License Dual MIT/GPLv2
The contents of this file are subject to the MIT license as set out below.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 ("GPL") in which case the provisions
of GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms of
GPL, and not to allow others to use your version of this file under the terms
of the MIT license, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by GPL as set
out in the file called "GPL-COPYING" included in this distribution. If you do
not delete the provisions above, a recipient may use your version of this file
under the terms of either the MIT license or GPL.
This License is also included in this distribution in the file called
"MIT-COPYING".
EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /**************************************************************************/
#include "img_defs.h"
#include "pvr_bridge.h"
#include "connection_server.h"
#include "syscommon.h"
#include "pvr_debug.h"
#include "pvr_debugfs.h"
#include "private_data.h"
#include "linkage.h"
#include "driverlock.h"
#if defined(SUPPORT_DRM)
#include <drm/drmP.h>
#include "pvr_drm.h"
#if defined(PVR_DRM_SECURE_AUTH_EXPORT)
#include "env_connection.h"
#endif
#endif /* defined(SUPPORT_DRM) */
/* RGX: */
#if defined(SUPPORT_RGX)
#include "rgx_bridge.h"
#endif
#include "srvcore.h"
#include "common_srvcore_bridge.h"
#include "cache_defines.h"
#if defined(MODULE_TEST)
/************************************************************************/
// additional includes for services testing
/************************************************************************/
#include "pvr_test_bridge.h"
#include "kern_test.h"
/************************************************************************/
// end of additional includes
/************************************************************************/
#endif
#if defined(SUPPORT_DRM)
#define PRIVATE_DATA(pFile) ((pFile)->driver_priv)
#else
#define PRIVATE_DATA(pFile) ((pFile)->private_data)
#endif
#if defined(DEBUG_BRIDGE_KM)
static PVR_DEBUGFS_ENTRY_DATA *gpsPVRDebugFSBridgeStatsEntry = NULL;
static struct seq_operations gsBridgeStatsReadOps;
#endif
PVRSRV_ERROR RegisterPDUMPFunctions(void);
#if defined(SUPPORT_DISPLAY_CLASS)
PVRSRV_ERROR RegisterDCFunctions(void);
#endif
PVRSRV_ERROR RegisterMMFunctions(void);
PVRSRV_ERROR RegisterCMMFunctions(void);
PVRSRV_ERROR RegisterPDUMPMMFunctions(void);
PVRSRV_ERROR RegisterPDUMPCMMFunctions(void);
PVRSRV_ERROR RegisterSRVCOREFunctions(void);
PVRSRV_ERROR RegisterSYNCFunctions(void);
#if defined(SUPPORT_INSECURE_EXPORT)
PVRSRV_ERROR RegisterSYNCEXPORTFunctions(void);
#endif
#if defined(SUPPORT_SECURE_EXPORT)
PVRSRV_ERROR RegisterSYNCSEXPORTFunctions(void);
#endif
#if defined (SUPPORT_RGX)
PVRSRV_ERROR RegisterRGXINITFunctions(void);
PVRSRV_ERROR RegisterRGXTA3DFunctions(void);
PVRSRV_ERROR RegisterRGXTQFunctions(void);
PVRSRV_ERROR RegisterRGXCMPFunctions(void);
PVRSRV_ERROR RegisterBREAKPOINTFunctions(void);
PVRSRV_ERROR RegisterDEBUGMISCFunctions(void);
PVRSRV_ERROR RegisterRGXPDUMPFunctions(void);
PVRSRV_ERROR RegisterRGXHWPERFFunctions(void);
#if defined(RGX_FEATURE_RAY_TRACING)
PVRSRV_ERROR RegisterRGXRAYFunctions(void);
#endif /* RGX_FEATURE_RAY_TRACING */
PVRSRV_ERROR RegisterREGCONFIGFunctions(void);
PVRSRV_ERROR RegisterTIMERQUERYFunctions(void);
#endif /* SUPPORT_RGX */
#if (CACHEFLUSH_TYPE == CACHEFLUSH_GENERIC)
PVRSRV_ERROR RegisterCACHEGENERICFunctions(void);
#endif
#if defined(SUPPORT_SECURE_EXPORT)
PVRSRV_ERROR RegisterSMMFunctions(void);
#endif
#if defined(SUPPORT_PMMIF)
PVRSRV_ERROR RegisterPMMIFFunctions(void);
#endif
PVRSRV_ERROR RegisterPVRTLFunctions(void);
#if defined(PVR_RI_DEBUG)
PVRSRV_ERROR RegisterRIFunctions(void);
#endif
#if defined(SUPPORT_ION)
PVRSRV_ERROR RegisterDMABUFFunctions(void);
#endif
/* These and their friends above will go when full bridge gen comes in */
PVRSRV_ERROR
LinuxBridgeInit(void);
void
LinuxBridgeDeInit(void);
PVRSRV_ERROR
LinuxBridgeInit(void)
{
PVRSRV_ERROR eError;
#if defined(DEBUG_BRIDGE_KM)
IMG_INT iResult;
iResult = PVRDebugFSCreateEntry("bridge_stats",
NULL,
&gsBridgeStatsReadOps,
NULL,
&g_BridgeDispatchTable[0],
&gpsPVRDebugFSBridgeStatsEntry);
if (iResult != 0)
{
return PVRSRV_ERROR_OUT_OF_MEMORY;
}
#endif
eError = RegisterSRVCOREFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterSYNCFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#if defined(SUPPORT_INSECURE_EXPORT)
eError = RegisterSYNCEXPORTFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif
#if defined(SUPPORT_SECURE_EXPORT)
eError = RegisterSYNCSEXPORTFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif
eError = RegisterPDUMPFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterMMFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterCMMFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterPDUMPMMFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterPDUMPCMMFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#if defined(SUPPORT_PMMIF)
eError = RegisterPMMIFFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif
#if defined(SUPPORT_ION)
eError = RegisterDMABUFFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif
#if defined(SUPPORT_DISPLAY_CLASS)
eError = RegisterDCFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif
#if (CACHEFLUSH_TYPE == CACHEFLUSH_GENERIC)
eError = RegisterCACHEGENERICFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif
#if defined(SUPPORT_SECURE_EXPORT)
eError = RegisterSMMFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif
eError = RegisterPVRTLFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#if defined(PVR_RI_DEBUG)
eError = RegisterRIFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif
#if defined (SUPPORT_RGX)
eError = RegisterRGXTQFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterRGXCMPFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterRGXINITFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterRGXTA3DFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterBREAKPOINTFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterDEBUGMISCFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterRGXPDUMPFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterRGXHWPERFFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#if defined(RGX_FEATURE_RAY_TRACING)
eError = RegisterRGXRAYFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif /* RGX_FEATURE_RAY_TRACING */
eError = RegisterREGCONFIGFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
eError = RegisterTIMERQUERYFunctions();
if (eError != PVRSRV_OK)
{
return eError;
}
#endif /* SUPPORT_RGX */
return eError;
}
void
LinuxBridgeDeInit(void)
{
#if defined(DEBUG_BRIDGE_KM)
PVRDebugFSRemoveEntry(gpsPVRDebugFSBridgeStatsEntry);
gpsPVRDebugFSBridgeStatsEntry = NULL;
#endif
}
#if defined(DEBUG_BRIDGE_KM)
static void *BridgeStatsSeqStart(struct seq_file *psSeqFile, loff_t *puiPosition)
{
PVRSRV_BRIDGE_DISPATCH_TABLE_ENTRY *psDispatchTable = (PVRSRV_BRIDGE_DISPATCH_TABLE_ENTRY *)psSeqFile->private;
OSAcquireBridgeLock();
if (psDispatchTable == NULL || (*puiPosition) > BRIDGE_DISPATCH_TABLE_ENTRY_COUNT)
{
return NULL;
}
if ((*puiPosition) == 0)
{
return SEQ_START_TOKEN;
}
return &(psDispatchTable[(*puiPosition) - 1]);
}
static void BridgeStatsSeqStop(struct seq_file *psSeqFile, void *pvData)
{
PVR_UNREFERENCED_PARAMETER(psSeqFile);
PVR_UNREFERENCED_PARAMETER(pvData);
OSReleaseBridgeLock();
}
static void *BridgeStatsSeqNext(struct seq_file *psSeqFile,
void *pvData,
loff_t *puiPosition)
{
PVRSRV_BRIDGE_DISPATCH_TABLE_ENTRY *psDispatchTable = (PVRSRV_BRIDGE_DISPATCH_TABLE_ENTRY *)psSeqFile->private;
PVR_UNREFERENCED_PARAMETER(pvData);
(*puiPosition)++;
if ((*puiPosition) > BRIDGE_DISPATCH_TABLE_ENTRY_COUNT)
{
return NULL;
}
return &(psDispatchTable[(*puiPosition) - 1]);
}
static int BridgeStatsSeqShow(struct seq_file *psSeqFile, void *pvData)
{
if (pvData == SEQ_START_TOKEN)
{
seq_printf(psSeqFile,
"Total ioctl call count = %u\n"
"Total number of bytes copied via copy_from_user = %u\n"
"Total number of bytes copied via copy_to_user = %u\n"
"Total number of bytes copied via copy_*_user = %u\n\n"
"%-60s | %-48s | %10s | %20s | %10s\n",
g_BridgeGlobalStats.ui32IOCTLCount,
g_BridgeGlobalStats.ui32TotalCopyFromUserBytes,
g_BridgeGlobalStats.ui32TotalCopyToUserBytes,
g_BridgeGlobalStats.ui32TotalCopyFromUserBytes + g_BridgeGlobalStats.ui32TotalCopyToUserBytes,
"Bridge Name",
"Wrapper Function",
"Call Count",
"copy_from_user Bytes",
"copy_to_user Bytes");
}
else if (pvData != NULL)
{
PVRSRV_BRIDGE_DISPATCH_TABLE_ENTRY *psEntry = ( PVRSRV_BRIDGE_DISPATCH_TABLE_ENTRY *)pvData;
seq_printf(psSeqFile,
"%-60s %-48s %-10u %-20u %-10u\n",
psEntry->pszIOCName,
psEntry->pszFunctionName,
psEntry->ui32CallCount,
psEntry->ui32CopyFromUserTotalBytes,
psEntry->ui32CopyToUserTotalBytes);
}
return 0;
}
static struct seq_operations gsBridgeStatsReadOps =
{
.start = BridgeStatsSeqStart,
.stop = BridgeStatsSeqStop,
.next = BridgeStatsSeqNext,
.show = BridgeStatsSeqShow,
};
#endif /* defined(DEBUG_BRIDGE_KM) */
#if defined(SUPPORT_DRM)
int
PVRSRV_BridgeDispatchKM(struct drm_device *dev, void *arg, struct drm_file *pFile)
#else
long
PVRSRV_BridgeDispatchKM(struct file *pFile, unsigned int unref__ ioctlCmd, unsigned long arg)
#endif
{
#if !defined(SUPPORT_DRM)
PVRSRV_BRIDGE_PACKAGE *psBridgePackageUM = (PVRSRV_BRIDGE_PACKAGE *)arg;
PVRSRV_BRIDGE_PACKAGE sBridgePackageKM;
#endif
PVRSRV_BRIDGE_PACKAGE *psBridgePackageKM;
CONNECTION_DATA *psConnection;
IMG_INT err = -EFAULT;
OSAcquireBridgeLock();
psConnection = LinuxConnectionFromFile(pFile);
if(psConnection == IMG_NULL)
{
PVR_DPF((PVR_DBG_ERROR, "%s: Connection is closed", __FUNCTION__));
OSReleaseBridgeLock();
return err;
}
#if defined(SUPPORT_DRM)
PVR_UNREFERENCED_PARAMETER(dev);
psBridgePackageKM = (PVRSRV_BRIDGE_PACKAGE *)arg;
PVR_ASSERT(psBridgePackageKM != IMG_NULL);
#else
PVR_UNREFERENCED_PARAMETER(ioctlCmd);
psBridgePackageKM = &sBridgePackageKM;
if(!OSAccessOK(PVR_VERIFY_WRITE,
psBridgePackageUM,
sizeof(PVRSRV_BRIDGE_PACKAGE)))
{
PVR_DPF((PVR_DBG_ERROR, "%s: Received invalid pointer to function arguments",
__FUNCTION__));
goto unlock_and_return;
}
if(OSCopyFromUser(IMG_NULL,
psBridgePackageKM,
psBridgePackageUM,
sizeof(PVRSRV_BRIDGE_PACKAGE))
!= PVRSRV_OK)
{
goto unlock_and_return;
}
#endif
#if defined(DEBUG_BRIDGE_CALLS)
{
IMG_UINT32 mangledID;
mangledID = psBridgePackageKM->ui32BridgeID;
psBridgePackageKM->ui32BridgeID = PVRSRV_GET_BRIDGE_ID(psBridgePackageKM->ui32BridgeID);
PVR_DPF((PVR_DBG_WARNING, "Bridge ID (x%8x) %8u (mangled: x%8x) ", psBridgePackageKM->ui32BridgeID, psBridgePackageKM->ui32BridgeID, mangledID));
}
#else
psBridgePackageKM->ui32BridgeID = PVRSRV_GET_BRIDGE_ID(psBridgePackageKM->ui32BridgeID);
#endif
err = BridgedDispatchKM(psConnection, psBridgePackageKM);
#if !defined(SUPPORT_DRM)
unlock_and_return:
#endif
OSReleaseBridgeLock();
return err;
}
#if defined(CONFIG_COMPAT)
#if defined(SUPPORT_DRM)
int
#else
long
#endif
PVRSRV_BridgeCompatDispatchKM(struct file *pFile,
unsigned int unref__ ioctlCmd,
unsigned long arg)
{
struct bridge_package_from_32
{
IMG_UINT32 bridge_id; /*!< ioctl/drvesc index */
IMG_UINT32 size; /*!< size of structure */
IMG_UINT32 addr_param_in; /*!< input data buffer */
IMG_UINT32 in_buffer_size; /*!< size of input data buffer */
IMG_UINT32 addr_param_out; /*!< output data buffer */
IMG_UINT32 out_buffer_size; /*!< size of output data buffer */
};
IMG_INT err = -EFAULT;
PVRSRV_BRIDGE_PACKAGE params_for_64;
struct bridge_package_from_32 params;
struct bridge_package_from_32 * const params_addr = ¶ms;
#if defined(SUPPORT_DRM)
struct drm_file *file_priv;
#endif
CONNECTION_DATA *psConnection;
// make sure there is no padding inserted by compiler
PVR_ASSERT(sizeof(struct bridge_package_from_32) == 6 * sizeof(IMG_UINT32));
OSAcquireBridgeLock();
#if !defined(SUPPORT_DRM)
psConnection = LinuxConnectionFromFile(pFile);
#else
file_priv = pFile->private_data;
psConnection = LinuxConnectionFromFile(file_priv);
#endif
if(psConnection == IMG_NULL)
{
PVR_DPF((PVR_DBG_ERROR, "%s: Connection is closed", __FUNCTION__));
goto unlock_and_return;
}
if(!OSAccessOK(PVR_VERIFY_READ, (void *) arg,
sizeof(struct bridge_package_from_32)))
{
PVR_DPF((PVR_DBG_ERROR, "%s: Received invalid pointer to function arguments",
__FUNCTION__));
goto unlock_and_return;
}
if(OSCopyFromUser(NULL, params_addr, (void*) arg,
sizeof(struct bridge_package_from_32))
!= PVRSRV_OK)
{
goto unlock_and_return;
}
PVR_ASSERT(params_addr->size == sizeof(struct bridge_package_from_32));
params_addr->bridge_id = PVRSRV_GET_BRIDGE_ID(params_addr->bridge_id);
#if defined(DEBUG_BRIDGE_KM)
PVR_DPF((PVR_DBG_MESSAGE, "ioctl %s -> func %s",
g_BridgeDispatchTable[params_addr->bridge_id].pszIOCName,
g_BridgeDispatchTable[params_addr->bridge_id].pszFunctionName));
#endif
params_for_64.ui32BridgeID = params_addr->bridge_id;
params_for_64.ui32Size = sizeof(params_for_64);
params_for_64.pvParamIn = (void*) ((size_t) params_addr->addr_param_in);
params_for_64.pvParamOut = (void*) ((size_t) params_addr->addr_param_out);
params_for_64.ui32InBufferSize = params_addr->in_buffer_size;
params_for_64.ui32OutBufferSize = params_addr->out_buffer_size;
err = BridgedDispatchKM(psConnection, ¶ms_for_64);
unlock_and_return:
OSReleaseBridgeLock();
return err;
}
#endif /* defined(CONFIG_COMPAT) */
| gpl-2.0 |
elektroschmock/android_kernel_google_msm | arch/arm/mach-msm/board-8960.c | 4 | 89724 | /* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/i2c.h>
#include <linux/i2c/sx150x.h>
#include <linux/i2c/isl9519.h>
#include <linux/gpio.h>
#include <linux/msm_ssbi.h>
#include <linux/regulator/msm-gpio-regulator.h>
#include <linux/mfd/pm8xxx/pm8921.h>
#include <linux/mfd/pm8xxx/pm8xxx-adc.h>
#include <linux/regulator/consumer.h>
#include <linux/spi/spi.h>
#include <linux/slimbus/slimbus.h>
#include <linux/bootmem.h>
#ifdef CONFIG_ANDROID_PMEM
#include <linux/android_pmem.h>
#endif
#include <linux/cyttsp-qc.h>
#include <linux/dma-contiguous.h>
#include <linux/dma-mapping.h>
#include <linux/platform_data/qcom_crypto_device.h>
#include <linux/platform_data/qcom_wcnss_device.h>
#include <linux/leds.h>
#include <linux/leds-pm8xxx.h>
#include <linux/i2c/atmel_mxt_ts.h>
#include <linux/msm_tsens.h>
#include <linux/ks8851.h>
#include <linux/i2c/isa1200.h>
#include <linux/memory.h>
#include <linux/memblock.h>
#include <linux/msm_thermal.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/setup.h>
#include <asm/hardware/gic.h>
#include <asm/mach/mmc.h>
#include <mach/board.h>
#include <mach/msm_tspp.h>
#include <mach/msm_iomap.h>
#include <mach/msm_spi.h>
#include <mach/msm_serial_hs.h>
#ifdef CONFIG_USB_MSM_OTG_72K
#include <mach/msm_hsusb.h>
#else
#include <linux/usb/msm_hsusb.h>
#endif
#include <linux/usb/android.h>
#include <mach/usbdiag.h>
#include <mach/socinfo.h>
#include <mach/rpm.h>
#include <mach/gpiomux.h>
#include <mach/msm_bus_board.h>
#include <mach/msm_memtypes.h>
#include <mach/dma.h>
#include <mach/msm_dsps.h>
#include <mach/msm_xo.h>
#include <mach/restart.h>
#ifdef CONFIG_WCD9310_CODEC
#include <linux/mfd/wcd9xxx/core.h>
#include <linux/mfd/wcd9xxx/pdata.h>
#endif
#include <linux/smsc3503.h>
#include <linux/msm_ion.h>
#include <mach/ion.h>
#include <mach/mdm2.h>
#include <mach/mdm-peripheral.h>
#include <mach/msm_rtb.h>
#include <mach/msm_cache_dump.h>
#include <mach/scm.h>
#include <mach/iommu_domains.h>
#include <mach/kgsl.h>
#include <linux/fmem.h>
#include "timer.h"
#include "devices.h"
#include "devices-msm8x60.h"
#include "spm.h"
#include "board-8960.h"
#include "pm.h"
#include <mach/cpuidle.h>
#include "rpm_resources.h"
#include <mach/mpm.h>
#include "clock.h"
#include "smd_private.h"
#include "pm-boot.h"
#include "msm_watchdog.h"
#if defined(CONFIG_BT) && defined(CONFIG_BT_HCIUART_ATH3K)
#include <linux/wlan_plat.h>
#include <linux/mutex.h>
#endif
static struct platform_device msm_fm_platform_init = {
.name = "iris_fm",
.id = -1,
};
#define KS8851_RST_GPIO 89
#define KS8851_IRQ_GPIO 90
#define MHL_GPIO_INT 4
#define MHL_GPIO_RESET 15
#if defined(CONFIG_GPIO_SX150X) || defined(CONFIG_GPIO_SX150X_MODULE)
struct sx150x_platform_data msm8960_sx150x_data[] = {
[SX150X_CAM] = {
.gpio_base = GPIO_CAM_EXPANDER_BASE,
.oscio_is_gpo = false,
.io_pullup_ena = 0x0,
.io_pulldn_ena = 0xc0,
.io_open_drain_ena = 0x0,
.irq_summary = -1,
},
[SX150X_LIQUID] = {
.gpio_base = GPIO_LIQUID_EXPANDER_BASE,
.oscio_is_gpo = false,
.io_pullup_ena = 0x0c08,
.io_pulldn_ena = 0x4060,
.io_open_drain_ena = 0x000c,
.io_polarity = 0,
.irq_summary = -1,
},
};
#endif
#define MSM_PMEM_ADSP_SIZE 0x7800000
#define MSM_PMEM_AUDIO_SIZE 0x4CF000
#define MSM_PMEM_SIZE 0x2800000 /* 40 Mbytes */
#define MSM_LIQUID_PMEM_SIZE 0x4000000 /* 64 Mbytes */
#define MSM_HDMI_PRIM_PMEM_SIZE 0x4000000 /* 64 Mbytes */
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
#define HOLE_SIZE 0x20000
#define MSM_CONTIG_MEM_SIZE 0x65000
#ifdef CONFIG_MSM_IOMMU
#define MSM_ION_MM_SIZE 0x3800000 /* Need to be multiple of 64K */
#define MSM_ION_SF_SIZE 0x0
#define MSM_ION_QSECOM_SIZE 0x780000 /* (7.5MB) */
#define MSM_ION_HEAP_NUM 8
#else
#define MSM_ION_MM_SIZE MSM_PMEM_ADSP_SIZE
#define MSM_ION_SF_SIZE MSM_PMEM_SIZE
#define MSM_ION_QSECOM_SIZE 0x600000 /* (6MB) */
#define MSM_ION_HEAP_NUM 8
#endif
#define MSM_ION_MM_FW_SIZE (0x200000 - HOLE_SIZE) /* 128kb */
#define MSM_ION_MFC_SIZE SZ_8K
#define MSM_ION_AUDIO_SIZE MSM_PMEM_AUDIO_SIZE
#define MSM_LIQUID_ION_MM_SIZE (MSM_ION_MM_SIZE + 0x600000)
#define MSM_LIQUID_ION_SF_SIZE MSM_LIQUID_PMEM_SIZE
#define MSM_HDMI_PRIM_ION_SF_SIZE MSM_HDMI_PRIM_PMEM_SIZE
#define MSM_MM_FW_SIZE (0x200000 - HOLE_SIZE) /* 2mb -128kb*/
#define MSM8960_FIXED_AREA_START (0xa0000000 - (MSM_ION_MM_FW_SIZE + \
HOLE_SIZE))
#define MAX_FIXED_AREA_SIZE 0x10000000
#define MSM8960_FW_START MSM8960_FIXED_AREA_START
#define MSM_ION_ADSP_SIZE SZ_8M
static unsigned msm_ion_sf_size = MSM_ION_SF_SIZE;
#else
#define MSM_CONTIG_MEM_SIZE 0x110C000
#define MSM_ION_HEAP_NUM 1
#endif
#ifdef CONFIG_KERNEL_MSM_CONTIG_MEM_REGION
static unsigned msm_contig_mem_size = MSM_CONTIG_MEM_SIZE;
static int __init msm_contig_mem_size_setup(char *p)
{
msm_contig_mem_size = memparse(p, NULL);
return 0;
}
early_param("msm_contig_mem_size", msm_contig_mem_size_setup);
#endif
#ifdef CONFIG_ANDROID_PMEM
static unsigned pmem_size = MSM_PMEM_SIZE;
static unsigned pmem_param_set;
static int __init pmem_size_setup(char *p)
{
pmem_size = memparse(p, NULL);
pmem_param_set = 1;
return 0;
}
early_param("pmem_size", pmem_size_setup);
static unsigned pmem_adsp_size = MSM_PMEM_ADSP_SIZE;
static int __init pmem_adsp_size_setup(char *p)
{
pmem_adsp_size = memparse(p, NULL);
return 0;
}
early_param("pmem_adsp_size", pmem_adsp_size_setup);
static unsigned pmem_audio_size = MSM_PMEM_AUDIO_SIZE;
static int __init pmem_audio_size_setup(char *p)
{
pmem_audio_size = memparse(p, NULL);
return 0;
}
early_param("pmem_audio_size", pmem_audio_size_setup);
#endif
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
static struct android_pmem_platform_data android_pmem_pdata = {
.name = "pmem",
.allocator_type = PMEM_ALLOCATORTYPE_ALLORNOTHING,
.cached = 1,
.memory_type = MEMTYPE_EBI1,
};
static struct platform_device msm8960_android_pmem_device = {
.name = "android_pmem",
.id = 0,
.dev = {.platform_data = &android_pmem_pdata},
};
static struct android_pmem_platform_data android_pmem_adsp_pdata = {
.name = "pmem_adsp",
.allocator_type = PMEM_ALLOCATORTYPE_BITMAP,
.cached = 0,
.memory_type = MEMTYPE_EBI1,
};
static struct platform_device msm8960_android_pmem_adsp_device = {
.name = "android_pmem",
.id = 2,
.dev = { .platform_data = &android_pmem_adsp_pdata },
};
static struct android_pmem_platform_data android_pmem_audio_pdata = {
.name = "pmem_audio",
.allocator_type = PMEM_ALLOCATORTYPE_BITMAP,
.cached = 0,
.memory_type = MEMTYPE_EBI1,
};
static struct platform_device msm8960_android_pmem_audio_device = {
.name = "android_pmem",
.id = 4,
.dev = { .platform_data = &android_pmem_audio_pdata },
};
#endif /*CONFIG_MSM_MULTIMEDIA_USE_ION*/
#endif /*CONFIG_ANDROID_PMEM*/
struct fmem_platform_data msm8960_fmem_pdata = {
};
#define DSP_RAM_BASE_8960 0x8da00000
#define DSP_RAM_SIZE_8960 0x1800000
static int dspcrashd_pdata_8960 = 0xDEADDEAD;
static struct resource resources_dspcrashd_8960[] = {
{
.name = "msm_dspcrashd",
.start = DSP_RAM_BASE_8960,
.end = DSP_RAM_BASE_8960 + DSP_RAM_SIZE_8960,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device msm_device_dspcrashd_8960 = {
.name = "msm_dspcrashd",
.num_resources = ARRAY_SIZE(resources_dspcrashd_8960),
.resource = resources_dspcrashd_8960,
.dev = { .platform_data = &dspcrashd_pdata_8960 },
};
static struct memtype_reserve msm8960_reserve_table[] __initdata = {
[MEMTYPE_SMI] = {
},
[MEMTYPE_EBI0] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
[MEMTYPE_EBI1] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
};
static void __init reserve_rtb_memory(void)
{
#if defined(CONFIG_MSM_RTB)
msm8960_reserve_table[MEMTYPE_EBI1].size += msm8960_rtb_pdata.size;
#endif
}
static void __init size_pmem_devices(void)
{
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
android_pmem_adsp_pdata.size = pmem_adsp_size;
if (!pmem_param_set) {
if (machine_is_msm8960_liquid())
pmem_size = MSM_LIQUID_PMEM_SIZE;
if (msm8960_hdmi_as_primary_selected())
pmem_size = MSM_HDMI_PRIM_PMEM_SIZE;
}
android_pmem_pdata.size = pmem_size;
android_pmem_audio_pdata.size = MSM_PMEM_AUDIO_SIZE;
#endif /*CONFIG_MSM_MULTIMEDIA_USE_ION*/
#endif /*CONFIG_ANDROID_PMEM*/
}
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
static void __init reserve_memory_for(struct android_pmem_platform_data *p)
{
msm8960_reserve_table[p->memory_type].size += p->size;
}
#endif /*CONFIG_MSM_MULTIMEDIA_USE_ION*/
#endif /*CONFIG_ANDROID_PMEM*/
static void __init reserve_pmem_memory(void)
{
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
reserve_memory_for(&android_pmem_adsp_pdata);
reserve_memory_for(&android_pmem_pdata);
reserve_memory_for(&android_pmem_audio_pdata);
#endif
msm8960_reserve_table[MEMTYPE_EBI1].size += msm_contig_mem_size;
#endif
}
static int msm8960_paddr_to_memtype(unsigned int paddr)
{
return MEMTYPE_EBI1;
}
#define FMEM_ENABLED 0
#ifdef CONFIG_ION_MSM
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
static struct ion_cp_heap_pdata cp_mm_msm8960_ion_pdata = {
.permission_type = IPT_TYPE_MM_CARVEOUT,
.align = SZ_64K,
.reusable = FMEM_ENABLED,
.mem_is_fmem = FMEM_ENABLED,
.fixed_position = FIXED_MIDDLE,
.iommu_map_all = 1,
.iommu_2x_map_domain = VIDEO_DOMAIN,
.is_cma = 1,
.no_nonsecure_alloc = 1,
};
static struct ion_cp_heap_pdata cp_mfc_msm8960_ion_pdata = {
.permission_type = IPT_TYPE_MFC_SHAREDMEM,
.align = PAGE_SIZE,
.reusable = 0,
.mem_is_fmem = FMEM_ENABLED,
.fixed_position = FIXED_HIGH,
.no_nonsecure_alloc = 1,
};
static struct ion_co_heap_pdata co_msm8960_ion_pdata = {
.adjacent_mem_id = INVALID_HEAP_ID,
.align = PAGE_SIZE,
.mem_is_fmem = 0,
};
static struct ion_co_heap_pdata fw_co_msm8960_ion_pdata = {
.adjacent_mem_id = ION_CP_MM_HEAP_ID,
.align = SZ_128K,
.mem_is_fmem = FMEM_ENABLED,
.fixed_position = FIXED_LOW,
};
#endif
static u64 msm_dmamask = DMA_BIT_MASK(32);
static struct platform_device ion_mm_heap_device = {
.name = "ion-mm-heap-device",
.id = -1,
.dev = {
.dma_mask = &msm_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
}
};
static struct platform_device ion_adsp_heap_device = {
.name = "ion-adsp-heap-device",
.id = -1,
.dev = {
.dma_mask = &msm_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
}
};
/**
* These heaps are listed in the order they will be allocated. Due to
* video hardware restrictions and content protection the FW heap has to
* be allocated adjacent (below) the MM heap and the MFC heap has to be
* allocated after the MM heap to ensure MFC heap is not more than 256MB
* away from the base address of the FW heap.
* However, the order of FW heap and MM heap doesn't matter since these
* two heaps are taken care of by separate code to ensure they are adjacent
* to each other.
* Don't swap the order unless you know what you are doing!
*/
struct ion_platform_heap msm8960_heaps[] = {
{
.id = ION_SYSTEM_HEAP_ID,
.type = ION_HEAP_TYPE_SYSTEM,
.name = ION_VMALLOC_HEAP_NAME,
},
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
{
.id = ION_CP_MM_HEAP_ID,
.type = ION_HEAP_TYPE_CP,
.name = ION_MM_HEAP_NAME,
.size = MSM_ION_MM_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &cp_mm_msm8960_ion_pdata,
.priv = &ion_mm_heap_device.dev,
},
{
.id = ION_MM_FIRMWARE_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_MM_FIRMWARE_HEAP_NAME,
.size = MSM_ION_MM_FW_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &fw_co_msm8960_ion_pdata,
},
{
.id = ION_CP_MFC_HEAP_ID,
.type = ION_HEAP_TYPE_CP,
.name = ION_MFC_HEAP_NAME,
.size = MSM_ION_MFC_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &cp_mfc_msm8960_ion_pdata,
},
#ifndef CONFIG_MSM_IOMMU
{
.id = ION_SF_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_SF_HEAP_NAME,
.size = MSM_ION_SF_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &co_msm8960_ion_pdata,
},
#endif
{
.id = ION_IOMMU_HEAP_ID,
.type = ION_HEAP_TYPE_IOMMU,
.name = ION_IOMMU_HEAP_NAME,
},
{
.id = ION_QSECOM_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_QSECOM_HEAP_NAME,
.size = MSM_ION_QSECOM_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &co_msm8960_ion_pdata,
},
{
.id = ION_AUDIO_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_AUDIO_HEAP_NAME,
.size = MSM_ION_AUDIO_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &co_msm8960_ion_pdata,
},
{
.id = ION_ADSP_HEAP_ID,
.type = ION_HEAP_TYPE_DMA,
.name = ION_ADSP_HEAP_NAME,
.size = MSM_ION_ADSP_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &co_msm8960_ion_pdata,
.priv = &ion_adsp_heap_device.dev,
},
#endif
};
static struct ion_platform_data msm8960_ion_pdata = {
.nr = MSM_ION_HEAP_NUM,
.heaps = msm8960_heaps,
};
static struct platform_device msm8960_ion_dev = {
.name = "ion-msm",
.id = 1,
.dev = { .platform_data = &msm8960_ion_pdata },
};
#endif
struct platform_device msm8960_fmem_device = {
.name = "fmem",
.id = 1,
.dev = { .platform_data = &msm8960_fmem_pdata },
};
static void __init adjust_mem_for_liquid(void)
{
unsigned int i;
if (!pmem_param_set) {
if (machine_is_msm8960_liquid())
msm_ion_sf_size = MSM_LIQUID_ION_SF_SIZE;
if (msm8960_hdmi_as_primary_selected())
msm_ion_sf_size = MSM_HDMI_PRIM_ION_SF_SIZE;
if (machine_is_msm8960_liquid() ||
msm8960_hdmi_as_primary_selected()) {
for (i = 0; i < msm8960_ion_pdata.nr; i++) {
if (msm8960_ion_pdata.heaps[i].id ==
ION_SF_HEAP_ID) {
msm8960_ion_pdata.heaps[i].size =
msm_ion_sf_size;
pr_debug("msm_ion_sf_size 0x%x\n",
msm_ion_sf_size);
break;
}
}
}
}
}
static void __init reserve_mem_for_ion(enum ion_memory_types mem_type,
unsigned long size)
{
msm8960_reserve_table[mem_type].size += size;
}
static void __init msm8960_reserve_fixed_area(unsigned long fixed_area_size)
{
#if defined(CONFIG_ION_MSM) && defined(CONFIG_MSM_MULTIMEDIA_USE_ION)
int ret;
if (fixed_area_size > MAX_FIXED_AREA_SIZE)
panic("fixed area size is larger than %dM\n",
MAX_FIXED_AREA_SIZE >> 20);
reserve_info->fixed_area_size = fixed_area_size;
reserve_info->fixed_area_start = MSM8960_FW_START;
ret = memblock_remove(reserve_info->fixed_area_start,
reserve_info->fixed_area_size);
BUG_ON(ret);
#endif
}
/**
* Reserve memory for ION and calculate amount of reusable memory for fmem.
* We only reserve memory for heaps that are not reusable. However, we only
* support one reusable heap at the moment so we ignore the reusable flag for
* other than the first heap with reusable flag set. Also handle special case
* for video heaps (MM,FW, and MFC). Video requires heaps MM and MFC to be
* at a higher address than FW in addition to not more than 256MB away from the
* base address of the firmware. This means that if MM is reusable the other
* two heaps must be allocated in the same region as FW. This is handled by the
* mem_is_fmem flag in the platform data. In addition the MM heap must be
* adjacent to the FW heap for content protection purposes.
*/
static void __init reserve_ion_memory(void)
{
#if defined(CONFIG_ION_MSM) && defined(CONFIG_MSM_MULTIMEDIA_USE_ION)
unsigned int i;
int ret;
unsigned int fixed_size = 0;
unsigned int fixed_low_size, fixed_middle_size, fixed_high_size;
unsigned long fixed_low_start, fixed_middle_start, fixed_high_start;
unsigned long cma_alignment;
unsigned int low_use_cma = 0;
unsigned int middle_use_cma = 0;
unsigned int high_use_cma = 0;
adjust_mem_for_liquid();
fixed_low_size = 0;
fixed_middle_size = 0;
fixed_high_size = 0;
cma_alignment = PAGE_SIZE << max(MAX_ORDER, pageblock_order);
for (i = 0; i < msm8960_ion_pdata.nr; ++i) {
struct ion_platform_heap *heap =
&(msm8960_ion_pdata.heaps[i]);
int align = SZ_4K;
int iommu_map_all = 0;
int adjacent_mem_id = INVALID_HEAP_ID;
int use_cma = 0;
if (heap->extra_data) {
int fixed_position = NOT_FIXED;
switch ((int) heap->type) {
case ION_HEAP_TYPE_CP:
fixed_position = ((struct ion_cp_heap_pdata *)
heap->extra_data)->fixed_position;
align = ((struct ion_cp_heap_pdata *)
heap->extra_data)->align;
iommu_map_all =
((struct ion_cp_heap_pdata *)
heap->extra_data)->iommu_map_all;
if (((struct ion_cp_heap_pdata *)
heap->extra_data)->is_cma) {
heap->size = ALIGN(heap->size,
cma_alignment);
use_cma = 1;
}
break;
case ION_HEAP_TYPE_DMA:
use_cma = 1;
/* Purposely fall through here */
case ION_HEAP_TYPE_CARVEOUT:
fixed_position = ((struct ion_co_heap_pdata *)
heap->extra_data)->fixed_position;
adjacent_mem_id = ((struct ion_co_heap_pdata *)
heap->extra_data)->adjacent_mem_id;
break;
default:
break;
}
if (iommu_map_all) {
if (heap->size & (SZ_64K-1)) {
heap->size = ALIGN(heap->size, SZ_64K);
pr_info("Heap %s not aligned to 64K. Adjusting size to %x\n",
heap->name, heap->size);
}
}
if (fixed_position != NOT_FIXED)
fixed_size += heap->size;
else
reserve_mem_for_ion(MEMTYPE_EBI1, heap->size);
if (fixed_position == FIXED_LOW) {
fixed_low_size += heap->size;
low_use_cma = use_cma;
} else if (fixed_position == FIXED_MIDDLE) {
fixed_middle_size += heap->size;
middle_use_cma = use_cma;
} else if (fixed_position == FIXED_HIGH) {
fixed_high_size += heap->size;
high_use_cma = use_cma;
} else if (use_cma) {
/*
* Heaps that use CMA but are not part of the
* fixed set. Create wherever.
*/
dma_declare_contiguous(
heap->priv,
heap->size,
0,
0xb0000000);
}
}
}
if (!fixed_size)
return;
/*
* Given the setup for the fixed area, we can't round up all sizes.
* Some sizes must be set up exactly and aligned correctly. Incorrect
* alignments are considered a configuration issue
*/
fixed_low_start = MSM8960_FIXED_AREA_START;
if (low_use_cma) {
BUG_ON(!IS_ALIGNED(fixed_low_start, cma_alignment));
BUG_ON(!IS_ALIGNED(fixed_low_size + HOLE_SIZE, cma_alignment));
} else {
BUG_ON(!IS_ALIGNED(fixed_low_size + HOLE_SIZE, SECTION_SIZE));
ret = memblock_remove(fixed_low_start,
fixed_low_size + HOLE_SIZE);
BUG_ON(ret);
}
fixed_middle_start = fixed_low_start + fixed_low_size + HOLE_SIZE;
if (middle_use_cma) {
BUG_ON(!IS_ALIGNED(fixed_middle_start, cma_alignment));
BUG_ON(!IS_ALIGNED(fixed_middle_size, cma_alignment));
} else {
BUG_ON(!IS_ALIGNED(fixed_middle_size, SECTION_SIZE));
ret = memblock_remove(fixed_middle_start, fixed_middle_size);
BUG_ON(ret);
}
fixed_high_start = fixed_middle_start + fixed_middle_size;
if (high_use_cma) {
fixed_high_size = ALIGN(fixed_high_size, cma_alignment);
BUG_ON(!IS_ALIGNED(fixed_high_start, cma_alignment));
} else {
/* This is the end of the fixed area so it's okay to round up */
fixed_high_size = ALIGN(fixed_high_size, SECTION_SIZE);
ret = memblock_remove(fixed_high_start, fixed_high_size);
BUG_ON(ret);
}
for (i = 0; i < msm8960_ion_pdata.nr; ++i) {
struct ion_platform_heap *heap = &(msm8960_ion_pdata.heaps[i]);
if (heap->extra_data) {
int fixed_position = NOT_FIXED;
struct ion_cp_heap_pdata *pdata = NULL;
switch ((int) heap->type) {
case ION_HEAP_TYPE_CP:
pdata =
(struct ion_cp_heap_pdata *)heap->extra_data;
fixed_position = pdata->fixed_position;
break;
case ION_HEAP_TYPE_CARVEOUT:
case ION_HEAP_TYPE_DMA:
fixed_position = ((struct ion_co_heap_pdata *)
heap->extra_data)->fixed_position;
break;
default:
break;
}
switch (fixed_position) {
case FIXED_LOW:
heap->base = fixed_low_start;
break;
case FIXED_MIDDLE:
heap->base = fixed_middle_start;
if (middle_use_cma) {
ret = dma_declare_contiguous(
&ion_mm_heap_device.dev,
heap->size,
fixed_middle_start,
0xa0000000);
WARN_ON(ret);
}
pdata->secure_base = fixed_middle_start
- HOLE_SIZE;
pdata->secure_size = HOLE_SIZE + heap->size;
break;
case FIXED_HIGH:
heap->base = fixed_high_start;
break;
default:
break;
}
}
}
#endif
}
static void ion_adjust_secure_allocation(void)
{
int i;
for (i = 0; i < msm8960_ion_pdata.nr; i++) {
struct ion_platform_heap *heap =
&(msm8960_ion_pdata.heaps[i]);
if (heap->extra_data) {
switch ((int) heap->type) {
case ION_HEAP_TYPE_CP:
if (cpu_is_msm8960()) {
((struct ion_cp_heap_pdata *)
heap->extra_data)->no_nonsecure_alloc =
0;
}
}
}
}
}
static void __init reserve_mdp_memory(void)
{
msm8960_mdp_writeback(msm8960_reserve_table);
}
static void __init reserve_cache_dump_memory(void)
{
#ifdef CONFIG_MSM_CACHE_DUMP
unsigned int total;
total = msm8960_cache_dump_pdata.l1_size +
msm8960_cache_dump_pdata.l2_size;
msm8960_reserve_table[MEMTYPE_EBI1].size += total;
#endif
}
static void __init msm8960_calculate_reserve_sizes(void)
{
size_pmem_devices();
reserve_pmem_memory();
reserve_ion_memory();
reserve_mdp_memory();
reserve_rtb_memory();
reserve_cache_dump_memory();
}
static struct reserve_info msm8960_reserve_info __initdata = {
.memtype_reserve_table = msm8960_reserve_table,
.calculate_reserve_sizes = msm8960_calculate_reserve_sizes,
.reserve_fixed_area = msm8960_reserve_fixed_area,
.paddr_to_memtype = msm8960_paddr_to_memtype,
};
static void __init msm8960_early_memory(void)
{
reserve_info = &msm8960_reserve_info;
}
static char prim_panel_name[PANEL_NAME_MAX_LEN];
static char ext_panel_name[PANEL_NAME_MAX_LEN];
static int __init prim_display_setup(char *param)
{
if (strnlen(param, PANEL_NAME_MAX_LEN))
strlcpy(prim_panel_name, param, PANEL_NAME_MAX_LEN);
return 0;
}
early_param("prim_display", prim_display_setup);
static int __init ext_display_setup(char *param)
{
if (strnlen(param, PANEL_NAME_MAX_LEN))
strlcpy(ext_panel_name, param, PANEL_NAME_MAX_LEN);
return 0;
}
early_param("ext_display", ext_display_setup);
static void __init msm8960_reserve(void)
{
msm8960_set_display_params(prim_panel_name, ext_panel_name);
msm_reserve();
}
static void __init msm8960_allocate_memory_regions(void)
{
msm8960_allocate_fb_region();
}
#ifdef CONFIG_WCD9310_CODEC
#define TABLA_INTERRUPT_BASE (NR_MSM_IRQS + NR_GPIO_IRQS + NR_PM8921_IRQS)
/* Micbias setting is based on 8660 CDP/MTP/FLUID requirement
* 4 micbiases are used to power various analog and digital
* microphones operating at 1800 mV. Technically, all micbiases
* can source from single cfilter since all microphones operate
* at the same voltage level. The arrangement below is to make
* sure all cfilters are exercised. LDO_H regulator ouput level
* does not need to be as high as 2.85V. It is choosen for
* microphone sensitivity purpose.
*/
static struct wcd9xxx_pdata tabla_platform_data = {
.slimbus_slave_device = {
.name = "tabla-slave",
.e_addr = {0, 0, 0x10, 0, 0x17, 2},
},
.irq = MSM_GPIO_TO_INT(62),
.irq_base = TABLA_INTERRUPT_BASE,
.num_irqs = NR_WCD9XXX_IRQS,
.reset_gpio = PM8921_GPIO_PM_TO_SYS(34),
.micbias = {
.ldoh_v = TABLA_LDOH_2P85_V,
.cfilt1_mv = 1800,
.cfilt2_mv = 2700,
.cfilt3_mv = 1800,
.bias1_cfilt_sel = TABLA_CFILT1_SEL,
.bias2_cfilt_sel = TABLA_CFILT2_SEL,
.bias3_cfilt_sel = TABLA_CFILT3_SEL,
.bias4_cfilt_sel = TABLA_CFILT3_SEL,
},
.regulator = {
{
.name = "CDC_VDD_CP",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_CP_CUR_MAX,
},
{
.name = "CDC_VDDA_RX",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_RX_CUR_MAX,
},
{
.name = "CDC_VDDA_TX",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_TX_CUR_MAX,
},
{
.name = "VDDIO_CDC",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_VDDIO_CDC_CUR_MAX,
},
{
.name = "VDDD_CDC_D",
.min_uV = 1225000,
.max_uV = 1250000,
.optimum_uA = WCD9XXX_VDDD_CDC_D_CUR_MAX,
},
{
.name = "CDC_VDDA_A_1P2V",
.min_uV = 1225000,
.max_uV = 1250000,
.optimum_uA = WCD9XXX_VDDD_CDC_A_CUR_MAX,
},
},
};
static struct slim_device msm_slim_tabla = {
.name = "tabla-slim",
.e_addr = {0, 1, 0x10, 0, 0x17, 2},
.dev = {
.platform_data = &tabla_platform_data,
},
};
static struct wcd9xxx_pdata tabla20_platform_data = {
.slimbus_slave_device = {
.name = "tabla-slave",
.e_addr = {0, 0, 0x60, 0, 0x17, 2},
},
.irq = MSM_GPIO_TO_INT(62),
.irq_base = TABLA_INTERRUPT_BASE,
.num_irqs = NR_WCD9XXX_IRQS,
.reset_gpio = PM8921_GPIO_PM_TO_SYS(34),
.micbias = {
.ldoh_v = TABLA_LDOH_2P85_V,
.cfilt1_mv = 1800,
.cfilt2_mv = 2700,
.cfilt3_mv = 1800,
.bias1_cfilt_sel = TABLA_CFILT1_SEL,
.bias2_cfilt_sel = TABLA_CFILT2_SEL,
.bias3_cfilt_sel = TABLA_CFILT3_SEL,
.bias4_cfilt_sel = TABLA_CFILT3_SEL,
},
.regulator = {
{
.name = "CDC_VDD_CP",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_CP_CUR_MAX,
},
{
.name = "CDC_VDDA_RX",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_RX_CUR_MAX,
},
{
.name = "CDC_VDDA_TX",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_TX_CUR_MAX,
},
{
.name = "VDDIO_CDC",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_VDDIO_CDC_CUR_MAX,
},
{
.name = "VDDD_CDC_D",
.min_uV = 1225000,
.max_uV = 1250000,
.optimum_uA = WCD9XXX_VDDD_CDC_D_CUR_MAX,
},
{
.name = "CDC_VDDA_A_1P2V",
.min_uV = 1225000,
.max_uV = 1250000,
.optimum_uA = WCD9XXX_VDDD_CDC_A_CUR_MAX,
},
},
};
static struct slim_device msm_slim_tabla20 = {
.name = "tabla2x-slim",
.e_addr = {0, 1, 0x60, 0, 0x17, 2},
.dev = {
.platform_data = &tabla20_platform_data,
},
};
#endif
static struct slim_boardinfo msm_slim_devices[] = {
#ifdef CONFIG_WCD9310_CODEC
{
.bus_num = 1,
.slim_slave = &msm_slim_tabla,
},
{
.bus_num = 1,
.slim_slave = &msm_slim_tabla20,
},
#endif
/* add more slimbus slaves as needed */
};
#define MSM_WCNSS_PHYS 0x03000000
#define MSM_WCNSS_SIZE 0x280000
static struct resource resources_wcnss_wlan[] = {
{
.start = RIVA_APPS_WLAN_RX_DATA_AVAIL_IRQ,
.end = RIVA_APPS_WLAN_RX_DATA_AVAIL_IRQ,
.name = "wcnss_wlanrx_irq",
.flags = IORESOURCE_IRQ,
},
{
.start = RIVA_APPS_WLAN_DATA_XFER_DONE_IRQ,
.end = RIVA_APPS_WLAN_DATA_XFER_DONE_IRQ,
.name = "wcnss_wlantx_irq",
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_WCNSS_PHYS,
.end = MSM_WCNSS_PHYS + MSM_WCNSS_SIZE - 1,
.name = "wcnss_mmio",
.flags = IORESOURCE_MEM,
},
{
.start = 84,
.end = 88,
.name = "wcnss_gpios_5wire",
.flags = IORESOURCE_IO,
},
};
static struct qcom_wcnss_opts qcom_wcnss_pdata = {
.has_48mhz_xo = 1,
};
static struct platform_device msm_device_wcnss_wlan = {
.name = "wcnss_wlan",
.id = 0,
.num_resources = ARRAY_SIZE(resources_wcnss_wlan),
.resource = resources_wcnss_wlan,
.dev = {.platform_data = &qcom_wcnss_pdata},
};
#ifdef CONFIG_QSEECOM
/* qseecom bus scaling */
static struct msm_bus_vectors qseecom_clks_init_vectors[] = {
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ib = 0,
.ab = 0,
},
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_SPS,
.ib = 0,
.ab = 0,
},
{
.src = MSM_BUS_MASTER_SPDM,
.dst = MSM_BUS_SLAVE_SPDM,
.ib = 0,
.ab = 0,
},
};
static struct msm_bus_vectors qseecom_enable_dfab_vectors[] = {
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ib = (492 * 8) * 1000000UL,
.ab = (492 * 8) * 100000UL,
},
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_SPS,
.ib = (492 * 8) * 1000000UL,
.ab = (492 * 8) * 100000UL,
},
{
.src = MSM_BUS_MASTER_SPDM,
.dst = MSM_BUS_SLAVE_SPDM,
.ib = 0,
.ab = 0,
},
};
static struct msm_bus_vectors qseecom_enable_sfpb_vectors[] = {
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ib = 0,
.ab = 0,
},
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_SPS,
.ib = 0,
.ab = 0,
},
{
.src = MSM_BUS_MASTER_SPDM,
.dst = MSM_BUS_SLAVE_SPDM,
.ib = (64 * 8) * 1000000UL,
.ab = (64 * 8) * 100000UL,
},
};
static struct msm_bus_vectors qseecom_enable_dfab_sfpb_vectors[] = {
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ib = (492 * 8) * 1000000UL,
.ab = (492 * 8) * 100000UL,
},
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_SPS,
.ib = (492 * 8) * 1000000UL,
.ab = (492 * 8) * 100000UL,
},
{
.src = MSM_BUS_MASTER_SPDM,
.dst = MSM_BUS_SLAVE_SPDM,
.ib = (64 * 8) * 1000000UL,
.ab = (64 * 8) * 100000UL,
},
};
static struct msm_bus_paths qseecom_hw_bus_scale_usecases[] = {
{
ARRAY_SIZE(qseecom_clks_init_vectors),
qseecom_clks_init_vectors,
},
{
ARRAY_SIZE(qseecom_enable_dfab_vectors),
qseecom_enable_dfab_vectors,
},
{
ARRAY_SIZE(qseecom_enable_sfpb_vectors),
qseecom_enable_sfpb_vectors,
},
{
ARRAY_SIZE(qseecom_enable_dfab_sfpb_vectors),
qseecom_enable_dfab_sfpb_vectors,
},
};
static struct msm_bus_scale_pdata qseecom_bus_pdata = {
qseecom_hw_bus_scale_usecases,
ARRAY_SIZE(qseecom_hw_bus_scale_usecases),
.name = "qsee",
};
static struct platform_device qseecom_device = {
.name = "qseecom",
.id = 0,
.dev = {
.platform_data = &qseecom_bus_pdata,
},
};
#endif
#if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \
defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE)
#define QCE_SIZE 0x10000
#define QCE_0_BASE 0x18500000
#define QCE_HW_KEY_SUPPORT 0
#define QCE_SHA_HMAC_SUPPORT 1
#define QCE_SHARE_CE_RESOURCE 1
#define QCE_CE_SHARED 0
/* Begin Bus scaling definitions */
static struct msm_bus_vectors crypto_hw_init_vectors[] = {
{
.src = MSM_BUS_MASTER_ADM_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_ADM_PORT1,
.dst = MSM_BUS_SLAVE_GSBI1_UART,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors crypto_hw_active_vectors[] = {
{
.src = MSM_BUS_MASTER_ADM_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 70000000UL,
.ib = 70000000UL,
},
{
.src = MSM_BUS_MASTER_ADM_PORT1,
.dst = MSM_BUS_SLAVE_GSBI1_UART,
.ab = 2480000000UL,
.ib = 2480000000UL,
},
};
static struct msm_bus_paths crypto_hw_bus_scale_usecases[] = {
{
ARRAY_SIZE(crypto_hw_init_vectors),
crypto_hw_init_vectors,
},
{
ARRAY_SIZE(crypto_hw_active_vectors),
crypto_hw_active_vectors,
},
};
static struct msm_bus_scale_pdata crypto_hw_bus_scale_pdata = {
crypto_hw_bus_scale_usecases,
ARRAY_SIZE(crypto_hw_bus_scale_usecases),
.name = "cryptohw",
};
/* End Bus Scaling Definitions*/
static struct resource qcrypto_resources[] = {
[0] = {
.start = QCE_0_BASE,
.end = QCE_0_BASE + QCE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "crypto_channels",
.start = DMOV_CE_IN_CHAN,
.end = DMOV_CE_OUT_CHAN,
.flags = IORESOURCE_DMA,
},
[2] = {
.name = "crypto_crci_in",
.start = DMOV_CE_IN_CRCI,
.end = DMOV_CE_IN_CRCI,
.flags = IORESOURCE_DMA,
},
[3] = {
.name = "crypto_crci_out",
.start = DMOV_CE_OUT_CRCI,
.end = DMOV_CE_OUT_CRCI,
.flags = IORESOURCE_DMA,
},
};
static struct resource qcedev_resources[] = {
[0] = {
.start = QCE_0_BASE,
.end = QCE_0_BASE + QCE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "crypto_channels",
.start = DMOV_CE_IN_CHAN,
.end = DMOV_CE_OUT_CHAN,
.flags = IORESOURCE_DMA,
},
[2] = {
.name = "crypto_crci_in",
.start = DMOV_CE_IN_CRCI,
.end = DMOV_CE_IN_CRCI,
.flags = IORESOURCE_DMA,
},
[3] = {
.name = "crypto_crci_out",
.start = DMOV_CE_OUT_CRCI,
.end = DMOV_CE_OUT_CRCI,
.flags = IORESOURCE_DMA,
},
};
#endif
#if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \
defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE)
static struct msm_ce_hw_support qcrypto_ce_hw_suppport = {
.ce_shared = QCE_CE_SHARED,
.shared_ce_resource = QCE_SHARE_CE_RESOURCE,
.hw_key_support = QCE_HW_KEY_SUPPORT,
.sha_hmac = QCE_SHA_HMAC_SUPPORT,
.bus_scale_table = &crypto_hw_bus_scale_pdata,
};
static struct platform_device qcrypto_device = {
.name = "qcrypto",
.id = 0,
.num_resources = ARRAY_SIZE(qcrypto_resources),
.resource = qcrypto_resources,
.dev = {
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &qcrypto_ce_hw_suppport,
},
};
#endif
#if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE)
static struct msm_ce_hw_support qcedev_ce_hw_suppport = {
.ce_shared = QCE_CE_SHARED,
.shared_ce_resource = QCE_SHARE_CE_RESOURCE,
.hw_key_support = QCE_HW_KEY_SUPPORT,
.sha_hmac = QCE_SHA_HMAC_SUPPORT,
.bus_scale_table = &crypto_hw_bus_scale_pdata,
};
static struct platform_device qcedev_device = {
.name = "qce",
.id = 0,
.num_resources = ARRAY_SIZE(qcedev_resources),
.resource = qcedev_resources,
.dev = {
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &qcedev_ce_hw_suppport,
},
};
#endif
static struct mdm_platform_data sglte_platform_data = {
.mdm_version = "4.0",
.ramdump_delay_ms = 1000,
.soft_reset_inverted = 1,
.peripheral_platform_device = NULL,
.ramdump_timeout_ms = 600000,
.no_powerdown_after_ramdumps = 1,
.image_upgrade_supported = 1,
};
#define MSM_TSIF0_PHYS (0x18200000)
#define MSM_TSIF1_PHYS (0x18201000)
#define MSM_TSIF_SIZE (0x200)
#define MSM_TSPP_PHYS (0x18202000)
#define MSM_TSPP_SIZE (0x1000)
#define MSM_TSPP_BAM_PHYS (0x18204000)
#define MSM_TSPP_BAM_SIZE (0x2000)
#define TSIF_0_CLK GPIO_CFG(75, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_EN GPIO_CFG(76, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_DATA GPIO_CFG(77, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_SYNC GPIO_CFG(82, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_CLK GPIO_CFG(79, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_EN GPIO_CFG(80, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_DATA GPIO_CFG(81, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_SYNC GPIO_CFG(78, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
static const struct msm_gpio tsif_gpios[] = {
{ .gpio_cfg = TSIF_0_CLK, .label = "tsif0_clk", },
{ .gpio_cfg = TSIF_0_EN, .label = "tsif0_en", },
{ .gpio_cfg = TSIF_0_DATA, .label = "tsif0_data", },
{ .gpio_cfg = TSIF_0_SYNC, .label = "tsif0_sync", },
{ .gpio_cfg = TSIF_1_CLK, .label = "tsif1_clk", },
{ .gpio_cfg = TSIF_1_EN, .label = "tsif1_en", },
{ .gpio_cfg = TSIF_1_DATA, .label = "tsif1_data", },
{ .gpio_cfg = TSIF_1_SYNC, .label = "tsif1_sync", },
};
static struct resource tspp_resources[] = {
[0] = {
.name = "TSIF_TSPP_IRQ",
.flags = IORESOURCE_IRQ,
.start = TSIF_TSPP_IRQ,
.end = TSIF_TSPP_IRQ,
},
[1] = {
.name = "TSIF0_IRQ",
.flags = IORESOURCE_IRQ,
.start = TSIF1_IRQ,
.end = TSIF1_IRQ,
},
[2] = {
.name = "TSIF1_IRQ",
.flags = IORESOURCE_IRQ,
.start = TSIF2_IRQ,
.end = TSIF2_IRQ,
},
[3] = {
.name = "TSIF_BAM_IRQ",
.flags = IORESOURCE_IRQ,
.start = TSIF_BAM_IRQ,
.end = TSIF_BAM_IRQ,
},
[4] = {
.name = "MSM_TSIF0_PHYS",
.flags = IORESOURCE_MEM,
.start = MSM_TSIF0_PHYS,
.end = MSM_TSIF0_PHYS + MSM_TSIF_SIZE - 1,
},
[5] = {
.name = "MSM_TSIF1_PHYS",
.flags = IORESOURCE_MEM,
.start = MSM_TSIF1_PHYS,
.end = MSM_TSIF1_PHYS + MSM_TSIF_SIZE - 1,
},
[6] = {
.name = "MSM_TSPP_PHYS",
.flags = IORESOURCE_MEM,
.start = MSM_TSPP_PHYS,
.end = MSM_TSPP_PHYS + MSM_TSPP_SIZE - 1,
},
[7] = {
.name = "MSM_TSPP_BAM_PHYS",
.flags = IORESOURCE_MEM,
.start = MSM_TSPP_BAM_PHYS,
.end = MSM_TSPP_BAM_PHYS + MSM_TSPP_BAM_SIZE - 1,
},
};
static struct msm_tspp_platform_data tspp_platform_data = {
.num_gpios = ARRAY_SIZE(tsif_gpios),
.gpios = tsif_gpios,
.tsif_pclk = "tsif_pclk",
.tsif_ref_clk = "tsif_ref_clk",
};
static struct platform_device msm_device_tspp = {
.name = "msm_tspp",
.id = 0,
.num_resources = ARRAY_SIZE(tspp_resources),
.resource = tspp_resources,
.dev = {
.platform_data = &tspp_platform_data
},
};
#define MSM_SHARED_RAM_PHYS 0x80000000
static void __init msm8960_map_io(void)
{
msm_shared_ram_phys = MSM_SHARED_RAM_PHYS;
msm_map_msm8960_io();
if (socinfo_init() < 0)
pr_err("socinfo_init() failed!\n");
}
static void __init msm8960_init_irq(void)
{
struct msm_mpm_device_data *data = NULL;
#ifdef CONFIG_MSM_MPM
data = &msm8960_mpm_dev_data;
#endif
msm_mpm_irq_extn_init(data);
gic_init(0, GIC_PPI_START, MSM_QGIC_DIST_BASE,
(void *)MSM_QGIC_CPU_BASE);
}
static void __init msm8960_init_buses(void)
{
#ifdef CONFIG_MSM_BUS_SCALING
msm_bus_rpm_set_mt_mask();
msm_bus_8960_apps_fabric_pdata.rpm_enabled = 1;
msm_bus_8960_sys_fabric_pdata.rpm_enabled = 1;
msm_bus_apps_fabric.dev.platform_data =
&msm_bus_8960_apps_fabric_pdata;
msm_bus_sys_fabric.dev.platform_data = &msm_bus_8960_sys_fabric_pdata;
if (cpu_is_msm8960ab()) {
msm_bus_8960_sg_mm_fabric_pdata.rpm_enabled = 1;
msm_bus_mm_fabric.dev.platform_data =
&msm_bus_8960_sg_mm_fabric_pdata;
} else {
msm_bus_8960_mm_fabric_pdata.rpm_enabled = 1;
msm_bus_mm_fabric.dev.platform_data =
&msm_bus_8960_mm_fabric_pdata;
}
msm_bus_sys_fpb.dev.platform_data = &msm_bus_8960_sys_fpb_pdata;
msm_bus_cpss_fpb.dev.platform_data = &msm_bus_8960_cpss_fpb_pdata;
#endif
}
static struct msm_spi_platform_data msm8960_qup_spi_gsbi1_pdata = {
.max_clock_speed = 15060000,
.infinite_mode = 0xFFC0,
};
#ifdef CONFIG_USB_MSM_OTG_72K
static struct msm_otg_platform_data msm_otg_pdata;
#else
static int wr_phy_init_seq[] = {
0x44, 0x80, /* set VBUS valid threshold
and disconnect valid threshold */
0x38, 0x81, /* update DC voltage level */
0x14, 0x82, /* set preemphasis and rise/fall time */
0x13, 0x83, /* set source impedance adjusment */
-1};
static int liquid_v1_phy_init_seq[] = {
0x44, 0x80,/* set VBUS valid threshold
and disconnect valid threshold */
0x3C, 0x81,/* update DC voltage level */
0x18, 0x82,/* set preemphasis and rise/fall time */
0x23, 0x83,/* set source impedance sdjusment */
-1};
static int sglte_phy_init_seq[] = {
0x44, 0x80, /* set VBUS valid threshold
and disconnect valid threshold */
0x3A, 0x81, /* update DC voltage level */
0x24, 0x82, /* set preemphasis and rise/fall time */
0x13, 0x83, /* set source impedance adjusment */
-1};
#ifdef CONFIG_MSM_BUS_SCALING
/* Bandwidth requests (zero) if no vote placed */
static struct msm_bus_vectors usb_init_vectors[] = {
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
/* Bus bandwidth requests in Bytes/sec */
static struct msm_bus_vectors usb_max_vectors[] = {
{
.src = MSM_BUS_MASTER_SPS,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 60000000, /* At least 480Mbps on bus. */
.ib = 960000000, /* MAX bursts rate */
},
};
static struct msm_bus_paths usb_bus_scale_usecases[] = {
{
ARRAY_SIZE(usb_init_vectors),
usb_init_vectors,
},
{
ARRAY_SIZE(usb_max_vectors),
usb_max_vectors,
},
};
static struct msm_bus_scale_pdata usb_bus_scale_pdata = {
usb_bus_scale_usecases,
ARRAY_SIZE(usb_bus_scale_usecases),
.name = "usb",
};
#endif
#define MSM_MPM_PIN_USB1_OTGSESSVLD 40
static struct msm_otg_platform_data msm_otg_pdata = {
.mode = USB_OTG,
.otg_control = OTG_PMIC_CONTROL,
.phy_type = SNPS_28NM_INTEGRATED_PHY,
.pmic_id_irq = PM8921_USB_ID_IN_IRQ(PM8921_IRQ_BASE),
.power_budget = 750,
#ifdef CONFIG_MSM_BUS_SCALING
.bus_scale_table = &usb_bus_scale_pdata,
.mpm_otgsessvld_int = MSM_MPM_PIN_USB1_OTGSESSVLD,
#endif
#ifdef CONFIG_FB_MSM_HDMI_MHL_8334
.mhl_dev_name = "sii8334",
#endif
};
#endif
#ifdef CONFIG_USB_EHCI_MSM_HSIC
#define HSIC_HUB_RESET_GPIO 91
static struct msm_hsic_host_platform_data msm_hsic_pdata = {
.strobe = 150,
.data = 151,
};
static struct smsc_hub_platform_data hsic_hub_pdata = {
.hub_reset = HSIC_HUB_RESET_GPIO,
};
#else
static struct msm_hsic_host_platform_data msm_hsic_pdata;
static struct smsc_hub_platform_data hsic_hub_pdata;
#endif
static struct platform_device smsc_hub_device = {
.name = "msm_smsc_hub",
.id = -1,
.dev = {
.platform_data = &hsic_hub_pdata,
},
};
#define PID_MAGIC_ID 0x71432909
#define SERIAL_NUM_MAGIC_ID 0x61945374
#define SERIAL_NUMBER_LENGTH 127
#define DLOAD_USB_BASE_ADD 0x2A03F0C8
struct magic_num_struct {
uint32_t pid;
uint32_t serial_num;
};
struct dload_struct {
uint32_t reserved1;
uint32_t reserved2;
uint32_t reserved3;
uint16_t reserved4;
uint16_t pid;
char serial_number[SERIAL_NUMBER_LENGTH];
uint16_t reserved5;
struct magic_num_struct magic_struct;
};
static int usb_diag_update_pid_and_serial_num(uint32_t pid, const char *snum)
{
struct dload_struct __iomem *dload = 0;
dload = ioremap(DLOAD_USB_BASE_ADD, sizeof(*dload));
if (!dload) {
pr_err("%s: cannot remap I/O memory region: %08x\n",
__func__, DLOAD_USB_BASE_ADD);
return -ENXIO;
}
pr_debug("%s: dload:%p pid:%x serial_num:%s\n",
__func__, dload, pid, snum);
/* update pid */
dload->magic_struct.pid = PID_MAGIC_ID;
dload->pid = pid;
/* update serial number */
dload->magic_struct.serial_num = 0;
if (!snum) {
memset(dload->serial_number, 0, SERIAL_NUMBER_LENGTH);
goto out;
}
dload->magic_struct.serial_num = SERIAL_NUM_MAGIC_ID;
strlcpy(dload->serial_number, snum, SERIAL_NUMBER_LENGTH);
out:
iounmap(dload);
return 0;
}
static struct android_usb_platform_data android_usb_pdata = {
.update_pid_and_serial_num = usb_diag_update_pid_and_serial_num,
};
static struct platform_device android_usb_device = {
.name = "android_usb",
.id = -1,
.dev = {
.platform_data = &android_usb_pdata,
},
};
static uint8_t spm_wfi_cmd_sequence[] __initdata = {
0x03, 0x0f,
};
static uint8_t spm_retention_cmd_sequence[] __initdata = {
0x00, 0x05, 0x03, 0x0D,
0x0B, 0x00, 0x0f,
};
static uint8_t spm_retention_with_krait_v3_cmd_sequence[] __initdata = {
0x42, 0x1B, 0x00,
0x05, 0x03, 0x0D, 0x0B,
0x00, 0x42, 0x1B,
0x0f,
};
static uint8_t spm_power_collapse_without_rpm[] __initdata = {
0x00, 0x24, 0x54, 0x10,
0x09, 0x03, 0x01,
0x10, 0x54, 0x30, 0x0C,
0x24, 0x30, 0x0f,
};
static uint8_t spm_power_collapse_with_rpm[] __initdata = {
0x00, 0x24, 0x54, 0x10,
0x09, 0x07, 0x01, 0x0B,
0x10, 0x54, 0x30, 0x0C,
0x24, 0x30, 0x0f,
};
/* 8960AB has a different command to assert apc_pdn */
static uint8_t spm_power_collapse_without_rpm_krait_v3[] __initdata = {
0x00, 0x24, 0x84, 0x10,
0x09, 0x03, 0x01,
0x10, 0x84, 0x30, 0x0C,
0x24, 0x30, 0x0f,
};
static uint8_t spm_power_collapse_with_rpm_krait_v3[] __initdata = {
0x00, 0x24, 0x84, 0x10,
0x09, 0x07, 0x01, 0x0B,
0x10, 0x84, 0x30, 0x0C,
0x24, 0x30, 0x0f,
};
static struct msm_spm_seq_entry msm_spm_boot_cpu_seq_list[] __initdata = {
[0] = {
.mode = MSM_SPM_MODE_CLOCK_GATING,
.notify_rpm = false,
.cmd = spm_wfi_cmd_sequence,
},
[1] = {
.mode = MSM_SPM_MODE_POWER_RETENTION,
.notify_rpm = false,
.cmd = spm_retention_cmd_sequence,
},
[2] = {
.mode = MSM_SPM_MODE_POWER_COLLAPSE,
.notify_rpm = false,
.cmd = spm_power_collapse_without_rpm,
},
[3] = {
.mode = MSM_SPM_MODE_POWER_COLLAPSE,
.notify_rpm = true,
.cmd = spm_power_collapse_with_rpm,
},
};
static struct msm_spm_seq_entry msm_spm_nonboot_cpu_seq_list[] __initdata = {
[0] = {
.mode = MSM_SPM_MODE_CLOCK_GATING,
.notify_rpm = false,
.cmd = spm_wfi_cmd_sequence,
},
[1] = {
.mode = MSM_SPM_MODE_POWER_RETENTION,
.notify_rpm = false,
.cmd = spm_retention_cmd_sequence,
},
[2] = {
.mode = MSM_SPM_MODE_POWER_COLLAPSE,
.notify_rpm = false,
.cmd = spm_power_collapse_without_rpm,
},
[3] = {
.mode = MSM_SPM_MODE_POWER_COLLAPSE,
.notify_rpm = true,
.cmd = spm_power_collapse_with_rpm,
},
};
static struct msm_spm_platform_data msm_spm_data[] __initdata = {
[0] = {
.reg_base_addr = MSM_SAW0_BASE,
.reg_init_values[MSM_SPM_REG_SAW2_CFG] = 0x1F,
#if defined(CONFIG_MSM_AVS_HW)
.reg_init_values[MSM_SPM_REG_SAW2_AVS_CTL] = 0x58589464,
.reg_init_values[MSM_SPM_REG_SAW2_AVS_HYSTERESIS] = 0x00020000,
#endif
.reg_init_values[MSM_SPM_REG_SAW2_SPM_CTL] = 0x01,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DLY] = 0x03020004,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_0] = 0x0084009C,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_1] = 0x00A4001C,
.vctl_timeout_us = 50,
.num_modes = ARRAY_SIZE(msm_spm_boot_cpu_seq_list),
.modes = msm_spm_boot_cpu_seq_list,
},
[1] = {
.reg_base_addr = MSM_SAW1_BASE,
.reg_init_values[MSM_SPM_REG_SAW2_CFG] = 0x1F,
#if defined(CONFIG_MSM_AVS_HW)
.reg_init_values[MSM_SPM_REG_SAW2_AVS_CTL] = 0x58589464,
.reg_init_values[MSM_SPM_REG_SAW2_AVS_HYSTERESIS] = 0x00020000,
#endif
.reg_init_values[MSM_SPM_REG_SAW2_SPM_CTL] = 0x01,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DLY] = 0x03020004,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_0] = 0x0084009C,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_1] = 0x00A4001C,
.vctl_timeout_us = 50,
.num_modes = ARRAY_SIZE(msm_spm_nonboot_cpu_seq_list),
.modes = msm_spm_nonboot_cpu_seq_list,
},
};
static uint8_t l2_spm_wfi_cmd_sequence[] __initdata = {
0x00, 0x20, 0x03, 0x20,
0x00, 0x0f,
};
static uint8_t l2_spm_gdhs_cmd_sequence[] __initdata = {
0x00, 0x20, 0x34, 0x64,
0x48, 0x07, 0x48, 0x20,
0x50, 0x64, 0x04, 0x34,
0x50, 0x0f,
};
static uint8_t l2_spm_power_off_cmd_sequence[] __initdata = {
0x00, 0x10, 0x34, 0x64,
0x48, 0x07, 0x48, 0x10,
0x50, 0x64, 0x04, 0x34,
0x50, 0x0F,
};
static struct msm_spm_seq_entry msm_spm_l2_seq_list[] __initdata = {
[0] = {
.mode = MSM_SPM_L2_MODE_RETENTION,
.notify_rpm = false,
.cmd = l2_spm_wfi_cmd_sequence,
},
[1] = {
.mode = MSM_SPM_L2_MODE_GDHS,
.notify_rpm = true,
.cmd = l2_spm_gdhs_cmd_sequence,
},
[2] = {
.mode = MSM_SPM_L2_MODE_POWER_COLLAPSE,
.notify_rpm = true,
.cmd = l2_spm_power_off_cmd_sequence,
},
};
static struct msm_spm_platform_data msm_spm_l2_data[] __initdata = {
[0] = {
.reg_base_addr = MSM_SAW_L2_BASE,
.reg_init_values[MSM_SPM_REG_SAW2_SPM_CTL] = 0x00,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DLY] = 0x02020204,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_0] = 0x00A000AE,
.reg_init_values[MSM_SPM_REG_SAW2_PMIC_DATA_1] = 0x00A00020,
.modes = msm_spm_l2_seq_list,
.num_modes = ARRAY_SIZE(msm_spm_l2_seq_list),
},
};
#define HAP_SHIFT_LVL_OE_GPIO 47
#define HAP_SHIFT_LVL_OE_GPIO_SGLTE 89
#define PM_HAP_EN_GPIO PM8921_GPIO_PM_TO_SYS(33)
#define PM_HAP_LEN_GPIO PM8921_GPIO_PM_TO_SYS(20)
static struct msm_xo_voter *xo_handle_d1;
static int isa1200_power(int on)
{
int rc = 0;
int hap_oe_gpio = HAP_SHIFT_LVL_OE_GPIO;
if (socinfo_get_platform_subtype() == PLATFORM_SUBTYPE_SGLTE)
hap_oe_gpio = HAP_SHIFT_LVL_OE_GPIO_SGLTE;
gpio_set_value(hap_oe_gpio, !!on);
rc = on ? msm_xo_mode_vote(xo_handle_d1, MSM_XO_MODE_ON) :
msm_xo_mode_vote(xo_handle_d1, MSM_XO_MODE_OFF);
if (rc < 0) {
pr_err("%s: failed to %svote for TCXO D1 buffer%d\n",
__func__, on ? "" : "de-", rc);
goto err_xo_vote;
}
return 0;
err_xo_vote:
gpio_set_value(hap_oe_gpio, !on);
return rc;
}
static int isa1200_dev_setup(bool enable)
{
int rc = 0;
int hap_oe_gpio = HAP_SHIFT_LVL_OE_GPIO;
struct pm_gpio hap_gpio_config = {
.direction = PM_GPIO_DIR_OUT,
.pull = PM_GPIO_PULL_NO,
.out_strength = PM_GPIO_STRENGTH_HIGH,
.function = PM_GPIO_FUNC_NORMAL,
.inv_int_pol = 0,
.vin_sel = 2,
.output_buffer = PM_GPIO_OUT_BUF_CMOS,
.output_value = 0,
};
if (socinfo_get_platform_subtype() == PLATFORM_SUBTYPE_SGLTE)
hap_oe_gpio = HAP_SHIFT_LVL_OE_GPIO_SGLTE;
if (enable == true) {
rc = pm8xxx_gpio_config(PM_HAP_EN_GPIO, &hap_gpio_config);
if (rc) {
pr_err("%s: pm8921 gpio %d config failed(%d)\n",
__func__, PM_HAP_EN_GPIO, rc);
return rc;
}
rc = pm8xxx_gpio_config(PM_HAP_LEN_GPIO, &hap_gpio_config);
if (rc) {
pr_err("%s: pm8921 gpio %d config failed(%d)\n",
__func__, PM_HAP_LEN_GPIO, rc);
return rc;
}
rc = gpio_request(hap_oe_gpio, "hap_shft_lvl_oe");
if (rc) {
pr_err("%s: unable to request gpio %d (%d)\n",
__func__, hap_oe_gpio, rc);
return rc;
}
rc = gpio_direction_output(hap_oe_gpio, 0);
if (rc) {
pr_err("%s: Unable to set direction\n", __func__);
goto free_gpio;
}
xo_handle_d1 = msm_xo_get(MSM_XO_TCXO_D1, "isa1200");
if (IS_ERR(xo_handle_d1)) {
rc = PTR_ERR(xo_handle_d1);
pr_err("%s: failed to get the handle for D1(%d)\n",
__func__, rc);
goto gpio_set_dir;
}
} else {
gpio_free(hap_oe_gpio);
msm_xo_put(xo_handle_d1);
}
return 0;
gpio_set_dir:
gpio_set_value(hap_oe_gpio, 0);
free_gpio:
gpio_free(hap_oe_gpio);
return rc;
}
static struct isa1200_regulator isa1200_reg_data[] = {
{
.name = "vcc_i2c",
.min_uV = ISA_I2C_VTG_MIN_UV,
.max_uV = ISA_I2C_VTG_MAX_UV,
.load_uA = ISA_I2C_CURR_UA,
},
};
static struct isa1200_platform_data isa1200_1_pdata = {
.name = "vibrator",
.dev_setup = isa1200_dev_setup,
.power_on = isa1200_power,
.hap_en_gpio = PM_HAP_EN_GPIO,
.hap_len_gpio = PM_HAP_LEN_GPIO,
.max_timeout = 15000,
.mode_ctrl = PWM_GEN_MODE,
.pwm_fd = {
.pwm_div = 256,
},
.is_erm = false,
.smart_en = true,
.ext_clk_en = true,
.chip_en = 1,
.regulator_info = isa1200_reg_data,
.num_regulators = ARRAY_SIZE(isa1200_reg_data),
};
static struct i2c_board_info msm_isa1200_board_info[] __initdata = {
{
I2C_BOARD_INFO("isa1200_1", 0x90>>1),
},
};
#define CYTTSP_TS_GPIO_IRQ 11
#define CYTTSP_TS_SLEEP_GPIO 50
#define CYTTSP_TS_RESOUT_N_GPIO 52
/*virtual key support */
static ssize_t tma340_vkeys_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return snprintf(buf, 200,
__stringify(EV_KEY) ":" __stringify(KEY_BACK) ":73:1120:97:97"
":" __stringify(EV_KEY) ":" __stringify(KEY_MENU) ":230:1120:97:97"
":" __stringify(EV_KEY) ":" __stringify(KEY_HOME) ":389:1120:97:97"
":" __stringify(EV_KEY) ":" __stringify(KEY_SEARCH) ":544:1120:97:97"
"\n");
}
static struct kobj_attribute tma340_vkeys_attr = {
.attr = {
.mode = S_IRUGO,
},
.show = &tma340_vkeys_show,
};
static struct attribute *tma340_properties_attrs[] = {
&tma340_vkeys_attr.attr,
NULL
};
static struct attribute_group tma340_properties_attr_group = {
.attrs = tma340_properties_attrs,
};
static int cyttsp_platform_init(struct i2c_client *client)
{
int rc = 0;
static struct kobject *tma340_properties_kobj;
tma340_vkeys_attr.attr.name = "virtualkeys.cyttsp-i2c";
tma340_properties_kobj = kobject_create_and_add("board_properties",
NULL);
if (tma340_properties_kobj)
rc = sysfs_create_group(tma340_properties_kobj,
&tma340_properties_attr_group);
if (!tma340_properties_kobj || rc)
pr_err("%s: failed to create board_properties\n",
__func__);
return 0;
}
static struct cyttsp_regulator regulator_data[] = {
{
.name = "vdd",
.min_uV = CY_TMA300_VTG_MIN_UV,
.max_uV = CY_TMA300_VTG_MAX_UV,
.hpm_load_uA = CY_TMA300_CURR_24HZ_UA,
.lpm_load_uA = CY_TMA300_SLEEP_CURR_UA,
},
/* TODO: Remove after runtime PM is enabled in I2C driver */
{
.name = "vcc_i2c",
.min_uV = CY_I2C_VTG_MIN_UV,
.max_uV = CY_I2C_VTG_MAX_UV,
.hpm_load_uA = CY_I2C_CURR_UA,
.lpm_load_uA = CY_I2C_SLEEP_CURR_UA,
},
};
static struct cyttsp_platform_data cyttsp_pdata = {
.panel_maxx = 634,
.panel_maxy = 1166,
.disp_maxx = 616,
.disp_maxy = 1023,
.disp_minx = 0,
.disp_miny = 16,
.flags = 0x01,
.gen = CY_GEN3, /* or */
.use_st = CY_USE_ST,
.use_mt = CY_USE_MT,
.use_hndshk = CY_SEND_HNDSHK,
.use_trk_id = CY_USE_TRACKING_ID,
.use_sleep = CY_USE_DEEP_SLEEP_SEL | CY_USE_LOW_POWER_SEL,
.use_gestures = CY_USE_GESTURES,
.fw_fname = "cyttsp_8960_cdp.hex",
/* activate up to 4 groups
* and set active distance
*/
.gest_set = CY_GEST_GRP1 | CY_GEST_GRP2 |
CY_GEST_GRP3 | CY_GEST_GRP4 |
CY_ACT_DIST,
.act_intrvl = 10,
.tch_tmout = 200,
.lp_intrvl = 30,
.sleep_gpio = CYTTSP_TS_SLEEP_GPIO,
.resout_gpio = CYTTSP_TS_RESOUT_N_GPIO,
.irq_gpio = CYTTSP_TS_GPIO_IRQ,
.regulator_info = regulator_data,
.num_regulators = ARRAY_SIZE(regulator_data),
.init = cyttsp_platform_init,
.correct_fw_ver = 9,
};
static struct i2c_board_info cyttsp_info[] __initdata = {
{
I2C_BOARD_INFO(CY_I2C_NAME, 0x24),
.platform_data = &cyttsp_pdata,
#ifndef CY_USE_TIMER
.irq = MSM_GPIO_TO_INT(CYTTSP_TS_GPIO_IRQ),
#endif /* CY_USE_TIMER */
},
};
/* configuration data for mxt1386 */
static const u8 mxt1386_config_data[] = {
/* T6 Object */
0, 0, 0, 0, 0, 0,
/* T38 Object */
11, 2, 0, 11, 11, 11, 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,
/* T7 Object */
100, 16, 50,
/* T8 Object */
8, 0, 0, 0, 0, 0, 8, 14, 50, 215,
/* T9 Object */
131, 0, 0, 26, 42, 0, 32, 63, 3, 5,
0, 2, 1, 113, 10, 10, 8, 10, 255, 2,
85, 5, 0, 0, 20, 20, 75, 25, 202, 29,
10, 10, 45, 46,
/* T15 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
/* T18 Object */
0, 0,
/* T22 Object */
5, 0, 0, 0, 0, 0, 0, 0, 30, 0,
0, 0, 5, 8, 10, 13, 0,
/* T24 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
/* T25 Object */
3, 0, 188, 52, 52, 33, 0, 0, 0, 0,
0, 0, 0, 0,
/* T27 Object */
0, 0, 0, 0, 0, 0, 0,
/* T28 Object */
0, 0, 0, 8, 12, 60,
/* T40 Object */
0, 0, 0, 0, 0,
/* T41 Object */
0, 0, 0, 0, 0, 0,
/* T43 Object */
0, 0, 0, 0, 0, 0,
};
/* configuration data for mxt1386e using V1.0 firmware */
static const u8 mxt1386e_config_data_v1_0[] = {
/* T6 Object */
0, 0, 0, 0, 0, 0,
/* T38 Object */
12, 1, 0, 17, 1, 12, 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,
/* T7 Object */
100, 16, 50,
/* T8 Object */
25, 0, 20, 20, 0, 0, 20, 50, 0, 0,
/* T9 Object */
131, 0, 0, 26, 42, 0, 32, 80, 2, 5,
0, 5, 5, 0, 10, 30, 10, 10, 255, 2,
85, 5, 10, 10, 10, 10, 135, 55, 70, 40,
10, 5, 0, 0, 0,
/* T18 Object */
0, 0,
/* T24 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
/* T25 Object */
3, 0, 60, 115, 156, 99,
/* T27 Object */
0, 0, 0, 0, 0, 0, 0,
/* T40 Object */
0, 0, 0, 0, 0,
/* T42 Object */
2, 0, 255, 0, 255, 0, 0, 0, 0, 0,
/* T43 Object */
0, 0, 0, 0, 0, 0, 0,
/* T46 Object */
64, 0, 20, 20, 0, 0, 0, 0, 0,
/* T47 Object */
0, 0, 0, 0, 0, 0, 3, 64, 66, 0,
/* T48 Object */
31, 64, 64, 0, 0, 0, 0, 0, 0, 0,
48, 40, 0, 10, 10, 0, 0, 100, 10, 80,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
52, 0, 12, 0, 17, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
/* T56 Object */
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,
2, 99, 33,
};
/* configuration data for mxt1386e using V2.1 firmware */
static const u8 mxt1386e_config_data_v2_1[] = {
/* T6 Object */
0, 0, 0, 0, 0, 0,
/* T38 Object */
12, 4, 0, 5, 7, 12, 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,
/* T7 Object */
100, 16, 50,
/* T8 Object */
25, 0, 20, 20, 0, 0, 20, 50, 0, 0,
/* T9 Object */
139, 0, 0, 26, 42, 0, 32, 80, 2, 5,
0, 5, 5, 79, 10, 30, 10, 10, 255, 2,
85, 5, 10, 10, 10, 10, 135, 55, 70, 40,
10, 5, 0, 0, 0,
/* T18 Object */
0, 0,
/* T24 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
/* T25 Object */
1, 0, 60, 115, 156, 99,
/* T27 Object */
0, 0, 0, 0, 0, 0, 0,
/* T40 Object */
0, 0, 0, 0, 0,
/* T42 Object */
0, 0, 255, 0, 255, 0, 0, 0, 0, 0,
/* T43 Object */
0, 0, 0, 0, 0, 0, 0, 64, 0, 8,
16,
/* T46 Object */
64, 0, 16, 16, 0, 0, 0, 0, 0,
/* T47 Object */
0, 0, 0, 0, 0, 0, 3, 64, 66, 0,
/* T48 Object */
1, 64, 64, 0, 0, 0, 0, 0, 0, 0,
48, 40, 0, 10, 10, 0, 0, 100, 10, 80,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
52, 0, 12, 0, 17, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
/* T56 Object */
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,
2, 99, 33, 0, 149, 24, 193, 255, 255, 255,
255,
};
/* configuration data for mxt1386e on 3D SKU using V2.1 firmware */
static const u8 mxt1386e_config_data_3d[] = {
/* T6 Object */
0, 0, 0, 0, 0, 0,
/* T38 Object */
13, 1, 0, 23, 2, 12, 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,
/* T7 Object */
100, 10, 50,
/* T8 Object */
25, 0, 20, 20, 0, 0, 0, 0, 0, 0,
/* T9 Object */
131, 0, 0, 26, 42, 0, 32, 80, 2, 5,
0, 5, 5, 0, 10, 30, 10, 10, 175, 4,
127, 7, 26, 21, 17, 19, 143, 35, 207, 40,
20, 5, 54, 49, 0,
/* T18 Object */
0, 0,
/* T24 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
/* T25 Object */
0, 0, 72, 113, 168, 97,
/* T27 Object */
0, 0, 0, 0, 0, 0, 0,
/* T40 Object */
0, 0, 0, 0, 0,
/* T42 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* T43 Object */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
/* T46 Object */
68, 0, 16, 16, 0, 0, 0, 0, 0,
/* T47 Object */
0, 0, 0, 0, 0, 0, 3, 64, 66, 0,
/* T48 Object */
31, 64, 64, 0, 0, 0, 0, 0, 0, 0,
32, 50, 0, 10, 10, 0, 0, 100, 10, 90,
0, 0, 0, 0, 0, 0, 0, 10, 1, 30,
52, 10, 5, 0, 33, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
/* T56 Object */
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,
};
#define MXT_TS_GPIO_IRQ 11
#define MXT_TS_LDO_EN_GPIO 50
#define MXT_TS_RESET_GPIO 52
static void mxt_init_hw_liquid(void)
{
int rc;
rc = gpio_request(MXT_TS_LDO_EN_GPIO, "mxt_ldo_en_gpio");
if (rc) {
pr_err("%s: unable to request mxt_ldo_en_gpio [%d]\n",
__func__, MXT_TS_LDO_EN_GPIO);
return;
}
rc = gpio_direction_output(MXT_TS_LDO_EN_GPIO, 1);
if (rc) {
pr_err("%s: unable to set_direction for mxt_ldo_en_gpio [%d]\n",
__func__, MXT_TS_LDO_EN_GPIO);
goto err_ldo_gpio_req;
}
return;
err_ldo_gpio_req:
gpio_free(MXT_TS_LDO_EN_GPIO);
}
static struct mxt_config_info mxt_config_array_2d[] = {
{
.config = mxt1386_config_data,
.config_length = ARRAY_SIZE(mxt1386_config_data),
.family_id = 0xA0,
.variant_id = 0x0,
.version = 0x10,
.build = 0xAA,
.bootldr_id = MXT_BOOTLOADER_ID_1386,
},
{
.config = mxt1386e_config_data_v1_0,
.config_length = ARRAY_SIZE(mxt1386e_config_data_v1_0),
.family_id = 0xA0,
.variant_id = 0x2,
.version = 0x10,
.build = 0xAA,
.bootldr_id = MXT_BOOTLOADER_ID_1386E,
.fw_name = "atmel_8960_liquid_v2_2_AA.hex",
},
{
.config = mxt1386e_config_data_v2_1,
.config_length = ARRAY_SIZE(mxt1386e_config_data_v2_1),
.family_id = 0xA0,
.variant_id = 0x7,
.version = 0x21,
.build = 0xAA,
.bootldr_id = MXT_BOOTLOADER_ID_1386E,
.fw_name = "atmel_8960_liquid_v2_2_AA.hex",
},
{
/* The config data for V2.2.AA is the same as for V2.1.AA */
.config = mxt1386e_config_data_v2_1,
.config_length = ARRAY_SIZE(mxt1386e_config_data_v2_1),
.family_id = 0xA0,
.variant_id = 0x7,
.version = 0x22,
.build = 0xAA,
.bootldr_id = MXT_BOOTLOADER_ID_1386E,
},
};
static struct mxt_platform_data mxt_platform_data_2d = {
.config_array = mxt_config_array_2d,
.config_array_size = ARRAY_SIZE(mxt_config_array_2d),
.panel_minx = 0,
.panel_maxx = 1365,
.panel_miny = 0,
.panel_maxy = 767,
.disp_minx = 0,
.disp_maxx = 1365,
.disp_miny = 0,
.disp_maxy = 767,
.irqflags = IRQF_TRIGGER_FALLING,
.i2c_pull_up = true,
.reset_gpio = MXT_TS_RESET_GPIO,
.irq_gpio = MXT_TS_GPIO_IRQ,
};
static struct mxt_config_info mxt_config_array_3d[] = {
{
.config = mxt1386e_config_data_3d,
.config_length = ARRAY_SIZE(mxt1386e_config_data_3d),
.family_id = 0xA0,
.variant_id = 0x7,
.version = 0x21,
.build = 0xAA,
},
};
static struct mxt_platform_data mxt_platform_data_3d = {
.config_array = mxt_config_array_3d,
.config_array_size = ARRAY_SIZE(mxt_config_array_3d),
.panel_minx = 0,
.panel_maxx = 1919,
.panel_miny = 0,
.panel_maxy = 1199,
.disp_minx = 0,
.disp_maxx = 1919,
.disp_miny = 0,
.disp_maxy = 1199,
.irqflags = IRQF_TRIGGER_FALLING,
.i2c_pull_up = true,
.reset_gpio = MXT_TS_RESET_GPIO,
.irq_gpio = MXT_TS_GPIO_IRQ,
};
static struct i2c_board_info mxt_device_info[] __initdata = {
{
I2C_BOARD_INFO("atmel_mxt_ts", 0x5b),
.irq = MSM_GPIO_TO_INT(MXT_TS_GPIO_IRQ),
},
};
static struct msm_mhl_platform_data mhl_platform_data = {
.irq = MSM_GPIO_TO_INT(4),
.gpio_mhl_int = MHL_GPIO_INT,
.gpio_mhl_reset = MHL_GPIO_RESET,
.gpio_mhl_power = 0,
.gpio_hdmi_mhl_mux = 0,
};
static struct i2c_board_info sii_device_info[] __initdata = {
{
#ifdef CONFIG_FB_MSM_HDMI_MHL_8334
/*
* keeps SI 8334 as the default
* MHL TX
*/
I2C_BOARD_INFO("sii8334", 0x39),
.platform_data = &mhl_platform_data,
#endif
#ifdef CONFIG_FB_MSM_HDMI_MHL_9244
I2C_BOARD_INFO("Sil-9244", 0x39),
.irq = MSM_GPIO_TO_INT(15),
#endif /* CONFIG_MSM_HDMI_MHL */
.flags = I2C_CLIENT_WAKE,
},
};
static struct msm_i2c_platform_data msm8960_i2c_qup_gsbi4_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
.keep_ahb_clk_on = 1,
};
static struct msm_i2c_platform_data msm8960_i2c_qup_gsbi3_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
};
static struct msm_i2c_platform_data msm8960_i2c_qup_gsbi10_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
};
static struct msm_i2c_platform_data msm8960_i2c_qup_gsbi12_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
};
static struct ks8851_pdata spi_eth_pdata = {
.irq_gpio = KS8851_IRQ_GPIO,
.rst_gpio = KS8851_RST_GPIO,
};
static struct spi_board_info spi_eth_info[] __initdata = {
{
.modalias = "ks8851",
.irq = MSM_GPIO_TO_INT(KS8851_IRQ_GPIO),
.max_speed_hz = 19200000,
.bus_num = 0,
.chip_select = 0,
.mode = SPI_MODE_0,
.platform_data = &spi_eth_pdata
},
};
static struct spi_board_info spi_board_info[] __initdata = {
{
.modalias = "dsi_novatek_3d_panel_spi",
.max_speed_hz = 10800000,
.bus_num = 0,
.chip_select = 1,
.mode = SPI_MODE_0,
},
};
static struct platform_device msm_device_saw_core0 = {
.name = "saw-regulator",
.id = 0,
.dev = {
.platform_data = &msm_saw_regulator_pdata_s5,
},
};
static struct platform_device msm_device_saw_core1 = {
.name = "saw-regulator",
.id = 1,
.dev = {
.platform_data = &msm_saw_regulator_pdata_s6,
},
};
static struct tsens_platform_data msm_tsens_pdata = {
.slope = {910, 910, 910, 910, 910},
.tsens_factor = 1000,
.hw_type = MSM_8960,
.tsens_num_sensor = 5,
};
static struct platform_device msm_tsens_device = {
.name = "tsens8960-tm",
.id = -1,
};
static struct msm_thermal_data msm_thermal_pdata = {
.sensor_id = 0,
.poll_ms = 250,
.limit_temp_degC = 60,
.temp_hysteresis_degC = 10,
.freq_step = 2,
};
#ifdef CONFIG_MSM_FAKE_BATTERY
static struct platform_device fish_battery_device = {
.name = "fish_battery",
};
#endif
static struct platform_device msm8960_device_ext_5v_vreg __devinitdata = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = PM8921_MPP_PM_TO_SYS(7),
.dev = {
.platform_data = &msm_gpio_regulator_pdata[GPIO_VREG_ID_EXT_5V],
},
};
static struct platform_device msm8960_device_ext_l2_vreg __devinitdata = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = 91,
.dev = {
.platform_data = &msm_gpio_regulator_pdata[GPIO_VREG_ID_EXT_L2],
},
};
static struct platform_device msm8960_device_ext_3p3v_vreg __devinitdata = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = PM8921_GPIO_PM_TO_SYS(17),
.dev = {
.platform_data =
&msm_gpio_regulator_pdata[GPIO_VREG_ID_EXT_3P3V],
},
};
static struct platform_device msm8960_device_ext_otg_sw_vreg __devinitdata = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = PM8921_GPIO_PM_TO_SYS(42),
.dev = {
.platform_data =
&msm_gpio_regulator_pdata[GPIO_VREG_ID_EXT_OTG_SW],
},
};
static struct platform_device msm8960_device_rpm_regulator __devinitdata = {
.name = "rpm-regulator",
.id = -1,
.dev = {
.platform_data = &msm_rpm_regulator_pdata,
},
};
#ifdef CONFIG_SERIAL_MSM_HS
static int configure_uart_gpios(int on)
{
int ret = 0, i;
int uart_gpios[] = {93, 94, 95, 96};
for (i = 0; i < ARRAY_SIZE(uart_gpios); i++) {
if (on) {
ret = gpio_request(uart_gpios[i], NULL);
if (ret) {
pr_err("%s: unable to request uart gpio[%d]\n",
__func__, uart_gpios[i]);
break;
}
} else {
gpio_free(uart_gpios[i]);
}
}
if (ret && on && i)
for (; i >= 0; i--)
gpio_free(uart_gpios[i]);
return ret;
}
static struct msm_serial_hs_platform_data msm_uart_dm9_pdata = {
.gpio_config = configure_uart_gpios,
};
static int configure_gsbi8_uart_gpios(int on)
{
int ret = 0, i;
int uart_gpios[] = {34, 35, 36, 37};
for (i = 0; i < ARRAY_SIZE(uart_gpios); i++) {
if (on) {
ret = gpio_request(uart_gpios[i], NULL);
if (ret) {
pr_err("%s: unable to request uart gpio[%d]\n",
__func__, uart_gpios[i]);
break;
}
} else {
gpio_free(uart_gpios[i]);
}
}
if (ret && on && i)
for (; i >= 0; i--)
gpio_free(uart_gpios[i]);
return ret;
}
static struct msm_serial_hs_platform_data msm_uart_dm8_pdata = {
.gpio_config = configure_gsbi8_uart_gpios,
};
#else
static struct msm_serial_hs_platform_data msm_uart_dm8_pdata;
static struct msm_serial_hs_platform_data msm_uart_dm9_pdata;
#endif
#if defined(CONFIG_BT) && defined(CONFIG_BT_HCIUART_ATH3K)
enum WLANBT_STATUS {
WLANOFF_BTOFF = 1,
WLANOFF_BTON,
WLANON_BTOFF,
WLANON_BTON
};
static DEFINE_MUTEX(ath_wlanbt_mutex);
static int gpio_wlan_sys_rest_en = 26;
static int ath_wlanbt_status = WLANOFF_BTOFF;
static int ath6kl_power_control(int on)
{
int rc;
if (on) {
rc = gpio_request(gpio_wlan_sys_rest_en, "wlan sys_rst_n");
if (rc) {
pr_err("%s: unable to request gpio %d (%d)\n",
__func__, gpio_wlan_sys_rest_en, rc);
return rc;
}
rc = gpio_direction_output(gpio_wlan_sys_rest_en, 0);
msleep(200);
rc = gpio_direction_output(gpio_wlan_sys_rest_en, 1);
msleep(100);
} else {
gpio_set_value(gpio_wlan_sys_rest_en, 0);
rc = gpio_direction_input(gpio_wlan_sys_rest_en);
msleep(100);
gpio_free(gpio_wlan_sys_rest_en);
}
return 0;
};
static int ath6kl_wlan_power(int on)
{
int ret = 0;
mutex_lock(&ath_wlanbt_mutex);
if (on) {
if (ath_wlanbt_status == WLANOFF_BTOFF) {
ret = ath6kl_power_control(1);
ath_wlanbt_status = WLANON_BTOFF;
} else if (ath_wlanbt_status == WLANOFF_BTON)
ath_wlanbt_status = WLANON_BTON;
} else {
if (ath_wlanbt_status == WLANON_BTOFF) {
ret = ath6kl_power_control(0);
ath_wlanbt_status = WLANOFF_BTOFF;
} else if (ath_wlanbt_status == WLANON_BTON)
ath_wlanbt_status = WLANOFF_BTON;
}
mutex_unlock(&ath_wlanbt_mutex);
pr_debug("%s on= %d, wlan_status= %d\n",
__func__, on, ath_wlanbt_status);
return ret;
};
static struct wifi_platform_data ath6kl_wifi_control = {
.set_power = ath6kl_wlan_power,
};
static struct platform_device msm_wlan_power_device = {
.name = "ath6kl_power",
.dev = {
.platform_data = &ath6kl_wifi_control,
},
};
static struct resource bluesleep_resources[] = {
{
.name = "gpio_host_wake",
.start = 27,
.end = 27,
.flags = IORESOURCE_IO,
},
{
.name = "gpio_ext_wake",
.start = 29,
.end = 29,
.flags = IORESOURCE_IO,
},
{
.name = "host_wake",
.start = MSM_GPIO_TO_INT(27),
.end = MSM_GPIO_TO_INT(27),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device msm_bluesleep_device = {
.name = "bluesleep",
.id = -1,
.num_resources = ARRAY_SIZE(bluesleep_resources),
.resource = bluesleep_resources,
};
static struct platform_device msm_bt_power_device = {
.name = "bt_power",
};
static int gpio_bt_sys_rest_en = 28;
static int bluetooth_power(int on)
{
int rc;
mutex_lock(&ath_wlanbt_mutex);
if (on) {
if (ath_wlanbt_status == WLANOFF_BTOFF) {
ath6kl_power_control(1);
ath_wlanbt_status = WLANOFF_BTON;
} else if (ath_wlanbt_status == WLANON_BTOFF)
ath_wlanbt_status = WLANON_BTON;
rc = gpio_request(gpio_bt_sys_rest_en, "bt sys_rst_n");
if (rc) {
pr_err("%s: unable to request gpio %d (%d)\n",
__func__, gpio_bt_sys_rest_en, rc);
mutex_unlock(&ath_wlanbt_mutex);
return rc;
}
rc = gpio_direction_output(gpio_bt_sys_rest_en, 0);
msleep(20);
rc = gpio_direction_output(gpio_bt_sys_rest_en, 1);
msleep(100);
} else {
gpio_set_value(gpio_bt_sys_rest_en, 0);
rc = gpio_direction_input(gpio_bt_sys_rest_en);
msleep(100);
gpio_free(gpio_bt_sys_rest_en);
if (ath_wlanbt_status == WLANOFF_BTON) {
ath6kl_power_control(0);
ath_wlanbt_status = WLANOFF_BTOFF;
} else if (ath_wlanbt_status == WLANON_BTON)
ath_wlanbt_status = WLANON_BTOFF;
}
mutex_unlock(&ath_wlanbt_mutex);
pr_debug("%s on= %d, wlan_status= %d\n",
__func__, on, ath_wlanbt_status);
return 0;
};
static void __init bt_power_init(void)
{
msm_bt_power_device.dev.platform_data = &bluetooth_power;
return;
};
#else
#define bt_power_init(x) do {} while (0)
#endif
static struct platform_device *common_devices[] __initdata = {
&msm8960_device_dmov,
&msm_device_smd,
&msm_device_uart_dm6,
&msm_device_saw_core0,
&msm_device_saw_core1,
&msm8960_device_ext_5v_vreg,
&msm8960_device_ssbi_pmic,
&msm8960_device_ext_otg_sw_vreg,
&msm8960_device_qup_spi_gsbi1,
&msm8960_device_qup_i2c_gsbi3,
&msm8960_device_qup_i2c_gsbi4,
&msm8960_device_qup_i2c_gsbi10,
#ifndef CONFIG_MSM_DSPS
&msm8960_device_qup_i2c_gsbi12,
#endif
&msm_slim_ctrl,
&msm_device_wcnss_wlan,
#if defined(CONFIG_BT) && defined(CONFIG_BT_HCIUART_ATH3K)
&msm_bluesleep_device,
&msm_bt_power_device,
&msm_wlan_power_device,
#endif
#if defined(CONFIG_QSEECOM)
&qseecom_device,
#endif
#if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \
defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE)
&qcrypto_device,
#endif
#if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE)
&qcedev_device,
#endif
#ifdef CONFIG_MSM_ROTATOR
&msm_rotator_device,
#endif
&msm_device_sps,
#ifdef CONFIG_MSM_FAKE_BATTERY
&fish_battery_device,
#endif
&msm8960_fmem_device,
#ifdef CONFIG_ANDROID_PMEM
#ifndef CONFIG_MSM_MULTIMEDIA_USE_ION
&msm8960_android_pmem_device,
&msm8960_android_pmem_adsp_device,
&msm8960_android_pmem_audio_device,
#endif
#endif
&msm_device_bam_dmux,
&msm_fm_platform_init,
#if defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE)
#ifdef CONFIG_MSM_USE_TSIF1
&msm_device_tsif[1],
#else
&msm_device_tsif[0],
#endif
#endif
&msm_device_tspp,
#ifdef CONFIG_HW_RANDOM_MSM
&msm_device_rng,
#endif
#ifdef CONFIG_ION_MSM
&msm8960_ion_dev,
#endif
&msm8960_rpm_device,
&msm8960_rpm_log_device,
&msm8960_rpm_stat_device,
&msm8960_rpm_master_stat_device,
&msm_device_tz_log,
&coresight_tpiu_device,
&coresight_etb_device,
&coresight_funnel_device,
&coresight_etm0_device,
&coresight_etm1_device,
&msm_device_dspcrashd_8960,
&msm8960_device_watchdog,
&msm8960_rtb_device,
&msm8960_device_cache_erp,
&msm8960_device_ebi1_ch0_erp,
&msm8960_device_ebi1_ch1_erp,
&msm8960_cache_dump_device,
&msm8960_iommu_domain_device,
&msm_tsens_device,
&msm8960_cpu_slp_status,
};
static struct platform_device *cdp_devices[] __initdata = {
&msm_8960_q6_lpass,
&msm_8960_riva,
&msm_pil_tzapps,
&msm_pil_dsps,
&msm_pil_vidc,
&msm8960_device_otg,
&msm8960_device_gadget_peripheral,
&msm_device_hsusb_host,
&android_usb_device,
&msm_pcm,
&msm_multi_ch_pcm,
&msm_lowlatency_pcm,
&msm_pcm_routing,
&msm_cpudai0,
&msm_cpudai1,
&msm8960_cpudai_slimbus_2_rx,
&msm8960_cpudai_slimbus_2_tx,
&msm_cpudai_hdmi_rx,
&msm_cpudai_bt_rx,
&msm_cpudai_bt_tx,
&msm_cpudai_fm_rx,
&msm_cpudai_fm_tx,
&msm_cpudai_auxpcm_rx,
&msm_cpudai_auxpcm_tx,
&msm_cpu_fe,
&msm_stub_codec,
#ifdef CONFIG_MSM_GEMINI
&msm8960_gemini_device,
#endif
#ifdef CONFIG_MSM_MERCURY
&msm8960_mercury_device,
#endif
&msm_voice,
&msm_voip,
&msm_lpa_pcm,
&msm_cpudai_afe_01_rx,
&msm_cpudai_afe_01_tx,
&msm_cpudai_afe_02_rx,
&msm_cpudai_afe_02_tx,
&msm_pcm_afe,
&msm_compr_dsp,
&msm_cpudai_incall_music_rx,
&msm_cpudai_incall_record_rx,
&msm_cpudai_incall_record_tx,
&msm_pcm_hostless,
&msm_bus_apps_fabric,
&msm_bus_sys_fabric,
&msm_bus_mm_fabric,
&msm_bus_sys_fpb,
&msm_bus_cpss_fpb,
};
static void __init msm8960_i2c_init(void)
{
msm8960_device_qup_i2c_gsbi4.dev.platform_data =
&msm8960_i2c_qup_gsbi4_pdata;
msm8960_device_qup_i2c_gsbi3.dev.platform_data =
&msm8960_i2c_qup_gsbi3_pdata;
msm8960_device_qup_i2c_gsbi10.dev.platform_data =
&msm8960_i2c_qup_gsbi10_pdata;
msm8960_device_qup_i2c_gsbi12.dev.platform_data =
&msm8960_i2c_qup_gsbi12_pdata;
}
static void __init msm8960_gfx_init(void)
{
struct kgsl_device_platform_data *kgsl_3d0_pdata =
msm_kgsl_3d0.dev.platform_data;
uint32_t soc_platform_version = socinfo_get_version();
/* Fixup data that needs to change based on GPU ID */
if (cpu_is_msm8960ab()) {
kgsl_3d0_pdata->chipid = ADRENO_CHIPID(3, 2, 1, 0);
/* 8960PRO nominal clock rate is 320Mhz */
kgsl_3d0_pdata->pwrlevel[1].gpu_freq = 320000000;
} else {
kgsl_3d0_pdata->iommu_count = 1;
if (SOCINFO_VERSION_MAJOR(soc_platform_version) == 1) {
kgsl_3d0_pdata->pwrlevel[0].gpu_freq = 320000000;
kgsl_3d0_pdata->pwrlevel[1].gpu_freq = 266667000;
}
if (SOCINFO_VERSION_MAJOR(soc_platform_version) >= 3) {
/* 8960v3 GPU registers returns 5 for patch release
* but it should be 6, so dummy up the chipid here
* based the platform type
*/
kgsl_3d0_pdata->chipid = ADRENO_CHIPID(2, 2, 0, 6);
}
}
/* Register the 3D core */
platform_device_register(&msm_kgsl_3d0);
/* Register the 2D cores if we are not 8960PRO */
if (!cpu_is_msm8960ab()) {
platform_device_register(&msm_kgsl_2d0);
platform_device_register(&msm_kgsl_2d1);
}
}
static struct msm_rpmrs_level msm_rpmrs_levels[] = {
{
MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT,
MSM_RPMRS_LIMITS(ON, ACTIVE, MAX, ACTIVE),
true,
1, 784, 180000, 100,
},
{
MSM_PM_SLEEP_MODE_RETENTION,
MSM_RPMRS_LIMITS(ON, ACTIVE, MAX, ACTIVE),
true,
415, 715, 340827, 475,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE,
MSM_RPMRS_LIMITS(ON, ACTIVE, MAX, ACTIVE),
true,
1300, 228, 1200000, 2000,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(ON, GDHS, MAX, ACTIVE),
false,
2000, 138, 1208400, 3200,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(ON, HSFS_OPEN, ACTIVE, RET_HIGH),
false,
6000, 119, 1850300, 9000,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(OFF, GDHS, MAX, ACTIVE),
false,
9200, 68, 2839200, 16400,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(OFF, HSFS_OPEN, MAX, ACTIVE),
false,
10300, 63, 3128000, 18200,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(OFF, HSFS_OPEN, ACTIVE, RET_HIGH),
false,
18000, 10, 4602600, 27000,
},
{
MSM_PM_SLEEP_MODE_POWER_COLLAPSE,
MSM_RPMRS_LIMITS(OFF, HSFS_OPEN, RET_HIGH, RET_LOW),
false,
20000, 2, 5752000, 32000,
},
};
static struct msm_rpmrs_platform_data msm_rpmrs_data __initdata = {
.levels = &msm_rpmrs_levels[0],
.num_levels = ARRAY_SIZE(msm_rpmrs_levels),
.vdd_mem_levels = {
[MSM_RPMRS_VDD_MEM_RET_LOW] = 750000,
[MSM_RPMRS_VDD_MEM_RET_HIGH] = 750000,
[MSM_RPMRS_VDD_MEM_ACTIVE] = 1050000,
[MSM_RPMRS_VDD_MEM_MAX] = 1150000,
},
.vdd_dig_levels = {
[MSM_RPMRS_VDD_DIG_RET_LOW] = 500000,
[MSM_RPMRS_VDD_DIG_RET_HIGH] = 750000,
[MSM_RPMRS_VDD_DIG_ACTIVE] = 950000,
[MSM_RPMRS_VDD_DIG_MAX] = 1150000,
},
.vdd_mask = 0x7FFFFF,
.rpmrs_target_id = {
[MSM_RPMRS_ID_PXO_CLK] = MSM_RPM_ID_PXO_CLK,
[MSM_RPMRS_ID_L2_CACHE_CTL] = MSM_RPM_ID_LAST,
[MSM_RPMRS_ID_VDD_DIG_0] = MSM_RPM_ID_PM8921_S3_0,
[MSM_RPMRS_ID_VDD_DIG_1] = MSM_RPM_ID_PM8921_S3_1,
[MSM_RPMRS_ID_VDD_MEM_0] = MSM_RPM_ID_PM8921_L24_0,
[MSM_RPMRS_ID_VDD_MEM_1] = MSM_RPM_ID_PM8921_L24_1,
[MSM_RPMRS_ID_RPM_CTL] = MSM_RPM_ID_RPM_CTL,
},
};
static struct msm_pm_boot_platform_data msm_pm_boot_pdata __initdata = {
.mode = MSM_PM_BOOT_CONFIG_TZ,
};
#ifdef CONFIG_I2C
#define I2C_SURF 1
#define I2C_FFA (1 << 1)
#define I2C_RUMI (1 << 2)
#define I2C_SIM (1 << 3)
#define I2C_FLUID (1 << 4)
#define I2C_LIQUID (1 << 5)
struct i2c_registry {
u8 machs;
int bus;
struct i2c_board_info *info;
int len;
};
/* Sensors DSPS platform data */
#ifdef CONFIG_MSM_DSPS
#define DSPS_PIL_GENERIC_NAME "dsps"
#endif /* CONFIG_MSM_DSPS */
static void __init msm8960_init_dsps(void)
{
#ifdef CONFIG_MSM_DSPS
struct msm_dsps_platform_data *pdata =
msm_dsps_device.dev.platform_data;
pdata->pil_name = DSPS_PIL_GENERIC_NAME;
pdata->gpios = NULL;
pdata->gpios_num = 0;
platform_device_register(&msm_dsps_device);
#endif /* CONFIG_MSM_DSPS */
}
static int hsic_peripheral_status = 1;
static DEFINE_MUTEX(hsic_status_lock);
void peripheral_connect()
{
mutex_lock(&hsic_status_lock);
if (hsic_peripheral_status)
goto out;
platform_device_add(&msm_device_hsic_host);
hsic_peripheral_status = 1;
out:
mutex_unlock(&hsic_status_lock);
}
EXPORT_SYMBOL(peripheral_connect);
void peripheral_disconnect()
{
mutex_lock(&hsic_status_lock);
if (!hsic_peripheral_status)
goto out;
platform_device_del(&msm_device_hsic_host);
hsic_peripheral_status = 0;
out:
mutex_unlock(&hsic_status_lock);
}
EXPORT_SYMBOL(peripheral_disconnect);
static void __init msm8960_init_smsc_hub(void)
{
uint32_t version = socinfo_get_version();
if (SOCINFO_VERSION_MAJOR(version) == 1)
return;
if (machine_is_msm8960_liquid())
platform_device_register(&smsc_hub_device);
}
static void __init msm8960_init_hsic(void)
{
#ifdef CONFIG_USB_EHCI_MSM_HSIC
uint32_t version = socinfo_get_version();
if (SOCINFO_VERSION_MAJOR(version) == 1)
return;
if (machine_is_msm8960_liquid())
platform_device_register(&msm_device_hsic_host);
#endif
}
#ifdef CONFIG_ISL9519_CHARGER
static struct isl_platform_data isl_data __initdata = {
.valid_n_gpio = 0, /* Not required when notify-by-pmic */
.chg_detection_config = NULL, /* Not required when notify-by-pmic */
.max_system_voltage = 4200,
.min_system_voltage = 3200,
.chgcurrent = 1900,
.term_current = 0,
.input_current = 2048,
};
static struct i2c_board_info isl_charger_i2c_info[] __initdata = {
{
I2C_BOARD_INFO("isl9519q", 0x9),
.irq = 0, /* Not required when notify-by-pmic */
.platform_data = &isl_data,
},
};
#endif /* CONFIG_ISL9519_CHARGER */
#if defined(CONFIG_GPIO_SX150X) || defined(CONFIG_GPIO_SX150X_MODULE)
static struct i2c_board_info liquid_io_expander_i2c_info[] __initdata = {
{
I2C_BOARD_INFO("sx1508q", 0x20),
.platform_data = &msm8960_sx150x_data[SX150X_LIQUID]
},
};
#endif
static struct i2c_registry msm8960_i2c_devices[] __initdata = {
#ifdef CONFIG_ISL9519_CHARGER
{
I2C_LIQUID,
MSM_8960_GSBI10_QUP_I2C_BUS_ID,
isl_charger_i2c_info,
ARRAY_SIZE(isl_charger_i2c_info),
},
#endif /* CONFIG_ISL9519_CHARGER */
{
I2C_SURF | I2C_FFA | I2C_FLUID,
MSM_8960_GSBI3_QUP_I2C_BUS_ID,
cyttsp_info,
ARRAY_SIZE(cyttsp_info),
},
{
I2C_LIQUID,
MSM_8960_GSBI3_QUP_I2C_BUS_ID,
mxt_device_info,
ARRAY_SIZE(mxt_device_info),
},
{
I2C_SURF | I2C_FFA | I2C_LIQUID,
MSM_8960_GSBI10_QUP_I2C_BUS_ID,
sii_device_info,
ARRAY_SIZE(sii_device_info),
},
{
I2C_LIQUID | I2C_FFA,
MSM_8960_GSBI10_QUP_I2C_BUS_ID,
msm_isa1200_board_info,
ARRAY_SIZE(msm_isa1200_board_info),
},
#if defined(CONFIG_GPIO_SX150X) || defined(CONFIG_GPIO_SX150X_MODULE)
{
I2C_LIQUID,
MSM_8960_GSBI10_QUP_I2C_BUS_ID,
liquid_io_expander_i2c_info,
ARRAY_SIZE(liquid_io_expander_i2c_info),
},
#endif
};
#endif /* CONFIG_I2C */
static void __init register_i2c_devices(void)
{
#ifdef CONFIG_I2C
u8 mach_mask = 0;
int i;
#ifdef CONFIG_MSM_CAMERA
struct i2c_registry msm8960_camera_i2c_devices = {
I2C_SURF | I2C_FFA | I2C_FLUID | I2C_LIQUID | I2C_RUMI,
MSM_8960_GSBI4_QUP_I2C_BUS_ID,
msm8960_camera_board_info.board_info,
msm8960_camera_board_info.num_i2c_board_info,
};
#endif
/* Build the matching 'supported_machs' bitmask */
if (machine_is_msm8960_cdp())
mach_mask = I2C_SURF;
else if (machine_is_msm8960_fluid())
mach_mask = I2C_FLUID;
else if (machine_is_msm8960_liquid())
mach_mask = I2C_LIQUID;
else if (machine_is_msm8960_mtp())
mach_mask = I2C_FFA;
else
pr_err("unmatched machine ID in register_i2c_devices\n");
if (machine_is_msm8960_liquid()) {
if (SOCINFO_VERSION_MAJOR(socinfo_get_platform_version()) == 3)
mxt_device_info[0].platform_data =
&mxt_platform_data_3d;
else
mxt_device_info[0].platform_data =
&mxt_platform_data_2d;
}
/* Run the array and install devices as appropriate */
for (i = 0; i < ARRAY_SIZE(msm8960_i2c_devices); ++i) {
if (msm8960_i2c_devices[i].machs & mach_mask)
i2c_register_board_info(msm8960_i2c_devices[i].bus,
msm8960_i2c_devices[i].info,
msm8960_i2c_devices[i].len);
}
if (!mhl_platform_data.gpio_mhl_power)
pr_debug("mhl device configured for ext debug board\n");
#ifdef CONFIG_MSM_CAMERA
if (msm8960_camera_i2c_devices.machs & mach_mask)
i2c_register_board_info(msm8960_camera_i2c_devices.bus,
msm8960_camera_i2c_devices.info,
msm8960_camera_i2c_devices.len);
#endif
#endif
}
static void __init msm8960_tsens_init(void)
{
if (cpu_is_msm8960())
if (SOCINFO_VERSION_MAJOR(socinfo_get_version()) == 1)
return;
msm_tsens_early_init(&msm_tsens_pdata);
}
static void __init msm8960ab_update_krait_spm(void)
{
int i;
/* Update the SPM sequences for SPC and PC */
for (i = 0; i < ARRAY_SIZE(msm_spm_data); i++) {
int j;
struct msm_spm_platform_data *pdata = &msm_spm_data[i];
for (j = 0; j < pdata->num_modes; j++) {
if (pdata->modes[j].cmd ==
spm_power_collapse_without_rpm)
pdata->modes[j].cmd =
spm_power_collapse_without_rpm_krait_v3;
else if (pdata->modes[j].cmd ==
spm_power_collapse_with_rpm)
pdata->modes[j].cmd =
spm_power_collapse_with_rpm_krait_v3;
}
}
}
static void __init msm8960ab_update_retention_spm(void)
{
int i;
/* Update the SPM sequences for krait retention on all cores */
for (i = 0; i < ARRAY_SIZE(msm_spm_data); i++) {
int j;
struct msm_spm_platform_data *pdata = &msm_spm_data[i];
for (j = 0; j < pdata->num_modes; j++) {
if (pdata->modes[j].cmd ==
spm_retention_cmd_sequence)
pdata->modes[j].cmd =
spm_retention_with_krait_v3_cmd_sequence;
}
}
}
static void __init msm8960_cdp_init(void)
{
if (meminfo_init(SYS_MEMORY, SZ_256M) < 0)
pr_err("meminfo_init() failed!\n");
platform_device_register(&msm_gpio_device);
msm8960_tsens_init();
msm_thermal_init(&msm_thermal_pdata);
BUG_ON(msm_rpm_init(&msm8960_rpm_data));
BUG_ON(msm_rpmrs_levels_init(&msm_rpmrs_data));
regulator_suppress_info_printing();
if (msm_xo_init())
pr_err("Failed to initialize XO votes\n");
configure_msm8960_power_grid();
platform_device_register(&msm8960_device_rpm_regulator);
msm_clock_init(&msm8960_clock_init_data);
if (machine_is_msm8960_liquid())
msm_otg_pdata.mhl_enable = true;
msm8960_device_otg.dev.platform_data = &msm_otg_pdata;
if (machine_is_msm8960_mtp() || machine_is_msm8960_fluid() ||
machine_is_msm8960_cdp()) {
/* Due to availability of USB Switch in SGLTE Platform
* it requires different HSUSB PHY settings compare to
* 8960 MTP/CDP platform.
*/
if (socinfo_get_platform_subtype() == PLATFORM_SUBTYPE_SGLTE)
msm_otg_pdata.phy_init_seq = sglte_phy_init_seq;
else
msm_otg_pdata.phy_init_seq = wr_phy_init_seq;
} else if (machine_is_msm8960_liquid()) {
msm_otg_pdata.phy_init_seq =
liquid_v1_phy_init_seq;
}
android_usb_pdata.swfi_latency =
msm_rpmrs_levels[0].latency_us;
msm_device_hsic_host.dev.platform_data = &msm_hsic_pdata;
if (SOCINFO_VERSION_MAJOR(socinfo_get_version()) >= 2 &&
machine_is_msm8960_liquid())
msm_device_hsic_host.dev.parent = &smsc_hub_device.dev;
msm8960_init_gpiomux();
msm8960_device_qup_spi_gsbi1.dev.platform_data =
&msm8960_qup_spi_gsbi1_pdata;
spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
if (socinfo_get_platform_subtype() != PLATFORM_SUBTYPE_SGLTE)
spi_register_board_info(spi_eth_info, ARRAY_SIZE(spi_eth_info));
msm8960_init_pmic();
if (machine_is_msm8960_liquid() || (machine_is_msm8960_mtp() &&
(socinfo_get_platform_subtype() == PLATFORM_SUBTYPE_SGLTE ||
cpu_is_msm8960ab())))
msm_isa1200_board_info[0].platform_data = &isa1200_1_pdata;
msm8960_i2c_init();
msm8960_gfx_init();
if (cpu_is_msm8960ab())
msm8960ab_update_krait_spm();
if (cpu_is_krait_v3()) {
struct msm_pm_init_data_type *pdata =
msm8960_pm_8x60.dev.platform_data;
pdata->retention_calls_tz = false;
msm8960ab_update_retention_spm();
}
platform_device_register(&msm8960_pm_8x60);
msm_spm_init(msm_spm_data, ARRAY_SIZE(msm_spm_data));
msm_spm_l2_init(msm_spm_l2_data);
msm8960_init_buses();
if (cpu_is_msm8960ab()) {
platform_add_devices(msm8960ab_footswitch,
msm8960ab_num_footswitch);
} else {
platform_add_devices(msm8960_footswitch,
msm8960_num_footswitch);
}
if (machine_is_msm8960_liquid())
platform_device_register(&msm8960_device_ext_3p3v_vreg);
if (machine_is_msm8960_cdp())
platform_device_register(&msm8960_device_ext_l2_vreg);
if (socinfo_get_platform_subtype() == PLATFORM_SUBTYPE_SGLTE)
platform_device_register(&msm8960_device_uart_gsbi8);
else
platform_device_register(&msm8960_device_uart_gsbi5);
/* For 8960 Fusion 2.2 Primary IPC */
if (socinfo_get_platform_subtype() == PLATFORM_SUBTYPE_SGLTE) {
msm_uart_dm9_pdata.wakeup_irq = gpio_to_irq(94); /* GSBI9(2) */
msm_device_uart_dm9.dev.platform_data = &msm_uart_dm9_pdata;
platform_device_register(&msm_device_uart_dm9);
}
/* For 8960 Standalone External Bluetooth Interface */
if (socinfo_get_platform_subtype() != PLATFORM_SUBTYPE_SGLTE) {
msm_device_uart_dm8.dev.platform_data = &msm_uart_dm8_pdata;
platform_device_register(&msm_device_uart_dm8);
}
if (cpu_is_msm8960ab())
platform_device_register(&msm8960ab_device_acpuclk);
else
platform_device_register(&msm8960_device_acpuclk);
platform_add_devices(common_devices, ARRAY_SIZE(common_devices));
msm8960_add_vidc_device();
msm8960_pm8921_gpio_mpp_init();
/* Don't add modem devices on APQ targets */
if (socinfo_get_id() != 124) {
platform_device_register(&msm_8960_q6_mss_fw);
platform_device_register(&msm_8960_q6_mss_sw);
}
platform_add_devices(cdp_devices, ARRAY_SIZE(cdp_devices));
msm8960_init_smsc_hub();
msm8960_init_hsic();
#ifdef CONFIG_MSM_CAMERA
msm8960_init_cam();
#endif
msm8960_init_mmc();
if (machine_is_msm8960_liquid())
mxt_init_hw_liquid();
register_i2c_devices();
msm8960_init_fb();
slim_register_board_info(msm_slim_devices,
ARRAY_SIZE(msm_slim_devices));
msm8960_init_dsps();
BUG_ON(msm_pm_boot_init(&msm_pm_boot_pdata));
bt_power_init();
if (socinfo_get_platform_subtype() == PLATFORM_SUBTYPE_SGLTE) {
mdm_sglte_device.dev.platform_data = &sglte_platform_data;
platform_device_register(&mdm_sglte_device);
}
ion_adjust_secure_allocation();
}
MACHINE_START(MSM8960_CDP, "QCT MSM8960 CDP")
.map_io = msm8960_map_io,
.reserve = msm8960_reserve,
.init_irq = msm8960_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8960_cdp_init,
.init_early = msm8960_allocate_memory_regions,
.init_very_early = msm8960_early_memory,
.restart = msm_restart,
MACHINE_END
MACHINE_START(MSM8960_MTP, "QCT MSM8960 MTP")
.map_io = msm8960_map_io,
.reserve = msm8960_reserve,
.init_irq = msm8960_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8960_cdp_init,
.init_early = msm8960_allocate_memory_regions,
.init_very_early = msm8960_early_memory,
.restart = msm_restart,
MACHINE_END
MACHINE_START(MSM8960_FLUID, "QCT MSM8960 FLUID")
.map_io = msm8960_map_io,
.reserve = msm8960_reserve,
.init_irq = msm8960_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8960_cdp_init,
.init_early = msm8960_allocate_memory_regions,
.init_very_early = msm8960_early_memory,
.restart = msm_restart,
MACHINE_END
MACHINE_START(MSM8960_LIQUID, "QCT MSM8960 LIQUID")
.map_io = msm8960_map_io,
.reserve = msm8960_reserve,
.init_irq = msm8960_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm8960_cdp_init,
.init_early = msm8960_allocate_memory_regions,
.init_very_early = msm8960_early_memory,
.restart = msm_restart,
MACHINE_END
| gpl-2.0 |
extremetempz/Wingray-Kernel | drivers/mtd/maps/bcm963xx-flash.c | 260 | 7256 | /*
* Copyright © 2006-2008 Florian Fainelli <florian@openwrt.org>
* Mike Albon <malbon@openwrt.org>
* Copyright © 2009-2010 Daniel Dickinson <openwrt@cshore.neomailbox.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mtd/map.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/vmalloc.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <asm/mach-bcm63xx/bcm963xx_tag.h>
#define BCM63XX_BUSWIDTH 2 /* Buswidth */
#define BCM63XX_EXTENDED_SIZE 0xBFC00000 /* Extended flash address */
#define PFX KBUILD_MODNAME ": "
static struct mtd_partition *parsed_parts;
static struct mtd_info *bcm963xx_mtd_info;
static struct map_info bcm963xx_map = {
.name = "bcm963xx",
.bankwidth = BCM63XX_BUSWIDTH,
};
static int parse_cfe_partitions(struct mtd_info *master,
struct mtd_partition **pparts)
{
/* CFE, NVRAM and global Linux are always present */
int nrparts = 3, curpart = 0;
struct bcm_tag *buf;
struct mtd_partition *parts;
int ret;
size_t retlen;
unsigned int rootfsaddr, kerneladdr, spareaddr;
unsigned int rootfslen, kernellen, sparelen, totallen;
int namelen = 0;
int i;
char *boardid;
char *tagversion;
/* Allocate memory for buffer */
buf = vmalloc(sizeof(struct bcm_tag));
if (!buf)
return -ENOMEM;
/* Get the tag */
ret = master->read(master, master->erasesize, sizeof(struct bcm_tag),
&retlen, (void *)buf);
if (retlen != sizeof(struct bcm_tag)) {
vfree(buf);
return -EIO;
}
sscanf(buf->kernel_address, "%u", &kerneladdr);
sscanf(buf->kernel_length, "%u", &kernellen);
sscanf(buf->total_length, "%u", &totallen);
tagversion = &(buf->tag_version[0]);
boardid = &(buf->board_id[0]);
printk(KERN_INFO PFX "CFE boot tag found with version %s "
"and board type %s\n", tagversion, boardid);
kerneladdr = kerneladdr - BCM63XX_EXTENDED_SIZE;
rootfsaddr = kerneladdr + kernellen;
spareaddr = roundup(totallen, master->erasesize) + master->erasesize;
sparelen = master->size - spareaddr - master->erasesize;
rootfslen = spareaddr - rootfsaddr;
/* Determine number of partitions */
namelen = 8;
if (rootfslen > 0) {
nrparts++;
namelen += 6;
};
if (kernellen > 0) {
nrparts++;
namelen += 6;
};
/* Ask kernel for more memory */
parts = kzalloc(sizeof(*parts) * nrparts + 10 * nrparts, GFP_KERNEL);
if (!parts) {
vfree(buf);
return -ENOMEM;
};
/* Start building partition list */
parts[curpart].name = "CFE";
parts[curpart].offset = 0;
parts[curpart].size = master->erasesize;
curpart++;
if (kernellen > 0) {
parts[curpart].name = "kernel";
parts[curpart].offset = kerneladdr;
parts[curpart].size = kernellen;
curpart++;
};
if (rootfslen > 0) {
parts[curpart].name = "rootfs";
parts[curpart].offset = rootfsaddr;
parts[curpart].size = rootfslen;
if (sparelen > 0)
parts[curpart].size += sparelen;
curpart++;
};
parts[curpart].name = "nvram";
parts[curpart].offset = master->size - master->erasesize;
parts[curpart].size = master->erasesize;
/* Global partition "linux" to make easy firmware upgrade */
curpart++;
parts[curpart].name = "linux";
parts[curpart].offset = parts[0].size;
parts[curpart].size = master->size - parts[0].size - parts[3].size;
for (i = 0; i < nrparts; i++)
printk(KERN_INFO PFX "Partition %d is %s offset %lx and "
"length %lx\n", i, parts[i].name,
(long unsigned int)(parts[i].offset),
(long unsigned int)(parts[i].size));
printk(KERN_INFO PFX "Spare partition is %x offset and length %x\n",
spareaddr, sparelen);
*pparts = parts;
vfree(buf);
return nrparts;
};
static int bcm963xx_detect_cfe(struct mtd_info *master)
{
int idoffset = 0x4e0;
static char idstring[8] = "CFE1CFE1";
char buf[9];
int ret;
size_t retlen;
ret = master->read(master, idoffset, 8, &retlen, (void *)buf);
buf[retlen] = 0;
printk(KERN_INFO PFX "Read Signature value of %s\n", buf);
return strncmp(idstring, buf, 8);
}
static int bcm963xx_probe(struct platform_device *pdev)
{
int err = 0;
int parsed_nr_parts = 0;
char *part_type;
struct resource *r;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
dev_err(&pdev->dev, "no resource supplied\n");
return -ENODEV;
}
bcm963xx_map.phys = r->start;
bcm963xx_map.size = resource_size(r);
bcm963xx_map.virt = ioremap(r->start, resource_size(r));
if (!bcm963xx_map.virt) {
dev_err(&pdev->dev, "failed to ioremap\n");
return -EIO;
}
dev_info(&pdev->dev, "0x%08lx at 0x%08x\n",
bcm963xx_map.size, bcm963xx_map.phys);
simple_map_init(&bcm963xx_map);
bcm963xx_mtd_info = do_map_probe("cfi_probe", &bcm963xx_map);
if (!bcm963xx_mtd_info) {
dev_err(&pdev->dev, "failed to probe using CFI\n");
bcm963xx_mtd_info = do_map_probe("jedec_probe", &bcm963xx_map);
if (bcm963xx_mtd_info)
goto probe_ok;
dev_err(&pdev->dev, "failed to probe using JEDEC\n");
err = -EIO;
goto err_probe;
}
probe_ok:
bcm963xx_mtd_info->owner = THIS_MODULE;
/* This is mutually exclusive */
if (bcm963xx_detect_cfe(bcm963xx_mtd_info) == 0) {
dev_info(&pdev->dev, "CFE bootloader detected\n");
if (parsed_nr_parts == 0) {
int ret = parse_cfe_partitions(bcm963xx_mtd_info,
&parsed_parts);
if (ret > 0) {
part_type = "CFE";
parsed_nr_parts = ret;
}
}
} else {
dev_info(&pdev->dev, "unsupported bootloader\n");
err = -ENODEV;
goto err_probe;
}
return add_mtd_partitions(bcm963xx_mtd_info, parsed_parts,
parsed_nr_parts);
err_probe:
iounmap(bcm963xx_map.virt);
return err;
}
static int bcm963xx_remove(struct platform_device *pdev)
{
if (bcm963xx_mtd_info) {
del_mtd_partitions(bcm963xx_mtd_info);
map_destroy(bcm963xx_mtd_info);
}
if (bcm963xx_map.virt) {
iounmap(bcm963xx_map.virt);
bcm963xx_map.virt = 0;
}
return 0;
}
static struct platform_driver bcm63xx_mtd_dev = {
.probe = bcm963xx_probe,
.remove = bcm963xx_remove,
.driver = {
.name = "bcm963xx-flash",
.owner = THIS_MODULE,
},
};
static int __init bcm963xx_mtd_init(void)
{
return platform_driver_register(&bcm63xx_mtd_dev);
}
static void __exit bcm963xx_mtd_exit(void)
{
platform_driver_unregister(&bcm63xx_mtd_dev);
}
module_init(bcm963xx_mtd_init);
module_exit(bcm963xx_mtd_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Broadcom BCM63xx MTD driver for CFE and RedBoot");
MODULE_AUTHOR("Daniel Dickinson <openwrt@cshore.neomailbox.net>");
MODULE_AUTHOR("Florian Fainelli <florian@openwrt.org>");
MODULE_AUTHOR("Mike Albon <malbon@openwrt.org>");
| gpl-2.0 |
asopov/linux-tpt-2.6.39 | drivers/media/dvb/mantis/mantis_cards.c | 260 | 8076 | /*
Mantis PCI bridge driver
Copyright (C) Manu Abraham (abraham.manu@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <asm/irq.h>
#include <linux/interrupt.h>
#include "dmxdev.h"
#include "dvbdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb_net.h"
#include "mantis_common.h"
#include "mantis_vp1033.h"
#include "mantis_vp1034.h"
#include "mantis_vp1041.h"
#include "mantis_vp2033.h"
#include "mantis_vp2040.h"
#include "mantis_vp3030.h"
#include "mantis_dma.h"
#include "mantis_ca.h"
#include "mantis_dvb.h"
#include "mantis_uart.h"
#include "mantis_ioc.h"
#include "mantis_pci.h"
#include "mantis_i2c.h"
#include "mantis_reg.h"
static unsigned int verbose;
module_param(verbose, int, 0644);
MODULE_PARM_DESC(verbose, "verbose startup messages, default is 1 (yes)");
static int devs;
#define DRIVER_NAME "Mantis"
static char *label[10] = {
"DMA",
"IRQ-0",
"IRQ-1",
"OCERR",
"PABRT",
"RIPRR",
"PPERR",
"FTRGT",
"RISCI",
"RACK"
};
static irqreturn_t mantis_irq_handler(int irq, void *dev_id)
{
u32 stat = 0, mask = 0, lstat = 0, mstat = 0;
u32 rst_stat = 0, rst_mask = 0;
struct mantis_pci *mantis;
struct mantis_ca *ca;
mantis = (struct mantis_pci *) dev_id;
if (unlikely(mantis == NULL)) {
dprintk(MANTIS_ERROR, 1, "Mantis == NULL");
return IRQ_NONE;
}
ca = mantis->mantis_ca;
stat = mmread(MANTIS_INT_STAT);
mask = mmread(MANTIS_INT_MASK);
mstat = lstat = stat & ~MANTIS_INT_RISCSTAT;
if (!(stat & mask))
return IRQ_NONE;
rst_mask = MANTIS_GPIF_WRACK |
MANTIS_GPIF_OTHERR |
MANTIS_SBUF_WSTO |
MANTIS_GPIF_EXTIRQ;
rst_stat = mmread(MANTIS_GPIF_STATUS);
rst_stat &= rst_mask;
mmwrite(rst_stat, MANTIS_GPIF_STATUS);
mantis->mantis_int_stat = stat;
mantis->mantis_int_mask = mask;
dprintk(MANTIS_DEBUG, 0, "\n-- Stat=<%02x> Mask=<%02x> --", stat, mask);
if (stat & MANTIS_INT_RISCEN) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[0]);
}
if (stat & MANTIS_INT_IRQ0) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[1]);
mantis->gpif_status = rst_stat;
wake_up(&ca->hif_write_wq);
schedule_work(&ca->hif_evm_work);
}
if (stat & MANTIS_INT_IRQ1) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[2]);
schedule_work(&mantis->uart_work);
}
if (stat & MANTIS_INT_OCERR) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[3]);
}
if (stat & MANTIS_INT_PABORT) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[4]);
}
if (stat & MANTIS_INT_RIPERR) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[5]);
}
if (stat & MANTIS_INT_PPERR) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[6]);
}
if (stat & MANTIS_INT_FTRGT) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[7]);
}
if (stat & MANTIS_INT_RISCI) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[8]);
mantis->finished_block = (stat & MANTIS_INT_RISCSTAT) >> 28;
tasklet_schedule(&mantis->tasklet);
}
if (stat & MANTIS_INT_I2CDONE) {
dprintk(MANTIS_DEBUG, 0, "<%s>", label[9]);
wake_up(&mantis->i2c_wq);
}
mmwrite(stat, MANTIS_INT_STAT);
stat &= ~(MANTIS_INT_RISCEN | MANTIS_INT_I2CDONE |
MANTIS_INT_I2CRACK | MANTIS_INT_PCMCIA7 |
MANTIS_INT_PCMCIA6 | MANTIS_INT_PCMCIA5 |
MANTIS_INT_PCMCIA4 | MANTIS_INT_PCMCIA3 |
MANTIS_INT_PCMCIA2 | MANTIS_INT_PCMCIA1 |
MANTIS_INT_PCMCIA0 | MANTIS_INT_IRQ1 |
MANTIS_INT_IRQ0 | MANTIS_INT_OCERR |
MANTIS_INT_PABORT | MANTIS_INT_RIPERR |
MANTIS_INT_PPERR | MANTIS_INT_FTRGT |
MANTIS_INT_RISCI);
if (stat)
dprintk(MANTIS_DEBUG, 0, "<Unknown> Stat=<%02x> Mask=<%02x>", stat, mask);
dprintk(MANTIS_DEBUG, 0, "\n");
return IRQ_HANDLED;
}
static int __devinit mantis_pci_probe(struct pci_dev *pdev, const struct pci_device_id *pci_id)
{
struct mantis_pci *mantis;
struct mantis_hwconfig *config;
int err = 0;
mantis = kzalloc(sizeof(struct mantis_pci), GFP_KERNEL);
if (mantis == NULL) {
printk(KERN_ERR "%s ERROR: Out of memory\n", __func__);
err = -ENOMEM;
goto fail0;
}
mantis->num = devs;
mantis->verbose = verbose;
mantis->pdev = pdev;
config = (struct mantis_hwconfig *) pci_id->driver_data;
config->irq_handler = &mantis_irq_handler;
mantis->hwconfig = config;
err = mantis_pci_init(mantis);
if (err) {
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis PCI initialization failed <%d>", err);
goto fail1;
}
err = mantis_stream_control(mantis, STREAM_TO_HIF);
if (err < 0) {
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis stream control failed <%d>", err);
goto fail1;
}
err = mantis_i2c_init(mantis);
if (err < 0) {
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis I2C initialization failed <%d>", err);
goto fail2;
}
err = mantis_get_mac(mantis);
if (err < 0) {
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis MAC address read failed <%d>", err);
goto fail2;
}
err = mantis_dma_init(mantis);
if (err < 0) {
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis DMA initialization failed <%d>", err);
goto fail3;
}
err = mantis_dvb_init(mantis);
if (err < 0) {
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis DVB initialization failed <%d>", err);
goto fail4;
}
err = mantis_uart_init(mantis);
if (err < 0) {
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis UART initialization failed <%d>", err);
goto fail6;
}
devs++;
return err;
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis UART exit! <%d>", err);
mantis_uart_exit(mantis);
fail6:
fail4:
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis DMA exit! <%d>", err);
mantis_dma_exit(mantis);
fail3:
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis I2C exit! <%d>", err);
mantis_i2c_exit(mantis);
fail2:
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis PCI exit! <%d>", err);
mantis_pci_exit(mantis);
fail1:
dprintk(MANTIS_ERROR, 1, "ERROR: Mantis free! <%d>", err);
kfree(mantis);
fail0:
return err;
}
static void __devexit mantis_pci_remove(struct pci_dev *pdev)
{
struct mantis_pci *mantis = pci_get_drvdata(pdev);
if (mantis) {
mantis_uart_exit(mantis);
mantis_dvb_exit(mantis);
mantis_dma_exit(mantis);
mantis_i2c_exit(mantis);
mantis_pci_exit(mantis);
kfree(mantis);
}
return;
}
static struct pci_device_id mantis_pci_table[] = {
MAKE_ENTRY(TWINHAN_TECHNOLOGIES, MANTIS_VP_1033_DVB_S, &vp1033_config),
MAKE_ENTRY(TWINHAN_TECHNOLOGIES, MANTIS_VP_1034_DVB_S, &vp1034_config),
MAKE_ENTRY(TWINHAN_TECHNOLOGIES, MANTIS_VP_1041_DVB_S2, &vp1041_config),
MAKE_ENTRY(TECHNISAT, SKYSTAR_HD2_10, &vp1041_config),
MAKE_ENTRY(TECHNISAT, SKYSTAR_HD2_20, &vp1041_config),
MAKE_ENTRY(TERRATEC, CINERGY_S2_PCI_HD, &vp1041_config),
MAKE_ENTRY(TWINHAN_TECHNOLOGIES, MANTIS_VP_2033_DVB_C, &vp2033_config),
MAKE_ENTRY(TWINHAN_TECHNOLOGIES, MANTIS_VP_2040_DVB_C, &vp2040_config),
MAKE_ENTRY(TECHNISAT, CABLESTAR_HD2, &vp2040_config),
MAKE_ENTRY(TERRATEC, CINERGY_C, &vp2033_config),
MAKE_ENTRY(TWINHAN_TECHNOLOGIES, MANTIS_VP_3030_DVB_T, &vp3030_config),
{ }
};
MODULE_DEVICE_TABLE(pci, mantis_pci_table);
static struct pci_driver mantis_pci_driver = {
.name = DRIVER_NAME,
.id_table = mantis_pci_table,
.probe = mantis_pci_probe,
.remove = mantis_pci_remove,
};
static int __devinit mantis_init(void)
{
return pci_register_driver(&mantis_pci_driver);
}
static void __devexit mantis_exit(void)
{
return pci_unregister_driver(&mantis_pci_driver);
}
module_init(mantis_init);
module_exit(mantis_exit);
MODULE_DESCRIPTION("MANTIS driver");
MODULE_AUTHOR("Manu Abraham");
MODULE_LICENSE("GPL");
| gpl-2.0 |
firstred/surfacepro3-kernel | drivers/staging/lustre/lustre/obdclass/lustre_peer.c | 516 | 5349 | /*
* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 only,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is included
* in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; If not, see
* http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* GPL HEADER END
*/
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*
* Copyright (c) 2011, 2012, Intel Corporation.
*/
/*
* This file is part of Lustre, http://www.lustre.org/
* Lustre is a trademark of Sun Microsystems, Inc.
*/
#define DEBUG_SUBSYSTEM S_RPC
#include <obd.h>
#include <obd_support.h>
#include <obd_class.h>
#include <lustre_lib.h>
#include <lustre_ha.h>
#include <lustre_net.h>
#include <lprocfs_status.h>
#define NIDS_MAX 32
struct uuid_nid_data {
struct list_head un_list;
struct obd_uuid un_uuid;
int un_nid_count;
lnet_nid_t un_nids[NIDS_MAX];
};
/* FIXME: This should probably become more elegant than a global linked list */
static struct list_head g_uuid_list;
static spinlock_t g_uuid_lock;
void class_init_uuidlist(void)
{
INIT_LIST_HEAD(&g_uuid_list);
spin_lock_init(&g_uuid_lock);
}
void class_exit_uuidlist(void)
{
/* delete all */
class_del_uuid(NULL);
}
int lustre_uuid_to_peer(const char *uuid, lnet_nid_t *peer_nid, int index)
{
struct uuid_nid_data *data;
struct obd_uuid tmp;
int rc = -ENOENT;
obd_str2uuid(&tmp, uuid);
spin_lock(&g_uuid_lock);
list_for_each_entry(data, &g_uuid_list, un_list) {
if (obd_uuid_equals(&data->un_uuid, &tmp)) {
if (index >= data->un_nid_count)
break;
rc = 0;
*peer_nid = data->un_nids[index];
break;
}
}
spin_unlock(&g_uuid_lock);
return rc;
}
EXPORT_SYMBOL(lustre_uuid_to_peer);
/* Add a nid to a niduuid. Multiple nids can be added to a single uuid;
LNET will choose the best one. */
int class_add_uuid(const char *uuid, __u64 nid)
{
struct uuid_nid_data *data, *entry;
int found = 0;
LASSERT(nid != 0); /* valid newconfig NID is never zero */
if (strlen(uuid) > UUID_MAX - 1)
return -EOVERFLOW;
OBD_ALLOC_PTR(data);
if (data == NULL)
return -ENOMEM;
obd_str2uuid(&data->un_uuid, uuid);
data->un_nids[0] = nid;
data->un_nid_count = 1;
spin_lock(&g_uuid_lock);
list_for_each_entry(entry, &g_uuid_list, un_list) {
if (obd_uuid_equals(&entry->un_uuid, &data->un_uuid)) {
int i;
found = 1;
for (i = 0; i < entry->un_nid_count; i++)
if (nid == entry->un_nids[i])
break;
if (i == entry->un_nid_count) {
LASSERT(entry->un_nid_count < NIDS_MAX);
entry->un_nids[entry->un_nid_count++] = nid;
}
break;
}
}
if (!found)
list_add(&data->un_list, &g_uuid_list);
spin_unlock(&g_uuid_lock);
if (found) {
CDEBUG(D_INFO, "found uuid %s %s cnt=%d\n", uuid,
libcfs_nid2str(nid), entry->un_nid_count);
OBD_FREE(data, sizeof(*data));
} else {
CDEBUG(D_INFO, "add uuid %s %s\n", uuid, libcfs_nid2str(nid));
}
return 0;
}
EXPORT_SYMBOL(class_add_uuid);
/* Delete the nids for one uuid if specified, otherwise delete all */
int class_del_uuid(const char *uuid)
{
LIST_HEAD(deathrow);
struct uuid_nid_data *data;
spin_lock(&g_uuid_lock);
if (uuid != NULL) {
struct obd_uuid tmp;
obd_str2uuid(&tmp, uuid);
list_for_each_entry(data, &g_uuid_list, un_list) {
if (obd_uuid_equals(&data->un_uuid, &tmp)) {
list_move(&data->un_list, &deathrow);
break;
}
}
} else
list_splice_init(&g_uuid_list, &deathrow);
spin_unlock(&g_uuid_lock);
if (uuid != NULL && list_empty(&deathrow)) {
CDEBUG(D_INFO, "Try to delete a non-existent uuid %s\n", uuid);
return -EINVAL;
}
while (!list_empty(&deathrow)) {
data = list_entry(deathrow.next, struct uuid_nid_data,
un_list);
list_del(&data->un_list);
CDEBUG(D_INFO, "del uuid %s %s/%d\n",
obd_uuid2str(&data->un_uuid),
libcfs_nid2str(data->un_nids[0]),
data->un_nid_count);
OBD_FREE(data, sizeof(*data));
}
return 0;
}
/* check if @nid exists in nid list of @uuid */
int class_check_uuid(struct obd_uuid *uuid, __u64 nid)
{
struct uuid_nid_data *entry;
int found = 0;
CDEBUG(D_INFO, "check if uuid %s has %s.\n",
obd_uuid2str(uuid), libcfs_nid2str(nid));
spin_lock(&g_uuid_lock);
list_for_each_entry(entry, &g_uuid_list, un_list) {
int i;
if (!obd_uuid_equals(&entry->un_uuid, uuid))
continue;
/* found the uuid, check if it has @nid */
for (i = 0; i < entry->un_nid_count; i++) {
if (entry->un_nids[i] == nid) {
found = 1;
break;
}
}
break;
}
spin_unlock(&g_uuid_lock);
return found;
}
EXPORT_SYMBOL(class_check_uuid);
| gpl-2.0 |
AndroidForWave/android_kernel_samsung_wave | net/core/rtnetlink.c | 516 | 51548 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Routing netlink socket interface: protocol independent part.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*
* 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.
*
* Fixes:
* Vitaly E. Lavrov RTA_OK arithmetics was wrong.
*/
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/security.h>
#include <linux/mutex.h>
#include <linux/if_addr.h>
#include <linux/pci.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <net/ip.h>
#include <net/protocol.h>
#include <net/arp.h>
#include <net/route.h>
#include <net/udp.h>
#include <net/sock.h>
#include <net/pkt_sched.h>
#include <net/fib_rules.h>
#include <net/rtnetlink.h>
#include <net/net_namespace.h>
struct rtnl_link {
rtnl_doit_func doit;
rtnl_dumpit_func dumpit;
rtnl_calcit_func calcit;
};
static DEFINE_MUTEX(rtnl_mutex);
void rtnl_lock(void)
{
mutex_lock(&rtnl_mutex);
}
EXPORT_SYMBOL(rtnl_lock);
void __rtnl_unlock(void)
{
mutex_unlock(&rtnl_mutex);
}
void rtnl_unlock(void)
{
/* This fellow will unlock it for us. */
netdev_run_todo();
}
EXPORT_SYMBOL(rtnl_unlock);
int rtnl_trylock(void)
{
return mutex_trylock(&rtnl_mutex);
}
EXPORT_SYMBOL(rtnl_trylock);
int rtnl_is_locked(void)
{
return mutex_is_locked(&rtnl_mutex);
}
EXPORT_SYMBOL(rtnl_is_locked);
#ifdef CONFIG_PROVE_LOCKING
int lockdep_rtnl_is_held(void)
{
return lockdep_is_held(&rtnl_mutex);
}
EXPORT_SYMBOL(lockdep_rtnl_is_held);
#endif /* #ifdef CONFIG_PROVE_LOCKING */
static struct rtnl_link *rtnl_msg_handlers[RTNL_FAMILY_MAX + 1];
static inline int rtm_msgindex(int msgtype)
{
int msgindex = msgtype - RTM_BASE;
/*
* msgindex < 0 implies someone tried to register a netlink
* control code. msgindex >= RTM_NR_MSGTYPES may indicate that
* the message type has not been added to linux/rtnetlink.h
*/
BUG_ON(msgindex < 0 || msgindex >= RTM_NR_MSGTYPES);
return msgindex;
}
static rtnl_doit_func rtnl_get_doit(int protocol, int msgindex)
{
struct rtnl_link *tab;
if (protocol <= RTNL_FAMILY_MAX)
tab = rtnl_msg_handlers[protocol];
else
tab = NULL;
if (tab == NULL || tab[msgindex].doit == NULL)
tab = rtnl_msg_handlers[PF_UNSPEC];
return tab ? tab[msgindex].doit : NULL;
}
static rtnl_dumpit_func rtnl_get_dumpit(int protocol, int msgindex)
{
struct rtnl_link *tab;
if (protocol <= RTNL_FAMILY_MAX)
tab = rtnl_msg_handlers[protocol];
else
tab = NULL;
if (tab == NULL || tab[msgindex].dumpit == NULL)
tab = rtnl_msg_handlers[PF_UNSPEC];
return tab ? tab[msgindex].dumpit : NULL;
}
static rtnl_calcit_func rtnl_get_calcit(int protocol, int msgindex)
{
struct rtnl_link *tab;
if (protocol <= RTNL_FAMILY_MAX)
tab = rtnl_msg_handlers[protocol];
else
tab = NULL;
if (tab == NULL || tab[msgindex].calcit == NULL)
tab = rtnl_msg_handlers[PF_UNSPEC];
return tab ? tab[msgindex].calcit : NULL;
}
/**
* __rtnl_register - Register a rtnetlink message type
* @protocol: Protocol family or PF_UNSPEC
* @msgtype: rtnetlink message type
* @doit: Function pointer called for each request message
* @dumpit: Function pointer called for each dump request (NLM_F_DUMP) message
* @calcit: Function pointer to calc size of dump message
*
* Registers the specified function pointers (at least one of them has
* to be non-NULL) to be called whenever a request message for the
* specified protocol family and message type is received.
*
* The special protocol family PF_UNSPEC may be used to define fallback
* function pointers for the case when no entry for the specific protocol
* family exists.
*
* Returns 0 on success or a negative error code.
*/
int __rtnl_register(int protocol, int msgtype,
rtnl_doit_func doit, rtnl_dumpit_func dumpit,
rtnl_calcit_func calcit)
{
struct rtnl_link *tab;
int msgindex;
BUG_ON(protocol < 0 || protocol > RTNL_FAMILY_MAX);
msgindex = rtm_msgindex(msgtype);
tab = rtnl_msg_handlers[protocol];
if (tab == NULL) {
tab = kcalloc(RTM_NR_MSGTYPES, sizeof(*tab), GFP_KERNEL);
if (tab == NULL)
return -ENOBUFS;
rtnl_msg_handlers[protocol] = tab;
}
if (doit)
tab[msgindex].doit = doit;
if (dumpit)
tab[msgindex].dumpit = dumpit;
if (calcit)
tab[msgindex].calcit = calcit;
return 0;
}
EXPORT_SYMBOL_GPL(__rtnl_register);
/**
* rtnl_register - Register a rtnetlink message type
*
* Identical to __rtnl_register() but panics on failure. This is useful
* as failure of this function is very unlikely, it can only happen due
* to lack of memory when allocating the chain to store all message
* handlers for a protocol. Meant for use in init functions where lack
* of memory implies no sense in continuing.
*/
void rtnl_register(int protocol, int msgtype,
rtnl_doit_func doit, rtnl_dumpit_func dumpit,
rtnl_calcit_func calcit)
{
if (__rtnl_register(protocol, msgtype, doit, dumpit, calcit) < 0)
panic("Unable to register rtnetlink message handler, "
"protocol = %d, message type = %d\n",
protocol, msgtype);
}
EXPORT_SYMBOL_GPL(rtnl_register);
/**
* rtnl_unregister - Unregister a rtnetlink message type
* @protocol: Protocol family or PF_UNSPEC
* @msgtype: rtnetlink message type
*
* Returns 0 on success or a negative error code.
*/
int rtnl_unregister(int protocol, int msgtype)
{
int msgindex;
BUG_ON(protocol < 0 || protocol > RTNL_FAMILY_MAX);
msgindex = rtm_msgindex(msgtype);
if (rtnl_msg_handlers[protocol] == NULL)
return -ENOENT;
rtnl_msg_handlers[protocol][msgindex].doit = NULL;
rtnl_msg_handlers[protocol][msgindex].dumpit = NULL;
return 0;
}
EXPORT_SYMBOL_GPL(rtnl_unregister);
/**
* rtnl_unregister_all - Unregister all rtnetlink message type of a protocol
* @protocol : Protocol family or PF_UNSPEC
*
* Identical to calling rtnl_unregster() for all registered message types
* of a certain protocol family.
*/
void rtnl_unregister_all(int protocol)
{
BUG_ON(protocol < 0 || protocol > RTNL_FAMILY_MAX);
kfree(rtnl_msg_handlers[protocol]);
rtnl_msg_handlers[protocol] = NULL;
}
EXPORT_SYMBOL_GPL(rtnl_unregister_all);
static LIST_HEAD(link_ops);
/**
* __rtnl_link_register - Register rtnl_link_ops with rtnetlink.
* @ops: struct rtnl_link_ops * to register
*
* The caller must hold the rtnl_mutex. This function should be used
* by drivers that create devices during module initialization. It
* must be called before registering the devices.
*
* Returns 0 on success or a negative error code.
*/
int __rtnl_link_register(struct rtnl_link_ops *ops)
{
if (!ops->dellink)
ops->dellink = unregister_netdevice_queue;
list_add_tail(&ops->list, &link_ops);
return 0;
}
EXPORT_SYMBOL_GPL(__rtnl_link_register);
/**
* rtnl_link_register - Register rtnl_link_ops with rtnetlink.
* @ops: struct rtnl_link_ops * to register
*
* Returns 0 on success or a negative error code.
*/
int rtnl_link_register(struct rtnl_link_ops *ops)
{
int err;
rtnl_lock();
err = __rtnl_link_register(ops);
rtnl_unlock();
return err;
}
EXPORT_SYMBOL_GPL(rtnl_link_register);
static void __rtnl_kill_links(struct net *net, struct rtnl_link_ops *ops)
{
struct net_device *dev;
LIST_HEAD(list_kill);
for_each_netdev(net, dev) {
if (dev->rtnl_link_ops == ops)
ops->dellink(dev, &list_kill);
}
unregister_netdevice_many(&list_kill);
}
/**
* __rtnl_link_unregister - Unregister rtnl_link_ops from rtnetlink.
* @ops: struct rtnl_link_ops * to unregister
*
* The caller must hold the rtnl_mutex.
*/
void __rtnl_link_unregister(struct rtnl_link_ops *ops)
{
struct net *net;
for_each_net(net) {
__rtnl_kill_links(net, ops);
}
list_del(&ops->list);
}
EXPORT_SYMBOL_GPL(__rtnl_link_unregister);
/**
* rtnl_link_unregister - Unregister rtnl_link_ops from rtnetlink.
* @ops: struct rtnl_link_ops * to unregister
*/
void rtnl_link_unregister(struct rtnl_link_ops *ops)
{
rtnl_lock();
__rtnl_link_unregister(ops);
rtnl_unlock();
}
EXPORT_SYMBOL_GPL(rtnl_link_unregister);
static const struct rtnl_link_ops *rtnl_link_ops_get(const char *kind)
{
const struct rtnl_link_ops *ops;
list_for_each_entry(ops, &link_ops, list) {
if (!strcmp(ops->kind, kind))
return ops;
}
return NULL;
}
static size_t rtnl_link_get_size(const struct net_device *dev)
{
const struct rtnl_link_ops *ops = dev->rtnl_link_ops;
size_t size;
if (!ops)
return 0;
size = nla_total_size(sizeof(struct nlattr)) + /* IFLA_LINKINFO */
nla_total_size(strlen(ops->kind) + 1); /* IFLA_INFO_KIND */
if (ops->get_size)
/* IFLA_INFO_DATA + nested data */
size += nla_total_size(sizeof(struct nlattr)) +
ops->get_size(dev);
if (ops->get_xstats_size)
/* IFLA_INFO_XSTATS */
size += nla_total_size(ops->get_xstats_size(dev));
return size;
}
static LIST_HEAD(rtnl_af_ops);
static const struct rtnl_af_ops *rtnl_af_lookup(const int family)
{
const struct rtnl_af_ops *ops;
list_for_each_entry(ops, &rtnl_af_ops, list) {
if (ops->family == family)
return ops;
}
return NULL;
}
/**
* __rtnl_af_register - Register rtnl_af_ops with rtnetlink.
* @ops: struct rtnl_af_ops * to register
*
* The caller must hold the rtnl_mutex.
*
* Returns 0 on success or a negative error code.
*/
int __rtnl_af_register(struct rtnl_af_ops *ops)
{
list_add_tail(&ops->list, &rtnl_af_ops);
return 0;
}
EXPORT_SYMBOL_GPL(__rtnl_af_register);
/**
* rtnl_af_register - Register rtnl_af_ops with rtnetlink.
* @ops: struct rtnl_af_ops * to register
*
* Returns 0 on success or a negative error code.
*/
int rtnl_af_register(struct rtnl_af_ops *ops)
{
int err;
rtnl_lock();
err = __rtnl_af_register(ops);
rtnl_unlock();
return err;
}
EXPORT_SYMBOL_GPL(rtnl_af_register);
/**
* __rtnl_af_unregister - Unregister rtnl_af_ops from rtnetlink.
* @ops: struct rtnl_af_ops * to unregister
*
* The caller must hold the rtnl_mutex.
*/
void __rtnl_af_unregister(struct rtnl_af_ops *ops)
{
list_del(&ops->list);
}
EXPORT_SYMBOL_GPL(__rtnl_af_unregister);
/**
* rtnl_af_unregister - Unregister rtnl_af_ops from rtnetlink.
* @ops: struct rtnl_af_ops * to unregister
*/
void rtnl_af_unregister(struct rtnl_af_ops *ops)
{
rtnl_lock();
__rtnl_af_unregister(ops);
rtnl_unlock();
}
EXPORT_SYMBOL_GPL(rtnl_af_unregister);
static size_t rtnl_link_get_af_size(const struct net_device *dev)
{
struct rtnl_af_ops *af_ops;
size_t size;
/* IFLA_AF_SPEC */
size = nla_total_size(sizeof(struct nlattr));
list_for_each_entry(af_ops, &rtnl_af_ops, list) {
if (af_ops->get_link_af_size) {
/* AF_* + nested data */
size += nla_total_size(sizeof(struct nlattr)) +
af_ops->get_link_af_size(dev);
}
}
return size;
}
static int rtnl_link_fill(struct sk_buff *skb, const struct net_device *dev)
{
const struct rtnl_link_ops *ops = dev->rtnl_link_ops;
struct nlattr *linkinfo, *data;
int err = -EMSGSIZE;
linkinfo = nla_nest_start(skb, IFLA_LINKINFO);
if (linkinfo == NULL)
goto out;
if (nla_put_string(skb, IFLA_INFO_KIND, ops->kind) < 0)
goto err_cancel_link;
if (ops->fill_xstats) {
err = ops->fill_xstats(skb, dev);
if (err < 0)
goto err_cancel_link;
}
if (ops->fill_info) {
data = nla_nest_start(skb, IFLA_INFO_DATA);
if (data == NULL)
goto err_cancel_link;
err = ops->fill_info(skb, dev);
if (err < 0)
goto err_cancel_data;
nla_nest_end(skb, data);
}
nla_nest_end(skb, linkinfo);
return 0;
err_cancel_data:
nla_nest_cancel(skb, data);
err_cancel_link:
nla_nest_cancel(skb, linkinfo);
out:
return err;
}
static const int rtm_min[RTM_NR_FAMILIES] =
{
[RTM_FAM(RTM_NEWLINK)] = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
[RTM_FAM(RTM_NEWADDR)] = NLMSG_LENGTH(sizeof(struct ifaddrmsg)),
[RTM_FAM(RTM_NEWROUTE)] = NLMSG_LENGTH(sizeof(struct rtmsg)),
[RTM_FAM(RTM_NEWRULE)] = NLMSG_LENGTH(sizeof(struct fib_rule_hdr)),
[RTM_FAM(RTM_NEWQDISC)] = NLMSG_LENGTH(sizeof(struct tcmsg)),
[RTM_FAM(RTM_NEWTCLASS)] = NLMSG_LENGTH(sizeof(struct tcmsg)),
[RTM_FAM(RTM_NEWTFILTER)] = NLMSG_LENGTH(sizeof(struct tcmsg)),
[RTM_FAM(RTM_NEWACTION)] = NLMSG_LENGTH(sizeof(struct tcamsg)),
[RTM_FAM(RTM_GETMULTICAST)] = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
[RTM_FAM(RTM_GETANYCAST)] = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
};
static const int rta_max[RTM_NR_FAMILIES] =
{
[RTM_FAM(RTM_NEWLINK)] = IFLA_MAX,
[RTM_FAM(RTM_NEWADDR)] = IFA_MAX,
[RTM_FAM(RTM_NEWROUTE)] = RTA_MAX,
[RTM_FAM(RTM_NEWRULE)] = FRA_MAX,
[RTM_FAM(RTM_NEWQDISC)] = TCA_MAX,
[RTM_FAM(RTM_NEWTCLASS)] = TCA_MAX,
[RTM_FAM(RTM_NEWTFILTER)] = TCA_MAX,
[RTM_FAM(RTM_NEWACTION)] = TCAA_MAX,
};
void __rta_fill(struct sk_buff *skb, int attrtype, int attrlen, const void *data)
{
struct rtattr *rta;
int size = RTA_LENGTH(attrlen);
rta = (struct rtattr *)skb_put(skb, RTA_ALIGN(size));
rta->rta_type = attrtype;
rta->rta_len = size;
memcpy(RTA_DATA(rta), data, attrlen);
memset(RTA_DATA(rta) + attrlen, 0, RTA_ALIGN(size) - size);
}
EXPORT_SYMBOL(__rta_fill);
int rtnetlink_send(struct sk_buff *skb, struct net *net, u32 pid, unsigned group, int echo)
{
struct sock *rtnl = net->rtnl;
int err = 0;
NETLINK_CB(skb).dst_group = group;
if (echo)
atomic_inc(&skb->users);
netlink_broadcast(rtnl, skb, pid, group, GFP_KERNEL);
if (echo)
err = netlink_unicast(rtnl, skb, pid, MSG_DONTWAIT);
return err;
}
int rtnl_unicast(struct sk_buff *skb, struct net *net, u32 pid)
{
struct sock *rtnl = net->rtnl;
return nlmsg_unicast(rtnl, skb, pid);
}
EXPORT_SYMBOL(rtnl_unicast);
void rtnl_notify(struct sk_buff *skb, struct net *net, u32 pid, u32 group,
struct nlmsghdr *nlh, gfp_t flags)
{
struct sock *rtnl = net->rtnl;
int report = 0;
if (nlh)
report = nlmsg_report(nlh);
nlmsg_notify(rtnl, skb, pid, group, report, flags);
}
EXPORT_SYMBOL(rtnl_notify);
void rtnl_set_sk_err(struct net *net, u32 group, int error)
{
struct sock *rtnl = net->rtnl;
netlink_set_err(rtnl, 0, group, error);
}
EXPORT_SYMBOL(rtnl_set_sk_err);
int rtnetlink_put_metrics(struct sk_buff *skb, u32 *metrics)
{
struct nlattr *mx;
int i, valid = 0;
mx = nla_nest_start(skb, RTA_METRICS);
if (mx == NULL)
return -ENOBUFS;
for (i = 0; i < RTAX_MAX; i++) {
if (metrics[i]) {
valid++;
NLA_PUT_U32(skb, i+1, metrics[i]);
}
}
if (!valid) {
nla_nest_cancel(skb, mx);
return 0;
}
return nla_nest_end(skb, mx);
nla_put_failure:
nla_nest_cancel(skb, mx);
return -EMSGSIZE;
}
EXPORT_SYMBOL(rtnetlink_put_metrics);
int rtnl_put_cacheinfo(struct sk_buff *skb, struct dst_entry *dst, u32 id,
u32 ts, u32 tsage, long expires, u32 error)
{
struct rta_cacheinfo ci = {
.rta_lastuse = jiffies_to_clock_t(jiffies - dst->lastuse),
.rta_used = dst->__use,
.rta_clntref = atomic_read(&(dst->__refcnt)),
.rta_error = error,
.rta_id = id,
.rta_ts = ts,
.rta_tsage = tsage,
};
if (expires)
ci.rta_expires = jiffies_to_clock_t(expires);
return nla_put(skb, RTA_CACHEINFO, sizeof(ci), &ci);
}
EXPORT_SYMBOL_GPL(rtnl_put_cacheinfo);
static void set_operstate(struct net_device *dev, unsigned char transition)
{
unsigned char operstate = dev->operstate;
switch (transition) {
case IF_OPER_UP:
if ((operstate == IF_OPER_DORMANT ||
operstate == IF_OPER_UNKNOWN) &&
!netif_dormant(dev))
operstate = IF_OPER_UP;
break;
case IF_OPER_DORMANT:
if (operstate == IF_OPER_UP ||
operstate == IF_OPER_UNKNOWN)
operstate = IF_OPER_DORMANT;
break;
}
if (dev->operstate != operstate) {
write_lock_bh(&dev_base_lock);
dev->operstate = operstate;
write_unlock_bh(&dev_base_lock);
netdev_state_change(dev);
}
}
static unsigned int rtnl_dev_get_flags(const struct net_device *dev)
{
return (dev->flags & ~(IFF_PROMISC | IFF_ALLMULTI)) |
(dev->gflags & (IFF_PROMISC | IFF_ALLMULTI));
}
static unsigned int rtnl_dev_combine_flags(const struct net_device *dev,
const struct ifinfomsg *ifm)
{
unsigned int flags = ifm->ifi_flags;
/* bugwards compatibility: ifi_change == 0 is treated as ~0 */
if (ifm->ifi_change)
flags = (flags & ifm->ifi_change) |
(rtnl_dev_get_flags(dev) & ~ifm->ifi_change);
return flags;
}
static void copy_rtnl_link_stats(struct rtnl_link_stats *a,
const struct rtnl_link_stats64 *b)
{
a->rx_packets = b->rx_packets;
a->tx_packets = b->tx_packets;
a->rx_bytes = b->rx_bytes;
a->tx_bytes = b->tx_bytes;
a->rx_errors = b->rx_errors;
a->tx_errors = b->tx_errors;
a->rx_dropped = b->rx_dropped;
a->tx_dropped = b->tx_dropped;
a->multicast = b->multicast;
a->collisions = b->collisions;
a->rx_length_errors = b->rx_length_errors;
a->rx_over_errors = b->rx_over_errors;
a->rx_crc_errors = b->rx_crc_errors;
a->rx_frame_errors = b->rx_frame_errors;
a->rx_fifo_errors = b->rx_fifo_errors;
a->rx_missed_errors = b->rx_missed_errors;
a->tx_aborted_errors = b->tx_aborted_errors;
a->tx_carrier_errors = b->tx_carrier_errors;
a->tx_fifo_errors = b->tx_fifo_errors;
a->tx_heartbeat_errors = b->tx_heartbeat_errors;
a->tx_window_errors = b->tx_window_errors;
a->rx_compressed = b->rx_compressed;
a->tx_compressed = b->tx_compressed;
}
static void copy_rtnl_link_stats64(void *v, const struct rtnl_link_stats64 *b)
{
memcpy(v, b, sizeof(*b));
}
/* All VF info */
static inline int rtnl_vfinfo_size(const struct net_device *dev,
u32 ext_filter_mask)
{
if (dev->dev.parent && dev_is_pci(dev->dev.parent) &&
(ext_filter_mask & RTEXT_FILTER_VF)) {
int num_vfs = dev_num_vf(dev->dev.parent);
size_t size = nla_total_size(sizeof(struct nlattr));
size += nla_total_size(num_vfs * sizeof(struct nlattr));
size += num_vfs *
(nla_total_size(sizeof(struct ifla_vf_mac)) +
nla_total_size(sizeof(struct ifla_vf_vlan)) +
nla_total_size(sizeof(struct ifla_vf_tx_rate)));
return size;
} else
return 0;
}
static size_t rtnl_port_size(const struct net_device *dev)
{
size_t port_size = nla_total_size(4) /* PORT_VF */
+ nla_total_size(PORT_PROFILE_MAX) /* PORT_PROFILE */
+ nla_total_size(sizeof(struct ifla_port_vsi))
/* PORT_VSI_TYPE */
+ nla_total_size(PORT_UUID_MAX) /* PORT_INSTANCE_UUID */
+ nla_total_size(PORT_UUID_MAX) /* PORT_HOST_UUID */
+ nla_total_size(1) /* PROT_VDP_REQUEST */
+ nla_total_size(2); /* PORT_VDP_RESPONSE */
size_t vf_ports_size = nla_total_size(sizeof(struct nlattr));
size_t vf_port_size = nla_total_size(sizeof(struct nlattr))
+ port_size;
size_t port_self_size = nla_total_size(sizeof(struct nlattr))
+ port_size;
if (!dev->netdev_ops->ndo_get_vf_port || !dev->dev.parent)
return 0;
if (dev_num_vf(dev->dev.parent))
return port_self_size + vf_ports_size +
vf_port_size * dev_num_vf(dev->dev.parent);
else
return port_self_size;
}
static noinline size_t if_nlmsg_size(const struct net_device *dev,
u32 ext_filter_mask)
{
return NLMSG_ALIGN(sizeof(struct ifinfomsg))
+ nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */
+ nla_total_size(IFALIASZ) /* IFLA_IFALIAS */
+ nla_total_size(IFNAMSIZ) /* IFLA_QDISC */
+ nla_total_size(sizeof(struct rtnl_link_ifmap))
+ nla_total_size(sizeof(struct rtnl_link_stats))
+ nla_total_size(sizeof(struct rtnl_link_stats64))
+ nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */
+ nla_total_size(MAX_ADDR_LEN) /* IFLA_BROADCAST */
+ nla_total_size(4) /* IFLA_TXQLEN */
+ nla_total_size(4) /* IFLA_WEIGHT */
+ nla_total_size(4) /* IFLA_MTU */
+ nla_total_size(4) /* IFLA_LINK */
+ nla_total_size(4) /* IFLA_MASTER */
+ nla_total_size(1) /* IFLA_OPERSTATE */
+ nla_total_size(1) /* IFLA_LINKMODE */
+ nla_total_size(ext_filter_mask
& RTEXT_FILTER_VF ? 4 : 0) /* IFLA_NUM_VF */
+ rtnl_vfinfo_size(dev, ext_filter_mask) /* IFLA_VFINFO_LIST */
+ rtnl_port_size(dev) /* IFLA_VF_PORTS + IFLA_PORT_SELF */
+ rtnl_link_get_size(dev) /* IFLA_LINKINFO */
+ rtnl_link_get_af_size(dev); /* IFLA_AF_SPEC */
}
static int rtnl_vf_ports_fill(struct sk_buff *skb, struct net_device *dev)
{
struct nlattr *vf_ports;
struct nlattr *vf_port;
int vf;
int err;
vf_ports = nla_nest_start(skb, IFLA_VF_PORTS);
if (!vf_ports)
return -EMSGSIZE;
for (vf = 0; vf < dev_num_vf(dev->dev.parent); vf++) {
vf_port = nla_nest_start(skb, IFLA_VF_PORT);
if (!vf_port)
goto nla_put_failure;
NLA_PUT_U32(skb, IFLA_PORT_VF, vf);
err = dev->netdev_ops->ndo_get_vf_port(dev, vf, skb);
if (err == -EMSGSIZE)
goto nla_put_failure;
if (err) {
nla_nest_cancel(skb, vf_port);
continue;
}
nla_nest_end(skb, vf_port);
}
nla_nest_end(skb, vf_ports);
return 0;
nla_put_failure:
nla_nest_cancel(skb, vf_ports);
return -EMSGSIZE;
}
static int rtnl_port_self_fill(struct sk_buff *skb, struct net_device *dev)
{
struct nlattr *port_self;
int err;
port_self = nla_nest_start(skb, IFLA_PORT_SELF);
if (!port_self)
return -EMSGSIZE;
err = dev->netdev_ops->ndo_get_vf_port(dev, PORT_SELF_VF, skb);
if (err) {
nla_nest_cancel(skb, port_self);
return (err == -EMSGSIZE) ? err : 0;
}
nla_nest_end(skb, port_self);
return 0;
}
static int rtnl_port_fill(struct sk_buff *skb, struct net_device *dev)
{
int err;
if (!dev->netdev_ops->ndo_get_vf_port || !dev->dev.parent)
return 0;
err = rtnl_port_self_fill(skb, dev);
if (err)
return err;
if (dev_num_vf(dev->dev.parent)) {
err = rtnl_vf_ports_fill(skb, dev);
if (err)
return err;
}
return 0;
}
static int rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev,
int type, u32 pid, u32 seq, u32 change,
unsigned int flags, u32 ext_filter_mask)
{
struct ifinfomsg *ifm;
struct nlmsghdr *nlh;
struct rtnl_link_stats64 temp;
const struct rtnl_link_stats64 *stats;
struct nlattr *attr, *af_spec;
struct rtnl_af_ops *af_ops;
ASSERT_RTNL();
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags);
if (nlh == NULL)
return -EMSGSIZE;
ifm = nlmsg_data(nlh);
ifm->ifi_family = AF_UNSPEC;
ifm->__ifi_pad = 0;
ifm->ifi_type = dev->type;
ifm->ifi_index = dev->ifindex;
ifm->ifi_flags = dev_get_flags(dev);
ifm->ifi_change = change;
NLA_PUT_STRING(skb, IFLA_IFNAME, dev->name);
NLA_PUT_U32(skb, IFLA_TXQLEN, dev->tx_queue_len);
NLA_PUT_U8(skb, IFLA_OPERSTATE,
netif_running(dev) ? dev->operstate : IF_OPER_DOWN);
NLA_PUT_U8(skb, IFLA_LINKMODE, dev->link_mode);
NLA_PUT_U32(skb, IFLA_MTU, dev->mtu);
NLA_PUT_U32(skb, IFLA_GROUP, dev->group);
if (dev->ifindex != dev->iflink)
NLA_PUT_U32(skb, IFLA_LINK, dev->iflink);
if (dev->master)
NLA_PUT_U32(skb, IFLA_MASTER, dev->master->ifindex);
if (dev->qdisc)
NLA_PUT_STRING(skb, IFLA_QDISC, dev->qdisc->ops->id);
if (dev->ifalias)
NLA_PUT_STRING(skb, IFLA_IFALIAS, dev->ifalias);
if (1) {
struct rtnl_link_ifmap map = {
.mem_start = dev->mem_start,
.mem_end = dev->mem_end,
.base_addr = dev->base_addr,
.irq = dev->irq,
.dma = dev->dma,
.port = dev->if_port,
};
NLA_PUT(skb, IFLA_MAP, sizeof(map), &map);
}
if (dev->addr_len) {
NLA_PUT(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr);
NLA_PUT(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast);
}
attr = nla_reserve(skb, IFLA_STATS,
sizeof(struct rtnl_link_stats));
if (attr == NULL)
goto nla_put_failure;
stats = dev_get_stats(dev, &temp);
copy_rtnl_link_stats(nla_data(attr), stats);
attr = nla_reserve(skb, IFLA_STATS64,
sizeof(struct rtnl_link_stats64));
if (attr == NULL)
goto nla_put_failure;
copy_rtnl_link_stats64(nla_data(attr), stats);
if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF))
NLA_PUT_U32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent));
if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent
&& (ext_filter_mask & RTEXT_FILTER_VF)) {
int i;
struct nlattr *vfinfo, *vf;
int num_vfs = dev_num_vf(dev->dev.parent);
vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST);
if (!vfinfo)
goto nla_put_failure;
for (i = 0; i < num_vfs; i++) {
struct ifla_vf_info ivi;
struct ifla_vf_mac vf_mac;
struct ifla_vf_vlan vf_vlan;
struct ifla_vf_tx_rate vf_tx_rate;
memset(ivi.mac, 0, sizeof(ivi.mac));
if (dev->netdev_ops->ndo_get_vf_config(dev, i, &ivi))
break;
vf_mac.vf = vf_vlan.vf = vf_tx_rate.vf = ivi.vf;
memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac));
vf_vlan.vlan = ivi.vlan;
vf_vlan.qos = ivi.qos;
vf_tx_rate.rate = ivi.tx_rate;
vf = nla_nest_start(skb, IFLA_VF_INFO);
if (!vf) {
nla_nest_cancel(skb, vfinfo);
goto nla_put_failure;
}
NLA_PUT(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac);
NLA_PUT(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan);
NLA_PUT(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate), &vf_tx_rate);
nla_nest_end(skb, vf);
}
nla_nest_end(skb, vfinfo);
}
if (rtnl_port_fill(skb, dev))
goto nla_put_failure;
if (dev->rtnl_link_ops) {
if (rtnl_link_fill(skb, dev) < 0)
goto nla_put_failure;
}
if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC)))
goto nla_put_failure;
list_for_each_entry(af_ops, &rtnl_af_ops, list) {
if (af_ops->fill_link_af) {
struct nlattr *af;
int err;
if (!(af = nla_nest_start(skb, af_ops->family)))
goto nla_put_failure;
err = af_ops->fill_link_af(skb, dev);
/*
* Caller may return ENODATA to indicate that there
* was no data to be dumped. This is not an error, it
* means we should trim the attribute header and
* continue.
*/
if (err == -ENODATA)
nla_nest_cancel(skb, af);
else if (err < 0)
goto nla_put_failure;
nla_nest_end(skb, af);
}
}
nla_nest_end(skb, af_spec);
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int rtnl_dump_ifinfo(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
int h, s_h;
int idx = 0, s_idx;
struct net_device *dev;
struct hlist_head *head;
struct hlist_node *node;
struct nlattr *tb[IFLA_MAX+1];
u32 ext_filter_mask = 0;
s_h = cb->args[0];
s_idx = cb->args[1];
rcu_read_lock();
if (nlmsg_parse(cb->nlh, sizeof(struct ifinfomsg), tb, IFLA_MAX,
ifla_policy) >= 0) {
if (tb[IFLA_EXT_MASK])
ext_filter_mask = nla_get_u32(tb[IFLA_EXT_MASK]);
}
for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
idx = 0;
head = &net->dev_index_head[h];
hlist_for_each_entry_rcu(dev, node, head, index_hlist) {
if (idx < s_idx)
goto cont;
if (rtnl_fill_ifinfo(skb, dev, RTM_NEWLINK,
NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, 0,
NLM_F_MULTI,
ext_filter_mask) <= 0)
goto out;
cont:
idx++;
}
}
out:
rcu_read_unlock();
cb->args[1] = idx;
cb->args[0] = h;
return skb->len;
}
const struct nla_policy ifla_policy[IFLA_MAX+1] = {
[IFLA_IFNAME] = { .type = NLA_STRING, .len = IFNAMSIZ-1 },
[IFLA_ADDRESS] = { .type = NLA_BINARY, .len = MAX_ADDR_LEN },
[IFLA_BROADCAST] = { .type = NLA_BINARY, .len = MAX_ADDR_LEN },
[IFLA_MAP] = { .len = sizeof(struct rtnl_link_ifmap) },
[IFLA_MTU] = { .type = NLA_U32 },
[IFLA_LINK] = { .type = NLA_U32 },
[IFLA_MASTER] = { .type = NLA_U32 },
[IFLA_TXQLEN] = { .type = NLA_U32 },
[IFLA_WEIGHT] = { .type = NLA_U32 },
[IFLA_OPERSTATE] = { .type = NLA_U8 },
[IFLA_LINKMODE] = { .type = NLA_U8 },
[IFLA_LINKINFO] = { .type = NLA_NESTED },
[IFLA_NET_NS_PID] = { .type = NLA_U32 },
[IFLA_NET_NS_FD] = { .type = NLA_U32 },
[IFLA_IFALIAS] = { .type = NLA_STRING, .len = IFALIASZ-1 },
[IFLA_VFINFO_LIST] = {. type = NLA_NESTED },
[IFLA_VF_PORTS] = { .type = NLA_NESTED },
[IFLA_PORT_SELF] = { .type = NLA_NESTED },
[IFLA_AF_SPEC] = { .type = NLA_NESTED },
[IFLA_EXT_MASK] = { .type = NLA_U32 },
};
EXPORT_SYMBOL(ifla_policy);
static const struct nla_policy ifla_info_policy[IFLA_INFO_MAX+1] = {
[IFLA_INFO_KIND] = { .type = NLA_STRING },
[IFLA_INFO_DATA] = { .type = NLA_NESTED },
};
static const struct nla_policy ifla_vfinfo_policy[IFLA_VF_INFO_MAX+1] = {
[IFLA_VF_INFO] = { .type = NLA_NESTED },
};
static const struct nla_policy ifla_vf_policy[IFLA_VF_MAX+1] = {
[IFLA_VF_MAC] = { .type = NLA_BINARY,
.len = sizeof(struct ifla_vf_mac) },
[IFLA_VF_VLAN] = { .type = NLA_BINARY,
.len = sizeof(struct ifla_vf_vlan) },
[IFLA_VF_TX_RATE] = { .type = NLA_BINARY,
.len = sizeof(struct ifla_vf_tx_rate) },
};
static const struct nla_policy ifla_port_policy[IFLA_PORT_MAX+1] = {
[IFLA_PORT_VF] = { .type = NLA_U32 },
[IFLA_PORT_PROFILE] = { .type = NLA_STRING,
.len = PORT_PROFILE_MAX },
[IFLA_PORT_VSI_TYPE] = { .type = NLA_BINARY,
.len = sizeof(struct ifla_port_vsi)},
[IFLA_PORT_INSTANCE_UUID] = { .type = NLA_BINARY,
.len = PORT_UUID_MAX },
[IFLA_PORT_HOST_UUID] = { .type = NLA_STRING,
.len = PORT_UUID_MAX },
[IFLA_PORT_REQUEST] = { .type = NLA_U8, },
[IFLA_PORT_RESPONSE] = { .type = NLA_U16, },
};
struct net *rtnl_link_get_net(struct net *src_net, struct nlattr *tb[])
{
struct net *net;
/* Examine the link attributes and figure out which
* network namespace we are talking about.
*/
if (tb[IFLA_NET_NS_PID])
net = get_net_ns_by_pid(nla_get_u32(tb[IFLA_NET_NS_PID]));
else if (tb[IFLA_NET_NS_FD])
net = get_net_ns_by_fd(nla_get_u32(tb[IFLA_NET_NS_FD]));
else
net = get_net(src_net);
return net;
}
EXPORT_SYMBOL(rtnl_link_get_net);
static int validate_linkmsg(struct net_device *dev, struct nlattr *tb[])
{
if (dev) {
if (tb[IFLA_ADDRESS] &&
nla_len(tb[IFLA_ADDRESS]) < dev->addr_len)
return -EINVAL;
if (tb[IFLA_BROADCAST] &&
nla_len(tb[IFLA_BROADCAST]) < dev->addr_len)
return -EINVAL;
}
if (tb[IFLA_AF_SPEC]) {
struct nlattr *af;
int rem, err;
nla_for_each_nested(af, tb[IFLA_AF_SPEC], rem) {
const struct rtnl_af_ops *af_ops;
if (!(af_ops = rtnl_af_lookup(nla_type(af))))
return -EAFNOSUPPORT;
if (!af_ops->set_link_af)
return -EOPNOTSUPP;
if (af_ops->validate_link_af) {
err = af_ops->validate_link_af(dev, af);
if (err < 0)
return err;
}
}
}
return 0;
}
static int do_setvfinfo(struct net_device *dev, struct nlattr *attr)
{
int rem, err = -EINVAL;
struct nlattr *vf;
const struct net_device_ops *ops = dev->netdev_ops;
nla_for_each_nested(vf, attr, rem) {
switch (nla_type(vf)) {
case IFLA_VF_MAC: {
struct ifla_vf_mac *ivm;
ivm = nla_data(vf);
err = -EOPNOTSUPP;
if (ops->ndo_set_vf_mac)
err = ops->ndo_set_vf_mac(dev, ivm->vf,
ivm->mac);
break;
}
case IFLA_VF_VLAN: {
struct ifla_vf_vlan *ivv;
ivv = nla_data(vf);
err = -EOPNOTSUPP;
if (ops->ndo_set_vf_vlan)
err = ops->ndo_set_vf_vlan(dev, ivv->vf,
ivv->vlan,
ivv->qos);
break;
}
case IFLA_VF_TX_RATE: {
struct ifla_vf_tx_rate *ivt;
ivt = nla_data(vf);
err = -EOPNOTSUPP;
if (ops->ndo_set_vf_tx_rate)
err = ops->ndo_set_vf_tx_rate(dev, ivt->vf,
ivt->rate);
break;
}
default:
err = -EINVAL;
break;
}
if (err)
break;
}
return err;
}
static int do_set_master(struct net_device *dev, int ifindex)
{
struct net_device *master_dev;
const struct net_device_ops *ops;
int err;
if (dev->master) {
if (dev->master->ifindex == ifindex)
return 0;
ops = dev->master->netdev_ops;
if (ops->ndo_del_slave) {
err = ops->ndo_del_slave(dev->master, dev);
if (err)
return err;
} else {
return -EOPNOTSUPP;
}
}
if (ifindex) {
master_dev = __dev_get_by_index(dev_net(dev), ifindex);
if (!master_dev)
return -EINVAL;
ops = master_dev->netdev_ops;
if (ops->ndo_add_slave) {
err = ops->ndo_add_slave(master_dev, dev);
if (err)
return err;
} else {
return -EOPNOTSUPP;
}
}
return 0;
}
static int do_setlink(struct net_device *dev, struct ifinfomsg *ifm,
struct nlattr **tb, char *ifname, int modified)
{
const struct net_device_ops *ops = dev->netdev_ops;
int send_addr_notify = 0;
int err;
if (tb[IFLA_NET_NS_PID] || tb[IFLA_NET_NS_FD]) {
struct net *net = rtnl_link_get_net(dev_net(dev), tb);
if (IS_ERR(net)) {
err = PTR_ERR(net);
goto errout;
}
err = dev_change_net_namespace(dev, net, ifname);
put_net(net);
if (err)
goto errout;
modified = 1;
}
if (tb[IFLA_MAP]) {
struct rtnl_link_ifmap *u_map;
struct ifmap k_map;
if (!ops->ndo_set_config) {
err = -EOPNOTSUPP;
goto errout;
}
if (!netif_device_present(dev)) {
err = -ENODEV;
goto errout;
}
u_map = nla_data(tb[IFLA_MAP]);
k_map.mem_start = (unsigned long) u_map->mem_start;
k_map.mem_end = (unsigned long) u_map->mem_end;
k_map.base_addr = (unsigned short) u_map->base_addr;
k_map.irq = (unsigned char) u_map->irq;
k_map.dma = (unsigned char) u_map->dma;
k_map.port = (unsigned char) u_map->port;
err = ops->ndo_set_config(dev, &k_map);
if (err < 0)
goto errout;
modified = 1;
}
if (tb[IFLA_ADDRESS]) {
struct sockaddr *sa;
int len;
if (!ops->ndo_set_mac_address) {
err = -EOPNOTSUPP;
goto errout;
}
if (!netif_device_present(dev)) {
err = -ENODEV;
goto errout;
}
len = sizeof(sa_family_t) + dev->addr_len;
sa = kmalloc(len, GFP_KERNEL);
if (!sa) {
err = -ENOMEM;
goto errout;
}
sa->sa_family = dev->type;
memcpy(sa->sa_data, nla_data(tb[IFLA_ADDRESS]),
dev->addr_len);
err = ops->ndo_set_mac_address(dev, sa);
kfree(sa);
if (err)
goto errout;
send_addr_notify = 1;
modified = 1;
add_device_randomness(dev->dev_addr, dev->addr_len);
}
if (tb[IFLA_MTU]) {
err = dev_set_mtu(dev, nla_get_u32(tb[IFLA_MTU]));
if (err < 0)
goto errout;
modified = 1;
}
if (tb[IFLA_GROUP]) {
dev_set_group(dev, nla_get_u32(tb[IFLA_GROUP]));
modified = 1;
}
/*
* Interface selected by interface index but interface
* name provided implies that a name change has been
* requested.
*/
if (ifm->ifi_index > 0 && ifname[0]) {
err = dev_change_name(dev, ifname);
if (err < 0)
goto errout;
modified = 1;
}
if (tb[IFLA_IFALIAS]) {
err = dev_set_alias(dev, nla_data(tb[IFLA_IFALIAS]),
nla_len(tb[IFLA_IFALIAS]));
if (err < 0)
goto errout;
modified = 1;
}
if (tb[IFLA_BROADCAST]) {
nla_memcpy(dev->broadcast, tb[IFLA_BROADCAST], dev->addr_len);
send_addr_notify = 1;
}
if (ifm->ifi_flags || ifm->ifi_change) {
err = dev_change_flags(dev, rtnl_dev_combine_flags(dev, ifm));
if (err < 0)
goto errout;
}
if (tb[IFLA_MASTER]) {
err = do_set_master(dev, nla_get_u32(tb[IFLA_MASTER]));
if (err)
goto errout;
modified = 1;
}
if (tb[IFLA_TXQLEN])
dev->tx_queue_len = nla_get_u32(tb[IFLA_TXQLEN]);
if (tb[IFLA_OPERSTATE])
set_operstate(dev, nla_get_u8(tb[IFLA_OPERSTATE]));
if (tb[IFLA_LINKMODE]) {
write_lock_bh(&dev_base_lock);
dev->link_mode = nla_get_u8(tb[IFLA_LINKMODE]);
write_unlock_bh(&dev_base_lock);
}
if (tb[IFLA_VFINFO_LIST]) {
struct nlattr *attr;
int rem;
nla_for_each_nested(attr, tb[IFLA_VFINFO_LIST], rem) {
if (nla_type(attr) != IFLA_VF_INFO) {
err = -EINVAL;
goto errout;
}
err = do_setvfinfo(dev, attr);
if (err < 0)
goto errout;
modified = 1;
}
}
err = 0;
if (tb[IFLA_VF_PORTS]) {
struct nlattr *port[IFLA_PORT_MAX+1];
struct nlattr *attr;
int vf;
int rem;
err = -EOPNOTSUPP;
if (!ops->ndo_set_vf_port)
goto errout;
nla_for_each_nested(attr, tb[IFLA_VF_PORTS], rem) {
if (nla_type(attr) != IFLA_VF_PORT)
continue;
err = nla_parse_nested(port, IFLA_PORT_MAX,
attr, ifla_port_policy);
if (err < 0)
goto errout;
if (!port[IFLA_PORT_VF]) {
err = -EOPNOTSUPP;
goto errout;
}
vf = nla_get_u32(port[IFLA_PORT_VF]);
err = ops->ndo_set_vf_port(dev, vf, port);
if (err < 0)
goto errout;
modified = 1;
}
}
err = 0;
if (tb[IFLA_PORT_SELF]) {
struct nlattr *port[IFLA_PORT_MAX+1];
err = nla_parse_nested(port, IFLA_PORT_MAX,
tb[IFLA_PORT_SELF], ifla_port_policy);
if (err < 0)
goto errout;
err = -EOPNOTSUPP;
if (ops->ndo_set_vf_port)
err = ops->ndo_set_vf_port(dev, PORT_SELF_VF, port);
if (err < 0)
goto errout;
modified = 1;
}
if (tb[IFLA_AF_SPEC]) {
struct nlattr *af;
int rem;
nla_for_each_nested(af, tb[IFLA_AF_SPEC], rem) {
const struct rtnl_af_ops *af_ops;
if (!(af_ops = rtnl_af_lookup(nla_type(af))))
BUG();
err = af_ops->set_link_af(dev, af);
if (err < 0)
goto errout;
modified = 1;
}
}
err = 0;
errout:
if (err < 0 && modified && net_ratelimit())
printk(KERN_WARNING "A link change request failed with "
"some changes committed already. Interface %s may "
"have been left with an inconsistent configuration, "
"please check.\n", dev->name);
if (send_addr_notify)
call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
return err;
}
static int rtnl_setlink(struct sk_buff *skb, struct nlmsghdr *nlh, void *arg)
{
struct net *net = sock_net(skb->sk);
struct ifinfomsg *ifm;
struct net_device *dev;
int err;
struct nlattr *tb[IFLA_MAX+1];
char ifname[IFNAMSIZ];
err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy);
if (err < 0)
goto errout;
if (tb[IFLA_IFNAME])
nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ);
else
ifname[0] = '\0';
err = -EINVAL;
ifm = nlmsg_data(nlh);
if (ifm->ifi_index > 0)
dev = __dev_get_by_index(net, ifm->ifi_index);
else if (tb[IFLA_IFNAME])
dev = __dev_get_by_name(net, ifname);
else
goto errout;
if (dev == NULL) {
err = -ENODEV;
goto errout;
}
err = validate_linkmsg(dev, tb);
if (err < 0)
goto errout;
err = do_setlink(dev, ifm, tb, ifname, 0);
errout:
return err;
}
static int rtnl_dellink(struct sk_buff *skb, struct nlmsghdr *nlh, void *arg)
{
struct net *net = sock_net(skb->sk);
const struct rtnl_link_ops *ops;
struct net_device *dev;
struct ifinfomsg *ifm;
char ifname[IFNAMSIZ];
struct nlattr *tb[IFLA_MAX+1];
int err;
LIST_HEAD(list_kill);
err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy);
if (err < 0)
return err;
if (tb[IFLA_IFNAME])
nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ);
ifm = nlmsg_data(nlh);
if (ifm->ifi_index > 0)
dev = __dev_get_by_index(net, ifm->ifi_index);
else if (tb[IFLA_IFNAME])
dev = __dev_get_by_name(net, ifname);
else
return -EINVAL;
if (!dev)
return -ENODEV;
ops = dev->rtnl_link_ops;
if (!ops)
return -EOPNOTSUPP;
ops->dellink(dev, &list_kill);
unregister_netdevice_many(&list_kill);
list_del(&list_kill);
return 0;
}
int rtnl_configure_link(struct net_device *dev, const struct ifinfomsg *ifm)
{
unsigned int old_flags;
int err;
old_flags = dev->flags;
if (ifm && (ifm->ifi_flags || ifm->ifi_change)) {
err = __dev_change_flags(dev, rtnl_dev_combine_flags(dev, ifm));
if (err < 0)
return err;
}
dev->rtnl_link_state = RTNL_LINK_INITIALIZED;
rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
__dev_notify_flags(dev, old_flags);
return 0;
}
EXPORT_SYMBOL(rtnl_configure_link);
struct net_device *rtnl_create_link(struct net *src_net, struct net *net,
char *ifname, const struct rtnl_link_ops *ops, struct nlattr *tb[])
{
int err;
struct net_device *dev;
unsigned int num_queues = 1;
unsigned int real_num_queues = 1;
if (ops->get_tx_queues) {
err = ops->get_tx_queues(src_net, tb, &num_queues,
&real_num_queues);
if (err)
goto err;
}
err = -ENOMEM;
dev = alloc_netdev_mq(ops->priv_size, ifname, ops->setup, num_queues);
if (!dev)
goto err;
dev_net_set(dev, net);
dev->rtnl_link_ops = ops;
dev->rtnl_link_state = RTNL_LINK_INITIALIZING;
dev->real_num_tx_queues = real_num_queues;
if (tb[IFLA_MTU])
dev->mtu = nla_get_u32(tb[IFLA_MTU]);
if (tb[IFLA_ADDRESS])
memcpy(dev->dev_addr, nla_data(tb[IFLA_ADDRESS]),
nla_len(tb[IFLA_ADDRESS]));
if (tb[IFLA_BROADCAST])
memcpy(dev->broadcast, nla_data(tb[IFLA_BROADCAST]),
nla_len(tb[IFLA_BROADCAST]));
if (tb[IFLA_TXQLEN])
dev->tx_queue_len = nla_get_u32(tb[IFLA_TXQLEN]);
if (tb[IFLA_OPERSTATE])
set_operstate(dev, nla_get_u8(tb[IFLA_OPERSTATE]));
if (tb[IFLA_LINKMODE])
dev->link_mode = nla_get_u8(tb[IFLA_LINKMODE]);
if (tb[IFLA_GROUP])
dev_set_group(dev, nla_get_u32(tb[IFLA_GROUP]));
return dev;
err:
return ERR_PTR(err);
}
EXPORT_SYMBOL(rtnl_create_link);
static int rtnl_group_changelink(struct net *net, int group,
struct ifinfomsg *ifm,
struct nlattr **tb)
{
struct net_device *dev;
int err;
for_each_netdev(net, dev) {
if (dev->group == group) {
err = do_setlink(dev, ifm, tb, NULL, 0);
if (err < 0)
return err;
}
}
return 0;
}
static int rtnl_newlink(struct sk_buff *skb, struct nlmsghdr *nlh, void *arg)
{
struct net *net = sock_net(skb->sk);
const struct rtnl_link_ops *ops;
struct net_device *dev;
struct ifinfomsg *ifm;
char kind[MODULE_NAME_LEN];
char ifname[IFNAMSIZ];
struct nlattr *tb[IFLA_MAX+1];
struct nlattr *linkinfo[IFLA_INFO_MAX+1];
int err;
#ifdef CONFIG_MODULES
replay:
#endif
err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy);
if (err < 0)
return err;
if (tb[IFLA_IFNAME])
nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ);
else
ifname[0] = '\0';
ifm = nlmsg_data(nlh);
if (ifm->ifi_index > 0)
dev = __dev_get_by_index(net, ifm->ifi_index);
else {
if (ifname[0])
dev = __dev_get_by_name(net, ifname);
else
dev = NULL;
}
err = validate_linkmsg(dev, tb);
if (err < 0)
return err;
if (tb[IFLA_LINKINFO]) {
err = nla_parse_nested(linkinfo, IFLA_INFO_MAX,
tb[IFLA_LINKINFO], ifla_info_policy);
if (err < 0)
return err;
} else
memset(linkinfo, 0, sizeof(linkinfo));
if (linkinfo[IFLA_INFO_KIND]) {
nla_strlcpy(kind, linkinfo[IFLA_INFO_KIND], sizeof(kind));
ops = rtnl_link_ops_get(kind);
} else {
kind[0] = '\0';
ops = NULL;
}
if (1) {
struct nlattr *attr[ops ? ops->maxtype + 1 : 0], **data = NULL;
struct net *dest_net;
if (ops) {
if (ops->maxtype && linkinfo[IFLA_INFO_DATA]) {
err = nla_parse_nested(attr, ops->maxtype,
linkinfo[IFLA_INFO_DATA],
ops->policy);
if (err < 0)
return err;
data = attr;
}
if (ops->validate) {
err = ops->validate(tb, data);
if (err < 0)
return err;
}
}
if (dev) {
int modified = 0;
if (nlh->nlmsg_flags & NLM_F_EXCL)
return -EEXIST;
if (nlh->nlmsg_flags & NLM_F_REPLACE)
return -EOPNOTSUPP;
if (linkinfo[IFLA_INFO_DATA]) {
if (!ops || ops != dev->rtnl_link_ops ||
!ops->changelink)
return -EOPNOTSUPP;
err = ops->changelink(dev, tb, data);
if (err < 0)
return err;
modified = 1;
}
return do_setlink(dev, ifm, tb, ifname, modified);
}
if (!(nlh->nlmsg_flags & NLM_F_CREATE)) {
if (ifm->ifi_index == 0 && tb[IFLA_GROUP])
return rtnl_group_changelink(net,
nla_get_u32(tb[IFLA_GROUP]),
ifm, tb);
return -ENODEV;
}
if (ifm->ifi_index)
return -EOPNOTSUPP;
if (tb[IFLA_MAP] || tb[IFLA_MASTER] || tb[IFLA_PROTINFO])
return -EOPNOTSUPP;
if (!ops) {
#ifdef CONFIG_MODULES
if (kind[0]) {
__rtnl_unlock();
request_module("rtnl-link-%s", kind);
rtnl_lock();
ops = rtnl_link_ops_get(kind);
if (ops)
goto replay;
}
#endif
return -EOPNOTSUPP;
}
if (!ifname[0])
snprintf(ifname, IFNAMSIZ, "%s%%d", ops->kind);
dest_net = rtnl_link_get_net(net, tb);
if (IS_ERR(dest_net))
return PTR_ERR(dest_net);
dev = rtnl_create_link(net, dest_net, ifname, ops, tb);
if (IS_ERR(dev))
err = PTR_ERR(dev);
else if (ops->newlink)
err = ops->newlink(net, dev, tb, data);
else
err = register_netdevice(dev);
if (err < 0 && !IS_ERR(dev))
free_netdev(dev);
if (err < 0)
goto out;
err = rtnl_configure_link(dev, ifm);
if (err < 0)
unregister_netdevice(dev);
out:
put_net(dest_net);
return err;
}
}
static int rtnl_getlink(struct sk_buff *skb, struct nlmsghdr* nlh, void *arg)
{
struct net *net = sock_net(skb->sk);
struct ifinfomsg *ifm;
char ifname[IFNAMSIZ];
struct nlattr *tb[IFLA_MAX+1];
struct net_device *dev = NULL;
struct sk_buff *nskb;
int err;
u32 ext_filter_mask = 0;
err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy);
if (err < 0)
return err;
if (tb[IFLA_IFNAME])
nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ);
if (tb[IFLA_EXT_MASK])
ext_filter_mask = nla_get_u32(tb[IFLA_EXT_MASK]);
ifm = nlmsg_data(nlh);
if (ifm->ifi_index > 0)
dev = __dev_get_by_index(net, ifm->ifi_index);
else if (tb[IFLA_IFNAME])
dev = __dev_get_by_name(net, ifname);
else
return -EINVAL;
if (dev == NULL)
return -ENODEV;
nskb = nlmsg_new(if_nlmsg_size(dev, ext_filter_mask), GFP_KERNEL);
if (nskb == NULL)
return -ENOBUFS;
err = rtnl_fill_ifinfo(nskb, dev, RTM_NEWLINK, NETLINK_CB(skb).pid,
nlh->nlmsg_seq, 0, 0, ext_filter_mask);
if (err < 0) {
/* -EMSGSIZE implies BUG in if_nlmsg_size */
WARN_ON(err == -EMSGSIZE);
kfree_skb(nskb);
} else
err = rtnl_unicast(nskb, net, NETLINK_CB(skb).pid);
return err;
}
static u16 rtnl_calcit(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct net_device *dev;
struct nlattr *tb[IFLA_MAX+1];
u32 ext_filter_mask = 0;
u16 min_ifinfo_dump_size = 0;
if (nlmsg_parse(nlh, sizeof(struct ifinfomsg), tb, IFLA_MAX,
ifla_policy) >= 0) {
if (tb[IFLA_EXT_MASK])
ext_filter_mask = nla_get_u32(tb[IFLA_EXT_MASK]);
}
if (!ext_filter_mask)
return NLMSG_GOODSIZE;
/*
* traverse the list of net devices and compute the minimum
* buffer size based upon the filter mask.
*/
list_for_each_entry(dev, &net->dev_base_head, dev_list) {
min_ifinfo_dump_size = max_t(u16, min_ifinfo_dump_size,
if_nlmsg_size(dev,
ext_filter_mask));
}
return min_ifinfo_dump_size;
}
static int rtnl_dump_all(struct sk_buff *skb, struct netlink_callback *cb)
{
int idx;
int s_idx = cb->family;
if (s_idx == 0)
s_idx = 1;
for (idx = 1; idx <= RTNL_FAMILY_MAX; idx++) {
int type = cb->nlh->nlmsg_type-RTM_BASE;
if (idx < s_idx || idx == PF_PACKET)
continue;
if (rtnl_msg_handlers[idx] == NULL ||
rtnl_msg_handlers[idx][type].dumpit == NULL)
continue;
if (idx > s_idx)
memset(&cb->args[0], 0, sizeof(cb->args));
if (rtnl_msg_handlers[idx][type].dumpit(skb, cb))
break;
}
cb->family = idx;
return skb->len;
}
void rtmsg_ifinfo(int type, struct net_device *dev, unsigned change)
{
struct net *net = dev_net(dev);
struct sk_buff *skb;
int err = -ENOBUFS;
size_t if_info_size;
skb = nlmsg_new((if_info_size = if_nlmsg_size(dev, 0)), GFP_KERNEL);
if (skb == NULL)
goto errout;
err = rtnl_fill_ifinfo(skb, dev, type, 0, 0, change, 0, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in if_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, GFP_KERNEL);
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_LINK, err);
}
/* Protected by RTNL sempahore. */
static struct rtattr **rta_buf;
static int rtattr_max;
/* Process one rtnetlink message. */
static int rtnetlink_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
rtnl_doit_func doit;
int sz_idx, kind;
int min_len;
int family;
int type;
int err;
type = nlh->nlmsg_type;
if (type > RTM_MAX)
return -EOPNOTSUPP;
type -= RTM_BASE;
/* All the messages must have at least 1 byte length */
if (nlh->nlmsg_len < NLMSG_LENGTH(sizeof(struct rtgenmsg)))
return 0;
family = ((struct rtgenmsg *)NLMSG_DATA(nlh))->rtgen_family;
sz_idx = type>>2;
kind = type&3;
if (kind != 2 && security_netlink_recv(skb, CAP_NET_ADMIN))
return -EPERM;
if (kind == 2 && nlh->nlmsg_flags&NLM_F_DUMP) {
struct sock *rtnl;
rtnl_dumpit_func dumpit;
rtnl_calcit_func calcit;
u16 min_dump_alloc = 0;
dumpit = rtnl_get_dumpit(family, type);
if (dumpit == NULL)
return -EOPNOTSUPP;
calcit = rtnl_get_calcit(family, type);
if (calcit)
min_dump_alloc = calcit(skb, nlh);
__rtnl_unlock();
rtnl = net->rtnl;
err = netlink_dump_start(rtnl, skb, nlh, dumpit,
NULL, min_dump_alloc);
rtnl_lock();
return err;
}
memset(rta_buf, 0, (rtattr_max * sizeof(struct rtattr *)));
min_len = rtm_min[sz_idx];
if (nlh->nlmsg_len < min_len)
return -EINVAL;
if (nlh->nlmsg_len > min_len) {
int attrlen = nlh->nlmsg_len - NLMSG_ALIGN(min_len);
struct rtattr *attr = (void *)nlh + NLMSG_ALIGN(min_len);
while (RTA_OK(attr, attrlen)) {
unsigned int flavor = attr->rta_type & NLA_TYPE_MASK;
if (flavor) {
if (flavor > rta_max[sz_idx])
return -EINVAL;
rta_buf[flavor-1] = attr;
}
attr = RTA_NEXT(attr, attrlen);
}
}
doit = rtnl_get_doit(family, type);
if (doit == NULL)
return -EOPNOTSUPP;
return doit(skb, nlh, (void *)&rta_buf[0]);
}
static void rtnetlink_rcv(struct sk_buff *skb)
{
rtnl_lock();
netlink_rcv_skb(skb, &rtnetlink_rcv_msg);
rtnl_unlock();
}
static int rtnetlink_event(struct notifier_block *this, unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
switch (event) {
case NETDEV_UP:
case NETDEV_DOWN:
case NETDEV_PRE_UP:
case NETDEV_POST_INIT:
case NETDEV_REGISTER:
case NETDEV_CHANGE:
case NETDEV_PRE_TYPE_CHANGE:
case NETDEV_GOING_DOWN:
case NETDEV_UNREGISTER:
case NETDEV_UNREGISTER_BATCH:
case NETDEV_RELEASE:
case NETDEV_JOIN:
break;
default:
rtmsg_ifinfo(RTM_NEWLINK, dev, 0);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block rtnetlink_dev_notifier = {
.notifier_call = rtnetlink_event,
};
static int __net_init rtnetlink_net_init(struct net *net)
{
struct sock *sk;
sk = netlink_kernel_create(net, NETLINK_ROUTE, RTNLGRP_MAX,
rtnetlink_rcv, &rtnl_mutex, THIS_MODULE);
if (!sk)
return -ENOMEM;
net->rtnl = sk;
return 0;
}
static void __net_exit rtnetlink_net_exit(struct net *net)
{
netlink_kernel_release(net->rtnl);
net->rtnl = NULL;
}
static struct pernet_operations rtnetlink_net_ops = {
.init = rtnetlink_net_init,
.exit = rtnetlink_net_exit,
};
void __init rtnetlink_init(void)
{
int i;
rtattr_max = 0;
for (i = 0; i < ARRAY_SIZE(rta_max); i++)
if (rta_max[i] > rtattr_max)
rtattr_max = rta_max[i];
rta_buf = kmalloc(rtattr_max * sizeof(struct rtattr *), GFP_KERNEL);
if (!rta_buf)
panic("rtnetlink_init: cannot allocate rta_buf\n");
if (register_pernet_subsys(&rtnetlink_net_ops))
panic("rtnetlink_init: cannot initialize rtnetlink\n");
netlink_set_nonroot(NETLINK_ROUTE, NL_NONROOT_RECV);
register_netdevice_notifier(&rtnetlink_dev_notifier);
rtnl_register(PF_UNSPEC, RTM_GETLINK, rtnl_getlink,
rtnl_dump_ifinfo, rtnl_calcit);
rtnl_register(PF_UNSPEC, RTM_SETLINK, rtnl_setlink, NULL, NULL);
rtnl_register(PF_UNSPEC, RTM_NEWLINK, rtnl_newlink, NULL, NULL);
rtnl_register(PF_UNSPEC, RTM_DELLINK, rtnl_dellink, NULL, NULL);
rtnl_register(PF_UNSPEC, RTM_GETADDR, NULL, rtnl_dump_all, NULL);
rtnl_register(PF_UNSPEC, RTM_GETROUTE, NULL, rtnl_dump_all, NULL);
}
| gpl-2.0 |
mozzwald/u-boot-pxa-zipitz2 | fs/ubifs/scan.c | 516 | 9083 | /*
* This file is part of UBIFS.
*
* Copyright (C) 2006-2008 Nokia Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors: Adrian Hunter
* Artem Bityutskiy (Битюцкий Артём)
*/
/*
* This file implements the scan which is a general-purpose function for
* determining what nodes are in an eraseblock. The scan is used to replay the
* journal, to do garbage collection. for the TNC in-the-gaps method, and by
* debugging functions.
*/
#include "ubifs.h"
/**
* scan_padding_bytes - scan for padding bytes.
* @buf: buffer to scan
* @len: length of buffer
*
* This function returns the number of padding bytes on success and
* %SCANNED_GARBAGE on failure.
*/
static int scan_padding_bytes(void *buf, int len)
{
int pad_len = 0, max_pad_len = min_t(int, UBIFS_PAD_NODE_SZ, len);
uint8_t *p = buf;
dbg_scan("not a node");
while (pad_len < max_pad_len && *p++ == UBIFS_PADDING_BYTE)
pad_len += 1;
if (!pad_len || (pad_len & 7))
return SCANNED_GARBAGE;
dbg_scan("%d padding bytes", pad_len);
return pad_len;
}
/**
* ubifs_scan_a_node - scan for a node or padding.
* @c: UBIFS file-system description object
* @buf: buffer to scan
* @len: length of buffer
* @lnum: logical eraseblock number
* @offs: offset within the logical eraseblock
* @quiet: print no messages
*
* This function returns a scanning code to indicate what was scanned.
*/
int ubifs_scan_a_node(const struct ubifs_info *c, void *buf, int len, int lnum,
int offs, int quiet)
{
struct ubifs_ch *ch = buf;
uint32_t magic;
magic = le32_to_cpu(ch->magic);
if (magic == 0xFFFFFFFF) {
dbg_scan("hit empty space");
return SCANNED_EMPTY_SPACE;
}
if (magic != UBIFS_NODE_MAGIC)
return scan_padding_bytes(buf, len);
if (len < UBIFS_CH_SZ)
return SCANNED_GARBAGE;
dbg_scan("scanning %s", dbg_ntype(ch->node_type));
if (ubifs_check_node(c, buf, lnum, offs, quiet, 1))
return SCANNED_A_CORRUPT_NODE;
if (ch->node_type == UBIFS_PAD_NODE) {
struct ubifs_pad_node *pad = buf;
int pad_len = le32_to_cpu(pad->pad_len);
int node_len = le32_to_cpu(ch->len);
/* Validate the padding node */
if (pad_len < 0 ||
offs + node_len + pad_len > c->leb_size) {
if (!quiet) {
ubifs_err("bad pad node at LEB %d:%d",
lnum, offs);
dbg_dump_node(c, pad);
}
return SCANNED_A_BAD_PAD_NODE;
}
/* Make the node pads to 8-byte boundary */
if ((node_len + pad_len) & 7) {
if (!quiet) {
dbg_err("bad padding length %d - %d",
offs, offs + node_len + pad_len);
}
return SCANNED_A_BAD_PAD_NODE;
}
dbg_scan("%d bytes padded, offset now %d",
pad_len, ALIGN(offs + node_len + pad_len, 8));
return node_len + pad_len;
}
return SCANNED_A_NODE;
}
/**
* ubifs_start_scan - create LEB scanning information at start of scan.
* @c: UBIFS file-system description object
* @lnum: logical eraseblock number
* @offs: offset to start at (usually zero)
* @sbuf: scan buffer (must be c->leb_size)
*
* This function returns %0 on success and a negative error code on failure.
*/
struct ubifs_scan_leb *ubifs_start_scan(const struct ubifs_info *c, int lnum,
int offs, void *sbuf)
{
struct ubifs_scan_leb *sleb;
int err;
dbg_scan("scan LEB %d:%d", lnum, offs);
sleb = kzalloc(sizeof(struct ubifs_scan_leb), GFP_NOFS);
if (!sleb)
return ERR_PTR(-ENOMEM);
sleb->lnum = lnum;
INIT_LIST_HEAD(&sleb->nodes);
sleb->buf = sbuf;
err = ubi_read(c->ubi, lnum, sbuf + offs, offs, c->leb_size - offs);
if (err && err != -EBADMSG) {
ubifs_err("cannot read %d bytes from LEB %d:%d,"
" error %d", c->leb_size - offs, lnum, offs, err);
kfree(sleb);
return ERR_PTR(err);
}
if (err == -EBADMSG)
sleb->ecc = 1;
return sleb;
}
/**
* ubifs_end_scan - update LEB scanning information at end of scan.
* @c: UBIFS file-system description object
* @sleb: scanning information
* @lnum: logical eraseblock number
* @offs: offset to start at (usually zero)
*
* This function returns %0 on success and a negative error code on failure.
*/
void ubifs_end_scan(const struct ubifs_info *c, struct ubifs_scan_leb *sleb,
int lnum, int offs)
{
lnum = lnum;
dbg_scan("stop scanning LEB %d at offset %d", lnum, offs);
ubifs_assert(offs % c->min_io_size == 0);
sleb->endpt = ALIGN(offs, c->min_io_size);
}
/**
* ubifs_add_snod - add a scanned node to LEB scanning information.
* @c: UBIFS file-system description object
* @sleb: scanning information
* @buf: buffer containing node
* @offs: offset of node on flash
*
* This function returns %0 on success and a negative error code on failure.
*/
int ubifs_add_snod(const struct ubifs_info *c, struct ubifs_scan_leb *sleb,
void *buf, int offs)
{
struct ubifs_ch *ch = buf;
struct ubifs_ino_node *ino = buf;
struct ubifs_scan_node *snod;
snod = kzalloc(sizeof(struct ubifs_scan_node), GFP_NOFS);
if (!snod)
return -ENOMEM;
snod->sqnum = le64_to_cpu(ch->sqnum);
snod->type = ch->node_type;
snod->offs = offs;
snod->len = le32_to_cpu(ch->len);
snod->node = buf;
switch (ch->node_type) {
case UBIFS_INO_NODE:
case UBIFS_DENT_NODE:
case UBIFS_XENT_NODE:
case UBIFS_DATA_NODE:
case UBIFS_TRUN_NODE:
/*
* The key is in the same place in all keyed
* nodes.
*/
key_read(c, &ino->key, &snod->key);
break;
}
list_add_tail(&snod->list, &sleb->nodes);
sleb->nodes_cnt += 1;
return 0;
}
/**
* ubifs_scanned_corruption - print information after UBIFS scanned corruption.
* @c: UBIFS file-system description object
* @lnum: LEB number of corruption
* @offs: offset of corruption
* @buf: buffer containing corruption
*/
void ubifs_scanned_corruption(const struct ubifs_info *c, int lnum, int offs,
void *buf)
{
int len;
ubifs_err("corrupted data at LEB %d:%d", lnum, offs);
if (dbg_failure_mode)
return;
len = c->leb_size - offs;
if (len > 4096)
len = 4096;
dbg_err("first %d bytes from LEB %d:%d", len, lnum, offs);
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 4, buf, len, 1);
}
/**
* ubifs_scan - scan a logical eraseblock.
* @c: UBIFS file-system description object
* @lnum: logical eraseblock number
* @offs: offset to start at (usually zero)
* @sbuf: scan buffer (must be c->leb_size)
*
* This function scans LEB number @lnum and returns complete information about
* its contents. Returns an error code in case of failure.
*/
struct ubifs_scan_leb *ubifs_scan(const struct ubifs_info *c, int lnum,
int offs, void *sbuf)
{
void *buf = sbuf + offs;
int err, len = c->leb_size - offs;
struct ubifs_scan_leb *sleb;
sleb = ubifs_start_scan(c, lnum, offs, sbuf);
if (IS_ERR(sleb))
return sleb;
while (len >= 8) {
struct ubifs_ch *ch = buf;
int node_len, ret;
dbg_scan("look at LEB %d:%d (%d bytes left)",
lnum, offs, len);
cond_resched();
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 0);
if (ret > 0) {
/* Padding bytes or a valid padding node */
offs += ret;
buf += ret;
len -= ret;
continue;
}
if (ret == SCANNED_EMPTY_SPACE)
/* Empty space is checked later */
break;
switch (ret) {
case SCANNED_GARBAGE:
dbg_err("garbage");
goto corrupted;
case SCANNED_A_NODE:
break;
case SCANNED_A_CORRUPT_NODE:
case SCANNED_A_BAD_PAD_NODE:
dbg_err("bad node");
goto corrupted;
default:
dbg_err("unknown");
goto corrupted;
}
err = ubifs_add_snod(c, sleb, buf, offs);
if (err)
goto error;
node_len = ALIGN(le32_to_cpu(ch->len), 8);
offs += node_len;
buf += node_len;
len -= node_len;
}
if (offs % c->min_io_size)
goto corrupted;
ubifs_end_scan(c, sleb, lnum, offs);
for (; len > 4; offs += 4, buf = buf + 4, len -= 4)
if (*(uint32_t *)buf != 0xffffffff)
break;
for (; len; offs++, buf++, len--)
if (*(uint8_t *)buf != 0xff) {
ubifs_err("corrupt empty space at LEB %d:%d",
lnum, offs);
goto corrupted;
}
return sleb;
corrupted:
ubifs_scanned_corruption(c, lnum, offs, buf);
err = -EUCLEAN;
error:
ubifs_err("LEB %d scanning failed", lnum);
ubifs_scan_destroy(sleb);
return ERR_PTR(err);
}
/**
* ubifs_scan_destroy - destroy LEB scanning information.
* @sleb: scanning information to free
*/
void ubifs_scan_destroy(struct ubifs_scan_leb *sleb)
{
struct ubifs_scan_node *node;
struct list_head *head;
head = &sleb->nodes;
while (!list_empty(head)) {
node = list_entry(head->next, struct ubifs_scan_node, list);
list_del(&node->list);
kfree(node);
}
kfree(sleb);
}
| gpl-2.0 |
zhang3/linux | arch/powerpc/kernel/kgdb.c | 772 | 15573 | /*
* PowerPC backend to the KGDB stub.
*
* 1998 (c) Michael AK Tesch (tesch@cs.wisc.edu)
* Copyright (C) 2003 Timesys Corporation.
* Copyright (C) 2004-2006 MontaVista Software, Inc.
* PPC64 Mods (C) 2005 Frank Rowand (frowand@mvista.com)
* PPC32 support restored by Vitaly Wool <vwool@ru.mvista.com> and
* Sergei Shtylyov <sshtylyov@ru.mvista.com>
* Copyright (C) 2007-2008 Wind River Systems, Inc.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program as licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/kgdb.h>
#include <linux/smp.h>
#include <linux/signal.h>
#include <linux/ptrace.h>
#include <linux/kdebug.h>
#include <asm/current.h>
#include <asm/processor.h>
#include <asm/machdep.h>
#include <asm/debug.h>
#include <linux/slab.h>
/*
* This table contains the mapping between PowerPC hardware trap types, and
* signals, which are primarily what GDB understands. GDB and the kernel
* don't always agree on values, so we use constants taken from gdb-6.2.
*/
static struct hard_trap_info
{
unsigned int tt; /* Trap type code for powerpc */
unsigned char signo; /* Signal that we map this trap into */
} hard_trap_info[] = {
{ 0x0100, 0x02 /* SIGINT */ }, /* system reset */
{ 0x0200, 0x0b /* SIGSEGV */ }, /* machine check */
{ 0x0300, 0x0b /* SIGSEGV */ }, /* data access */
{ 0x0400, 0x0b /* SIGSEGV */ }, /* instruction access */
{ 0x0500, 0x02 /* SIGINT */ }, /* external interrupt */
{ 0x0600, 0x0a /* SIGBUS */ }, /* alignment */
{ 0x0700, 0x05 /* SIGTRAP */ }, /* program check */
{ 0x0800, 0x08 /* SIGFPE */ }, /* fp unavailable */
{ 0x0900, 0x0e /* SIGALRM */ }, /* decrementer */
{ 0x0c00, 0x14 /* SIGCHLD */ }, /* system call */
#if defined(CONFIG_40x) || defined(CONFIG_BOOKE)
{ 0x2002, 0x05 /* SIGTRAP */ }, /* debug */
#if defined(CONFIG_FSL_BOOKE)
{ 0x2010, 0x08 /* SIGFPE */ }, /* spe unavailable */
{ 0x2020, 0x08 /* SIGFPE */ }, /* spe unavailable */
{ 0x2030, 0x08 /* SIGFPE */ }, /* spe fp data */
{ 0x2040, 0x08 /* SIGFPE */ }, /* spe fp data */
{ 0x2050, 0x08 /* SIGFPE */ }, /* spe fp round */
{ 0x2060, 0x0e /* SIGILL */ }, /* performance monitor */
{ 0x2900, 0x08 /* SIGFPE */ }, /* apu unavailable */
{ 0x3100, 0x0e /* SIGALRM */ }, /* fixed interval timer */
{ 0x3200, 0x02 /* SIGINT */ }, /* watchdog */
#else /* ! CONFIG_FSL_BOOKE */
{ 0x1000, 0x0e /* SIGALRM */ }, /* prog interval timer */
{ 0x1010, 0x0e /* SIGALRM */ }, /* fixed interval timer */
{ 0x1020, 0x02 /* SIGINT */ }, /* watchdog */
{ 0x2010, 0x08 /* SIGFPE */ }, /* fp unavailable */
{ 0x2020, 0x08 /* SIGFPE */ }, /* ap unavailable */
#endif
#else /* ! (defined(CONFIG_40x) || defined(CONFIG_BOOKE)) */
{ 0x0d00, 0x05 /* SIGTRAP */ }, /* single-step */
#if defined(CONFIG_8xx)
{ 0x1000, 0x04 /* SIGILL */ }, /* software emulation */
#else /* ! CONFIG_8xx */
{ 0x0f00, 0x04 /* SIGILL */ }, /* performance monitor */
{ 0x0f20, 0x08 /* SIGFPE */ }, /* altivec unavailable */
{ 0x1300, 0x05 /* SIGTRAP */ }, /* instruction address break */
#if defined(CONFIG_PPC64)
{ 0x1200, 0x05 /* SIGILL */ }, /* system error */
{ 0x1500, 0x04 /* SIGILL */ }, /* soft patch */
{ 0x1600, 0x04 /* SIGILL */ }, /* maintenance */
{ 0x1700, 0x08 /* SIGFPE */ }, /* altivec assist */
{ 0x1800, 0x04 /* SIGILL */ }, /* thermal */
#else /* ! CONFIG_PPC64 */
{ 0x1400, 0x02 /* SIGINT */ }, /* SMI */
{ 0x1600, 0x08 /* SIGFPE */ }, /* altivec assist */
{ 0x1700, 0x04 /* SIGILL */ }, /* TAU */
{ 0x2000, 0x05 /* SIGTRAP */ }, /* run mode */
#endif
#endif
#endif
{ 0x0000, 0x00 } /* Must be last */
};
static int computeSignal(unsigned int tt)
{
struct hard_trap_info *ht;
for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
if (ht->tt == tt)
return ht->signo;
return SIGHUP; /* default for things we don't know about */
}
/**
*
* kgdb_skipexception - Bail out of KGDB when we've been triggered.
* @exception: Exception vector number
* @regs: Current &struct pt_regs.
*
* On some architectures we need to skip a breakpoint exception when
* it occurs after a breakpoint has been removed.
*
*/
int kgdb_skipexception(int exception, struct pt_regs *regs)
{
return kgdb_isremovedbreak(regs->nip);
}
static int kgdb_call_nmi_hook(struct pt_regs *regs)
{
kgdb_nmicallback(raw_smp_processor_id(), regs);
return 0;
}
#ifdef CONFIG_SMP
void kgdb_roundup_cpus(unsigned long flags)
{
smp_send_debugger_break();
}
#endif
/* KGDB functions to use existing PowerPC64 hooks. */
static int kgdb_debugger(struct pt_regs *regs)
{
return !kgdb_handle_exception(1, computeSignal(TRAP(regs)),
DIE_OOPS, regs);
}
static int kgdb_handle_breakpoint(struct pt_regs *regs)
{
if (user_mode(regs))
return 0;
if (kgdb_handle_exception(1, SIGTRAP, 0, regs) != 0)
return 0;
if (*(u32 *) (regs->nip) == *(u32 *) (&arch_kgdb_ops.gdb_bpt_instr))
regs->nip += BREAK_INSTR_SIZE;
return 1;
}
static DEFINE_PER_CPU(struct thread_info, kgdb_thread_info);
static int kgdb_singlestep(struct pt_regs *regs)
{
struct thread_info *thread_info, *exception_thread_info;
struct thread_info *backup_current_thread_info =
&__get_cpu_var(kgdb_thread_info);
if (user_mode(regs))
return 0;
/*
* On Book E and perhaps other processors, singlestep is handled on
* the critical exception stack. This causes current_thread_info()
* to fail, since it it locates the thread_info by masking off
* the low bits of the current stack pointer. We work around
* this issue by copying the thread_info from the kernel stack
* before calling kgdb_handle_exception, and copying it back
* afterwards. On most processors the copy is avoided since
* exception_thread_info == thread_info.
*/
thread_info = (struct thread_info *)(regs->gpr[1] & ~(THREAD_SIZE-1));
exception_thread_info = current_thread_info();
if (thread_info != exception_thread_info) {
/* Save the original current_thread_info. */
memcpy(backup_current_thread_info, exception_thread_info, sizeof *thread_info);
memcpy(exception_thread_info, thread_info, sizeof *thread_info);
}
kgdb_handle_exception(0, SIGTRAP, 0, regs);
if (thread_info != exception_thread_info)
/* Restore current_thread_info lastly. */
memcpy(exception_thread_info, backup_current_thread_info, sizeof *thread_info);
return 1;
}
static int kgdb_iabr_match(struct pt_regs *regs)
{
if (user_mode(regs))
return 0;
if (kgdb_handle_exception(0, computeSignal(TRAP(regs)), 0, regs) != 0)
return 0;
return 1;
}
static int kgdb_break_match(struct pt_regs *regs)
{
if (user_mode(regs))
return 0;
if (kgdb_handle_exception(0, computeSignal(TRAP(regs)), 0, regs) != 0)
return 0;
return 1;
}
#define PACK64(ptr, src) do { *(ptr++) = (src); } while (0)
#define PACK32(ptr, src) do { \
u32 *ptr32; \
ptr32 = (u32 *)ptr; \
*(ptr32++) = (src); \
ptr = (unsigned long *)ptr32; \
} while (0)
void sleeping_thread_to_gdb_regs(unsigned long *gdb_regs, struct task_struct *p)
{
struct pt_regs *regs = (struct pt_regs *)(p->thread.ksp +
STACK_FRAME_OVERHEAD);
unsigned long *ptr = gdb_regs;
int reg;
memset(gdb_regs, 0, NUMREGBYTES);
/* Regs GPR0-2 */
for (reg = 0; reg < 3; reg++)
PACK64(ptr, regs->gpr[reg]);
/* Regs GPR3-13 are caller saved, not in regs->gpr[] */
ptr += 11;
/* Regs GPR14-31 */
for (reg = 14; reg < 32; reg++)
PACK64(ptr, regs->gpr[reg]);
#ifdef CONFIG_FSL_BOOKE
#ifdef CONFIG_SPE
for (reg = 0; reg < 32; reg++)
PACK64(ptr, p->thread.evr[reg]);
#else
ptr += 32;
#endif
#else
/* fp registers not used by kernel, leave zero */
ptr += 32 * 8 / sizeof(long);
#endif
PACK64(ptr, regs->nip);
PACK64(ptr, regs->msr);
PACK32(ptr, regs->ccr);
PACK64(ptr, regs->link);
PACK64(ptr, regs->ctr);
PACK32(ptr, regs->xer);
BUG_ON((unsigned long)ptr >
(unsigned long)(((void *)gdb_regs) + NUMREGBYTES));
}
#define GDB_SIZEOF_REG sizeof(unsigned long)
#define GDB_SIZEOF_REG_U32 sizeof(u32)
#ifdef CONFIG_FSL_BOOKE
#define GDB_SIZEOF_FLOAT_REG sizeof(unsigned long)
#else
#define GDB_SIZEOF_FLOAT_REG sizeof(u64)
#endif
struct dbg_reg_def_t dbg_reg_def[DBG_MAX_REG_NUM] =
{
{ "r0", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[0]) },
{ "r1", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[1]) },
{ "r2", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[2]) },
{ "r3", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[3]) },
{ "r4", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[4]) },
{ "r5", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[5]) },
{ "r6", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[6]) },
{ "r7", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[7]) },
{ "r8", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[8]) },
{ "r9", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[9]) },
{ "r10", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[10]) },
{ "r11", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[11]) },
{ "r12", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[12]) },
{ "r13", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[13]) },
{ "r14", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[14]) },
{ "r15", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[15]) },
{ "r16", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[16]) },
{ "r17", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[17]) },
{ "r18", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[18]) },
{ "r19", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[19]) },
{ "r20", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[20]) },
{ "r21", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[21]) },
{ "r22", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[22]) },
{ "r23", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[23]) },
{ "r24", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[24]) },
{ "r25", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[25]) },
{ "r26", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[26]) },
{ "r27", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[27]) },
{ "r28", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[28]) },
{ "r29", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[29]) },
{ "r30", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[30]) },
{ "r31", GDB_SIZEOF_REG, offsetof(struct pt_regs, gpr[31]) },
{ "f0", GDB_SIZEOF_FLOAT_REG, 0 },
{ "f1", GDB_SIZEOF_FLOAT_REG, 1 },
{ "f2", GDB_SIZEOF_FLOAT_REG, 2 },
{ "f3", GDB_SIZEOF_FLOAT_REG, 3 },
{ "f4", GDB_SIZEOF_FLOAT_REG, 4 },
{ "f5", GDB_SIZEOF_FLOAT_REG, 5 },
{ "f6", GDB_SIZEOF_FLOAT_REG, 6 },
{ "f7", GDB_SIZEOF_FLOAT_REG, 7 },
{ "f8", GDB_SIZEOF_FLOAT_REG, 8 },
{ "f9", GDB_SIZEOF_FLOAT_REG, 9 },
{ "f10", GDB_SIZEOF_FLOAT_REG, 10 },
{ "f11", GDB_SIZEOF_FLOAT_REG, 11 },
{ "f12", GDB_SIZEOF_FLOAT_REG, 12 },
{ "f13", GDB_SIZEOF_FLOAT_REG, 13 },
{ "f14", GDB_SIZEOF_FLOAT_REG, 14 },
{ "f15", GDB_SIZEOF_FLOAT_REG, 15 },
{ "f16", GDB_SIZEOF_FLOAT_REG, 16 },
{ "f17", GDB_SIZEOF_FLOAT_REG, 17 },
{ "f18", GDB_SIZEOF_FLOAT_REG, 18 },
{ "f19", GDB_SIZEOF_FLOAT_REG, 19 },
{ "f20", GDB_SIZEOF_FLOAT_REG, 20 },
{ "f21", GDB_SIZEOF_FLOAT_REG, 21 },
{ "f22", GDB_SIZEOF_FLOAT_REG, 22 },
{ "f23", GDB_SIZEOF_FLOAT_REG, 23 },
{ "f24", GDB_SIZEOF_FLOAT_REG, 24 },
{ "f25", GDB_SIZEOF_FLOAT_REG, 25 },
{ "f26", GDB_SIZEOF_FLOAT_REG, 26 },
{ "f27", GDB_SIZEOF_FLOAT_REG, 27 },
{ "f28", GDB_SIZEOF_FLOAT_REG, 28 },
{ "f29", GDB_SIZEOF_FLOAT_REG, 29 },
{ "f30", GDB_SIZEOF_FLOAT_REG, 30 },
{ "f31", GDB_SIZEOF_FLOAT_REG, 31 },
{ "pc", GDB_SIZEOF_REG, offsetof(struct pt_regs, nip) },
{ "msr", GDB_SIZEOF_REG, offsetof(struct pt_regs, msr) },
{ "cr", GDB_SIZEOF_REG_U32, offsetof(struct pt_regs, ccr) },
{ "lr", GDB_SIZEOF_REG, offsetof(struct pt_regs, link) },
{ "ctr", GDB_SIZEOF_REG_U32, offsetof(struct pt_regs, ctr) },
{ "xer", GDB_SIZEOF_REG, offsetof(struct pt_regs, xer) },
};
char *dbg_get_reg(int regno, void *mem, struct pt_regs *regs)
{
if (regno >= DBG_MAX_REG_NUM || regno < 0)
return NULL;
if (regno < 32 || regno >= 64)
/* First 0 -> 31 gpr registers*/
/* pc, msr, ls... registers 64 -> 69 */
memcpy(mem, (void *)regs + dbg_reg_def[regno].offset,
dbg_reg_def[regno].size);
if (regno >= 32 && regno < 64) {
/* FP registers 32 -> 63 */
#if defined(CONFIG_FSL_BOOKE) && defined(CONFIG_SPE)
if (current)
memcpy(mem, ¤t->thread.evr[regno-32],
dbg_reg_def[regno].size);
#else
/* fp registers not used by kernel, leave zero */
memset(mem, 0, dbg_reg_def[regno].size);
#endif
}
return dbg_reg_def[regno].name;
}
int dbg_set_reg(int regno, void *mem, struct pt_regs *regs)
{
if (regno >= DBG_MAX_REG_NUM || regno < 0)
return -EINVAL;
if (regno < 32 || regno >= 64)
/* First 0 -> 31 gpr registers*/
/* pc, msr, ls... registers 64 -> 69 */
memcpy((void *)regs + dbg_reg_def[regno].offset, mem,
dbg_reg_def[regno].size);
if (regno >= 32 && regno < 64) {
/* FP registers 32 -> 63 */
#if defined(CONFIG_FSL_BOOKE) && defined(CONFIG_SPE)
memcpy(¤t->thread.evr[regno-32], mem,
dbg_reg_def[regno].size);
#else
/* fp registers not used by kernel, leave zero */
return 0;
#endif
}
return 0;
}
void kgdb_arch_set_pc(struct pt_regs *regs, unsigned long pc)
{
regs->nip = pc;
}
/*
* This function does PowerPC specific procesing for interfacing to gdb.
*/
int kgdb_arch_handle_exception(int vector, int signo, int err_code,
char *remcom_in_buffer, char *remcom_out_buffer,
struct pt_regs *linux_regs)
{
char *ptr = &remcom_in_buffer[1];
unsigned long addr;
switch (remcom_in_buffer[0]) {
/*
* sAA..AA Step one instruction from AA..AA
* This will return an error to gdb ..
*/
case 's':
case 'c':
/* handle the optional parameter */
if (kgdb_hex2long(&ptr, &addr))
linux_regs->nip = addr;
atomic_set(&kgdb_cpu_doing_single_step, -1);
/* set the trace bit if we're stepping */
if (remcom_in_buffer[0] == 's') {
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
mtspr(SPRN_DBCR0,
mfspr(SPRN_DBCR0) | DBCR0_IC | DBCR0_IDM);
linux_regs->msr |= MSR_DE;
#else
linux_regs->msr |= MSR_SE;
#endif
atomic_set(&kgdb_cpu_doing_single_step,
raw_smp_processor_id());
}
return 0;
}
return -1;
}
/*
* Global data
*/
struct kgdb_arch arch_kgdb_ops = {
.gdb_bpt_instr = {0x7d, 0x82, 0x10, 0x08},
};
static int kgdb_not_implemented(struct pt_regs *regs)
{
return 0;
}
static void *old__debugger_ipi;
static void *old__debugger;
static void *old__debugger_bpt;
static void *old__debugger_sstep;
static void *old__debugger_iabr_match;
static void *old__debugger_break_match;
static void *old__debugger_fault_handler;
int kgdb_arch_init(void)
{
old__debugger_ipi = __debugger_ipi;
old__debugger = __debugger;
old__debugger_bpt = __debugger_bpt;
old__debugger_sstep = __debugger_sstep;
old__debugger_iabr_match = __debugger_iabr_match;
old__debugger_break_match = __debugger_break_match;
old__debugger_fault_handler = __debugger_fault_handler;
__debugger_ipi = kgdb_call_nmi_hook;
__debugger = kgdb_debugger;
__debugger_bpt = kgdb_handle_breakpoint;
__debugger_sstep = kgdb_singlestep;
__debugger_iabr_match = kgdb_iabr_match;
__debugger_break_match = kgdb_break_match;
__debugger_fault_handler = kgdb_not_implemented;
return 0;
}
void kgdb_arch_exit(void)
{
__debugger_ipi = old__debugger_ipi;
__debugger = old__debugger;
__debugger_bpt = old__debugger_bpt;
__debugger_sstep = old__debugger_sstep;
__debugger_iabr_match = old__debugger_iabr_match;
__debugger_break_match = old__debugger_break_match;
__debugger_fault_handler = old__debugger_fault_handler;
}
| gpl-2.0 |
HCDRJacob/u8800-2.6.32 | arch/sh/drivers/dma/dma-pvr2.c | 772 | 2423 | /*
* arch/sh/drivers/dma/dma-pvr2.c
*
* NEC PowerVR 2 (Dreamcast) DMA support
*
* Copyright (C) 2003, 2004 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <mach/sysasic.h>
#include <mach/dma.h>
#include <asm/dma.h>
#include <asm/io.h>
static unsigned int xfer_complete;
static int count;
static irqreturn_t pvr2_dma_interrupt(int irq, void *dev_id)
{
if (get_dma_residue(PVR2_CASCADE_CHAN)) {
printk(KERN_WARNING "DMA: SH DMAC did not complete transfer "
"on channel %d, waiting..\n", PVR2_CASCADE_CHAN);
dma_wait_for_completion(PVR2_CASCADE_CHAN);
}
if (count++ < 10)
pr_debug("Got a pvr2 dma interrupt for channel %d\n",
irq - HW_EVENT_PVR2_DMA);
xfer_complete = 1;
return IRQ_HANDLED;
}
static int pvr2_request_dma(struct dma_channel *chan)
{
if (ctrl_inl(PVR2_DMA_MODE) != 0)
return -EBUSY;
ctrl_outl(0, PVR2_DMA_LMMODE0);
return 0;
}
static int pvr2_get_dma_residue(struct dma_channel *chan)
{
return xfer_complete == 0;
}
static int pvr2_xfer_dma(struct dma_channel *chan)
{
if (chan->sar || !chan->dar)
return -EINVAL;
xfer_complete = 0;
ctrl_outl(chan->dar, PVR2_DMA_ADDR);
ctrl_outl(chan->count, PVR2_DMA_COUNT);
ctrl_outl(chan->mode & DMA_MODE_MASK, PVR2_DMA_MODE);
return 0;
}
static struct irqaction pvr2_dma_irq = {
.name = "pvr2 DMA handler",
.handler = pvr2_dma_interrupt,
.flags = IRQF_DISABLED,
};
static struct dma_ops pvr2_dma_ops = {
.request = pvr2_request_dma,
.get_residue = pvr2_get_dma_residue,
.xfer = pvr2_xfer_dma,
};
static struct dma_info pvr2_dma_info = {
.name = "pvr2_dmac",
.nr_channels = 1,
.ops = &pvr2_dma_ops,
.flags = DMAC_CHANNELS_TEI_CAPABLE,
};
static int __init pvr2_dma_init(void)
{
setup_irq(HW_EVENT_PVR2_DMA, &pvr2_dma_irq);
request_dma(PVR2_CASCADE_CHAN, "pvr2 cascade");
return register_dmac(&pvr2_dma_info);
}
static void __exit pvr2_dma_exit(void)
{
free_dma(PVR2_CASCADE_CHAN);
free_irq(HW_EVENT_PVR2_DMA, 0);
unregister_dmac(&pvr2_dma_info);
}
subsys_initcall(pvr2_dma_init);
module_exit(pvr2_dma_exit);
MODULE_AUTHOR("Paul Mundt <lethal@linux-sh.org>");
MODULE_DESCRIPTION("NEC PowerVR 2 DMA driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
vl197602/htc_msm8960 | net/core/sock_diag.c | 772 | 4816 | #include <linux/mutex.h>
#include <linux/socket.h>
#include <linux/skbuff.h>
#include <net/netlink.h>
#include <net/net_namespace.h>
#include <linux/module.h>
#include <linux/rtnetlink.h>
#include <net/sock.h>
#include <linux/inet_diag.h>
#include <linux/sock_diag.h>
static struct sock_diag_handler *sock_diag_handlers[AF_MAX];
static int (*inet_rcv_compat)(struct sk_buff *skb, struct nlmsghdr *nlh);
static DEFINE_MUTEX(sock_diag_table_mutex);
int sock_diag_check_cookie(void *sk, __u32 *cookie)
{
if ((cookie[0] != INET_DIAG_NOCOOKIE ||
cookie[1] != INET_DIAG_NOCOOKIE) &&
((u32)(unsigned long)sk != cookie[0] ||
(u32)((((unsigned long)sk) >> 31) >> 1) != cookie[1]))
return -ESTALE;
else
return 0;
}
EXPORT_SYMBOL_GPL(sock_diag_check_cookie);
void sock_diag_save_cookie(void *sk, __u32 *cookie)
{
cookie[0] = (u32)(unsigned long)sk;
cookie[1] = (u32)(((unsigned long)sk >> 31) >> 1);
}
EXPORT_SYMBOL_GPL(sock_diag_save_cookie);
int sock_diag_put_meminfo(struct sock *sk, struct sk_buff *skb, int attrtype)
{
__u32 *mem;
mem = RTA_DATA(__RTA_PUT(skb, attrtype, SK_MEMINFO_VARS * sizeof(__u32)));
mem[SK_MEMINFO_RMEM_ALLOC] = sk_rmem_alloc_get(sk);
mem[SK_MEMINFO_RCVBUF] = sk->sk_rcvbuf;
mem[SK_MEMINFO_WMEM_ALLOC] = sk_wmem_alloc_get(sk);
mem[SK_MEMINFO_SNDBUF] = sk->sk_sndbuf;
mem[SK_MEMINFO_FWD_ALLOC] = sk->sk_forward_alloc;
mem[SK_MEMINFO_WMEM_QUEUED] = sk->sk_wmem_queued;
mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc);
return 0;
rtattr_failure:
return -EMSGSIZE;
}
EXPORT_SYMBOL_GPL(sock_diag_put_meminfo);
void sock_diag_register_inet_compat(int (*fn)(struct sk_buff *skb, struct nlmsghdr *nlh))
{
mutex_lock(&sock_diag_table_mutex);
inet_rcv_compat = fn;
mutex_unlock(&sock_diag_table_mutex);
}
EXPORT_SYMBOL_GPL(sock_diag_register_inet_compat);
void sock_diag_unregister_inet_compat(int (*fn)(struct sk_buff *skb, struct nlmsghdr *nlh))
{
mutex_lock(&sock_diag_table_mutex);
inet_rcv_compat = NULL;
mutex_unlock(&sock_diag_table_mutex);
}
EXPORT_SYMBOL_GPL(sock_diag_unregister_inet_compat);
int sock_diag_register(struct sock_diag_handler *hndl)
{
int err = 0;
if (hndl->family >= AF_MAX)
return -EINVAL;
mutex_lock(&sock_diag_table_mutex);
if (sock_diag_handlers[hndl->family])
err = -EBUSY;
else
sock_diag_handlers[hndl->family] = hndl;
mutex_unlock(&sock_diag_table_mutex);
return err;
}
EXPORT_SYMBOL_GPL(sock_diag_register);
void sock_diag_unregister(struct sock_diag_handler *hnld)
{
int family = hnld->family;
if (family >= AF_MAX)
return;
mutex_lock(&sock_diag_table_mutex);
BUG_ON(sock_diag_handlers[family] != hnld);
sock_diag_handlers[family] = NULL;
mutex_unlock(&sock_diag_table_mutex);
}
EXPORT_SYMBOL_GPL(sock_diag_unregister);
static inline struct sock_diag_handler *sock_diag_lock_handler(int family)
{
if (sock_diag_handlers[family] == NULL)
request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK,
NETLINK_SOCK_DIAG, family);
mutex_lock(&sock_diag_table_mutex);
return sock_diag_handlers[family];
}
static inline void sock_diag_unlock_handler(struct sock_diag_handler *h)
{
mutex_unlock(&sock_diag_table_mutex);
}
static int __sock_diag_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
int err;
struct sock_diag_req *req = NLMSG_DATA(nlh);
struct sock_diag_handler *hndl;
if (nlmsg_len(nlh) < sizeof(*req))
return -EINVAL;
hndl = sock_diag_lock_handler(req->sdiag_family);
if (hndl == NULL)
err = -ENOENT;
else
err = hndl->dump(skb, nlh);
sock_diag_unlock_handler(hndl);
return err;
}
static int sock_diag_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
int ret;
switch (nlh->nlmsg_type) {
case TCPDIAG_GETSOCK:
case DCCPDIAG_GETSOCK:
if (inet_rcv_compat == NULL)
request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK,
NETLINK_SOCK_DIAG, AF_INET);
mutex_lock(&sock_diag_table_mutex);
if (inet_rcv_compat != NULL)
ret = inet_rcv_compat(skb, nlh);
else
ret = -EOPNOTSUPP;
mutex_unlock(&sock_diag_table_mutex);
return ret;
case SOCK_DIAG_BY_FAMILY:
return __sock_diag_rcv_msg(skb, nlh);
default:
return -EINVAL;
}
}
static DEFINE_MUTEX(sock_diag_mutex);
static void sock_diag_rcv(struct sk_buff *skb)
{
mutex_lock(&sock_diag_mutex);
netlink_rcv_skb(skb, &sock_diag_rcv_msg);
mutex_unlock(&sock_diag_mutex);
}
struct sock *sock_diag_nlsk;
EXPORT_SYMBOL_GPL(sock_diag_nlsk);
static int __init sock_diag_init(void)
{
sock_diag_nlsk = netlink_kernel_create(&init_net, NETLINK_SOCK_DIAG, 0,
sock_diag_rcv, NULL, THIS_MODULE);
return sock_diag_nlsk == NULL ? -ENOMEM : 0;
}
static void __exit sock_diag_exit(void)
{
netlink_kernel_release(sock_diag_nlsk);
}
module_init(sock_diag_init);
module_exit(sock_diag_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_SOCK_DIAG);
| gpl-2.0 |
Split-Screen/android_kernel_motorola_otus | drivers/gpu/ion/ion_cma_heap.c | 1284 | 5995 | /*
* drivers/gpu/ion/ion_cma_heap.c
*
* Copyright (C) Linaro 2012
* Author: <benjamin.gaignard@linaro.org> for ST-Ericsson.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/device.h>
#include <linux/ion.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/dma-mapping.h>
#include <linux/msm_ion.h>
#include <mach/iommu_domains.h>
#include <asm/cacheflush.h>
/* for ion_heap_ops structure */
#include "ion_priv.h"
#define ION_CMA_ALLOCATE_FAILED -1
struct ion_cma_buffer_info {
void *cpu_addr;
dma_addr_t handle;
struct sg_table *table;
bool is_cached;
};
static int cma_heap_has_outer_cache;
/*
* Create scatter-list for the already allocated DMA buffer.
* This function could be replace by dma_common_get_sgtable
* as soon as it will avalaible.
*/
int ion_cma_get_sgtable(struct device *dev, struct sg_table *sgt,
void *cpu_addr, dma_addr_t handle, size_t size)
{
struct page *page = phys_to_page(handle);
int ret;
ret = sg_alloc_table(sgt, 1, GFP_KERNEL);
if (unlikely(ret))
return ret;
sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0);
return 0;
}
/* ION CMA heap operations functions */
static int ion_cma_allocate(struct ion_heap *heap, struct ion_buffer *buffer,
unsigned long len, unsigned long align,
unsigned long flags)
{
struct device *dev = heap->priv;
struct ion_cma_buffer_info *info;
dev_dbg(dev, "Request buffer allocation len %ld\n", len);
info = kzalloc(sizeof(struct ion_cma_buffer_info), GFP_KERNEL);
if (!info) {
dev_err(dev, "Can't allocate buffer info\n");
return ION_CMA_ALLOCATE_FAILED;
}
if (!ION_IS_CACHED(flags))
info->cpu_addr = dma_alloc_writecombine(dev, len,
&(info->handle), GFP_KERNEL);
else
info->cpu_addr = dma_alloc_nonconsistent(dev, len,
&(info->handle), GFP_KERNEL);
if (!info->cpu_addr) {
dev_err(dev, "Fail to allocate buffer\n");
goto err;
}
info->table = kmalloc(sizeof(struct sg_table), GFP_KERNEL);
if (!info->table) {
dev_err(dev, "Fail to allocate sg table\n");
goto err;
}
info->is_cached = ION_IS_CACHED(flags);
ion_cma_get_sgtable(dev,
info->table, info->cpu_addr, info->handle, len);
/* keep this for memory release */
buffer->priv_virt = info;
dev_dbg(dev, "Allocate buffer %p\n", buffer);
return 0;
err:
kfree(info);
return ION_CMA_ALLOCATE_FAILED;
}
static void ion_cma_free(struct ion_buffer *buffer)
{
struct device *dev = buffer->heap->priv;
struct ion_cma_buffer_info *info = buffer->priv_virt;
dev_dbg(dev, "Release buffer %p\n", buffer);
/* release memory */
dma_free_coherent(dev, buffer->size, info->cpu_addr, info->handle);
sg_free_table(info->table);
/* release sg table */
kfree(info->table);
kfree(info);
}
/* return physical address in addr */
static int ion_cma_phys(struct ion_heap *heap, struct ion_buffer *buffer,
ion_phys_addr_t *addr, size_t *len)
{
struct device *dev = heap->priv;
struct ion_cma_buffer_info *info = buffer->priv_virt;
dev_dbg(dev, "Return buffer %p physical address 0x%pa\n", buffer,
&info->handle);
*addr = info->handle;
*len = buffer->size;
return 0;
}
struct sg_table *ion_cma_heap_map_dma(struct ion_heap *heap,
struct ion_buffer *buffer)
{
struct ion_cma_buffer_info *info = buffer->priv_virt;
return info->table;
}
void ion_cma_heap_unmap_dma(struct ion_heap *heap,
struct ion_buffer *buffer)
{
return;
}
static int ion_cma_mmap(struct ion_heap *mapper, struct ion_buffer *buffer,
struct vm_area_struct *vma)
{
struct device *dev = buffer->heap->priv;
struct ion_cma_buffer_info *info = buffer->priv_virt;
if (info->is_cached)
return dma_mmap_nonconsistent(dev, vma, info->cpu_addr,
info->handle, buffer->size);
else
return dma_mmap_writecombine(dev, vma, info->cpu_addr,
info->handle, buffer->size);
}
static void *ion_cma_map_kernel(struct ion_heap *heap,
struct ion_buffer *buffer)
{
struct ion_cma_buffer_info *info = buffer->priv_virt;
return info->cpu_addr;
}
static void ion_cma_unmap_kernel(struct ion_heap *heap,
struct ion_buffer *buffer)
{
return;
}
static int ion_cma_print_debug(struct ion_heap *heap, struct seq_file *s,
const struct list_head *mem_map)
{
if (mem_map) {
struct mem_map_data *data;
seq_printf(s, "\nMemory Map\n");
seq_printf(s, "%16.s %14.s %14.s %14.s\n",
"client", "start address", "end address",
"size (hex)");
list_for_each_entry(data, mem_map, node) {
const char *client_name = "(null)";
if (data->client_name)
client_name = data->client_name;
seq_printf(s, "%16.s %14pa %14pa %14lu (%lx)\n",
client_name, &data->addr,
&data->addr_end,
data->size, data->size);
}
}
return 0;
}
static struct ion_heap_ops ion_cma_ops = {
.allocate = ion_cma_allocate,
.free = ion_cma_free,
.map_dma = ion_cma_heap_map_dma,
.unmap_dma = ion_cma_heap_unmap_dma,
.phys = ion_cma_phys,
.map_user = ion_cma_mmap,
.map_kernel = ion_cma_map_kernel,
.unmap_kernel = ion_cma_unmap_kernel,
.print_debug = ion_cma_print_debug,
};
struct ion_heap *ion_cma_heap_create(struct ion_platform_heap *data)
{
struct ion_heap *heap;
heap = kzalloc(sizeof(struct ion_heap), GFP_KERNEL);
if (!heap)
return ERR_PTR(-ENOMEM);
heap->ops = &ion_cma_ops;
/* set device as private heaps data, later it will be
* used to make the link with reserved CMA memory */
heap->priv = data->priv;
heap->type = ION_HEAP_TYPE_DMA;
cma_heap_has_outer_cache = data->has_outer_cache;
return heap;
}
void ion_cma_heap_destroy(struct ion_heap *heap)
{
kfree(heap);
}
| gpl-2.0 |
alvislin/openwrt | kernel/linux-3.18.45/drivers/staging/rtl8192e/rtl8192e/rtl_eeprom.c | 1540 | 3665 | /******************************************************************************
* Copyright(c) 2008 - 2010 Realtek Corporation. All rights reserved.
*
* Based on the r8180 driver, which is:
* Copyright 2004-2005 Andrea Merello <andrea.merello@gmail.com>, et al.
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
******************************************************************************/
#include "rtl_core.h"
#include "rtl_eeprom.h"
static void eprom_cs(struct net_device *dev, short bit)
{
if (bit)
write_nic_byte(dev, EPROM_CMD,
(1 << EPROM_CS_SHIFT) |
read_nic_byte(dev, EPROM_CMD));
else
write_nic_byte(dev, EPROM_CMD, read_nic_byte(dev, EPROM_CMD)
& ~(1<<EPROM_CS_SHIFT));
udelay(EPROM_DELAY);
}
static void eprom_ck_cycle(struct net_device *dev)
{
write_nic_byte(dev, EPROM_CMD,
(1<<EPROM_CK_SHIFT) | read_nic_byte(dev, EPROM_CMD));
udelay(EPROM_DELAY);
write_nic_byte(dev, EPROM_CMD,
read_nic_byte(dev, EPROM_CMD) & ~(1<<EPROM_CK_SHIFT));
udelay(EPROM_DELAY);
}
static void eprom_w(struct net_device *dev, short bit)
{
if (bit)
write_nic_byte(dev, EPROM_CMD, (1<<EPROM_W_SHIFT) |
read_nic_byte(dev, EPROM_CMD));
else
write_nic_byte(dev, EPROM_CMD, read_nic_byte(dev, EPROM_CMD)
& ~(1<<EPROM_W_SHIFT));
udelay(EPROM_DELAY);
}
static short eprom_r(struct net_device *dev)
{
short bit;
bit = (read_nic_byte(dev, EPROM_CMD) & (1<<EPROM_R_SHIFT));
udelay(EPROM_DELAY);
if (bit)
return 1;
return 0;
}
static void eprom_send_bits_string(struct net_device *dev, short b[], int len)
{
int i;
for (i = 0; i < len; i++) {
eprom_w(dev, b[i]);
eprom_ck_cycle(dev);
}
}
u32 eprom_read(struct net_device *dev, u32 addr)
{
struct r8192_priv *priv = rtllib_priv(dev);
short read_cmd[] = {1, 1, 0};
short addr_str[8];
int i;
int addr_len;
u32 ret;
ret = 0;
write_nic_byte(dev, EPROM_CMD,
(EPROM_CMD_PROGRAM << EPROM_CMD_OPERATING_MODE_SHIFT));
udelay(EPROM_DELAY);
if (priv->epromtype == EEPROM_93C56) {
addr_str[7] = addr & 1;
addr_str[6] = addr & (1<<1);
addr_str[5] = addr & (1<<2);
addr_str[4] = addr & (1<<3);
addr_str[3] = addr & (1<<4);
addr_str[2] = addr & (1<<5);
addr_str[1] = addr & (1<<6);
addr_str[0] = addr & (1<<7);
addr_len = 8;
} else {
addr_str[5] = addr & 1;
addr_str[4] = addr & (1<<1);
addr_str[3] = addr & (1<<2);
addr_str[2] = addr & (1<<3);
addr_str[1] = addr & (1<<4);
addr_str[0] = addr & (1<<5);
addr_len = 6;
}
eprom_cs(dev, 1);
eprom_ck_cycle(dev);
eprom_send_bits_string(dev, read_cmd, 3);
eprom_send_bits_string(dev, addr_str, addr_len);
eprom_w(dev, 0);
for (i = 0; i < 16; i++) {
eprom_ck_cycle(dev);
ret |= (eprom_r(dev)<<(15-i));
}
eprom_cs(dev, 0);
eprom_ck_cycle(dev);
write_nic_byte(dev, EPROM_CMD,
(EPROM_CMD_NORMAL<<EPROM_CMD_OPERATING_MODE_SHIFT));
return ret;
}
| gpl-2.0 |
BORETS24/Zenfone-2-500CL | linux/kernel/fs/f2fs/checkpoint.c | 1540 | 20322 | /*
* fs/f2fs/checkpoint.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.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 <linux/fs.h>
#include <linux/bio.h>
#include <linux/mpage.h>
#include <linux/writeback.h>
#include <linux/blkdev.h>
#include <linux/f2fs_fs.h>
#include <linux/pagevec.h>
#include <linux/swap.h>
#include "f2fs.h"
#include "node.h"
#include "segment.h"
#include <trace/events/f2fs.h>
static struct kmem_cache *orphan_entry_slab;
static struct kmem_cache *inode_entry_slab;
/*
* We guarantee no failure on the returned page.
*/
struct page *grab_meta_page(struct f2fs_sb_info *sbi, pgoff_t index)
{
struct address_space *mapping = sbi->meta_inode->i_mapping;
struct page *page = NULL;
repeat:
page = grab_cache_page(mapping, index);
if (!page) {
cond_resched();
goto repeat;
}
/* We wait writeback only inside grab_meta_page() */
wait_on_page_writeback(page);
SetPageUptodate(page);
return page;
}
/*
* We guarantee no failure on the returned page.
*/
struct page *get_meta_page(struct f2fs_sb_info *sbi, pgoff_t index)
{
struct address_space *mapping = sbi->meta_inode->i_mapping;
struct page *page;
repeat:
page = grab_cache_page(mapping, index);
if (!page) {
cond_resched();
goto repeat;
}
if (PageUptodate(page))
goto out;
if (f2fs_readpage(sbi, page, index, READ_SYNC))
goto repeat;
lock_page(page);
if (page->mapping != mapping) {
f2fs_put_page(page, 1);
goto repeat;
}
out:
mark_page_accessed(page);
return page;
}
static int f2fs_write_meta_page(struct page *page,
struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
struct f2fs_sb_info *sbi = F2FS_SB(inode->i_sb);
/* Should not write any meta pages, if any IO error was occurred */
if (wbc->for_reclaim ||
is_set_ckpt_flags(F2FS_CKPT(sbi), CP_ERROR_FLAG)) {
dec_page_count(sbi, F2FS_DIRTY_META);
wbc->pages_skipped++;
set_page_dirty(page);
return AOP_WRITEPAGE_ACTIVATE;
}
wait_on_page_writeback(page);
write_meta_page(sbi, page);
dec_page_count(sbi, F2FS_DIRTY_META);
unlock_page(page);
return 0;
}
static int f2fs_write_meta_pages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct f2fs_sb_info *sbi = F2FS_SB(mapping->host->i_sb);
struct block_device *bdev = sbi->sb->s_bdev;
long written;
if (wbc->for_kupdate)
return 0;
if (get_pages(sbi, F2FS_DIRTY_META) == 0)
return 0;
/* if mounting is failed, skip writing node pages */
mutex_lock(&sbi->cp_mutex);
written = sync_meta_pages(sbi, META, bio_get_nr_vecs(bdev));
mutex_unlock(&sbi->cp_mutex);
wbc->nr_to_write -= written;
return 0;
}
long sync_meta_pages(struct f2fs_sb_info *sbi, enum page_type type,
long nr_to_write)
{
struct address_space *mapping = sbi->meta_inode->i_mapping;
pgoff_t index = 0, end = LONG_MAX;
struct pagevec pvec;
long nwritten = 0;
struct writeback_control wbc = {
.for_reclaim = 0,
};
pagevec_init(&pvec, 0);
while (index <= end) {
int i, nr_pages;
nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
PAGECACHE_TAG_DIRTY,
min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
if (nr_pages == 0)
break;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
lock_page(page);
BUG_ON(page->mapping != mapping);
BUG_ON(!PageDirty(page));
clear_page_dirty_for_io(page);
if (f2fs_write_meta_page(page, &wbc)) {
unlock_page(page);
break;
}
if (nwritten++ >= nr_to_write)
break;
}
pagevec_release(&pvec);
cond_resched();
}
if (nwritten)
f2fs_submit_bio(sbi, type, nr_to_write == LONG_MAX);
return nwritten;
}
static int f2fs_set_meta_page_dirty(struct page *page)
{
struct address_space *mapping = page->mapping;
struct f2fs_sb_info *sbi = F2FS_SB(mapping->host->i_sb);
SetPageUptodate(page);
if (!PageDirty(page)) {
__set_page_dirty_nobuffers(page);
inc_page_count(sbi, F2FS_DIRTY_META);
return 1;
}
return 0;
}
const struct address_space_operations f2fs_meta_aops = {
.writepage = f2fs_write_meta_page,
.writepages = f2fs_write_meta_pages,
.set_page_dirty = f2fs_set_meta_page_dirty,
};
int check_orphan_space(struct f2fs_sb_info *sbi)
{
unsigned int max_orphans;
int err = 0;
/*
* considering 512 blocks in a segment 5 blocks are needed for cp
* and log segment summaries. Remaining blocks are used to keep
* orphan entries with the limitation one reserved segment
* for cp pack we can have max 1020*507 orphan entries
*/
max_orphans = (sbi->blocks_per_seg - 5) * F2FS_ORPHANS_PER_BLOCK;
mutex_lock(&sbi->orphan_inode_mutex);
if (sbi->n_orphans >= max_orphans)
err = -ENOSPC;
mutex_unlock(&sbi->orphan_inode_mutex);
return err;
}
void add_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino)
{
struct list_head *head, *this;
struct orphan_inode_entry *new = NULL, *orphan = NULL;
mutex_lock(&sbi->orphan_inode_mutex);
head = &sbi->orphan_inode_list;
list_for_each(this, head) {
orphan = list_entry(this, struct orphan_inode_entry, list);
if (orphan->ino == ino)
goto out;
if (orphan->ino > ino)
break;
orphan = NULL;
}
retry:
new = kmem_cache_alloc(orphan_entry_slab, GFP_ATOMIC);
if (!new) {
cond_resched();
goto retry;
}
new->ino = ino;
/* add new_oentry into list which is sorted by inode number */
if (orphan)
list_add(&new->list, this->prev);
else
list_add_tail(&new->list, head);
sbi->n_orphans++;
out:
mutex_unlock(&sbi->orphan_inode_mutex);
}
void remove_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino)
{
struct list_head *this, *next, *head;
struct orphan_inode_entry *orphan;
mutex_lock(&sbi->orphan_inode_mutex);
head = &sbi->orphan_inode_list;
list_for_each_safe(this, next, head) {
orphan = list_entry(this, struct orphan_inode_entry, list);
if (orphan->ino == ino) {
list_del(&orphan->list);
kmem_cache_free(orphan_entry_slab, orphan);
sbi->n_orphans--;
break;
}
}
mutex_unlock(&sbi->orphan_inode_mutex);
}
static void recover_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino)
{
struct inode *inode = f2fs_iget(sbi->sb, ino);
BUG_ON(IS_ERR(inode));
clear_nlink(inode);
/* truncate all the data during iput */
iput(inode);
}
int recover_orphan_inodes(struct f2fs_sb_info *sbi)
{
block_t start_blk, orphan_blkaddr, i, j;
if (!is_set_ckpt_flags(F2FS_CKPT(sbi), CP_ORPHAN_PRESENT_FLAG))
return 0;
sbi->por_doing = 1;
start_blk = __start_cp_addr(sbi) + 1;
orphan_blkaddr = __start_sum_addr(sbi) - 1;
for (i = 0; i < orphan_blkaddr; i++) {
struct page *page = get_meta_page(sbi, start_blk + i);
struct f2fs_orphan_block *orphan_blk;
orphan_blk = (struct f2fs_orphan_block *)page_address(page);
for (j = 0; j < le32_to_cpu(orphan_blk->entry_count); j++) {
nid_t ino = le32_to_cpu(orphan_blk->ino[j]);
recover_orphan_inode(sbi, ino);
}
f2fs_put_page(page, 1);
}
/* clear Orphan Flag */
clear_ckpt_flags(F2FS_CKPT(sbi), CP_ORPHAN_PRESENT_FLAG);
sbi->por_doing = 0;
return 0;
}
static void write_orphan_inodes(struct f2fs_sb_info *sbi, block_t start_blk)
{
struct list_head *head, *this, *next;
struct f2fs_orphan_block *orphan_blk = NULL;
struct page *page = NULL;
unsigned int nentries = 0;
unsigned short index = 1;
unsigned short orphan_blocks;
orphan_blocks = (unsigned short)((sbi->n_orphans +
(F2FS_ORPHANS_PER_BLOCK - 1)) / F2FS_ORPHANS_PER_BLOCK);
mutex_lock(&sbi->orphan_inode_mutex);
head = &sbi->orphan_inode_list;
/* loop for each orphan inode entry and write them in Jornal block */
list_for_each_safe(this, next, head) {
struct orphan_inode_entry *orphan;
orphan = list_entry(this, struct orphan_inode_entry, list);
if (nentries == F2FS_ORPHANS_PER_BLOCK) {
/*
* an orphan block is full of 1020 entries,
* then we need to flush current orphan blocks
* and bring another one in memory
*/
orphan_blk->blk_addr = cpu_to_le16(index);
orphan_blk->blk_count = cpu_to_le16(orphan_blocks);
orphan_blk->entry_count = cpu_to_le32(nentries);
set_page_dirty(page);
f2fs_put_page(page, 1);
index++;
start_blk++;
nentries = 0;
page = NULL;
}
if (page)
goto page_exist;
page = grab_meta_page(sbi, start_blk);
orphan_blk = (struct f2fs_orphan_block *)page_address(page);
memset(orphan_blk, 0, sizeof(*orphan_blk));
page_exist:
orphan_blk->ino[nentries++] = cpu_to_le32(orphan->ino);
}
if (!page)
goto end;
orphan_blk->blk_addr = cpu_to_le16(index);
orphan_blk->blk_count = cpu_to_le16(orphan_blocks);
orphan_blk->entry_count = cpu_to_le32(nentries);
set_page_dirty(page);
f2fs_put_page(page, 1);
end:
mutex_unlock(&sbi->orphan_inode_mutex);
}
static struct page *validate_checkpoint(struct f2fs_sb_info *sbi,
block_t cp_addr, unsigned long long *version)
{
struct page *cp_page_1, *cp_page_2 = NULL;
unsigned long blk_size = sbi->blocksize;
struct f2fs_checkpoint *cp_block;
unsigned long long cur_version = 0, pre_version = 0;
unsigned int crc = 0;
size_t crc_offset;
/* Read the 1st cp block in this CP pack */
cp_page_1 = get_meta_page(sbi, cp_addr);
/* get the version number */
cp_block = (struct f2fs_checkpoint *)page_address(cp_page_1);
crc_offset = le32_to_cpu(cp_block->checksum_offset);
if (crc_offset >= blk_size)
goto invalid_cp1;
crc = *(unsigned int *)((unsigned char *)cp_block + crc_offset);
if (!f2fs_crc_valid(crc, cp_block, crc_offset))
goto invalid_cp1;
pre_version = le64_to_cpu(cp_block->checkpoint_ver);
/* Read the 2nd cp block in this CP pack */
cp_addr += le32_to_cpu(cp_block->cp_pack_total_block_count) - 1;
cp_page_2 = get_meta_page(sbi, cp_addr);
cp_block = (struct f2fs_checkpoint *)page_address(cp_page_2);
crc_offset = le32_to_cpu(cp_block->checksum_offset);
if (crc_offset >= blk_size)
goto invalid_cp2;
crc = *(unsigned int *)((unsigned char *)cp_block + crc_offset);
if (!f2fs_crc_valid(crc, cp_block, crc_offset))
goto invalid_cp2;
cur_version = le64_to_cpu(cp_block->checkpoint_ver);
if (cur_version == pre_version) {
*version = cur_version;
f2fs_put_page(cp_page_2, 1);
return cp_page_1;
}
invalid_cp2:
f2fs_put_page(cp_page_2, 1);
invalid_cp1:
f2fs_put_page(cp_page_1, 1);
return NULL;
}
int get_valid_checkpoint(struct f2fs_sb_info *sbi)
{
struct f2fs_checkpoint *cp_block;
struct f2fs_super_block *fsb = sbi->raw_super;
struct page *cp1, *cp2, *cur_page;
unsigned long blk_size = sbi->blocksize;
unsigned long long cp1_version = 0, cp2_version = 0;
unsigned long long cp_start_blk_no;
sbi->ckpt = kzalloc(blk_size, GFP_KERNEL);
if (!sbi->ckpt)
return -ENOMEM;
/*
* Finding out valid cp block involves read both
* sets( cp pack1 and cp pack 2)
*/
cp_start_blk_no = le32_to_cpu(fsb->cp_blkaddr);
cp1 = validate_checkpoint(sbi, cp_start_blk_no, &cp1_version);
/* The second checkpoint pack should start at the next segment */
cp_start_blk_no += 1 << le32_to_cpu(fsb->log_blocks_per_seg);
cp2 = validate_checkpoint(sbi, cp_start_blk_no, &cp2_version);
if (cp1 && cp2) {
if (ver_after(cp2_version, cp1_version))
cur_page = cp2;
else
cur_page = cp1;
} else if (cp1) {
cur_page = cp1;
} else if (cp2) {
cur_page = cp2;
} else {
goto fail_no_cp;
}
cp_block = (struct f2fs_checkpoint *)page_address(cur_page);
memcpy(sbi->ckpt, cp_block, blk_size);
f2fs_put_page(cp1, 1);
f2fs_put_page(cp2, 1);
return 0;
fail_no_cp:
kfree(sbi->ckpt);
return -EINVAL;
}
void set_dirty_dir_page(struct inode *inode, struct page *page)
{
struct f2fs_sb_info *sbi = F2FS_SB(inode->i_sb);
struct list_head *head = &sbi->dir_inode_list;
struct dir_inode_entry *new;
struct list_head *this;
if (!S_ISDIR(inode->i_mode))
return;
retry:
new = kmem_cache_alloc(inode_entry_slab, GFP_NOFS);
if (!new) {
cond_resched();
goto retry;
}
new->inode = inode;
INIT_LIST_HEAD(&new->list);
spin_lock(&sbi->dir_inode_lock);
list_for_each(this, head) {
struct dir_inode_entry *entry;
entry = list_entry(this, struct dir_inode_entry, list);
if (entry->inode == inode) {
kmem_cache_free(inode_entry_slab, new);
goto out;
}
}
list_add_tail(&new->list, head);
sbi->n_dirty_dirs++;
BUG_ON(!S_ISDIR(inode->i_mode));
out:
inc_page_count(sbi, F2FS_DIRTY_DENTS);
inode_inc_dirty_dents(inode);
SetPagePrivate(page);
spin_unlock(&sbi->dir_inode_lock);
}
void remove_dirty_dir_inode(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_SB(inode->i_sb);
struct list_head *head = &sbi->dir_inode_list;
struct list_head *this;
if (!S_ISDIR(inode->i_mode))
return;
spin_lock(&sbi->dir_inode_lock);
if (atomic_read(&F2FS_I(inode)->dirty_dents))
goto out;
list_for_each(this, head) {
struct dir_inode_entry *entry;
entry = list_entry(this, struct dir_inode_entry, list);
if (entry->inode == inode) {
list_del(&entry->list);
kmem_cache_free(inode_entry_slab, entry);
sbi->n_dirty_dirs--;
break;
}
}
out:
spin_unlock(&sbi->dir_inode_lock);
}
void sync_dirty_dir_inodes(struct f2fs_sb_info *sbi)
{
struct list_head *head = &sbi->dir_inode_list;
struct dir_inode_entry *entry;
struct inode *inode;
retry:
spin_lock(&sbi->dir_inode_lock);
if (list_empty(head)) {
spin_unlock(&sbi->dir_inode_lock);
return;
}
entry = list_entry(head->next, struct dir_inode_entry, list);
inode = igrab(entry->inode);
spin_unlock(&sbi->dir_inode_lock);
if (inode) {
filemap_flush(inode->i_mapping);
iput(inode);
} else {
/*
* We should submit bio, since it exists several
* wribacking dentry pages in the freeing inode.
*/
f2fs_submit_bio(sbi, DATA, true);
}
goto retry;
}
/*
* Freeze all the FS-operations for checkpoint.
*/
static void block_operations(struct f2fs_sb_info *sbi)
{
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = LONG_MAX,
.for_reclaim = 0,
};
struct blk_plug plug;
blk_start_plug(&plug);
retry_flush_dents:
mutex_lock_all(sbi);
/* write all the dirty dentry pages */
if (get_pages(sbi, F2FS_DIRTY_DENTS)) {
mutex_unlock_all(sbi);
sync_dirty_dir_inodes(sbi);
goto retry_flush_dents;
}
/*
* POR: we should ensure that there is no dirty node pages
* until finishing nat/sit flush.
*/
retry_flush_nodes:
mutex_lock(&sbi->node_write);
if (get_pages(sbi, F2FS_DIRTY_NODES)) {
mutex_unlock(&sbi->node_write);
sync_node_pages(sbi, 0, &wbc);
goto retry_flush_nodes;
}
blk_finish_plug(&plug);
}
static void unblock_operations(struct f2fs_sb_info *sbi)
{
mutex_unlock(&sbi->node_write);
mutex_unlock_all(sbi);
}
static void do_checkpoint(struct f2fs_sb_info *sbi, bool is_umount)
{
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
nid_t last_nid = 0;
block_t start_blk;
struct page *cp_page;
unsigned int data_sum_blocks, orphan_blocks;
unsigned int crc32 = 0;
void *kaddr;
int i;
/* Flush all the NAT/SIT pages */
while (get_pages(sbi, F2FS_DIRTY_META))
sync_meta_pages(sbi, META, LONG_MAX);
next_free_nid(sbi, &last_nid);
/*
* modify checkpoint
* version number is already updated
*/
ckpt->elapsed_time = cpu_to_le64(get_mtime(sbi));
ckpt->valid_block_count = cpu_to_le64(valid_user_blocks(sbi));
ckpt->free_segment_count = cpu_to_le32(free_segments(sbi));
for (i = 0; i < 3; i++) {
ckpt->cur_node_segno[i] =
cpu_to_le32(curseg_segno(sbi, i + CURSEG_HOT_NODE));
ckpt->cur_node_blkoff[i] =
cpu_to_le16(curseg_blkoff(sbi, i + CURSEG_HOT_NODE));
ckpt->alloc_type[i + CURSEG_HOT_NODE] =
curseg_alloc_type(sbi, i + CURSEG_HOT_NODE);
}
for (i = 0; i < 3; i++) {
ckpt->cur_data_segno[i] =
cpu_to_le32(curseg_segno(sbi, i + CURSEG_HOT_DATA));
ckpt->cur_data_blkoff[i] =
cpu_to_le16(curseg_blkoff(sbi, i + CURSEG_HOT_DATA));
ckpt->alloc_type[i + CURSEG_HOT_DATA] =
curseg_alloc_type(sbi, i + CURSEG_HOT_DATA);
}
ckpt->valid_node_count = cpu_to_le32(valid_node_count(sbi));
ckpt->valid_inode_count = cpu_to_le32(valid_inode_count(sbi));
ckpt->next_free_nid = cpu_to_le32(last_nid);
/* 2 cp + n data seg summary + orphan inode blocks */
data_sum_blocks = npages_for_summary_flush(sbi);
if (data_sum_blocks < 3)
set_ckpt_flags(ckpt, CP_COMPACT_SUM_FLAG);
else
clear_ckpt_flags(ckpt, CP_COMPACT_SUM_FLAG);
orphan_blocks = (sbi->n_orphans + F2FS_ORPHANS_PER_BLOCK - 1)
/ F2FS_ORPHANS_PER_BLOCK;
ckpt->cp_pack_start_sum = cpu_to_le32(1 + orphan_blocks);
if (is_umount) {
set_ckpt_flags(ckpt, CP_UMOUNT_FLAG);
ckpt->cp_pack_total_block_count = cpu_to_le32(2 +
data_sum_blocks + orphan_blocks + NR_CURSEG_NODE_TYPE);
} else {
clear_ckpt_flags(ckpt, CP_UMOUNT_FLAG);
ckpt->cp_pack_total_block_count = cpu_to_le32(2 +
data_sum_blocks + orphan_blocks);
}
if (sbi->n_orphans)
set_ckpt_flags(ckpt, CP_ORPHAN_PRESENT_FLAG);
else
clear_ckpt_flags(ckpt, CP_ORPHAN_PRESENT_FLAG);
/* update SIT/NAT bitmap */
get_sit_bitmap(sbi, __bitmap_ptr(sbi, SIT_BITMAP));
get_nat_bitmap(sbi, __bitmap_ptr(sbi, NAT_BITMAP));
crc32 = f2fs_crc32(ckpt, le32_to_cpu(ckpt->checksum_offset));
*(__le32 *)((unsigned char *)ckpt +
le32_to_cpu(ckpt->checksum_offset))
= cpu_to_le32(crc32);
start_blk = __start_cp_addr(sbi);
/* write out checkpoint buffer at block 0 */
cp_page = grab_meta_page(sbi, start_blk++);
kaddr = page_address(cp_page);
memcpy(kaddr, ckpt, (1 << sbi->log_blocksize));
set_page_dirty(cp_page);
f2fs_put_page(cp_page, 1);
if (sbi->n_orphans) {
write_orphan_inodes(sbi, start_blk);
start_blk += orphan_blocks;
}
write_data_summaries(sbi, start_blk);
start_blk += data_sum_blocks;
if (is_umount) {
write_node_summaries(sbi, start_blk);
start_blk += NR_CURSEG_NODE_TYPE;
}
/* writeout checkpoint block */
cp_page = grab_meta_page(sbi, start_blk);
kaddr = page_address(cp_page);
memcpy(kaddr, ckpt, (1 << sbi->log_blocksize));
set_page_dirty(cp_page);
f2fs_put_page(cp_page, 1);
/* wait for previous submitted node/meta pages writeback */
while (get_pages(sbi, F2FS_WRITEBACK))
congestion_wait(BLK_RW_ASYNC, HZ / 50);
filemap_fdatawait_range(sbi->node_inode->i_mapping, 0, LONG_MAX);
filemap_fdatawait_range(sbi->meta_inode->i_mapping, 0, LONG_MAX);
/* update user_block_counts */
sbi->last_valid_block_count = sbi->total_valid_block_count;
sbi->alloc_valid_block_count = 0;
/* Here, we only have one bio having CP pack */
sync_meta_pages(sbi, META_FLUSH, LONG_MAX);
if (!is_set_ckpt_flags(ckpt, CP_ERROR_FLAG)) {
clear_prefree_segments(sbi);
F2FS_RESET_SB_DIRT(sbi);
}
}
/*
* We guarantee that this checkpoint procedure should not fail.
*/
void write_checkpoint(struct f2fs_sb_info *sbi, bool is_umount)
{
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
unsigned long long ckpt_ver;
trace_f2fs_write_checkpoint(sbi->sb, is_umount, "start block_ops");
mutex_lock(&sbi->cp_mutex);
block_operations(sbi);
trace_f2fs_write_checkpoint(sbi->sb, is_umount, "finish block_ops");
f2fs_submit_bio(sbi, DATA, true);
f2fs_submit_bio(sbi, NODE, true);
f2fs_submit_bio(sbi, META, true);
/*
* update checkpoint pack index
* Increase the version number so that
* SIT entries and seg summaries are written at correct place
*/
ckpt_ver = le64_to_cpu(ckpt->checkpoint_ver);
ckpt->checkpoint_ver = cpu_to_le64(++ckpt_ver);
/* write cached NAT/SIT entries to NAT/SIT area */
flush_nat_entries(sbi);
flush_sit_entries(sbi);
/* unlock all the fs_lock[] in do_checkpoint() */
do_checkpoint(sbi, is_umount);
unblock_operations(sbi);
mutex_unlock(&sbi->cp_mutex);
trace_f2fs_write_checkpoint(sbi->sb, is_umount, "finish checkpoint");
}
void init_orphan_info(struct f2fs_sb_info *sbi)
{
mutex_init(&sbi->orphan_inode_mutex);
INIT_LIST_HEAD(&sbi->orphan_inode_list);
sbi->n_orphans = 0;
}
int __init create_checkpoint_caches(void)
{
orphan_entry_slab = f2fs_kmem_cache_create("f2fs_orphan_entry",
sizeof(struct orphan_inode_entry), NULL);
if (unlikely(!orphan_entry_slab))
return -ENOMEM;
inode_entry_slab = f2fs_kmem_cache_create("f2fs_dirty_dir_entry",
sizeof(struct dir_inode_entry), NULL);
if (unlikely(!inode_entry_slab)) {
kmem_cache_destroy(orphan_entry_slab);
return -ENOMEM;
}
return 0;
}
void destroy_checkpoint_caches(void)
{
kmem_cache_destroy(orphan_entry_slab);
kmem_cache_destroy(inode_entry_slab);
}
| gpl-2.0 |
95A31/android_kernel_msm | arch/powerpc/kvm/book3s_hv_ras.c | 2308 | 4115 | /*
* 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.
*
* Copyright 2012 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
*/
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kvm.h>
#include <linux/kvm_host.h>
#include <linux/kernel.h>
#include <asm/opal.h>
/* SRR1 bits for machine check on POWER7 */
#define SRR1_MC_LDSTERR (1ul << (63-42))
#define SRR1_MC_IFETCH_SH (63-45)
#define SRR1_MC_IFETCH_MASK 0x7
#define SRR1_MC_IFETCH_SLBPAR 2 /* SLB parity error */
#define SRR1_MC_IFETCH_SLBMULTI 3 /* SLB multi-hit */
#define SRR1_MC_IFETCH_SLBPARMULTI 4 /* SLB parity + multi-hit */
#define SRR1_MC_IFETCH_TLBMULTI 5 /* I-TLB multi-hit */
/* DSISR bits for machine check on POWER7 */
#define DSISR_MC_DERAT_MULTI 0x800 /* D-ERAT multi-hit */
#define DSISR_MC_TLB_MULTI 0x400 /* D-TLB multi-hit */
#define DSISR_MC_SLB_PARITY 0x100 /* SLB parity error */
#define DSISR_MC_SLB_MULTI 0x080 /* SLB multi-hit */
#define DSISR_MC_SLB_PARMULTI 0x040 /* SLB parity + multi-hit */
/* POWER7 SLB flush and reload */
static void reload_slb(struct kvm_vcpu *vcpu)
{
struct slb_shadow *slb;
unsigned long i, n;
/* First clear out SLB */
asm volatile("slbmte %0,%0; slbia" : : "r" (0));
/* Do they have an SLB shadow buffer registered? */
slb = vcpu->arch.slb_shadow.pinned_addr;
if (!slb)
return;
/* Sanity check */
n = min_t(u32, slb->persistent, SLB_MIN_SIZE);
if ((void *) &slb->save_area[n] > vcpu->arch.slb_shadow.pinned_end)
return;
/* Load up the SLB from that */
for (i = 0; i < n; ++i) {
unsigned long rb = slb->save_area[i].esid;
unsigned long rs = slb->save_area[i].vsid;
rb = (rb & ~0xFFFul) | i; /* insert entry number */
asm volatile("slbmte %0,%1" : : "r" (rs), "r" (rb));
}
}
/* POWER7 TLB flush */
static void flush_tlb_power7(struct kvm_vcpu *vcpu)
{
unsigned long i, rb;
rb = TLBIEL_INVAL_SET_LPID;
for (i = 0; i < POWER7_TLB_SETS; ++i) {
asm volatile("tlbiel %0" : : "r" (rb));
rb += 1 << TLBIEL_INVAL_SET_SHIFT;
}
}
/*
* On POWER7, see if we can handle a machine check that occurred inside
* the guest in real mode, without switching to the host partition.
*
* Returns: 0 => exit guest, 1 => deliver machine check to guest
*/
static long kvmppc_realmode_mc_power7(struct kvm_vcpu *vcpu)
{
unsigned long srr1 = vcpu->arch.shregs.msr;
#ifdef CONFIG_PPC_POWERNV
struct opal_machine_check_event *opal_evt;
#endif
long handled = 1;
if (srr1 & SRR1_MC_LDSTERR) {
/* error on load/store */
unsigned long dsisr = vcpu->arch.shregs.dsisr;
if (dsisr & (DSISR_MC_SLB_PARMULTI | DSISR_MC_SLB_MULTI |
DSISR_MC_SLB_PARITY | DSISR_MC_DERAT_MULTI)) {
/* flush and reload SLB; flushes D-ERAT too */
reload_slb(vcpu);
dsisr &= ~(DSISR_MC_SLB_PARMULTI | DSISR_MC_SLB_MULTI |
DSISR_MC_SLB_PARITY | DSISR_MC_DERAT_MULTI);
}
if (dsisr & DSISR_MC_TLB_MULTI) {
flush_tlb_power7(vcpu);
dsisr &= ~DSISR_MC_TLB_MULTI;
}
/* Any other errors we don't understand? */
if (dsisr & 0xffffffffUL)
handled = 0;
}
switch ((srr1 >> SRR1_MC_IFETCH_SH) & SRR1_MC_IFETCH_MASK) {
case 0:
break;
case SRR1_MC_IFETCH_SLBPAR:
case SRR1_MC_IFETCH_SLBMULTI:
case SRR1_MC_IFETCH_SLBPARMULTI:
reload_slb(vcpu);
break;
case SRR1_MC_IFETCH_TLBMULTI:
flush_tlb_power7(vcpu);
break;
default:
handled = 0;
}
#ifdef CONFIG_PPC_POWERNV
/*
* See if OPAL has already handled the condition.
* We assume that if the condition is recovered then OPAL
* will have generated an error log event that we will pick
* up and log later.
*/
opal_evt = local_paca->opal_mc_evt;
if (opal_evt->version == OpalMCE_V1 &&
(opal_evt->severity == OpalMCE_SEV_NO_ERROR ||
opal_evt->disposition == OpalMCE_DISPOSITION_RECOVERED))
handled = 1;
if (handled)
opal_evt->in_use = 0;
#endif
return handled;
}
long kvmppc_realmode_machine_check(struct kvm_vcpu *vcpu)
{
if (cpu_has_feature(CPU_FTR_ARCH_206))
return kvmppc_realmode_mc_power7(vcpu);
return 0;
}
| gpl-2.0 |
gotokernel/linux-3.14.4-qemu | net/x25/x25_dev.c | 2308 | 4518 | /*
* X.25 Packet Layer release 002
*
* This is ALPHA test software. This code may break your machine, randomly fail to work with new
* releases, misbehave and/or generally screw up. It might even work.
*
* This code REQUIRES 2.1.15 or higher
*
* This module:
* This module 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.
*
* History
* X.25 001 Jonathan Naylor Started coding.
* 2000-09-04 Henner Eisen Prevent freeing a dangling skb.
*/
#define pr_fmt(fmt) "X25: " fmt
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/if_arp.h>
#include <net/x25.h>
#include <net/x25device.h>
static int x25_receive_data(struct sk_buff *skb, struct x25_neigh *nb)
{
struct sock *sk;
unsigned short frametype;
unsigned int lci;
if (!pskb_may_pull(skb, X25_STD_MIN_LEN))
return 0;
frametype = skb->data[2];
lci = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);
/*
* LCI of zero is always for us, and its always a link control
* frame.
*/
if (lci == 0) {
x25_link_control(skb, nb, frametype);
return 0;
}
/*
* Find an existing socket.
*/
if ((sk = x25_find_socket(lci, nb)) != NULL) {
int queued = 1;
skb_reset_transport_header(skb);
bh_lock_sock(sk);
if (!sock_owned_by_user(sk)) {
queued = x25_process_rx_frame(sk, skb);
} else {
queued = !sk_add_backlog(sk, skb, sk->sk_rcvbuf);
}
bh_unlock_sock(sk);
sock_put(sk);
return queued;
}
/*
* Is is a Call Request ? if so process it.
*/
if (frametype == X25_CALL_REQUEST)
return x25_rx_call_request(skb, nb, lci);
/*
* Its not a Call Request, nor is it a control frame.
* Can we forward it?
*/
if (x25_forward_data(lci, nb, skb)) {
if (frametype == X25_CLEAR_CONFIRMATION) {
x25_clear_forward_by_lci(lci);
}
kfree_skb(skb);
return 1;
}
/*
x25_transmit_clear_request(nb, lci, 0x0D);
*/
if (frametype != X25_CLEAR_CONFIRMATION)
pr_debug("x25_receive_data(): unknown frame type %2x\n",frametype);
return 0;
}
int x25_lapb_receive_frame(struct sk_buff *skb, struct net_device *dev,
struct packet_type *ptype, struct net_device *orig_dev)
{
struct sk_buff *nskb;
struct x25_neigh *nb;
if (!net_eq(dev_net(dev), &init_net))
goto drop;
nskb = skb_copy(skb, GFP_ATOMIC);
if (!nskb)
goto drop;
kfree_skb(skb);
skb = nskb;
/*
* Packet received from unrecognised device, throw it away.
*/
nb = x25_get_neigh(dev);
if (!nb) {
pr_debug("unknown neighbour - %s\n", dev->name);
goto drop;
}
if (!pskb_may_pull(skb, 1))
return 0;
switch (skb->data[0]) {
case X25_IFACE_DATA:
skb_pull(skb, 1);
if (x25_receive_data(skb, nb)) {
x25_neigh_put(nb);
goto out;
}
break;
case X25_IFACE_CONNECT:
x25_link_established(nb);
break;
case X25_IFACE_DISCONNECT:
x25_link_terminated(nb);
break;
}
x25_neigh_put(nb);
drop:
kfree_skb(skb);
out:
return 0;
}
void x25_establish_link(struct x25_neigh *nb)
{
struct sk_buff *skb;
unsigned char *ptr;
switch (nb->dev->type) {
case ARPHRD_X25:
if ((skb = alloc_skb(1, GFP_ATOMIC)) == NULL) {
pr_err("x25_dev: out of memory\n");
return;
}
ptr = skb_put(skb, 1);
*ptr = X25_IFACE_CONNECT;
break;
#if IS_ENABLED(CONFIG_LLC)
case ARPHRD_ETHER:
return;
#endif
default:
return;
}
skb->protocol = htons(ETH_P_X25);
skb->dev = nb->dev;
dev_queue_xmit(skb);
}
void x25_terminate_link(struct x25_neigh *nb)
{
struct sk_buff *skb;
unsigned char *ptr;
#if IS_ENABLED(CONFIG_LLC)
if (nb->dev->type == ARPHRD_ETHER)
return;
#endif
if (nb->dev->type != ARPHRD_X25)
return;
skb = alloc_skb(1, GFP_ATOMIC);
if (!skb) {
pr_err("x25_dev: out of memory\n");
return;
}
ptr = skb_put(skb, 1);
*ptr = X25_IFACE_DISCONNECT;
skb->protocol = htons(ETH_P_X25);
skb->dev = nb->dev;
dev_queue_xmit(skb);
}
void x25_send_frame(struct sk_buff *skb, struct x25_neigh *nb)
{
unsigned char *dptr;
skb_reset_network_header(skb);
switch (nb->dev->type) {
case ARPHRD_X25:
dptr = skb_push(skb, 1);
*dptr = X25_IFACE_DATA;
break;
#if IS_ENABLED(CONFIG_LLC)
case ARPHRD_ETHER:
kfree_skb(skb);
return;
#endif
default:
kfree_skb(skb);
return;
}
skb->protocol = htons(ETH_P_X25);
skb->dev = nb->dev;
dev_queue_xmit(skb);
}
| gpl-2.0 |
PyroDD/Pyro | drivers/staging/iio/adc/ad7476_core.c | 2308 | 6890 | /*
* AD7466/7/8 AD7476/5/7/8 (A) SPI ADC driver
*
* Copyright 2010 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/spi/spi.h>
#include <linux/regulator/consumer.h>
#include <linux/err.h>
#include "../iio.h"
#include "../sysfs.h"
#include "../ring_generic.h"
#include "adc.h"
#include "ad7476.h"
static int ad7476_scan_direct(struct ad7476_state *st)
{
int ret;
ret = spi_sync(st->spi, &st->msg);
if (ret)
return ret;
return (st->data[0] << 8) | st->data[1];
}
static int ad7476_read_raw(struct iio_dev *dev_info,
struct iio_chan_spec const *chan,
int *val,
int *val2,
long m)
{
int ret;
struct ad7476_state *st = dev_info->dev_data;
unsigned int scale_uv;
switch (m) {
case 0:
mutex_lock(&dev_info->mlock);
if (iio_ring_enabled(dev_info))
ret = ad7476_scan_from_ring(st);
else
ret = ad7476_scan_direct(st);
mutex_unlock(&dev_info->mlock);
if (ret < 0)
return ret;
*val = (ret >> st->chip_info->channel[0].scan_type.shift) &
RES_MASK(st->chip_info->channel[0].scan_type.realbits);
return IIO_VAL_INT;
case (1 << IIO_CHAN_INFO_SCALE_SHARED):
scale_uv = (st->int_vref_mv * 1000)
>> st->chip_info->channel[0].scan_type.realbits;
*val = scale_uv/1000;
*val2 = (scale_uv%1000)*1000;
return IIO_VAL_INT_PLUS_MICRO;
}
return -EINVAL;
}
static const struct ad7476_chip_info ad7476_chip_info_tbl[] = {
[ID_AD7466] = {
.channel[0] = IIO_CHAN(IIO_IN, 0, 1, 0, NULL, 0, 0,
(1 << IIO_CHAN_INFO_SCALE_SHARED),
0, 0, IIO_ST('u', 12, 16, 0), 0),
.channel[1] = IIO_CHAN_SOFT_TIMESTAMP(1),
},
[ID_AD7467] = {
.channel[0] = IIO_CHAN(IIO_IN, 0, 1, 0, NULL, 0, 0,
(1 << IIO_CHAN_INFO_SCALE_SHARED),
0, 0, IIO_ST('u', 10, 16, 2), 0),
.channel[1] = IIO_CHAN_SOFT_TIMESTAMP(1),
},
[ID_AD7468] = {
.channel[0] = IIO_CHAN(IIO_IN, 0, 1 , 0, NULL, 0, 0,
(1 << IIO_CHAN_INFO_SCALE_SHARED),
0, 0, IIO_ST('u', 8, 16, 4), 0),
.channel[1] = IIO_CHAN_SOFT_TIMESTAMP(1),
},
[ID_AD7475] = {
.channel[0] = IIO_CHAN(IIO_IN, 0, 1, 0, NULL, 0, 0,
(1 << IIO_CHAN_INFO_SCALE_SHARED),
0, 0, IIO_ST('u', 12, 16, 0), 0),
.channel[1] = IIO_CHAN_SOFT_TIMESTAMP(1),
},
[ID_AD7476] = {
.channel[0] = IIO_CHAN(IIO_IN, 0, 1, 0, NULL, 0, 0,
(1 << IIO_CHAN_INFO_SCALE_SHARED),
0, 0, IIO_ST('u', 12, 16, 0), 0),
.channel[1] = IIO_CHAN_SOFT_TIMESTAMP(1),
},
[ID_AD7477] = {
.channel[0] = IIO_CHAN(IIO_IN, 0, 1, 0, NULL, 0, 0,
(1 << IIO_CHAN_INFO_SCALE_SHARED),
0, 0, IIO_ST('u', 10, 16, 2), 0),
.channel[1] = IIO_CHAN_SOFT_TIMESTAMP(1),
},
[ID_AD7478] = {
.channel[0] = IIO_CHAN(IIO_IN, 0, 1, 0, NULL, 0, 0,
(1 << IIO_CHAN_INFO_SCALE_SHARED),
0, 0, IIO_ST('u', 8, 16, 4), 0),
.channel[1] = IIO_CHAN_SOFT_TIMESTAMP(1),
},
[ID_AD7495] = {
.channel[0] = IIO_CHAN(IIO_IN, 0, 1, 0, NULL, 0, 0,
(1 << IIO_CHAN_INFO_SCALE_SHARED),
0, 0, IIO_ST('u', 12, 16, 0), 0),
.channel[1] = IIO_CHAN_SOFT_TIMESTAMP(1),
.int_vref_mv = 2500,
},
};
static const struct iio_info ad7476_info = {
.driver_module = THIS_MODULE,
.read_raw = &ad7476_read_raw,
};
static int __devinit ad7476_probe(struct spi_device *spi)
{
struct ad7476_platform_data *pdata = spi->dev.platform_data;
struct ad7476_state *st;
int ret, voltage_uv = 0;
st = kzalloc(sizeof(*st), GFP_KERNEL);
if (st == NULL) {
ret = -ENOMEM;
goto error_ret;
}
st->reg = regulator_get(&spi->dev, "vcc");
if (!IS_ERR(st->reg)) {
ret = regulator_enable(st->reg);
if (ret)
goto error_put_reg;
voltage_uv = regulator_get_voltage(st->reg);
}
st->chip_info =
&ad7476_chip_info_tbl[spi_get_device_id(spi)->driver_data];
if (st->chip_info->int_vref_mv)
st->int_vref_mv = st->chip_info->int_vref_mv;
else if (pdata && pdata->vref_mv)
st->int_vref_mv = pdata->vref_mv;
else if (voltage_uv)
st->int_vref_mv = voltage_uv / 1000;
else
dev_warn(&spi->dev, "reference voltage unspecified\n");
spi_set_drvdata(spi, st);
st->spi = spi;
st->indio_dev = iio_allocate_device(0);
if (st->indio_dev == NULL) {
ret = -ENOMEM;
goto error_disable_reg;
}
/* Establish that the iio_dev is a child of the spi device */
st->indio_dev->dev.parent = &spi->dev;
st->indio_dev->name = spi_get_device_id(spi)->name;
st->indio_dev->dev_data = (void *)(st);
st->indio_dev->modes = INDIO_DIRECT_MODE;
st->indio_dev->channels = st->chip_info->channel;
st->indio_dev->num_channels = 2;
st->indio_dev->info = &ad7476_info;
/* Setup default message */
st->xfer.rx_buf = &st->data;
st->xfer.len = st->chip_info->channel[0].scan_type.storagebits / 8;
spi_message_init(&st->msg);
spi_message_add_tail(&st->xfer, &st->msg);
ret = ad7476_register_ring_funcs_and_init(st->indio_dev);
if (ret)
goto error_free_device;
ret = iio_device_register(st->indio_dev);
if (ret)
goto error_free_device;
ret = iio_ring_buffer_register_ex(st->indio_dev->ring, 0,
st->chip_info->channel,
ARRAY_SIZE(st->chip_info->channel));
if (ret)
goto error_cleanup_ring;
return 0;
error_cleanup_ring:
ad7476_ring_cleanup(st->indio_dev);
iio_device_unregister(st->indio_dev);
error_free_device:
iio_free_device(st->indio_dev);
error_disable_reg:
if (!IS_ERR(st->reg))
regulator_disable(st->reg);
error_put_reg:
if (!IS_ERR(st->reg))
regulator_put(st->reg);
kfree(st);
error_ret:
return ret;
}
static int ad7476_remove(struct spi_device *spi)
{
struct ad7476_state *st = spi_get_drvdata(spi);
struct iio_dev *indio_dev = st->indio_dev;
iio_ring_buffer_unregister(indio_dev->ring);
ad7476_ring_cleanup(indio_dev);
iio_device_unregister(indio_dev);
if (!IS_ERR(st->reg)) {
regulator_disable(st->reg);
regulator_put(st->reg);
}
kfree(st);
return 0;
}
static const struct spi_device_id ad7476_id[] = {
{"ad7466", ID_AD7466},
{"ad7467", ID_AD7467},
{"ad7468", ID_AD7468},
{"ad7475", ID_AD7475},
{"ad7476", ID_AD7476},
{"ad7476a", ID_AD7476},
{"ad7477", ID_AD7477},
{"ad7477a", ID_AD7477},
{"ad7478", ID_AD7478},
{"ad7478a", ID_AD7478},
{"ad7495", ID_AD7495},
{}
};
static struct spi_driver ad7476_driver = {
.driver = {
.name = "ad7476",
.bus = &spi_bus_type,
.owner = THIS_MODULE,
},
.probe = ad7476_probe,
.remove = __devexit_p(ad7476_remove),
.id_table = ad7476_id,
};
static int __init ad7476_init(void)
{
return spi_register_driver(&ad7476_driver);
}
module_init(ad7476_init);
static void __exit ad7476_exit(void)
{
spi_unregister_driver(&ad7476_driver);
}
module_exit(ad7476_exit);
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Analog Devices AD7475/6/7/8(A) AD7466/7/8 ADC");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("spi:ad7476");
| gpl-2.0 |
thoemy/enru-3.1.10-g517147e | lib/debugobjects.c | 2564 | 25921 | /*
* Generic infrastructure for lifetime debugging of objects.
*
* Started by Thomas Gleixner
*
* Copyright (C) 2008, Thomas Gleixner <tglx@linutronix.de>
*
* For licencing details see kernel-base/COPYING
*/
#include <linux/debugobjects.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <linux/hash.h>
#define ODEBUG_HASH_BITS 14
#define ODEBUG_HASH_SIZE (1 << ODEBUG_HASH_BITS)
#define ODEBUG_POOL_SIZE 512
#define ODEBUG_POOL_MIN_LEVEL 256
#define ODEBUG_CHUNK_SHIFT PAGE_SHIFT
#define ODEBUG_CHUNK_SIZE (1 << ODEBUG_CHUNK_SHIFT)
#define ODEBUG_CHUNK_MASK (~(ODEBUG_CHUNK_SIZE - 1))
struct debug_bucket {
struct hlist_head list;
raw_spinlock_t lock;
};
static struct debug_bucket obj_hash[ODEBUG_HASH_SIZE];
static struct debug_obj obj_static_pool[ODEBUG_POOL_SIZE] __initdata;
static DEFINE_RAW_SPINLOCK(pool_lock);
static HLIST_HEAD(obj_pool);
static int obj_pool_min_free = ODEBUG_POOL_SIZE;
static int obj_pool_free = ODEBUG_POOL_SIZE;
static int obj_pool_used;
static int obj_pool_max_used;
static struct kmem_cache *obj_cache;
static int debug_objects_maxchain __read_mostly;
static int debug_objects_fixups __read_mostly;
static int debug_objects_warnings __read_mostly;
static int debug_objects_enabled __read_mostly
= CONFIG_DEBUG_OBJECTS_ENABLE_DEFAULT;
static struct debug_obj_descr *descr_test __read_mostly;
static void free_obj_work(struct work_struct *work);
static DECLARE_WORK(debug_obj_work, free_obj_work);
static int __init enable_object_debug(char *str)
{
debug_objects_enabled = 1;
return 0;
}
static int __init disable_object_debug(char *str)
{
debug_objects_enabled = 0;
return 0;
}
early_param("debug_objects", enable_object_debug);
early_param("no_debug_objects", disable_object_debug);
static const char *obj_states[ODEBUG_STATE_MAX] = {
[ODEBUG_STATE_NONE] = "none",
[ODEBUG_STATE_INIT] = "initialized",
[ODEBUG_STATE_INACTIVE] = "inactive",
[ODEBUG_STATE_ACTIVE] = "active",
[ODEBUG_STATE_DESTROYED] = "destroyed",
[ODEBUG_STATE_NOTAVAILABLE] = "not available",
};
static int fill_pool(void)
{
gfp_t gfp = GFP_ATOMIC | __GFP_NORETRY | __GFP_NOWARN;
struct debug_obj *new;
unsigned long flags;
if (likely(obj_pool_free >= ODEBUG_POOL_MIN_LEVEL))
return obj_pool_free;
if (unlikely(!obj_cache))
return obj_pool_free;
while (obj_pool_free < ODEBUG_POOL_MIN_LEVEL) {
new = kmem_cache_zalloc(obj_cache, gfp);
if (!new)
return obj_pool_free;
raw_spin_lock_irqsave(&pool_lock, flags);
hlist_add_head(&new->node, &obj_pool);
obj_pool_free++;
raw_spin_unlock_irqrestore(&pool_lock, flags);
}
return obj_pool_free;
}
/*
* Lookup an object in the hash bucket.
*/
static struct debug_obj *lookup_object(void *addr, struct debug_bucket *b)
{
struct hlist_node *node;
struct debug_obj *obj;
int cnt = 0;
hlist_for_each_entry(obj, node, &b->list, node) {
cnt++;
if (obj->object == addr)
return obj;
}
if (cnt > debug_objects_maxchain)
debug_objects_maxchain = cnt;
return NULL;
}
/*
* Allocate a new object. If the pool is empty, switch off the debugger.
* Must be called with interrupts disabled.
*/
static struct debug_obj *
alloc_object(void *addr, struct debug_bucket *b, struct debug_obj_descr *descr)
{
struct debug_obj *obj = NULL;
raw_spin_lock(&pool_lock);
if (obj_pool.first) {
obj = hlist_entry(obj_pool.first, typeof(*obj), node);
obj->object = addr;
obj->descr = descr;
obj->state = ODEBUG_STATE_NONE;
obj->astate = 0;
hlist_del(&obj->node);
hlist_add_head(&obj->node, &b->list);
obj_pool_used++;
if (obj_pool_used > obj_pool_max_used)
obj_pool_max_used = obj_pool_used;
obj_pool_free--;
if (obj_pool_free < obj_pool_min_free)
obj_pool_min_free = obj_pool_free;
}
raw_spin_unlock(&pool_lock);
return obj;
}
/*
* workqueue function to free objects.
*/
static void free_obj_work(struct work_struct *work)
{
struct debug_obj *obj;
unsigned long flags;
raw_spin_lock_irqsave(&pool_lock, flags);
while (obj_pool_free > ODEBUG_POOL_SIZE) {
obj = hlist_entry(obj_pool.first, typeof(*obj), node);
hlist_del(&obj->node);
obj_pool_free--;
/*
* We release pool_lock across kmem_cache_free() to
* avoid contention on pool_lock.
*/
raw_spin_unlock_irqrestore(&pool_lock, flags);
kmem_cache_free(obj_cache, obj);
raw_spin_lock_irqsave(&pool_lock, flags);
}
raw_spin_unlock_irqrestore(&pool_lock, flags);
}
/*
* Put the object back into the pool and schedule work to free objects
* if necessary.
*/
static void free_object(struct debug_obj *obj)
{
unsigned long flags;
int sched = 0;
raw_spin_lock_irqsave(&pool_lock, flags);
/*
* schedule work when the pool is filled and the cache is
* initialized:
*/
if (obj_pool_free > ODEBUG_POOL_SIZE && obj_cache)
sched = keventd_up() && !work_pending(&debug_obj_work);
hlist_add_head(&obj->node, &obj_pool);
obj_pool_free++;
obj_pool_used--;
raw_spin_unlock_irqrestore(&pool_lock, flags);
if (sched)
schedule_work(&debug_obj_work);
}
/*
* We run out of memory. That means we probably have tons of objects
* allocated.
*/
static void debug_objects_oom(void)
{
struct debug_bucket *db = obj_hash;
struct hlist_node *node, *tmp;
HLIST_HEAD(freelist);
struct debug_obj *obj;
unsigned long flags;
int i;
printk(KERN_WARNING "ODEBUG: Out of memory. ODEBUG disabled\n");
for (i = 0; i < ODEBUG_HASH_SIZE; i++, db++) {
raw_spin_lock_irqsave(&db->lock, flags);
hlist_move_list(&db->list, &freelist);
raw_spin_unlock_irqrestore(&db->lock, flags);
/* Now free them */
hlist_for_each_entry_safe(obj, node, tmp, &freelist, node) {
hlist_del(&obj->node);
free_object(obj);
}
}
}
/*
* We use the pfn of the address for the hash. That way we can check
* for freed objects simply by checking the affected bucket.
*/
static struct debug_bucket *get_bucket(unsigned long addr)
{
unsigned long hash;
hash = hash_long((addr >> ODEBUG_CHUNK_SHIFT), ODEBUG_HASH_BITS);
return &obj_hash[hash];
}
static void debug_print_object(struct debug_obj *obj, char *msg)
{
struct debug_obj_descr *descr = obj->descr;
static int limit;
if (limit < 5 && descr != descr_test) {
void *hint = descr->debug_hint ?
descr->debug_hint(obj->object) : NULL;
limit++;
WARN(1, KERN_ERR "ODEBUG: %s %s (active state %u) "
"object type: %s hint: %pS\n",
msg, obj_states[obj->state], obj->astate,
descr->name, hint);
}
debug_objects_warnings++;
}
/*
* Try to repair the damage, so we have a better chance to get useful
* debug output.
*/
static void
debug_object_fixup(int (*fixup)(void *addr, enum debug_obj_state state),
void * addr, enum debug_obj_state state)
{
if (fixup)
debug_objects_fixups += fixup(addr, state);
}
static void debug_object_is_on_stack(void *addr, int onstack)
{
int is_on_stack;
static int limit;
if (limit > 4)
return;
is_on_stack = object_is_on_stack(addr);
if (is_on_stack == onstack)
return;
limit++;
if (is_on_stack)
printk(KERN_WARNING
"ODEBUG: object is on stack, but not annotated\n");
else
printk(KERN_WARNING
"ODEBUG: object is not on stack, but annotated\n");
WARN_ON(1);
}
static void
__debug_object_init(void *addr, struct debug_obj_descr *descr, int onstack)
{
enum debug_obj_state state;
struct debug_bucket *db;
struct debug_obj *obj;
unsigned long flags;
fill_pool();
db = get_bucket((unsigned long) addr);
raw_spin_lock_irqsave(&db->lock, flags);
obj = lookup_object(addr, db);
if (!obj) {
obj = alloc_object(addr, db, descr);
if (!obj) {
debug_objects_enabled = 0;
raw_spin_unlock_irqrestore(&db->lock, flags);
debug_objects_oom();
return;
}
debug_object_is_on_stack(addr, onstack);
}
switch (obj->state) {
case ODEBUG_STATE_NONE:
case ODEBUG_STATE_INIT:
case ODEBUG_STATE_INACTIVE:
obj->state = ODEBUG_STATE_INIT;
break;
case ODEBUG_STATE_ACTIVE:
debug_print_object(obj, "init");
state = obj->state;
raw_spin_unlock_irqrestore(&db->lock, flags);
debug_object_fixup(descr->fixup_init, addr, state);
return;
case ODEBUG_STATE_DESTROYED:
debug_print_object(obj, "init");
break;
default:
break;
}
raw_spin_unlock_irqrestore(&db->lock, flags);
}
/**
* debug_object_init - debug checks when an object is initialized
* @addr: address of the object
* @descr: pointer to an object specific debug description structure
*/
void debug_object_init(void *addr, struct debug_obj_descr *descr)
{
if (!debug_objects_enabled)
return;
__debug_object_init(addr, descr, 0);
}
/**
* debug_object_init_on_stack - debug checks when an object on stack is
* initialized
* @addr: address of the object
* @descr: pointer to an object specific debug description structure
*/
void debug_object_init_on_stack(void *addr, struct debug_obj_descr *descr)
{
if (!debug_objects_enabled)
return;
__debug_object_init(addr, descr, 1);
}
/**
* debug_object_activate - debug checks when an object is activated
* @addr: address of the object
* @descr: pointer to an object specific debug description structure
*/
void debug_object_activate(void *addr, struct debug_obj_descr *descr)
{
enum debug_obj_state state;
struct debug_bucket *db;
struct debug_obj *obj;
unsigned long flags;
if (!debug_objects_enabled)
return;
db = get_bucket((unsigned long) addr);
raw_spin_lock_irqsave(&db->lock, flags);
obj = lookup_object(addr, db);
if (obj) {
switch (obj->state) {
case ODEBUG_STATE_INIT:
case ODEBUG_STATE_INACTIVE:
obj->state = ODEBUG_STATE_ACTIVE;
break;
case ODEBUG_STATE_ACTIVE:
debug_print_object(obj, "activate");
state = obj->state;
raw_spin_unlock_irqrestore(&db->lock, flags);
debug_object_fixup(descr->fixup_activate, addr, state);
return;
case ODEBUG_STATE_DESTROYED:
debug_print_object(obj, "activate");
break;
default:
break;
}
raw_spin_unlock_irqrestore(&db->lock, flags);
return;
}
raw_spin_unlock_irqrestore(&db->lock, flags);
/*
* This happens when a static object is activated. We
* let the type specific code decide whether this is
* true or not.
*/
debug_object_fixup(descr->fixup_activate, addr,
ODEBUG_STATE_NOTAVAILABLE);
}
/**
* debug_object_deactivate - debug checks when an object is deactivated
* @addr: address of the object
* @descr: pointer to an object specific debug description structure
*/
void debug_object_deactivate(void *addr, struct debug_obj_descr *descr)
{
struct debug_bucket *db;
struct debug_obj *obj;
unsigned long flags;
if (!debug_objects_enabled)
return;
db = get_bucket((unsigned long) addr);
raw_spin_lock_irqsave(&db->lock, flags);
obj = lookup_object(addr, db);
if (obj) {
switch (obj->state) {
case ODEBUG_STATE_INIT:
case ODEBUG_STATE_INACTIVE:
case ODEBUG_STATE_ACTIVE:
if (!obj->astate)
obj->state = ODEBUG_STATE_INACTIVE;
else
debug_print_object(obj, "deactivate");
break;
case ODEBUG_STATE_DESTROYED:
debug_print_object(obj, "deactivate");
break;
default:
break;
}
} else {
struct debug_obj o = { .object = addr,
.state = ODEBUG_STATE_NOTAVAILABLE,
.descr = descr };
debug_print_object(&o, "deactivate");
}
raw_spin_unlock_irqrestore(&db->lock, flags);
}
/**
* debug_object_destroy - debug checks when an object is destroyed
* @addr: address of the object
* @descr: pointer to an object specific debug description structure
*/
void debug_object_destroy(void *addr, struct debug_obj_descr *descr)
{
enum debug_obj_state state;
struct debug_bucket *db;
struct debug_obj *obj;
unsigned long flags;
if (!debug_objects_enabled)
return;
db = get_bucket((unsigned long) addr);
raw_spin_lock_irqsave(&db->lock, flags);
obj = lookup_object(addr, db);
if (!obj)
goto out_unlock;
switch (obj->state) {
case ODEBUG_STATE_NONE:
case ODEBUG_STATE_INIT:
case ODEBUG_STATE_INACTIVE:
obj->state = ODEBUG_STATE_DESTROYED;
break;
case ODEBUG_STATE_ACTIVE:
debug_print_object(obj, "destroy");
state = obj->state;
raw_spin_unlock_irqrestore(&db->lock, flags);
debug_object_fixup(descr->fixup_destroy, addr, state);
return;
case ODEBUG_STATE_DESTROYED:
debug_print_object(obj, "destroy");
break;
default:
break;
}
out_unlock:
raw_spin_unlock_irqrestore(&db->lock, flags);
}
/**
* debug_object_free - debug checks when an object is freed
* @addr: address of the object
* @descr: pointer to an object specific debug description structure
*/
void debug_object_free(void *addr, struct debug_obj_descr *descr)
{
enum debug_obj_state state;
struct debug_bucket *db;
struct debug_obj *obj;
unsigned long flags;
if (!debug_objects_enabled)
return;
db = get_bucket((unsigned long) addr);
raw_spin_lock_irqsave(&db->lock, flags);
obj = lookup_object(addr, db);
if (!obj)
goto out_unlock;
switch (obj->state) {
case ODEBUG_STATE_ACTIVE:
debug_print_object(obj, "free");
state = obj->state;
raw_spin_unlock_irqrestore(&db->lock, flags);
debug_object_fixup(descr->fixup_free, addr, state);
return;
default:
hlist_del(&obj->node);
raw_spin_unlock_irqrestore(&db->lock, flags);
free_object(obj);
return;
}
out_unlock:
raw_spin_unlock_irqrestore(&db->lock, flags);
}
/**
* debug_object_active_state - debug checks object usage state machine
* @addr: address of the object
* @descr: pointer to an object specific debug description structure
* @expect: expected state
* @next: state to move to if expected state is found
*/
void
debug_object_active_state(void *addr, struct debug_obj_descr *descr,
unsigned int expect, unsigned int next)
{
struct debug_bucket *db;
struct debug_obj *obj;
unsigned long flags;
if (!debug_objects_enabled)
return;
db = get_bucket((unsigned long) addr);
raw_spin_lock_irqsave(&db->lock, flags);
obj = lookup_object(addr, db);
if (obj) {
switch (obj->state) {
case ODEBUG_STATE_ACTIVE:
if (obj->astate == expect)
obj->astate = next;
else
debug_print_object(obj, "active_state");
break;
default:
debug_print_object(obj, "active_state");
break;
}
} else {
struct debug_obj o = { .object = addr,
.state = ODEBUG_STATE_NOTAVAILABLE,
.descr = descr };
debug_print_object(&o, "active_state");
}
raw_spin_unlock_irqrestore(&db->lock, flags);
}
#ifdef CONFIG_DEBUG_OBJECTS_FREE
static void __debug_check_no_obj_freed(const void *address, unsigned long size)
{
unsigned long flags, oaddr, saddr, eaddr, paddr, chunks;
struct hlist_node *node, *tmp;
HLIST_HEAD(freelist);
struct debug_obj_descr *descr;
enum debug_obj_state state;
struct debug_bucket *db;
struct debug_obj *obj;
int cnt;
saddr = (unsigned long) address;
eaddr = saddr + size;
paddr = saddr & ODEBUG_CHUNK_MASK;
chunks = ((eaddr - paddr) + (ODEBUG_CHUNK_SIZE - 1));
chunks >>= ODEBUG_CHUNK_SHIFT;
for (;chunks > 0; chunks--, paddr += ODEBUG_CHUNK_SIZE) {
db = get_bucket(paddr);
repeat:
cnt = 0;
raw_spin_lock_irqsave(&db->lock, flags);
hlist_for_each_entry_safe(obj, node, tmp, &db->list, node) {
cnt++;
oaddr = (unsigned long) obj->object;
if (oaddr < saddr || oaddr >= eaddr)
continue;
switch (obj->state) {
case ODEBUG_STATE_ACTIVE:
debug_print_object(obj, "free");
descr = obj->descr;
state = obj->state;
raw_spin_unlock_irqrestore(&db->lock, flags);
debug_object_fixup(descr->fixup_free,
(void *) oaddr, state);
goto repeat;
default:
hlist_del(&obj->node);
hlist_add_head(&obj->node, &freelist);
break;
}
}
raw_spin_unlock_irqrestore(&db->lock, flags);
/* Now free them */
hlist_for_each_entry_safe(obj, node, tmp, &freelist, node) {
hlist_del(&obj->node);
free_object(obj);
}
if (cnt > debug_objects_maxchain)
debug_objects_maxchain = cnt;
}
}
void debug_check_no_obj_freed(const void *address, unsigned long size)
{
if (debug_objects_enabled)
__debug_check_no_obj_freed(address, size);
}
#endif
#ifdef CONFIG_DEBUG_FS
static int debug_stats_show(struct seq_file *m, void *v)
{
seq_printf(m, "max_chain :%d\n", debug_objects_maxchain);
seq_printf(m, "warnings :%d\n", debug_objects_warnings);
seq_printf(m, "fixups :%d\n", debug_objects_fixups);
seq_printf(m, "pool_free :%d\n", obj_pool_free);
seq_printf(m, "pool_min_free :%d\n", obj_pool_min_free);
seq_printf(m, "pool_used :%d\n", obj_pool_used);
seq_printf(m, "pool_max_used :%d\n", obj_pool_max_used);
return 0;
}
static int debug_stats_open(struct inode *inode, struct file *filp)
{
return single_open(filp, debug_stats_show, NULL);
}
static const struct file_operations debug_stats_fops = {
.open = debug_stats_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init debug_objects_init_debugfs(void)
{
struct dentry *dbgdir, *dbgstats;
if (!debug_objects_enabled)
return 0;
dbgdir = debugfs_create_dir("debug_objects", NULL);
if (!dbgdir)
return -ENOMEM;
dbgstats = debugfs_create_file("stats", 0444, dbgdir, NULL,
&debug_stats_fops);
if (!dbgstats)
goto err;
return 0;
err:
debugfs_remove(dbgdir);
return -ENOMEM;
}
__initcall(debug_objects_init_debugfs);
#else
static inline void debug_objects_init_debugfs(void) { }
#endif
#ifdef CONFIG_DEBUG_OBJECTS_SELFTEST
/* Random data structure for the self test */
struct self_test {
unsigned long dummy1[6];
int static_init;
unsigned long dummy2[3];
};
static __initdata struct debug_obj_descr descr_type_test;
/*
* fixup_init is called when:
* - an active object is initialized
*/
static int __init fixup_init(void *addr, enum debug_obj_state state)
{
struct self_test *obj = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
debug_object_deactivate(obj, &descr_type_test);
debug_object_init(obj, &descr_type_test);
return 1;
default:
return 0;
}
}
/*
* fixup_activate is called when:
* - an active object is activated
* - an unknown object is activated (might be a statically initialized object)
*/
static int __init fixup_activate(void *addr, enum debug_obj_state state)
{
struct self_test *obj = addr;
switch (state) {
case ODEBUG_STATE_NOTAVAILABLE:
if (obj->static_init == 1) {
debug_object_init(obj, &descr_type_test);
debug_object_activate(obj, &descr_type_test);
/*
* Real code should return 0 here ! This is
* not a fixup of some bad behaviour. We
* merily call the debug_init function to keep
* track of the object.
*/
return 1;
} else {
/* Real code needs to emit a warning here */
}
return 0;
case ODEBUG_STATE_ACTIVE:
debug_object_deactivate(obj, &descr_type_test);
debug_object_activate(obj, &descr_type_test);
return 1;
default:
return 0;
}
}
/*
* fixup_destroy is called when:
* - an active object is destroyed
*/
static int __init fixup_destroy(void *addr, enum debug_obj_state state)
{
struct self_test *obj = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
debug_object_deactivate(obj, &descr_type_test);
debug_object_destroy(obj, &descr_type_test);
return 1;
default:
return 0;
}
}
/*
* fixup_free is called when:
* - an active object is freed
*/
static int __init fixup_free(void *addr, enum debug_obj_state state)
{
struct self_test *obj = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
debug_object_deactivate(obj, &descr_type_test);
debug_object_free(obj, &descr_type_test);
return 1;
default:
return 0;
}
}
static int __init
check_results(void *addr, enum debug_obj_state state, int fixups, int warnings)
{
struct debug_bucket *db;
struct debug_obj *obj;
unsigned long flags;
int res = -EINVAL;
db = get_bucket((unsigned long) addr);
raw_spin_lock_irqsave(&db->lock, flags);
obj = lookup_object(addr, db);
if (!obj && state != ODEBUG_STATE_NONE) {
WARN(1, KERN_ERR "ODEBUG: selftest object not found\n");
goto out;
}
if (obj && obj->state != state) {
WARN(1, KERN_ERR "ODEBUG: selftest wrong state: %d != %d\n",
obj->state, state);
goto out;
}
if (fixups != debug_objects_fixups) {
WARN(1, KERN_ERR "ODEBUG: selftest fixups failed %d != %d\n",
fixups, debug_objects_fixups);
goto out;
}
if (warnings != debug_objects_warnings) {
WARN(1, KERN_ERR "ODEBUG: selftest warnings failed %d != %d\n",
warnings, debug_objects_warnings);
goto out;
}
res = 0;
out:
raw_spin_unlock_irqrestore(&db->lock, flags);
if (res)
debug_objects_enabled = 0;
return res;
}
static __initdata struct debug_obj_descr descr_type_test = {
.name = "selftest",
.fixup_init = fixup_init,
.fixup_activate = fixup_activate,
.fixup_destroy = fixup_destroy,
.fixup_free = fixup_free,
};
static __initdata struct self_test obj = { .static_init = 0 };
static void __init debug_objects_selftest(void)
{
int fixups, oldfixups, warnings, oldwarnings;
unsigned long flags;
local_irq_save(flags);
fixups = oldfixups = debug_objects_fixups;
warnings = oldwarnings = debug_objects_warnings;
descr_test = &descr_type_test;
debug_object_init(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_INIT, fixups, warnings))
goto out;
debug_object_activate(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_ACTIVE, fixups, warnings))
goto out;
debug_object_activate(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_ACTIVE, ++fixups, ++warnings))
goto out;
debug_object_deactivate(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_INACTIVE, fixups, warnings))
goto out;
debug_object_destroy(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_DESTROYED, fixups, warnings))
goto out;
debug_object_init(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_DESTROYED, fixups, ++warnings))
goto out;
debug_object_activate(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_DESTROYED, fixups, ++warnings))
goto out;
debug_object_deactivate(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_DESTROYED, fixups, ++warnings))
goto out;
debug_object_free(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_NONE, fixups, warnings))
goto out;
obj.static_init = 1;
debug_object_activate(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_ACTIVE, ++fixups, warnings))
goto out;
debug_object_init(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_INIT, ++fixups, ++warnings))
goto out;
debug_object_free(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_NONE, fixups, warnings))
goto out;
#ifdef CONFIG_DEBUG_OBJECTS_FREE
debug_object_init(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_INIT, fixups, warnings))
goto out;
debug_object_activate(&obj, &descr_type_test);
if (check_results(&obj, ODEBUG_STATE_ACTIVE, fixups, warnings))
goto out;
__debug_check_no_obj_freed(&obj, sizeof(obj));
if (check_results(&obj, ODEBUG_STATE_NONE, ++fixups, ++warnings))
goto out;
#endif
printk(KERN_INFO "ODEBUG: selftest passed\n");
out:
debug_objects_fixups = oldfixups;
debug_objects_warnings = oldwarnings;
descr_test = NULL;
local_irq_restore(flags);
}
#else
static inline void debug_objects_selftest(void) { }
#endif
/*
* Called during early boot to initialize the hash buckets and link
* the static object pool objects into the poll list. After this call
* the object tracker is fully operational.
*/
void __init debug_objects_early_init(void)
{
int i;
for (i = 0; i < ODEBUG_HASH_SIZE; i++)
raw_spin_lock_init(&obj_hash[i].lock);
for (i = 0; i < ODEBUG_POOL_SIZE; i++)
hlist_add_head(&obj_static_pool[i].node, &obj_pool);
}
/*
* Convert the statically allocated objects to dynamic ones:
*/
static int __init debug_objects_replace_static_objects(void)
{
struct debug_bucket *db = obj_hash;
struct hlist_node *node, *tmp;
struct debug_obj *obj, *new;
HLIST_HEAD(objects);
int i, cnt = 0;
for (i = 0; i < ODEBUG_POOL_SIZE; i++) {
obj = kmem_cache_zalloc(obj_cache, GFP_KERNEL);
if (!obj)
goto free;
hlist_add_head(&obj->node, &objects);
}
/*
* When debug_objects_mem_init() is called we know that only
* one CPU is up, so disabling interrupts is enough
* protection. This avoids the lockdep hell of lock ordering.
*/
local_irq_disable();
/* Remove the statically allocated objects from the pool */
hlist_for_each_entry_safe(obj, node, tmp, &obj_pool, node)
hlist_del(&obj->node);
/* Move the allocated objects to the pool */
hlist_move_list(&objects, &obj_pool);
/* Replace the active object references */
for (i = 0; i < ODEBUG_HASH_SIZE; i++, db++) {
hlist_move_list(&db->list, &objects);
hlist_for_each_entry(obj, node, &objects, node) {
new = hlist_entry(obj_pool.first, typeof(*obj), node);
hlist_del(&new->node);
/* copy object data */
*new = *obj;
hlist_add_head(&new->node, &db->list);
cnt++;
}
}
printk(KERN_DEBUG "ODEBUG: %d of %d active objects replaced\n", cnt,
obj_pool_used);
local_irq_enable();
return 0;
free:
hlist_for_each_entry_safe(obj, node, tmp, &objects, node) {
hlist_del(&obj->node);
kmem_cache_free(obj_cache, obj);
}
return -ENOMEM;
}
/*
* Called after the kmem_caches are functional to setup a dedicated
* cache pool, which has the SLAB_DEBUG_OBJECTS flag set. This flag
* prevents that the debug code is called on kmem_cache_free() for the
* debug tracker objects to avoid recursive calls.
*/
void __init debug_objects_mem_init(void)
{
if (!debug_objects_enabled)
return;
obj_cache = kmem_cache_create("debug_objects_cache",
sizeof (struct debug_obj), 0,
SLAB_DEBUG_OBJECTS, NULL);
if (!obj_cache || debug_objects_replace_static_objects()) {
debug_objects_enabled = 0;
if (obj_cache)
kmem_cache_destroy(obj_cache);
printk(KERN_WARNING "ODEBUG: out of memory.\n");
} else
debug_objects_selftest();
}
| gpl-2.0 |
Fuzion24/SM-G900V_NA_KK_Opensource-S5-Kernel- | drivers/target/iscsi/iscsi_target_parameters.c | 3588 | 52369 | /*******************************************************************************
* This file contains main functions related to iSCSI Parameter negotiation.
*
* \u00a9 Copyright 2007-2011 RisingTide Systems LLC.
*
* Licensed to the Linux Foundation under the General Public License (GPL) version 2.
*
* Author: Nicholas A. Bellinger <nab@linux-iscsi.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
******************************************************************************/
#include <linux/slab.h>
#include "iscsi_target_core.h"
#include "iscsi_target_util.h"
#include "iscsi_target_parameters.h"
int iscsi_login_rx_data(
struct iscsi_conn *conn,
char *buf,
int length)
{
int rx_got;
struct kvec iov;
memset(&iov, 0, sizeof(struct kvec));
iov.iov_len = length;
iov.iov_base = buf;
/*
* Initial Marker-less Interval.
* Add the values regardless of IFMarker/OFMarker, considering
* it may not be negoitated yet.
*/
conn->of_marker += length;
rx_got = rx_data(conn, &iov, 1, length);
if (rx_got != length) {
pr_err("rx_data returned %d, expecting %d.\n",
rx_got, length);
return -1;
}
return 0 ;
}
int iscsi_login_tx_data(
struct iscsi_conn *conn,
char *pdu_buf,
char *text_buf,
int text_length)
{
int length, tx_sent;
struct kvec iov[2];
length = (ISCSI_HDR_LEN + text_length);
memset(&iov[0], 0, 2 * sizeof(struct kvec));
iov[0].iov_len = ISCSI_HDR_LEN;
iov[0].iov_base = pdu_buf;
iov[1].iov_len = text_length;
iov[1].iov_base = text_buf;
/*
* Initial Marker-less Interval.
* Add the values regardless of IFMarker/OFMarker, considering
* it may not be negoitated yet.
*/
conn->if_marker += length;
tx_sent = tx_data(conn, &iov[0], 2, length);
if (tx_sent != length) {
pr_err("tx_data returned %d, expecting %d.\n",
tx_sent, length);
return -1;
}
return 0;
}
void iscsi_dump_conn_ops(struct iscsi_conn_ops *conn_ops)
{
pr_debug("HeaderDigest: %s\n", (conn_ops->HeaderDigest) ?
"CRC32C" : "None");
pr_debug("DataDigest: %s\n", (conn_ops->DataDigest) ?
"CRC32C" : "None");
pr_debug("MaxRecvDataSegmentLength: %u\n",
conn_ops->MaxRecvDataSegmentLength);
pr_debug("OFMarker: %s\n", (conn_ops->OFMarker) ? "Yes" : "No");
pr_debug("IFMarker: %s\n", (conn_ops->IFMarker) ? "Yes" : "No");
if (conn_ops->OFMarker)
pr_debug("OFMarkInt: %u\n", conn_ops->OFMarkInt);
if (conn_ops->IFMarker)
pr_debug("IFMarkInt: %u\n", conn_ops->IFMarkInt);
}
void iscsi_dump_sess_ops(struct iscsi_sess_ops *sess_ops)
{
pr_debug("InitiatorName: %s\n", sess_ops->InitiatorName);
pr_debug("InitiatorAlias: %s\n", sess_ops->InitiatorAlias);
pr_debug("TargetName: %s\n", sess_ops->TargetName);
pr_debug("TargetAlias: %s\n", sess_ops->TargetAlias);
pr_debug("TargetPortalGroupTag: %hu\n",
sess_ops->TargetPortalGroupTag);
pr_debug("MaxConnections: %hu\n", sess_ops->MaxConnections);
pr_debug("InitialR2T: %s\n",
(sess_ops->InitialR2T) ? "Yes" : "No");
pr_debug("ImmediateData: %s\n", (sess_ops->ImmediateData) ?
"Yes" : "No");
pr_debug("MaxBurstLength: %u\n", sess_ops->MaxBurstLength);
pr_debug("FirstBurstLength: %u\n", sess_ops->FirstBurstLength);
pr_debug("DefaultTime2Wait: %hu\n", sess_ops->DefaultTime2Wait);
pr_debug("DefaultTime2Retain: %hu\n",
sess_ops->DefaultTime2Retain);
pr_debug("MaxOutstandingR2T: %hu\n",
sess_ops->MaxOutstandingR2T);
pr_debug("DataPDUInOrder: %s\n",
(sess_ops->DataPDUInOrder) ? "Yes" : "No");
pr_debug("DataSequenceInOrder: %s\n",
(sess_ops->DataSequenceInOrder) ? "Yes" : "No");
pr_debug("ErrorRecoveryLevel: %hu\n",
sess_ops->ErrorRecoveryLevel);
pr_debug("SessionType: %s\n", (sess_ops->SessionType) ?
"Discovery" : "Normal");
}
void iscsi_print_params(struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
list_for_each_entry(param, ¶m_list->param_list, p_list)
pr_debug("%s: %s\n", param->name, param->value);
}
static struct iscsi_param *iscsi_set_default_param(struct iscsi_param_list *param_list,
char *name, char *value, u8 phase, u8 scope, u8 sender,
u16 type_range, u8 use)
{
struct iscsi_param *param = NULL;
param = kzalloc(sizeof(struct iscsi_param), GFP_KERNEL);
if (!param) {
pr_err("Unable to allocate memory for parameter.\n");
goto out;
}
INIT_LIST_HEAD(¶m->p_list);
param->name = kzalloc(strlen(name) + 1, GFP_KERNEL);
if (!param->name) {
pr_err("Unable to allocate memory for parameter name.\n");
goto out;
}
param->value = kzalloc(strlen(value) + 1, GFP_KERNEL);
if (!param->value) {
pr_err("Unable to allocate memory for parameter value.\n");
goto out;
}
memcpy(param->name, name, strlen(name));
param->name[strlen(name)] = '\0';
memcpy(param->value, value, strlen(value));
param->value[strlen(value)] = '\0';
param->phase = phase;
param->scope = scope;
param->sender = sender;
param->use = use;
param->type_range = type_range;
switch (param->type_range) {
case TYPERANGE_BOOL_AND:
param->type = TYPE_BOOL_AND;
break;
case TYPERANGE_BOOL_OR:
param->type = TYPE_BOOL_OR;
break;
case TYPERANGE_0_TO_2:
case TYPERANGE_0_TO_3600:
case TYPERANGE_0_TO_32767:
case TYPERANGE_0_TO_65535:
case TYPERANGE_1_TO_65535:
case TYPERANGE_2_TO_3600:
case TYPERANGE_512_TO_16777215:
param->type = TYPE_NUMBER;
break;
case TYPERANGE_AUTH:
case TYPERANGE_DIGEST:
param->type = TYPE_VALUE_LIST | TYPE_STRING;
break;
case TYPERANGE_MARKINT:
param->type = TYPE_NUMBER_RANGE;
param->type_range |= TYPERANGE_1_TO_65535;
break;
case TYPERANGE_ISCSINAME:
case TYPERANGE_SESSIONTYPE:
case TYPERANGE_TARGETADDRESS:
case TYPERANGE_UTF8:
param->type = TYPE_STRING;
break;
default:
pr_err("Unknown type_range 0x%02x\n",
param->type_range);
goto out;
}
list_add_tail(¶m->p_list, ¶m_list->param_list);
return param;
out:
if (param) {
kfree(param->value);
kfree(param->name);
kfree(param);
}
return NULL;
}
/* #warning Add extension keys */
int iscsi_create_default_params(struct iscsi_param_list **param_list_ptr)
{
struct iscsi_param *param = NULL;
struct iscsi_param_list *pl;
pl = kzalloc(sizeof(struct iscsi_param_list), GFP_KERNEL);
if (!pl) {
pr_err("Unable to allocate memory for"
" struct iscsi_param_list.\n");
return -1 ;
}
INIT_LIST_HEAD(&pl->param_list);
INIT_LIST_HEAD(&pl->extra_response_list);
/*
* The format for setting the initial parameter definitions are:
*
* Parameter name:
* Initial value:
* Allowable phase:
* Scope:
* Allowable senders:
* Typerange:
* Use:
*/
param = iscsi_set_default_param(pl, AUTHMETHOD, INITIAL_AUTHMETHOD,
PHASE_SECURITY, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_AUTH, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, HEADERDIGEST, INITIAL_HEADERDIGEST,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_DIGEST, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DATADIGEST, INITIAL_DATADIGEST,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_DIGEST, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXCONNECTIONS,
INITIAL_MAXCONNECTIONS, PHASE_OPERATIONAL,
SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_1_TO_65535, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, SENDTARGETS, INITIAL_SENDTARGETS,
PHASE_FFP0, SCOPE_SESSION_WIDE, SENDER_INITIATOR,
TYPERANGE_UTF8, 0);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETNAME, INITIAL_TARGETNAME,
PHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_ISCSINAME, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, INITIATORNAME,
INITIAL_INITIATORNAME, PHASE_DECLARATIVE,
SCOPE_SESSION_WIDE, SENDER_INITIATOR,
TYPERANGE_ISCSINAME, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETALIAS, INITIAL_TARGETALIAS,
PHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_TARGET,
TYPERANGE_UTF8, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, INITIATORALIAS,
INITIAL_INITIATORALIAS, PHASE_DECLARATIVE,
SCOPE_SESSION_WIDE, SENDER_INITIATOR, TYPERANGE_UTF8,
USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETADDRESS,
INITIAL_TARGETADDRESS, PHASE_DECLARATIVE,
SCOPE_SESSION_WIDE, SENDER_TARGET,
TYPERANGE_TARGETADDRESS, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETPORTALGROUPTAG,
INITIAL_TARGETPORTALGROUPTAG,
PHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_TARGET,
TYPERANGE_0_TO_65535, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, INITIALR2T, INITIAL_INITIALR2T,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_BOOL_OR, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, IMMEDIATEDATA,
INITIAL_IMMEDIATEDATA, PHASE_OPERATIONAL,
SCOPE_SESSION_WIDE, SENDER_BOTH, TYPERANGE_BOOL_AND,
USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXRECVDATASEGMENTLENGTH,
INITIAL_MAXRECVDATASEGMENTLENGTH,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXBURSTLENGTH,
INITIAL_MAXBURSTLENGTH, PHASE_OPERATIONAL,
SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, FIRSTBURSTLENGTH,
INITIAL_FIRSTBURSTLENGTH,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DEFAULTTIME2WAIT,
INITIAL_DEFAULTTIME2WAIT,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_0_TO_3600, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DEFAULTTIME2RETAIN,
INITIAL_DEFAULTTIME2RETAIN,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_0_TO_3600, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXOUTSTANDINGR2T,
INITIAL_MAXOUTSTANDINGR2T,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_1_TO_65535, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DATAPDUINORDER,
INITIAL_DATAPDUINORDER, PHASE_OPERATIONAL,
SCOPE_SESSION_WIDE, SENDER_BOTH, TYPERANGE_BOOL_OR,
USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DATASEQUENCEINORDER,
INITIAL_DATASEQUENCEINORDER,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_BOOL_OR, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, ERRORRECOVERYLEVEL,
INITIAL_ERRORRECOVERYLEVEL,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_0_TO_2, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, SESSIONTYPE, INITIAL_SESSIONTYPE,
PHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_INITIATOR,
TYPERANGE_SESSIONTYPE, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, IFMARKER, INITIAL_IFMARKER,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_BOOL_AND, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, OFMARKER, INITIAL_OFMARKER,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_BOOL_AND, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, IFMARKINT, INITIAL_IFMARKINT,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_MARKINT, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, OFMARKINT, INITIAL_OFMARKINT,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_MARKINT, USE_INITIAL_ONLY);
if (!param)
goto out;
*param_list_ptr = pl;
return 0;
out:
iscsi_release_param_list(pl);
return -1;
}
int iscsi_set_keys_to_negotiate(
int sessiontype,
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
param->state = 0;
if (!strcmp(param->name, AUTHMETHOD)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, HEADERDIGEST)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DATADIGEST)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, MAXCONNECTIONS)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, TARGETNAME)) {
continue;
} else if (!strcmp(param->name, INITIATORNAME)) {
continue;
} else if (!strcmp(param->name, TARGETALIAS)) {
if (param->value)
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, INITIATORALIAS)) {
continue;
} else if (!strcmp(param->name, TARGETPORTALGROUPTAG)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, INITIALR2T)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, IMMEDIATEDATA)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, MAXBURSTLENGTH)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, FIRSTBURSTLENGTH)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DEFAULTTIME2WAIT)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DEFAULTTIME2RETAIN)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, MAXOUTSTANDINGR2T)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DATAPDUINORDER)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DATASEQUENCEINORDER)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, ERRORRECOVERYLEVEL)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, SESSIONTYPE)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, IFMARKER)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, OFMARKER)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, IFMARKINT)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, OFMARKINT)) {
SET_PSTATE_NEGOTIATE(param);
}
}
return 0;
}
int iscsi_set_keys_irrelevant_for_discovery(
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!strcmp(param->name, MAXCONNECTIONS))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, INITIALR2T))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, IMMEDIATEDATA))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, MAXBURSTLENGTH))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, FIRSTBURSTLENGTH))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, MAXOUTSTANDINGR2T))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, DATAPDUINORDER))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, DATASEQUENCEINORDER))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, ERRORRECOVERYLEVEL))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, DEFAULTTIME2WAIT))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, DEFAULTTIME2RETAIN))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, IFMARKER))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, OFMARKER))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, IFMARKINT))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, OFMARKINT))
param->state &= ~PSTATE_NEGOTIATE;
}
return 0;
}
int iscsi_copy_param_list(
struct iscsi_param_list **dst_param_list,
struct iscsi_param_list *src_param_list,
int leading)
{
struct iscsi_param *param = NULL;
struct iscsi_param *new_param = NULL;
struct iscsi_param_list *param_list = NULL;
param_list = kzalloc(sizeof(struct iscsi_param_list), GFP_KERNEL);
if (!param_list) {
pr_err("Unable to allocate memory for struct iscsi_param_list.\n");
goto err_out;
}
INIT_LIST_HEAD(¶m_list->param_list);
INIT_LIST_HEAD(¶m_list->extra_response_list);
list_for_each_entry(param, &src_param_list->param_list, p_list) {
if (!leading && (param->scope & SCOPE_SESSION_WIDE)) {
if ((strcmp(param->name, "TargetName") != 0) &&
(strcmp(param->name, "InitiatorName") != 0) &&
(strcmp(param->name, "TargetPortalGroupTag") != 0))
continue;
}
new_param = kzalloc(sizeof(struct iscsi_param), GFP_KERNEL);
if (!new_param) {
pr_err("Unable to allocate memory for struct iscsi_param.\n");
goto err_out;
}
new_param->name = kstrdup(param->name, GFP_KERNEL);
new_param->value = kstrdup(param->value, GFP_KERNEL);
if (!new_param->value || !new_param->name) {
kfree(new_param->value);
kfree(new_param->name);
kfree(new_param);
pr_err("Unable to allocate memory for parameter name/value.\n");
goto err_out;
}
new_param->set_param = param->set_param;
new_param->phase = param->phase;
new_param->scope = param->scope;
new_param->sender = param->sender;
new_param->type = param->type;
new_param->use = param->use;
new_param->type_range = param->type_range;
list_add_tail(&new_param->p_list, ¶m_list->param_list);
}
if (!list_empty(¶m_list->param_list)) {
*dst_param_list = param_list;
} else {
pr_err("No parameters allocated.\n");
goto err_out;
}
return 0;
err_out:
iscsi_release_param_list(param_list);
return -1;
}
static void iscsi_release_extra_responses(struct iscsi_param_list *param_list)
{
struct iscsi_extra_response *er, *er_tmp;
list_for_each_entry_safe(er, er_tmp, ¶m_list->extra_response_list,
er_list) {
list_del(&er->er_list);
kfree(er);
}
}
void iscsi_release_param_list(struct iscsi_param_list *param_list)
{
struct iscsi_param *param, *param_tmp;
list_for_each_entry_safe(param, param_tmp, ¶m_list->param_list,
p_list) {
list_del(¶m->p_list);
kfree(param->name);
param->name = NULL;
kfree(param->value);
param->value = NULL;
kfree(param);
param = NULL;
}
iscsi_release_extra_responses(param_list);
kfree(param_list);
}
struct iscsi_param *iscsi_find_param_from_key(
char *key,
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
if (!key || !param_list) {
pr_err("Key or parameter list pointer is NULL.\n");
return NULL;
}
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!strcmp(key, param->name))
return param;
}
pr_err("Unable to locate key \"%s\".\n", key);
return NULL;
}
int iscsi_extract_key_value(char *textbuf, char **key, char **value)
{
*value = strchr(textbuf, '=');
if (!*value) {
pr_err("Unable to locate \"=\" seperator for key,"
" ignoring request.\n");
return -1;
}
*key = textbuf;
**value = '\0';
*value = *value + 1;
return 0;
}
int iscsi_update_param_value(struct iscsi_param *param, char *value)
{
kfree(param->value);
param->value = kzalloc(strlen(value) + 1, GFP_KERNEL);
if (!param->value) {
pr_err("Unable to allocate memory for value.\n");
return -1;
}
memcpy(param->value, value, strlen(value));
param->value[strlen(value)] = '\0';
pr_debug("iSCSI Parameter updated to %s=%s\n",
param->name, param->value);
return 0;
}
static int iscsi_add_notunderstood_response(
char *key,
char *value,
struct iscsi_param_list *param_list)
{
struct iscsi_extra_response *extra_response;
if (strlen(value) > VALUE_MAXLEN) {
pr_err("Value for notunderstood key \"%s\" exceeds %d,"
" protocol error.\n", key, VALUE_MAXLEN);
return -1;
}
extra_response = kzalloc(sizeof(struct iscsi_extra_response), GFP_KERNEL);
if (!extra_response) {
pr_err("Unable to allocate memory for"
" struct iscsi_extra_response.\n");
return -1;
}
INIT_LIST_HEAD(&extra_response->er_list);
strncpy(extra_response->key, key, strlen(key) + 1);
strncpy(extra_response->value, NOTUNDERSTOOD,
strlen(NOTUNDERSTOOD) + 1);
list_add_tail(&extra_response->er_list,
¶m_list->extra_response_list);
return 0;
}
static int iscsi_check_for_auth_key(char *key)
{
/*
* RFC 1994
*/
if (!strcmp(key, "CHAP_A") || !strcmp(key, "CHAP_I") ||
!strcmp(key, "CHAP_C") || !strcmp(key, "CHAP_N") ||
!strcmp(key, "CHAP_R"))
return 1;
/*
* RFC 2945
*/
if (!strcmp(key, "SRP_U") || !strcmp(key, "SRP_N") ||
!strcmp(key, "SRP_g") || !strcmp(key, "SRP_s") ||
!strcmp(key, "SRP_A") || !strcmp(key, "SRP_B") ||
!strcmp(key, "SRP_M") || !strcmp(key, "SRP_HM"))
return 1;
return 0;
}
static void iscsi_check_proposer_for_optional_reply(struct iscsi_param *param)
{
if (IS_TYPE_BOOL_AND(param)) {
if (!strcmp(param->value, NO))
SET_PSTATE_REPLY_OPTIONAL(param);
} else if (IS_TYPE_BOOL_OR(param)) {
if (!strcmp(param->value, YES))
SET_PSTATE_REPLY_OPTIONAL(param);
/*
* Required for gPXE iSCSI boot client
*/
if (!strcmp(param->name, IMMEDIATEDATA))
SET_PSTATE_REPLY_OPTIONAL(param);
} else if (IS_TYPE_NUMBER(param)) {
if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH))
SET_PSTATE_REPLY_OPTIONAL(param);
/*
* The GlobalSAN iSCSI Initiator for MacOSX does
* not respond to MaxBurstLength, FirstBurstLength,
* DefaultTime2Wait or DefaultTime2Retain parameter keys.
* So, we set them to 'reply optional' here, and assume the
* the defaults from iscsi_parameters.h if the initiator
* is not RFC compliant and the keys are not negotiated.
*/
if (!strcmp(param->name, MAXBURSTLENGTH))
SET_PSTATE_REPLY_OPTIONAL(param);
if (!strcmp(param->name, FIRSTBURSTLENGTH))
SET_PSTATE_REPLY_OPTIONAL(param);
if (!strcmp(param->name, DEFAULTTIME2WAIT))
SET_PSTATE_REPLY_OPTIONAL(param);
if (!strcmp(param->name, DEFAULTTIME2RETAIN))
SET_PSTATE_REPLY_OPTIONAL(param);
/*
* Required for gPXE iSCSI boot client
*/
if (!strcmp(param->name, MAXCONNECTIONS))
SET_PSTATE_REPLY_OPTIONAL(param);
} else if (IS_PHASE_DECLARATIVE(param))
SET_PSTATE_REPLY_OPTIONAL(param);
}
static int iscsi_check_boolean_value(struct iscsi_param *param, char *value)
{
if (strcmp(value, YES) && strcmp(value, NO)) {
pr_err("Illegal value for \"%s\", must be either"
" \"%s\" or \"%s\".\n", param->name, YES, NO);
return -1;
}
return 0;
}
static int iscsi_check_numerical_value(struct iscsi_param *param, char *value_ptr)
{
char *tmpptr;
int value = 0;
value = simple_strtoul(value_ptr, &tmpptr, 0);
/* #warning FIXME: Fix this */
#if 0
if (strspn(endptr, WHITE_SPACE) != strlen(endptr)) {
pr_err("Illegal value \"%s\" for \"%s\".\n",
value, param->name);
return -1;
}
#endif
if (IS_TYPERANGE_0_TO_2(param)) {
if ((value < 0) || (value > 2)) {
pr_err("Illegal value for \"%s\", must be"
" between 0 and 2.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_0_TO_3600(param)) {
if ((value < 0) || (value > 3600)) {
pr_err("Illegal value for \"%s\", must be"
" between 0 and 3600.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_0_TO_32767(param)) {
if ((value < 0) || (value > 32767)) {
pr_err("Illegal value for \"%s\", must be"
" between 0 and 32767.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_0_TO_65535(param)) {
if ((value < 0) || (value > 65535)) {
pr_err("Illegal value for \"%s\", must be"
" between 0 and 65535.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_1_TO_65535(param)) {
if ((value < 1) || (value > 65535)) {
pr_err("Illegal value for \"%s\", must be"
" between 1 and 65535.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_2_TO_3600(param)) {
if ((value < 2) || (value > 3600)) {
pr_err("Illegal value for \"%s\", must be"
" between 2 and 3600.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_512_TO_16777215(param)) {
if ((value < 512) || (value > 16777215)) {
pr_err("Illegal value for \"%s\", must be"
" between 512 and 16777215.\n", param->name);
return -1;
}
return 0;
}
return 0;
}
static int iscsi_check_numerical_range_value(struct iscsi_param *param, char *value)
{
char *left_val_ptr = NULL, *right_val_ptr = NULL;
char *tilde_ptr = NULL;
u32 left_val, right_val, local_left_val;
if (strcmp(param->name, IFMARKINT) &&
strcmp(param->name, OFMARKINT)) {
pr_err("Only parameters \"%s\" or \"%s\" may contain a"
" numerical range value.\n", IFMARKINT, OFMARKINT);
return -1;
}
if (IS_PSTATE_PROPOSER(param))
return 0;
tilde_ptr = strchr(value, '~');
if (!tilde_ptr) {
pr_err("Unable to locate numerical range indicator"
" \"~\" for \"%s\".\n", param->name);
return -1;
}
*tilde_ptr = '\0';
left_val_ptr = value;
right_val_ptr = value + strlen(left_val_ptr) + 1;
if (iscsi_check_numerical_value(param, left_val_ptr) < 0)
return -1;
if (iscsi_check_numerical_value(param, right_val_ptr) < 0)
return -1;
left_val = simple_strtoul(left_val_ptr, NULL, 0);
right_val = simple_strtoul(right_val_ptr, NULL, 0);
*tilde_ptr = '~';
if (right_val < left_val) {
pr_err("Numerical range for parameter \"%s\" contains"
" a right value which is less than the left.\n",
param->name);
return -1;
}
/*
* For now, enforce reasonable defaults for [I,O]FMarkInt.
*/
tilde_ptr = strchr(param->value, '~');
if (!tilde_ptr) {
pr_err("Unable to locate numerical range indicator"
" \"~\" for \"%s\".\n", param->name);
return -1;
}
*tilde_ptr = '\0';
left_val_ptr = param->value;
right_val_ptr = param->value + strlen(left_val_ptr) + 1;
local_left_val = simple_strtoul(left_val_ptr, NULL, 0);
*tilde_ptr = '~';
if (param->set_param) {
if ((left_val < local_left_val) ||
(right_val < local_left_val)) {
pr_err("Passed value range \"%u~%u\" is below"
" minimum left value \"%u\" for key \"%s\","
" rejecting.\n", left_val, right_val,
local_left_val, param->name);
return -1;
}
} else {
if ((left_val < local_left_val) &&
(right_val < local_left_val)) {
pr_err("Received value range \"%u~%u\" is"
" below minimum left value \"%u\" for key"
" \"%s\", rejecting.\n", left_val, right_val,
local_left_val, param->name);
SET_PSTATE_REJECT(param);
if (iscsi_update_param_value(param, REJECT) < 0)
return -1;
}
}
return 0;
}
static int iscsi_check_string_or_list_value(struct iscsi_param *param, char *value)
{
if (IS_PSTATE_PROPOSER(param))
return 0;
if (IS_TYPERANGE_AUTH_PARAM(param)) {
if (strcmp(value, KRB5) && strcmp(value, SPKM1) &&
strcmp(value, SPKM2) && strcmp(value, SRP) &&
strcmp(value, CHAP) && strcmp(value, NONE)) {
pr_err("Illegal value for \"%s\", must be"
" \"%s\", \"%s\", \"%s\", \"%s\", \"%s\""
" or \"%s\".\n", param->name, KRB5,
SPKM1, SPKM2, SRP, CHAP, NONE);
return -1;
}
}
if (IS_TYPERANGE_DIGEST_PARAM(param)) {
if (strcmp(value, CRC32C) && strcmp(value, NONE)) {
pr_err("Illegal value for \"%s\", must be"
" \"%s\" or \"%s\".\n", param->name,
CRC32C, NONE);
return -1;
}
}
if (IS_TYPERANGE_SESSIONTYPE(param)) {
if (strcmp(value, DISCOVERY) && strcmp(value, NORMAL)) {
pr_err("Illegal value for \"%s\", must be"
" \"%s\" or \"%s\".\n", param->name,
DISCOVERY, NORMAL);
return -1;
}
}
return 0;
}
/*
* This function is used to pick a value range number, currently just
* returns the lesser of both right values.
*/
static char *iscsi_get_value_from_number_range(
struct iscsi_param *param,
char *value)
{
char *end_ptr, *tilde_ptr1 = NULL, *tilde_ptr2 = NULL;
u32 acceptor_right_value, proposer_right_value;
tilde_ptr1 = strchr(value, '~');
if (!tilde_ptr1)
return NULL;
*tilde_ptr1++ = '\0';
proposer_right_value = simple_strtoul(tilde_ptr1, &end_ptr, 0);
tilde_ptr2 = strchr(param->value, '~');
if (!tilde_ptr2)
return NULL;
*tilde_ptr2++ = '\0';
acceptor_right_value = simple_strtoul(tilde_ptr2, &end_ptr, 0);
return (acceptor_right_value >= proposer_right_value) ?
tilde_ptr1 : tilde_ptr2;
}
static char *iscsi_check_valuelist_for_support(
struct iscsi_param *param,
char *value)
{
char *tmp1 = NULL, *tmp2 = NULL;
char *acceptor_values = NULL, *proposer_values = NULL;
acceptor_values = param->value;
proposer_values = value;
do {
if (!proposer_values)
return NULL;
tmp1 = strchr(proposer_values, ',');
if (tmp1)
*tmp1 = '\0';
acceptor_values = param->value;
do {
if (!acceptor_values) {
if (tmp1)
*tmp1 = ',';
return NULL;
}
tmp2 = strchr(acceptor_values, ',');
if (tmp2)
*tmp2 = '\0';
if (!acceptor_values || !proposer_values) {
if (tmp1)
*tmp1 = ',';
if (tmp2)
*tmp2 = ',';
return NULL;
}
if (!strcmp(acceptor_values, proposer_values)) {
if (tmp2)
*tmp2 = ',';
goto out;
}
if (tmp2)
*tmp2++ = ',';
acceptor_values = tmp2;
if (!acceptor_values)
break;
} while (acceptor_values);
if (tmp1)
*tmp1++ = ',';
proposer_values = tmp1;
} while (proposer_values);
out:
return proposer_values;
}
static int iscsi_check_acceptor_state(struct iscsi_param *param, char *value)
{
u8 acceptor_boolean_value = 0, proposer_boolean_value = 0;
char *negoitated_value = NULL;
if (IS_PSTATE_ACCEPTOR(param)) {
pr_err("Received key \"%s\" twice, protocol error.\n",
param->name);
return -1;
}
if (IS_PSTATE_REJECT(param))
return 0;
if (IS_TYPE_BOOL_AND(param)) {
if (!strcmp(value, YES))
proposer_boolean_value = 1;
if (!strcmp(param->value, YES))
acceptor_boolean_value = 1;
if (acceptor_boolean_value && proposer_boolean_value)
do {} while (0);
else {
if (iscsi_update_param_value(param, NO) < 0)
return -1;
if (!proposer_boolean_value)
SET_PSTATE_REPLY_OPTIONAL(param);
}
} else if (IS_TYPE_BOOL_OR(param)) {
if (!strcmp(value, YES))
proposer_boolean_value = 1;
if (!strcmp(param->value, YES))
acceptor_boolean_value = 1;
if (acceptor_boolean_value || proposer_boolean_value) {
if (iscsi_update_param_value(param, YES) < 0)
return -1;
if (proposer_boolean_value)
SET_PSTATE_REPLY_OPTIONAL(param);
}
} else if (IS_TYPE_NUMBER(param)) {
char *tmpptr, buf[10];
u32 acceptor_value = simple_strtoul(param->value, &tmpptr, 0);
u32 proposer_value = simple_strtoul(value, &tmpptr, 0);
memset(buf, 0, 10);
if (!strcmp(param->name, MAXCONNECTIONS) ||
!strcmp(param->name, MAXBURSTLENGTH) ||
!strcmp(param->name, FIRSTBURSTLENGTH) ||
!strcmp(param->name, MAXOUTSTANDINGR2T) ||
!strcmp(param->name, DEFAULTTIME2RETAIN) ||
!strcmp(param->name, ERRORRECOVERYLEVEL)) {
if (proposer_value > acceptor_value) {
sprintf(buf, "%u", acceptor_value);
if (iscsi_update_param_value(param,
&buf[0]) < 0)
return -1;
} else {
if (iscsi_update_param_value(param, value) < 0)
return -1;
}
} else if (!strcmp(param->name, DEFAULTTIME2WAIT)) {
if (acceptor_value > proposer_value) {
sprintf(buf, "%u", acceptor_value);
if (iscsi_update_param_value(param,
&buf[0]) < 0)
return -1;
} else {
if (iscsi_update_param_value(param, value) < 0)
return -1;
}
} else {
if (iscsi_update_param_value(param, value) < 0)
return -1;
}
if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH))
SET_PSTATE_REPLY_OPTIONAL(param);
} else if (IS_TYPE_NUMBER_RANGE(param)) {
negoitated_value = iscsi_get_value_from_number_range(
param, value);
if (!negoitated_value)
return -1;
if (iscsi_update_param_value(param, negoitated_value) < 0)
return -1;
} else if (IS_TYPE_VALUE_LIST(param)) {
negoitated_value = iscsi_check_valuelist_for_support(
param, value);
if (!negoitated_value) {
pr_err("Proposer's value list \"%s\" contains"
" no valid values from Acceptor's value list"
" \"%s\".\n", value, param->value);
return -1;
}
if (iscsi_update_param_value(param, negoitated_value) < 0)
return -1;
} else if (IS_PHASE_DECLARATIVE(param)) {
if (iscsi_update_param_value(param, value) < 0)
return -1;
SET_PSTATE_REPLY_OPTIONAL(param);
}
return 0;
}
static int iscsi_check_proposer_state(struct iscsi_param *param, char *value)
{
if (IS_PSTATE_RESPONSE_GOT(param)) {
pr_err("Received key \"%s\" twice, protocol error.\n",
param->name);
return -1;
}
if (IS_TYPE_NUMBER_RANGE(param)) {
u32 left_val = 0, right_val = 0, recieved_value = 0;
char *left_val_ptr = NULL, *right_val_ptr = NULL;
char *tilde_ptr = NULL;
if (!strcmp(value, IRRELEVANT) || !strcmp(value, REJECT)) {
if (iscsi_update_param_value(param, value) < 0)
return -1;
return 0;
}
tilde_ptr = strchr(value, '~');
if (tilde_ptr) {
pr_err("Illegal \"~\" in response for \"%s\".\n",
param->name);
return -1;
}
tilde_ptr = strchr(param->value, '~');
if (!tilde_ptr) {
pr_err("Unable to locate numerical range"
" indicator \"~\" for \"%s\".\n", param->name);
return -1;
}
*tilde_ptr = '\0';
left_val_ptr = param->value;
right_val_ptr = param->value + strlen(left_val_ptr) + 1;
left_val = simple_strtoul(left_val_ptr, NULL, 0);
right_val = simple_strtoul(right_val_ptr, NULL, 0);
recieved_value = simple_strtoul(value, NULL, 0);
*tilde_ptr = '~';
if ((recieved_value < left_val) ||
(recieved_value > right_val)) {
pr_err("Illegal response \"%s=%u\", value must"
" be between %u and %u.\n", param->name,
recieved_value, left_val, right_val);
return -1;
}
} else if (IS_TYPE_VALUE_LIST(param)) {
char *comma_ptr = NULL, *tmp_ptr = NULL;
comma_ptr = strchr(value, ',');
if (comma_ptr) {
pr_err("Illegal \",\" in response for \"%s\".\n",
param->name);
return -1;
}
tmp_ptr = iscsi_check_valuelist_for_support(param, value);
if (!tmp_ptr)
return -1;
}
if (iscsi_update_param_value(param, value) < 0)
return -1;
return 0;
}
static int iscsi_check_value(struct iscsi_param *param, char *value)
{
char *comma_ptr = NULL;
if (!strcmp(value, REJECT)) {
if (!strcmp(param->name, IFMARKINT) ||
!strcmp(param->name, OFMARKINT)) {
/*
* Reject is not fatal for [I,O]FMarkInt, and causes
* [I,O]FMarker to be reset to No. (See iSCSI v20 A.3.2)
*/
SET_PSTATE_REJECT(param);
return 0;
}
pr_err("Received %s=%s\n", param->name, value);
return -1;
}
if (!strcmp(value, IRRELEVANT)) {
pr_debug("Received %s=%s\n", param->name, value);
SET_PSTATE_IRRELEVANT(param);
return 0;
}
if (!strcmp(value, NOTUNDERSTOOD)) {
if (!IS_PSTATE_PROPOSER(param)) {
pr_err("Received illegal offer %s=%s\n",
param->name, value);
return -1;
}
/* #warning FIXME: Add check for X-ExtensionKey here */
pr_err("Standard iSCSI key \"%s\" cannot be answered"
" with \"%s\", protocol error.\n", param->name, value);
return -1;
}
do {
comma_ptr = NULL;
comma_ptr = strchr(value, ',');
if (comma_ptr && !IS_TYPE_VALUE_LIST(param)) {
pr_err("Detected value seperator \",\", but"
" key \"%s\" does not allow a value list,"
" protocol error.\n", param->name);
return -1;
}
if (comma_ptr)
*comma_ptr = '\0';
if (strlen(value) > VALUE_MAXLEN) {
pr_err("Value for key \"%s\" exceeds %d,"
" protocol error.\n", param->name,
VALUE_MAXLEN);
return -1;
}
if (IS_TYPE_BOOL_AND(param) || IS_TYPE_BOOL_OR(param)) {
if (iscsi_check_boolean_value(param, value) < 0)
return -1;
} else if (IS_TYPE_NUMBER(param)) {
if (iscsi_check_numerical_value(param, value) < 0)
return -1;
} else if (IS_TYPE_NUMBER_RANGE(param)) {
if (iscsi_check_numerical_range_value(param, value) < 0)
return -1;
} else if (IS_TYPE_STRING(param) || IS_TYPE_VALUE_LIST(param)) {
if (iscsi_check_string_or_list_value(param, value) < 0)
return -1;
} else {
pr_err("Huh? 0x%02x\n", param->type);
return -1;
}
if (comma_ptr)
*comma_ptr++ = ',';
value = comma_ptr;
} while (value);
return 0;
}
static struct iscsi_param *__iscsi_check_key(
char *key,
int sender,
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
if (strlen(key) > KEY_MAXLEN) {
pr_err("Length of key name \"%s\" exceeds %d.\n",
key, KEY_MAXLEN);
return NULL;
}
param = iscsi_find_param_from_key(key, param_list);
if (!param)
return NULL;
if ((sender & SENDER_INITIATOR) && !IS_SENDER_INITIATOR(param)) {
pr_err("Key \"%s\" may not be sent to %s,"
" protocol error.\n", param->name,
(sender & SENDER_RECEIVER) ? "target" : "initiator");
return NULL;
}
if ((sender & SENDER_TARGET) && !IS_SENDER_TARGET(param)) {
pr_err("Key \"%s\" may not be sent to %s,"
" protocol error.\n", param->name,
(sender & SENDER_RECEIVER) ? "initiator" : "target");
return NULL;
}
return param;
}
static struct iscsi_param *iscsi_check_key(
char *key,
int phase,
int sender,
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
/*
* Key name length must not exceed 63 bytes. (See iSCSI v20 5.1)
*/
if (strlen(key) > KEY_MAXLEN) {
pr_err("Length of key name \"%s\" exceeds %d.\n",
key, KEY_MAXLEN);
return NULL;
}
param = iscsi_find_param_from_key(key, param_list);
if (!param)
return NULL;
if ((sender & SENDER_INITIATOR) && !IS_SENDER_INITIATOR(param)) {
pr_err("Key \"%s\" may not be sent to %s,"
" protocol error.\n", param->name,
(sender & SENDER_RECEIVER) ? "target" : "initiator");
return NULL;
}
if ((sender & SENDER_TARGET) && !IS_SENDER_TARGET(param)) {
pr_err("Key \"%s\" may not be sent to %s,"
" protocol error.\n", param->name,
(sender & SENDER_RECEIVER) ? "initiator" : "target");
return NULL;
}
if (IS_PSTATE_ACCEPTOR(param)) {
pr_err("Key \"%s\" received twice, protocol error.\n",
key);
return NULL;
}
if (!phase)
return param;
if (!(param->phase & phase)) {
pr_err("Key \"%s\" may not be negotiated during ",
param->name);
switch (phase) {
case PHASE_SECURITY:
pr_debug("Security phase.\n");
break;
case PHASE_OPERATIONAL:
pr_debug("Operational phase.\n");
default:
pr_debug("Unknown phase.\n");
}
return NULL;
}
return param;
}
static int iscsi_enforce_integrity_rules(
u8 phase,
struct iscsi_param_list *param_list)
{
char *tmpptr;
u8 DataSequenceInOrder = 0;
u8 ErrorRecoveryLevel = 0, SessionType = 0;
u8 IFMarker = 0, OFMarker = 0;
u8 IFMarkInt_Reject = 1, OFMarkInt_Reject = 1;
u32 FirstBurstLength = 0, MaxBurstLength = 0;
struct iscsi_param *param = NULL;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!(param->phase & phase))
continue;
if (!strcmp(param->name, SESSIONTYPE))
if (!strcmp(param->value, NORMAL))
SessionType = 1;
if (!strcmp(param->name, ERRORRECOVERYLEVEL))
ErrorRecoveryLevel = simple_strtoul(param->value,
&tmpptr, 0);
if (!strcmp(param->name, DATASEQUENCEINORDER))
if (!strcmp(param->value, YES))
DataSequenceInOrder = 1;
if (!strcmp(param->name, MAXBURSTLENGTH))
MaxBurstLength = simple_strtoul(param->value,
&tmpptr, 0);
if (!strcmp(param->name, IFMARKER))
if (!strcmp(param->value, YES))
IFMarker = 1;
if (!strcmp(param->name, OFMARKER))
if (!strcmp(param->value, YES))
OFMarker = 1;
if (!strcmp(param->name, IFMARKINT))
if (!strcmp(param->value, REJECT))
IFMarkInt_Reject = 1;
if (!strcmp(param->name, OFMARKINT))
if (!strcmp(param->value, REJECT))
OFMarkInt_Reject = 1;
}
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!(param->phase & phase))
continue;
if (!SessionType && (!IS_PSTATE_ACCEPTOR(param) &&
(strcmp(param->name, IFMARKER) &&
strcmp(param->name, OFMARKER) &&
strcmp(param->name, IFMARKINT) &&
strcmp(param->name, OFMARKINT))))
continue;
if (!strcmp(param->name, MAXOUTSTANDINGR2T) &&
DataSequenceInOrder && (ErrorRecoveryLevel > 0)) {
if (strcmp(param->value, "1")) {
if (iscsi_update_param_value(param, "1") < 0)
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
}
if (!strcmp(param->name, MAXCONNECTIONS) && !SessionType) {
if (strcmp(param->value, "1")) {
if (iscsi_update_param_value(param, "1") < 0)
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
}
if (!strcmp(param->name, FIRSTBURSTLENGTH)) {
FirstBurstLength = simple_strtoul(param->value,
&tmpptr, 0);
if (FirstBurstLength > MaxBurstLength) {
char tmpbuf[10];
memset(tmpbuf, 0, 10);
sprintf(tmpbuf, "%u", MaxBurstLength);
if (iscsi_update_param_value(param, tmpbuf))
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
}
if (!strcmp(param->name, IFMARKER) && IFMarkInt_Reject) {
if (iscsi_update_param_value(param, NO) < 0)
return -1;
IFMarker = 0;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
if (!strcmp(param->name, OFMARKER) && OFMarkInt_Reject) {
if (iscsi_update_param_value(param, NO) < 0)
return -1;
OFMarker = 0;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
if (!strcmp(param->name, IFMARKINT) && !IFMarker) {
if (!strcmp(param->value, REJECT))
continue;
param->state &= ~PSTATE_NEGOTIATE;
if (iscsi_update_param_value(param, IRRELEVANT) < 0)
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
if (!strcmp(param->name, OFMARKINT) && !OFMarker) {
if (!strcmp(param->value, REJECT))
continue;
param->state &= ~PSTATE_NEGOTIATE;
if (iscsi_update_param_value(param, IRRELEVANT) < 0)
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
}
return 0;
}
int iscsi_decode_text_input(
u8 phase,
u8 sender,
char *textbuf,
u32 length,
struct iscsi_param_list *param_list)
{
char *tmpbuf, *start = NULL, *end = NULL;
tmpbuf = kzalloc(length + 1, GFP_KERNEL);
if (!tmpbuf) {
pr_err("Unable to allocate memory for tmpbuf.\n");
return -1;
}
memcpy(tmpbuf, textbuf, length);
tmpbuf[length] = '\0';
start = tmpbuf;
end = (start + length);
while (start < end) {
char *key, *value;
struct iscsi_param *param;
if (iscsi_extract_key_value(start, &key, &value) < 0) {
kfree(tmpbuf);
return -1;
}
pr_debug("Got key: %s=%s\n", key, value);
if (phase & PHASE_SECURITY) {
if (iscsi_check_for_auth_key(key) > 0) {
char *tmpptr = key + strlen(key);
*tmpptr = '=';
kfree(tmpbuf);
return 1;
}
}
param = iscsi_check_key(key, phase, sender, param_list);
if (!param) {
if (iscsi_add_notunderstood_response(key,
value, param_list) < 0) {
kfree(tmpbuf);
return -1;
}
start += strlen(key) + strlen(value) + 2;
continue;
}
if (iscsi_check_value(param, value) < 0) {
kfree(tmpbuf);
return -1;
}
start += strlen(key) + strlen(value) + 2;
if (IS_PSTATE_PROPOSER(param)) {
if (iscsi_check_proposer_state(param, value) < 0) {
kfree(tmpbuf);
return -1;
}
SET_PSTATE_RESPONSE_GOT(param);
} else {
if (iscsi_check_acceptor_state(param, value) < 0) {
kfree(tmpbuf);
return -1;
}
SET_PSTATE_ACCEPTOR(param);
}
}
kfree(tmpbuf);
return 0;
}
int iscsi_encode_text_output(
u8 phase,
u8 sender,
char *textbuf,
u32 *length,
struct iscsi_param_list *param_list)
{
char *output_buf = NULL;
struct iscsi_extra_response *er;
struct iscsi_param *param;
output_buf = textbuf + *length;
if (iscsi_enforce_integrity_rules(phase, param_list) < 0)
return -1;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!(param->sender & sender))
continue;
if (IS_PSTATE_ACCEPTOR(param) &&
!IS_PSTATE_RESPONSE_SENT(param) &&
!IS_PSTATE_REPLY_OPTIONAL(param) &&
(param->phase & phase)) {
*length += sprintf(output_buf, "%s=%s",
param->name, param->value);
*length += 1;
output_buf = textbuf + *length;
SET_PSTATE_RESPONSE_SENT(param);
pr_debug("Sending key: %s=%s\n",
param->name, param->value);
continue;
}
if (IS_PSTATE_NEGOTIATE(param) &&
!IS_PSTATE_ACCEPTOR(param) &&
!IS_PSTATE_PROPOSER(param) &&
(param->phase & phase)) {
*length += sprintf(output_buf, "%s=%s",
param->name, param->value);
*length += 1;
output_buf = textbuf + *length;
SET_PSTATE_PROPOSER(param);
iscsi_check_proposer_for_optional_reply(param);
pr_debug("Sending key: %s=%s\n",
param->name, param->value);
}
}
list_for_each_entry(er, ¶m_list->extra_response_list, er_list) {
*length += sprintf(output_buf, "%s=%s", er->key, er->value);
*length += 1;
output_buf = textbuf + *length;
pr_debug("Sending key: %s=%s\n", er->key, er->value);
}
iscsi_release_extra_responses(param_list);
return 0;
}
int iscsi_check_negotiated_keys(struct iscsi_param_list *param_list)
{
int ret = 0;
struct iscsi_param *param;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (IS_PSTATE_NEGOTIATE(param) &&
IS_PSTATE_PROPOSER(param) &&
!IS_PSTATE_RESPONSE_GOT(param) &&
!IS_PSTATE_REPLY_OPTIONAL(param) &&
!IS_PHASE_DECLARATIVE(param)) {
pr_err("No response for proposed key \"%s\".\n",
param->name);
ret = -1;
}
}
return ret;
}
int iscsi_change_param_value(
char *keyvalue,
struct iscsi_param_list *param_list,
int check_key)
{
char *key = NULL, *value = NULL;
struct iscsi_param *param;
int sender = 0;
if (iscsi_extract_key_value(keyvalue, &key, &value) < 0)
return -1;
if (!check_key) {
param = __iscsi_check_key(keyvalue, sender, param_list);
if (!param)
return -1;
} else {
param = iscsi_check_key(keyvalue, 0, sender, param_list);
if (!param)
return -1;
param->set_param = 1;
if (iscsi_check_value(param, value) < 0) {
param->set_param = 0;
return -1;
}
param->set_param = 0;
}
if (iscsi_update_param_value(param, value) < 0)
return -1;
return 0;
}
void iscsi_set_connection_parameters(
struct iscsi_conn_ops *ops,
struct iscsi_param_list *param_list)
{
char *tmpptr;
struct iscsi_param *param;
pr_debug("---------------------------------------------------"
"---------------\n");
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!IS_PSTATE_ACCEPTOR(param) && !IS_PSTATE_PROPOSER(param))
continue;
if (!strcmp(param->name, AUTHMETHOD)) {
pr_debug("AuthMethod: %s\n",
param->value);
} else if (!strcmp(param->name, HEADERDIGEST)) {
ops->HeaderDigest = !strcmp(param->value, CRC32C);
pr_debug("HeaderDigest: %s\n",
param->value);
} else if (!strcmp(param->name, DATADIGEST)) {
ops->DataDigest = !strcmp(param->value, CRC32C);
pr_debug("DataDigest: %s\n",
param->value);
} else if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH)) {
ops->MaxRecvDataSegmentLength =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("MaxRecvDataSegmentLength: %s\n",
param->value);
} else if (!strcmp(param->name, OFMARKER)) {
ops->OFMarker = !strcmp(param->value, YES);
pr_debug("OFMarker: %s\n",
param->value);
} else if (!strcmp(param->name, IFMARKER)) {
ops->IFMarker = !strcmp(param->value, YES);
pr_debug("IFMarker: %s\n",
param->value);
} else if (!strcmp(param->name, OFMARKINT)) {
ops->OFMarkInt =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("OFMarkInt: %s\n",
param->value);
} else if (!strcmp(param->name, IFMARKINT)) {
ops->IFMarkInt =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("IFMarkInt: %s\n",
param->value);
}
}
pr_debug("----------------------------------------------------"
"--------------\n");
}
void iscsi_set_session_parameters(
struct iscsi_sess_ops *ops,
struct iscsi_param_list *param_list,
int leading)
{
char *tmpptr;
struct iscsi_param *param;
pr_debug("----------------------------------------------------"
"--------------\n");
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!IS_PSTATE_ACCEPTOR(param) && !IS_PSTATE_PROPOSER(param))
continue;
if (!strcmp(param->name, INITIATORNAME)) {
if (!param->value)
continue;
if (leading)
snprintf(ops->InitiatorName,
sizeof(ops->InitiatorName),
"%s", param->value);
pr_debug("InitiatorName: %s\n",
param->value);
} else if (!strcmp(param->name, INITIATORALIAS)) {
if (!param->value)
continue;
snprintf(ops->InitiatorAlias,
sizeof(ops->InitiatorAlias),
"%s", param->value);
pr_debug("InitiatorAlias: %s\n",
param->value);
} else if (!strcmp(param->name, TARGETNAME)) {
if (!param->value)
continue;
if (leading)
snprintf(ops->TargetName,
sizeof(ops->TargetName),
"%s", param->value);
pr_debug("TargetName: %s\n",
param->value);
} else if (!strcmp(param->name, TARGETALIAS)) {
if (!param->value)
continue;
snprintf(ops->TargetAlias, sizeof(ops->TargetAlias),
"%s", param->value);
pr_debug("TargetAlias: %s\n",
param->value);
} else if (!strcmp(param->name, TARGETPORTALGROUPTAG)) {
ops->TargetPortalGroupTag =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("TargetPortalGroupTag: %s\n",
param->value);
} else if (!strcmp(param->name, MAXCONNECTIONS)) {
ops->MaxConnections =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("MaxConnections: %s\n",
param->value);
} else if (!strcmp(param->name, INITIALR2T)) {
ops->InitialR2T = !strcmp(param->value, YES);
pr_debug("InitialR2T: %s\n",
param->value);
} else if (!strcmp(param->name, IMMEDIATEDATA)) {
ops->ImmediateData = !strcmp(param->value, YES);
pr_debug("ImmediateData: %s\n",
param->value);
} else if (!strcmp(param->name, MAXBURSTLENGTH)) {
ops->MaxBurstLength =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("MaxBurstLength: %s\n",
param->value);
} else if (!strcmp(param->name, FIRSTBURSTLENGTH)) {
ops->FirstBurstLength =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("FirstBurstLength: %s\n",
param->value);
} else if (!strcmp(param->name, DEFAULTTIME2WAIT)) {
ops->DefaultTime2Wait =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("DefaultTime2Wait: %s\n",
param->value);
} else if (!strcmp(param->name, DEFAULTTIME2RETAIN)) {
ops->DefaultTime2Retain =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("DefaultTime2Retain: %s\n",
param->value);
} else if (!strcmp(param->name, MAXOUTSTANDINGR2T)) {
ops->MaxOutstandingR2T =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("MaxOutstandingR2T: %s\n",
param->value);
} else if (!strcmp(param->name, DATAPDUINORDER)) {
ops->DataPDUInOrder = !strcmp(param->value, YES);
pr_debug("DataPDUInOrder: %s\n",
param->value);
} else if (!strcmp(param->name, DATASEQUENCEINORDER)) {
ops->DataSequenceInOrder = !strcmp(param->value, YES);
pr_debug("DataSequenceInOrder: %s\n",
param->value);
} else if (!strcmp(param->name, ERRORRECOVERYLEVEL)) {
ops->ErrorRecoveryLevel =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("ErrorRecoveryLevel: %s\n",
param->value);
} else if (!strcmp(param->name, SESSIONTYPE)) {
ops->SessionType = !strcmp(param->value, DISCOVERY);
pr_debug("SessionType: %s\n",
param->value);
}
}
pr_debug("----------------------------------------------------"
"--------------\n");
}
| gpl-2.0 |
Alberto97/android_kernel_motorola_msm8226 | kernel/sched/clock.c | 3844 | 9077 | /*
* sched_clock for unstable cpu clocks
*
* Copyright (C) 2008 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
*
* Updates and enhancements:
* Copyright (C) 2008 Red Hat, Inc. Steven Rostedt <srostedt@redhat.com>
*
* Based on code by:
* Ingo Molnar <mingo@redhat.com>
* Guillaume Chazarain <guichaz@gmail.com>
*
*
* What:
*
* cpu_clock(i) provides a fast (execution time) high resolution
* clock with bounded drift between CPUs. The value of cpu_clock(i)
* is monotonic for constant i. The timestamp returned is in nanoseconds.
*
* ######################### BIG FAT WARNING ##########################
* # when comparing cpu_clock(i) to cpu_clock(j) for i != j, time can #
* # go backwards !! #
* ####################################################################
*
* There is no strict promise about the base, although it tends to start
* at 0 on boot (but people really shouldn't rely on that).
*
* cpu_clock(i) -- can be used from any context, including NMI.
* sched_clock_cpu(i) -- must be used with local IRQs disabled (implied by NMI)
* local_clock() -- is cpu_clock() on the current cpu.
*
* How:
*
* The implementation either uses sched_clock() when
* !CONFIG_HAVE_UNSTABLE_SCHED_CLOCK, which means in that case the
* sched_clock() is assumed to provide these properties (mostly it means
* the architecture provides a globally synchronized highres time source).
*
* Otherwise it tries to create a semi stable clock from a mixture of other
* clocks, including:
*
* - GTOD (clock monotomic)
* - sched_clock()
* - explicit idle events
*
* We use GTOD as base and use sched_clock() deltas to improve resolution. The
* deltas are filtered to provide monotonicity and keeping it within an
* expected window.
*
* Furthermore, explicit sleep and wakeup hooks allow us to account for time
* that is otherwise invisible (TSC gets stopped).
*
*
* Notes:
*
* The !IRQ-safetly of sched_clock() and sched_clock_cpu() comes from things
* like cpufreq interrupts that can change the base clock (TSC) multiplier
* and cause funny jumps in time -- although the filtering provided by
* sched_clock_cpu() should mitigate serious artifacts we cannot rely on it
* in general since for !CONFIG_HAVE_UNSTABLE_SCHED_CLOCK we fully rely on
* sched_clock().
*/
#include <linux/spinlock.h>
#include <linux/hardirq.h>
#include <linux/export.h>
#include <linux/percpu.h>
#include <linux/ktime.h>
#include <linux/sched.h>
/*
* Scheduler clock - returns current time in nanosec units.
* This is default implementation.
* Architectures and sub-architectures can override this.
*/
unsigned long long __attribute__((weak)) sched_clock(void)
{
return (unsigned long long)(jiffies - INITIAL_JIFFIES)
* (NSEC_PER_SEC / HZ);
}
EXPORT_SYMBOL_GPL(sched_clock);
__read_mostly int sched_clock_running;
#ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
__read_mostly int sched_clock_stable;
struct sched_clock_data {
u64 tick_raw;
u64 tick_gtod;
u64 clock;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct sched_clock_data, sched_clock_data);
static inline struct sched_clock_data *this_scd(void)
{
return &__get_cpu_var(sched_clock_data);
}
static inline struct sched_clock_data *cpu_sdc(int cpu)
{
return &per_cpu(sched_clock_data, cpu);
}
void sched_clock_init(void)
{
u64 ktime_now = ktime_to_ns(ktime_get());
int cpu;
for_each_possible_cpu(cpu) {
struct sched_clock_data *scd = cpu_sdc(cpu);
scd->tick_raw = 0;
scd->tick_gtod = ktime_now;
scd->clock = ktime_now;
}
sched_clock_running = 1;
}
/*
* min, max except they take wrapping into account
*/
static inline u64 wrap_min(u64 x, u64 y)
{
return (s64)(x - y) < 0 ? x : y;
}
static inline u64 wrap_max(u64 x, u64 y)
{
return (s64)(x - y) > 0 ? x : y;
}
/*
* update the percpu scd from the raw @now value
*
* - filter out backward motion
* - use the GTOD tick value to create a window to filter crazy TSC values
*/
static u64 sched_clock_local(struct sched_clock_data *scd)
{
u64 now, clock, old_clock, min_clock, max_clock;
s64 delta;
again:
now = sched_clock();
delta = now - scd->tick_raw;
if (unlikely(delta < 0))
delta = 0;
old_clock = scd->clock;
/*
* scd->clock = clamp(scd->tick_gtod + delta,
* max(scd->tick_gtod, scd->clock),
* scd->tick_gtod + TICK_NSEC);
*/
clock = scd->tick_gtod + delta;
min_clock = wrap_max(scd->tick_gtod, old_clock);
max_clock = wrap_max(old_clock, scd->tick_gtod + TICK_NSEC);
clock = wrap_max(clock, min_clock);
clock = wrap_min(clock, max_clock);
if (cmpxchg64(&scd->clock, old_clock, clock) != old_clock)
goto again;
return clock;
}
static u64 sched_clock_remote(struct sched_clock_data *scd)
{
struct sched_clock_data *my_scd = this_scd();
u64 this_clock, remote_clock;
u64 *ptr, old_val, val;
#if BITS_PER_LONG != 64
again:
/*
* Careful here: The local and the remote clock values need to
* be read out atomic as we need to compare the values and
* then update either the local or the remote side. So the
* cmpxchg64 below only protects one readout.
*
* We must reread via sched_clock_local() in the retry case on
* 32bit as an NMI could use sched_clock_local() via the
* tracer and hit between the readout of
* the low32bit and the high 32bit portion.
*/
this_clock = sched_clock_local(my_scd);
/*
* We must enforce atomic readout on 32bit, otherwise the
* update on the remote cpu can hit inbetween the readout of
* the low32bit and the high 32bit portion.
*/
remote_clock = cmpxchg64(&scd->clock, 0, 0);
#else
/*
* On 64bit the read of [my]scd->clock is atomic versus the
* update, so we can avoid the above 32bit dance.
*/
sched_clock_local(my_scd);
again:
this_clock = my_scd->clock;
remote_clock = scd->clock;
#endif
/*
* Use the opportunity that we have both locks
* taken to couple the two clocks: we take the
* larger time as the latest time for both
* runqueues. (this creates monotonic movement)
*/
if (likely((s64)(remote_clock - this_clock) < 0)) {
ptr = &scd->clock;
old_val = remote_clock;
val = this_clock;
} else {
/*
* Should be rare, but possible:
*/
ptr = &my_scd->clock;
old_val = this_clock;
val = remote_clock;
}
if (cmpxchg64(ptr, old_val, val) != old_val)
goto again;
return val;
}
/*
* Similar to cpu_clock(), but requires local IRQs to be disabled.
*
* See cpu_clock().
*/
u64 sched_clock_cpu(int cpu)
{
struct sched_clock_data *scd;
u64 clock;
WARN_ON_ONCE(!irqs_disabled());
if (sched_clock_stable)
return sched_clock();
if (unlikely(!sched_clock_running))
return 0ull;
scd = cpu_sdc(cpu);
if (cpu != smp_processor_id())
clock = sched_clock_remote(scd);
else
clock = sched_clock_local(scd);
return clock;
}
void sched_clock_tick(void)
{
struct sched_clock_data *scd;
u64 now, now_gtod;
if (sched_clock_stable)
return;
if (unlikely(!sched_clock_running))
return;
WARN_ON_ONCE(!irqs_disabled());
scd = this_scd();
now_gtod = ktime_to_ns(ktime_get());
now = sched_clock();
scd->tick_raw = now;
scd->tick_gtod = now_gtod;
sched_clock_local(scd);
}
/*
* We are going deep-idle (irqs are disabled):
*/
void sched_clock_idle_sleep_event(void)
{
sched_clock_cpu(smp_processor_id());
}
EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
/*
* We just idled delta nanoseconds (called with irqs disabled):
*/
void sched_clock_idle_wakeup_event(u64 delta_ns)
{
if (timekeeping_suspended)
return;
sched_clock_tick();
touch_softlockup_watchdog();
}
EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
/*
* As outlined at the top, provides a fast, high resolution, nanosecond
* time source that is monotonic per cpu argument and has bounded drift
* between cpus.
*
* ######################### BIG FAT WARNING ##########################
* # when comparing cpu_clock(i) to cpu_clock(j) for i != j, time can #
* # go backwards !! #
* ####################################################################
*/
u64 cpu_clock(int cpu)
{
u64 clock;
unsigned long flags;
local_irq_save(flags);
clock = sched_clock_cpu(cpu);
local_irq_restore(flags);
return clock;
}
/*
* Similar to cpu_clock() for the current cpu. Time will only be observed
* to be monotonic if care is taken to only compare timestampt taken on the
* same CPU.
*
* See cpu_clock().
*/
u64 local_clock(void)
{
u64 clock;
unsigned long flags;
local_irq_save(flags);
clock = sched_clock_cpu(smp_processor_id());
local_irq_restore(flags);
return clock;
}
#else /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
void sched_clock_init(void)
{
sched_clock_running = 1;
}
u64 sched_clock_cpu(int cpu)
{
if (unlikely(!sched_clock_running))
return 0;
return sched_clock();
}
u64 cpu_clock(int cpu)
{
return sched_clock_cpu(cpu);
}
u64 local_clock(void)
{
return sched_clock_cpu(0);
}
#endif /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
EXPORT_SYMBOL_GPL(cpu_clock);
EXPORT_SYMBOL_GPL(local_clock);
| gpl-2.0 |
MechanicalAndroids/android_kernel_motorola_msm8226 | kernel/sched/clock.c | 3844 | 9077 | /*
* sched_clock for unstable cpu clocks
*
* Copyright (C) 2008 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
*
* Updates and enhancements:
* Copyright (C) 2008 Red Hat, Inc. Steven Rostedt <srostedt@redhat.com>
*
* Based on code by:
* Ingo Molnar <mingo@redhat.com>
* Guillaume Chazarain <guichaz@gmail.com>
*
*
* What:
*
* cpu_clock(i) provides a fast (execution time) high resolution
* clock with bounded drift between CPUs. The value of cpu_clock(i)
* is monotonic for constant i. The timestamp returned is in nanoseconds.
*
* ######################### BIG FAT WARNING ##########################
* # when comparing cpu_clock(i) to cpu_clock(j) for i != j, time can #
* # go backwards !! #
* ####################################################################
*
* There is no strict promise about the base, although it tends to start
* at 0 on boot (but people really shouldn't rely on that).
*
* cpu_clock(i) -- can be used from any context, including NMI.
* sched_clock_cpu(i) -- must be used with local IRQs disabled (implied by NMI)
* local_clock() -- is cpu_clock() on the current cpu.
*
* How:
*
* The implementation either uses sched_clock() when
* !CONFIG_HAVE_UNSTABLE_SCHED_CLOCK, which means in that case the
* sched_clock() is assumed to provide these properties (mostly it means
* the architecture provides a globally synchronized highres time source).
*
* Otherwise it tries to create a semi stable clock from a mixture of other
* clocks, including:
*
* - GTOD (clock monotomic)
* - sched_clock()
* - explicit idle events
*
* We use GTOD as base and use sched_clock() deltas to improve resolution. The
* deltas are filtered to provide monotonicity and keeping it within an
* expected window.
*
* Furthermore, explicit sleep and wakeup hooks allow us to account for time
* that is otherwise invisible (TSC gets stopped).
*
*
* Notes:
*
* The !IRQ-safetly of sched_clock() and sched_clock_cpu() comes from things
* like cpufreq interrupts that can change the base clock (TSC) multiplier
* and cause funny jumps in time -- although the filtering provided by
* sched_clock_cpu() should mitigate serious artifacts we cannot rely on it
* in general since for !CONFIG_HAVE_UNSTABLE_SCHED_CLOCK we fully rely on
* sched_clock().
*/
#include <linux/spinlock.h>
#include <linux/hardirq.h>
#include <linux/export.h>
#include <linux/percpu.h>
#include <linux/ktime.h>
#include <linux/sched.h>
/*
* Scheduler clock - returns current time in nanosec units.
* This is default implementation.
* Architectures and sub-architectures can override this.
*/
unsigned long long __attribute__((weak)) sched_clock(void)
{
return (unsigned long long)(jiffies - INITIAL_JIFFIES)
* (NSEC_PER_SEC / HZ);
}
EXPORT_SYMBOL_GPL(sched_clock);
__read_mostly int sched_clock_running;
#ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
__read_mostly int sched_clock_stable;
struct sched_clock_data {
u64 tick_raw;
u64 tick_gtod;
u64 clock;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct sched_clock_data, sched_clock_data);
static inline struct sched_clock_data *this_scd(void)
{
return &__get_cpu_var(sched_clock_data);
}
static inline struct sched_clock_data *cpu_sdc(int cpu)
{
return &per_cpu(sched_clock_data, cpu);
}
void sched_clock_init(void)
{
u64 ktime_now = ktime_to_ns(ktime_get());
int cpu;
for_each_possible_cpu(cpu) {
struct sched_clock_data *scd = cpu_sdc(cpu);
scd->tick_raw = 0;
scd->tick_gtod = ktime_now;
scd->clock = ktime_now;
}
sched_clock_running = 1;
}
/*
* min, max except they take wrapping into account
*/
static inline u64 wrap_min(u64 x, u64 y)
{
return (s64)(x - y) < 0 ? x : y;
}
static inline u64 wrap_max(u64 x, u64 y)
{
return (s64)(x - y) > 0 ? x : y;
}
/*
* update the percpu scd from the raw @now value
*
* - filter out backward motion
* - use the GTOD tick value to create a window to filter crazy TSC values
*/
static u64 sched_clock_local(struct sched_clock_data *scd)
{
u64 now, clock, old_clock, min_clock, max_clock;
s64 delta;
again:
now = sched_clock();
delta = now - scd->tick_raw;
if (unlikely(delta < 0))
delta = 0;
old_clock = scd->clock;
/*
* scd->clock = clamp(scd->tick_gtod + delta,
* max(scd->tick_gtod, scd->clock),
* scd->tick_gtod + TICK_NSEC);
*/
clock = scd->tick_gtod + delta;
min_clock = wrap_max(scd->tick_gtod, old_clock);
max_clock = wrap_max(old_clock, scd->tick_gtod + TICK_NSEC);
clock = wrap_max(clock, min_clock);
clock = wrap_min(clock, max_clock);
if (cmpxchg64(&scd->clock, old_clock, clock) != old_clock)
goto again;
return clock;
}
static u64 sched_clock_remote(struct sched_clock_data *scd)
{
struct sched_clock_data *my_scd = this_scd();
u64 this_clock, remote_clock;
u64 *ptr, old_val, val;
#if BITS_PER_LONG != 64
again:
/*
* Careful here: The local and the remote clock values need to
* be read out atomic as we need to compare the values and
* then update either the local or the remote side. So the
* cmpxchg64 below only protects one readout.
*
* We must reread via sched_clock_local() in the retry case on
* 32bit as an NMI could use sched_clock_local() via the
* tracer and hit between the readout of
* the low32bit and the high 32bit portion.
*/
this_clock = sched_clock_local(my_scd);
/*
* We must enforce atomic readout on 32bit, otherwise the
* update on the remote cpu can hit inbetween the readout of
* the low32bit and the high 32bit portion.
*/
remote_clock = cmpxchg64(&scd->clock, 0, 0);
#else
/*
* On 64bit the read of [my]scd->clock is atomic versus the
* update, so we can avoid the above 32bit dance.
*/
sched_clock_local(my_scd);
again:
this_clock = my_scd->clock;
remote_clock = scd->clock;
#endif
/*
* Use the opportunity that we have both locks
* taken to couple the two clocks: we take the
* larger time as the latest time for both
* runqueues. (this creates monotonic movement)
*/
if (likely((s64)(remote_clock - this_clock) < 0)) {
ptr = &scd->clock;
old_val = remote_clock;
val = this_clock;
} else {
/*
* Should be rare, but possible:
*/
ptr = &my_scd->clock;
old_val = this_clock;
val = remote_clock;
}
if (cmpxchg64(ptr, old_val, val) != old_val)
goto again;
return val;
}
/*
* Similar to cpu_clock(), but requires local IRQs to be disabled.
*
* See cpu_clock().
*/
u64 sched_clock_cpu(int cpu)
{
struct sched_clock_data *scd;
u64 clock;
WARN_ON_ONCE(!irqs_disabled());
if (sched_clock_stable)
return sched_clock();
if (unlikely(!sched_clock_running))
return 0ull;
scd = cpu_sdc(cpu);
if (cpu != smp_processor_id())
clock = sched_clock_remote(scd);
else
clock = sched_clock_local(scd);
return clock;
}
void sched_clock_tick(void)
{
struct sched_clock_data *scd;
u64 now, now_gtod;
if (sched_clock_stable)
return;
if (unlikely(!sched_clock_running))
return;
WARN_ON_ONCE(!irqs_disabled());
scd = this_scd();
now_gtod = ktime_to_ns(ktime_get());
now = sched_clock();
scd->tick_raw = now;
scd->tick_gtod = now_gtod;
sched_clock_local(scd);
}
/*
* We are going deep-idle (irqs are disabled):
*/
void sched_clock_idle_sleep_event(void)
{
sched_clock_cpu(smp_processor_id());
}
EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
/*
* We just idled delta nanoseconds (called with irqs disabled):
*/
void sched_clock_idle_wakeup_event(u64 delta_ns)
{
if (timekeeping_suspended)
return;
sched_clock_tick();
touch_softlockup_watchdog();
}
EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
/*
* As outlined at the top, provides a fast, high resolution, nanosecond
* time source that is monotonic per cpu argument and has bounded drift
* between cpus.
*
* ######################### BIG FAT WARNING ##########################
* # when comparing cpu_clock(i) to cpu_clock(j) for i != j, time can #
* # go backwards !! #
* ####################################################################
*/
u64 cpu_clock(int cpu)
{
u64 clock;
unsigned long flags;
local_irq_save(flags);
clock = sched_clock_cpu(cpu);
local_irq_restore(flags);
return clock;
}
/*
* Similar to cpu_clock() for the current cpu. Time will only be observed
* to be monotonic if care is taken to only compare timestampt taken on the
* same CPU.
*
* See cpu_clock().
*/
u64 local_clock(void)
{
u64 clock;
unsigned long flags;
local_irq_save(flags);
clock = sched_clock_cpu(smp_processor_id());
local_irq_restore(flags);
return clock;
}
#else /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
void sched_clock_init(void)
{
sched_clock_running = 1;
}
u64 sched_clock_cpu(int cpu)
{
if (unlikely(!sched_clock_running))
return 0;
return sched_clock();
}
u64 cpu_clock(int cpu)
{
return sched_clock_cpu(cpu);
}
u64 local_clock(void)
{
return sched_clock_cpu(0);
}
#endif /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
EXPORT_SYMBOL_GPL(cpu_clock);
EXPORT_SYMBOL_GPL(local_clock);
| gpl-2.0 |
walter79/android_kernel_sony_tsubasa | drivers/cpuidle/driver.c | 4356 | 2214 | /*
* driver.c - driver support
*
* (C) 2006-2007 Venkatesh Pallipadi <venkatesh.pallipadi@intel.com>
* Shaohua Li <shaohua.li@intel.com>
* Adam Belay <abelay@novell.com>
*
* This code is licenced under the GPL.
*/
#include <linux/mutex.h>
#include <linux/module.h>
#include <linux/cpuidle.h>
#include "cpuidle.h"
static struct cpuidle_driver *cpuidle_curr_driver;
DEFINE_SPINLOCK(cpuidle_driver_lock);
static void __cpuidle_register_driver(struct cpuidle_driver *drv)
{
int i;
/*
* cpuidle driver should set the drv->power_specified bit
* before registering if the driver provides
* power_usage numbers.
*
* If power_specified is not set,
* we fill in power_usage with decreasing values as the
* cpuidle code has an implicit assumption that state Cn
* uses less power than C(n-1).
*
* With CONFIG_ARCH_HAS_CPU_RELAX, C0 is already assigned
* an power value of -1. So we use -2, -3, etc, for other
* c-states.
*/
if (!drv->power_specified) {
for (i = CPUIDLE_DRIVER_STATE_START; i < drv->state_count; i++)
drv->states[i].power_usage = -1 - i;
}
}
/**
* cpuidle_register_driver - registers a driver
* @drv: the driver
*/
int cpuidle_register_driver(struct cpuidle_driver *drv)
{
if (!drv || !drv->state_count)
return -EINVAL;
if (cpuidle_disabled())
return -ENODEV;
spin_lock(&cpuidle_driver_lock);
if (cpuidle_curr_driver) {
spin_unlock(&cpuidle_driver_lock);
return -EBUSY;
}
__cpuidle_register_driver(drv);
cpuidle_curr_driver = drv;
spin_unlock(&cpuidle_driver_lock);
return 0;
}
EXPORT_SYMBOL_GPL(cpuidle_register_driver);
/**
* cpuidle_get_driver - return the current driver
*/
struct cpuidle_driver *cpuidle_get_driver(void)
{
return cpuidle_curr_driver;
}
EXPORT_SYMBOL_GPL(cpuidle_get_driver);
/**
* cpuidle_unregister_driver - unregisters a driver
* @drv: the driver
*/
void cpuidle_unregister_driver(struct cpuidle_driver *drv)
{
if (drv != cpuidle_curr_driver) {
WARN(1, "invalid cpuidle_unregister_driver(%s)\n",
drv->name);
return;
}
spin_lock(&cpuidle_driver_lock);
cpuidle_curr_driver = NULL;
spin_unlock(&cpuidle_driver_lock);
}
EXPORT_SYMBOL_GPL(cpuidle_unregister_driver);
| gpl-2.0 |
tamirda/G900F_PhoeniX_Kernel_Lollipop_OLD | kernel/auditfilter.c | 4868 | 34129 | /* auditfilter.c -- filtering of audit events
*
* Copyright 2003-2004 Red Hat, Inc.
* Copyright 2005 Hewlett-Packard Development Company, L.P.
* Copyright 2005 IBM Corporation
*
* 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/kernel.h>
#include <linux/audit.h>
#include <linux/kthread.h>
#include <linux/mutex.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/netlink.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/security.h>
#include "audit.h"
/*
* Locking model:
*
* audit_filter_mutex:
* Synchronizes writes and blocking reads of audit's filterlist
* data. Rcu is used to traverse the filterlist and access
* contents of structs audit_entry, audit_watch and opaque
* LSM rules during filtering. If modified, these structures
* must be copied and replace their counterparts in the filterlist.
* An audit_parent struct is not accessed during filtering, so may
* be written directly provided audit_filter_mutex is held.
*/
/* Audit filter lists, defined in <linux/audit.h> */
struct list_head audit_filter_list[AUDIT_NR_FILTERS] = {
LIST_HEAD_INIT(audit_filter_list[0]),
LIST_HEAD_INIT(audit_filter_list[1]),
LIST_HEAD_INIT(audit_filter_list[2]),
LIST_HEAD_INIT(audit_filter_list[3]),
LIST_HEAD_INIT(audit_filter_list[4]),
LIST_HEAD_INIT(audit_filter_list[5]),
#if AUDIT_NR_FILTERS != 6
#error Fix audit_filter_list initialiser
#endif
};
static struct list_head audit_rules_list[AUDIT_NR_FILTERS] = {
LIST_HEAD_INIT(audit_rules_list[0]),
LIST_HEAD_INIT(audit_rules_list[1]),
LIST_HEAD_INIT(audit_rules_list[2]),
LIST_HEAD_INIT(audit_rules_list[3]),
LIST_HEAD_INIT(audit_rules_list[4]),
LIST_HEAD_INIT(audit_rules_list[5]),
};
DEFINE_MUTEX(audit_filter_mutex);
static inline void audit_free_rule(struct audit_entry *e)
{
int i;
struct audit_krule *erule = &e->rule;
/* some rules don't have associated watches */
if (erule->watch)
audit_put_watch(erule->watch);
if (erule->fields)
for (i = 0; i < erule->field_count; i++) {
struct audit_field *f = &erule->fields[i];
kfree(f->lsm_str);
security_audit_rule_free(f->lsm_rule);
}
kfree(erule->fields);
kfree(erule->filterkey);
kfree(e);
}
void audit_free_rule_rcu(struct rcu_head *head)
{
struct audit_entry *e = container_of(head, struct audit_entry, rcu);
audit_free_rule(e);
}
/* Initialize an audit filterlist entry. */
static inline struct audit_entry *audit_init_entry(u32 field_count)
{
struct audit_entry *entry;
struct audit_field *fields;
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (unlikely(!entry))
return NULL;
fields = kzalloc(sizeof(*fields) * field_count, GFP_KERNEL);
if (unlikely(!fields)) {
kfree(entry);
return NULL;
}
entry->rule.fields = fields;
return entry;
}
/* Unpack a filter field's string representation from user-space
* buffer. */
char *audit_unpack_string(void **bufp, size_t *remain, size_t len)
{
char *str;
if (!*bufp || (len == 0) || (len > *remain))
return ERR_PTR(-EINVAL);
/* Of the currently implemented string fields, PATH_MAX
* defines the longest valid length.
*/
if (len > PATH_MAX)
return ERR_PTR(-ENAMETOOLONG);
str = kmalloc(len + 1, GFP_KERNEL);
if (unlikely(!str))
return ERR_PTR(-ENOMEM);
memcpy(str, *bufp, len);
str[len] = 0;
*bufp += len;
*remain -= len;
return str;
}
/* Translate an inode field to kernel respresentation. */
static inline int audit_to_inode(struct audit_krule *krule,
struct audit_field *f)
{
if (krule->listnr != AUDIT_FILTER_EXIT ||
krule->watch || krule->inode_f || krule->tree ||
(f->op != Audit_equal && f->op != Audit_not_equal))
return -EINVAL;
krule->inode_f = f;
return 0;
}
static __u32 *classes[AUDIT_SYSCALL_CLASSES];
int __init audit_register_class(int class, unsigned *list)
{
__u32 *p = kzalloc(AUDIT_BITMASK_SIZE * sizeof(__u32), GFP_KERNEL);
if (!p)
return -ENOMEM;
while (*list != ~0U) {
unsigned n = *list++;
if (n >= AUDIT_BITMASK_SIZE * 32 - AUDIT_SYSCALL_CLASSES) {
kfree(p);
return -EINVAL;
}
p[AUDIT_WORD(n)] |= AUDIT_BIT(n);
}
if (class >= AUDIT_SYSCALL_CLASSES || classes[class]) {
kfree(p);
return -EINVAL;
}
classes[class] = p;
return 0;
}
int audit_match_class(int class, unsigned syscall)
{
if (unlikely(syscall >= AUDIT_BITMASK_SIZE * 32))
return 0;
if (unlikely(class >= AUDIT_SYSCALL_CLASSES || !classes[class]))
return 0;
return classes[class][AUDIT_WORD(syscall)] & AUDIT_BIT(syscall);
}
#ifdef CONFIG_AUDITSYSCALL
static inline int audit_match_class_bits(int class, u32 *mask)
{
int i;
if (classes[class]) {
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
if (mask[i] & classes[class][i])
return 0;
}
return 1;
}
static int audit_match_signal(struct audit_entry *entry)
{
struct audit_field *arch = entry->rule.arch_f;
if (!arch) {
/* When arch is unspecified, we must check both masks on biarch
* as syscall number alone is ambiguous. */
return (audit_match_class_bits(AUDIT_CLASS_SIGNAL,
entry->rule.mask) &&
audit_match_class_bits(AUDIT_CLASS_SIGNAL_32,
entry->rule.mask));
}
switch(audit_classify_arch(arch->val)) {
case 0: /* native */
return (audit_match_class_bits(AUDIT_CLASS_SIGNAL,
entry->rule.mask));
case 1: /* 32bit on biarch */
return (audit_match_class_bits(AUDIT_CLASS_SIGNAL_32,
entry->rule.mask));
default:
return 1;
}
}
#endif
/* Common user-space to kernel rule translation. */
static inline struct audit_entry *audit_to_entry_common(struct audit_rule *rule)
{
unsigned listnr;
struct audit_entry *entry;
int i, err;
err = -EINVAL;
listnr = rule->flags & ~AUDIT_FILTER_PREPEND;
switch(listnr) {
default:
goto exit_err;
#ifdef CONFIG_AUDITSYSCALL
case AUDIT_FILTER_ENTRY:
if (rule->action == AUDIT_ALWAYS)
goto exit_err;
case AUDIT_FILTER_EXIT:
case AUDIT_FILTER_TASK:
#endif
case AUDIT_FILTER_USER:
case AUDIT_FILTER_TYPE:
;
}
if (unlikely(rule->action == AUDIT_POSSIBLE)) {
printk(KERN_ERR "AUDIT_POSSIBLE is deprecated\n");
goto exit_err;
}
if (rule->action != AUDIT_NEVER && rule->action != AUDIT_ALWAYS)
goto exit_err;
if (rule->field_count > AUDIT_MAX_FIELDS)
goto exit_err;
err = -ENOMEM;
entry = audit_init_entry(rule->field_count);
if (!entry)
goto exit_err;
entry->rule.flags = rule->flags & AUDIT_FILTER_PREPEND;
entry->rule.listnr = listnr;
entry->rule.action = rule->action;
entry->rule.field_count = rule->field_count;
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
entry->rule.mask[i] = rule->mask[i];
for (i = 0; i < AUDIT_SYSCALL_CLASSES; i++) {
int bit = AUDIT_BITMASK_SIZE * 32 - i - 1;
__u32 *p = &entry->rule.mask[AUDIT_WORD(bit)];
__u32 *class;
if (!(*p & AUDIT_BIT(bit)))
continue;
*p &= ~AUDIT_BIT(bit);
class = classes[i];
if (class) {
int j;
for (j = 0; j < AUDIT_BITMASK_SIZE; j++)
entry->rule.mask[j] |= class[j];
}
}
return entry;
exit_err:
return ERR_PTR(err);
}
static u32 audit_ops[] =
{
[Audit_equal] = AUDIT_EQUAL,
[Audit_not_equal] = AUDIT_NOT_EQUAL,
[Audit_bitmask] = AUDIT_BIT_MASK,
[Audit_bittest] = AUDIT_BIT_TEST,
[Audit_lt] = AUDIT_LESS_THAN,
[Audit_gt] = AUDIT_GREATER_THAN,
[Audit_le] = AUDIT_LESS_THAN_OR_EQUAL,
[Audit_ge] = AUDIT_GREATER_THAN_OR_EQUAL,
};
static u32 audit_to_op(u32 op)
{
u32 n;
for (n = Audit_equal; n < Audit_bad && audit_ops[n] != op; n++)
;
return n;
}
/* Translate struct audit_rule to kernel's rule respresentation.
* Exists for backward compatibility with userspace. */
static struct audit_entry *audit_rule_to_entry(struct audit_rule *rule)
{
struct audit_entry *entry;
int err = 0;
int i;
entry = audit_to_entry_common(rule);
if (IS_ERR(entry))
goto exit_nofree;
for (i = 0; i < rule->field_count; i++) {
struct audit_field *f = &entry->rule.fields[i];
u32 n;
n = rule->fields[i] & (AUDIT_NEGATE|AUDIT_OPERATORS);
/* Support for legacy operators where
* AUDIT_NEGATE bit signifies != and otherwise assumes == */
if (n & AUDIT_NEGATE)
f->op = Audit_not_equal;
else if (!n)
f->op = Audit_equal;
else
f->op = audit_to_op(n);
entry->rule.vers_ops = (n & AUDIT_OPERATORS) ? 2 : 1;
f->type = rule->fields[i] & ~(AUDIT_NEGATE|AUDIT_OPERATORS);
f->val = rule->values[i];
err = -EINVAL;
if (f->op == Audit_bad)
goto exit_free;
switch(f->type) {
default:
goto exit_free;
case AUDIT_PID:
case AUDIT_UID:
case AUDIT_EUID:
case AUDIT_SUID:
case AUDIT_FSUID:
case AUDIT_GID:
case AUDIT_EGID:
case AUDIT_SGID:
case AUDIT_FSGID:
case AUDIT_LOGINUID:
case AUDIT_PERS:
case AUDIT_MSGTYPE:
case AUDIT_PPID:
case AUDIT_DEVMAJOR:
case AUDIT_DEVMINOR:
case AUDIT_EXIT:
case AUDIT_SUCCESS:
/* bit ops are only useful on syscall args */
if (f->op == Audit_bitmask || f->op == Audit_bittest)
goto exit_free;
break;
case AUDIT_ARG0:
case AUDIT_ARG1:
case AUDIT_ARG2:
case AUDIT_ARG3:
break;
/* arch is only allowed to be = or != */
case AUDIT_ARCH:
if (f->op != Audit_not_equal && f->op != Audit_equal)
goto exit_free;
entry->rule.arch_f = f;
break;
case AUDIT_PERM:
if (f->val & ~15)
goto exit_free;
break;
case AUDIT_FILETYPE:
if (f->val & ~S_IFMT)
goto exit_free;
break;
case AUDIT_INODE:
err = audit_to_inode(&entry->rule, f);
if (err)
goto exit_free;
break;
}
}
if (entry->rule.inode_f && entry->rule.inode_f->op == Audit_not_equal)
entry->rule.inode_f = NULL;
exit_nofree:
return entry;
exit_free:
audit_free_rule(entry);
return ERR_PTR(err);
}
/* Translate struct audit_rule_data to kernel's rule respresentation. */
static struct audit_entry *audit_data_to_entry(struct audit_rule_data *data,
size_t datasz)
{
int err = 0;
struct audit_entry *entry;
void *bufp;
size_t remain = datasz - sizeof(struct audit_rule_data);
int i;
char *str;
entry = audit_to_entry_common((struct audit_rule *)data);
if (IS_ERR(entry))
goto exit_nofree;
bufp = data->buf;
entry->rule.vers_ops = 2;
for (i = 0; i < data->field_count; i++) {
struct audit_field *f = &entry->rule.fields[i];
err = -EINVAL;
f->op = audit_to_op(data->fieldflags[i]);
if (f->op == Audit_bad)
goto exit_free;
f->type = data->fields[i];
f->val = data->values[i];
f->lsm_str = NULL;
f->lsm_rule = NULL;
switch(f->type) {
case AUDIT_PID:
case AUDIT_UID:
case AUDIT_EUID:
case AUDIT_SUID:
case AUDIT_FSUID:
case AUDIT_GID:
case AUDIT_EGID:
case AUDIT_SGID:
case AUDIT_FSGID:
case AUDIT_LOGINUID:
case AUDIT_PERS:
case AUDIT_MSGTYPE:
case AUDIT_PPID:
case AUDIT_DEVMAJOR:
case AUDIT_DEVMINOR:
case AUDIT_EXIT:
case AUDIT_SUCCESS:
case AUDIT_ARG0:
case AUDIT_ARG1:
case AUDIT_ARG2:
case AUDIT_ARG3:
case AUDIT_OBJ_UID:
case AUDIT_OBJ_GID:
break;
case AUDIT_ARCH:
entry->rule.arch_f = f;
break;
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = security_audit_rule_init(f->type, f->op, str,
(void **)&f->lsm_rule);
/* Keep currently invalid fields around in case they
* become valid after a policy reload. */
if (err == -EINVAL) {
printk(KERN_WARNING "audit rule for LSM "
"\'%s\' is invalid\n", str);
err = 0;
}
if (err) {
kfree(str);
goto exit_free;
} else
f->lsm_str = str;
break;
case AUDIT_WATCH:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = audit_to_watch(&entry->rule, str, f->val, f->op);
if (err) {
kfree(str);
goto exit_free;
}
break;
case AUDIT_DIR:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = audit_make_tree(&entry->rule, str, f->op);
kfree(str);
if (err)
goto exit_free;
break;
case AUDIT_INODE:
err = audit_to_inode(&entry->rule, f);
if (err)
goto exit_free;
break;
case AUDIT_FILTERKEY:
if (entry->rule.filterkey || f->val > AUDIT_MAX_KEY_LEN)
goto exit_free;
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
entry->rule.filterkey = str;
break;
case AUDIT_PERM:
if (f->val & ~15)
goto exit_free;
break;
case AUDIT_FILETYPE:
if (f->val & ~S_IFMT)
goto exit_free;
break;
case AUDIT_FIELD_COMPARE:
if (f->val > AUDIT_MAX_FIELD_COMPARE)
goto exit_free;
break;
default:
goto exit_free;
}
}
if (entry->rule.inode_f && entry->rule.inode_f->op == Audit_not_equal)
entry->rule.inode_f = NULL;
exit_nofree:
return entry;
exit_free:
audit_free_rule(entry);
return ERR_PTR(err);
}
/* Pack a filter field's string representation into data block. */
static inline size_t audit_pack_string(void **bufp, const char *str)
{
size_t len = strlen(str);
memcpy(*bufp, str, len);
*bufp += len;
return len;
}
/* Translate kernel rule respresentation to struct audit_rule.
* Exists for backward compatibility with userspace. */
static struct audit_rule *audit_krule_to_rule(struct audit_krule *krule)
{
struct audit_rule *rule;
int i;
rule = kzalloc(sizeof(*rule), GFP_KERNEL);
if (unlikely(!rule))
return NULL;
rule->flags = krule->flags | krule->listnr;
rule->action = krule->action;
rule->field_count = krule->field_count;
for (i = 0; i < rule->field_count; i++) {
rule->values[i] = krule->fields[i].val;
rule->fields[i] = krule->fields[i].type;
if (krule->vers_ops == 1) {
if (krule->fields[i].op == Audit_not_equal)
rule->fields[i] |= AUDIT_NEGATE;
} else {
rule->fields[i] |= audit_ops[krule->fields[i].op];
}
}
for (i = 0; i < AUDIT_BITMASK_SIZE; i++) rule->mask[i] = krule->mask[i];
return rule;
}
/* Translate kernel rule respresentation to struct audit_rule_data. */
static struct audit_rule_data *audit_krule_to_data(struct audit_krule *krule)
{
struct audit_rule_data *data;
void *bufp;
int i;
data = kmalloc(sizeof(*data) + krule->buflen, GFP_KERNEL);
if (unlikely(!data))
return NULL;
memset(data, 0, sizeof(*data));
data->flags = krule->flags | krule->listnr;
data->action = krule->action;
data->field_count = krule->field_count;
bufp = data->buf;
for (i = 0; i < data->field_count; i++) {
struct audit_field *f = &krule->fields[i];
data->fields[i] = f->type;
data->fieldflags[i] = audit_ops[f->op];
switch(f->type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
data->buflen += data->values[i] =
audit_pack_string(&bufp, f->lsm_str);
break;
case AUDIT_WATCH:
data->buflen += data->values[i] =
audit_pack_string(&bufp,
audit_watch_path(krule->watch));
break;
case AUDIT_DIR:
data->buflen += data->values[i] =
audit_pack_string(&bufp,
audit_tree_path(krule->tree));
break;
case AUDIT_FILTERKEY:
data->buflen += data->values[i] =
audit_pack_string(&bufp, krule->filterkey);
break;
default:
data->values[i] = f->val;
}
}
for (i = 0; i < AUDIT_BITMASK_SIZE; i++) data->mask[i] = krule->mask[i];
return data;
}
/* Compare two rules in kernel format. Considered success if rules
* don't match. */
static int audit_compare_rule(struct audit_krule *a, struct audit_krule *b)
{
int i;
if (a->flags != b->flags ||
a->listnr != b->listnr ||
a->action != b->action ||
a->field_count != b->field_count)
return 1;
for (i = 0; i < a->field_count; i++) {
if (a->fields[i].type != b->fields[i].type ||
a->fields[i].op != b->fields[i].op)
return 1;
switch(a->fields[i].type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
if (strcmp(a->fields[i].lsm_str, b->fields[i].lsm_str))
return 1;
break;
case AUDIT_WATCH:
if (strcmp(audit_watch_path(a->watch),
audit_watch_path(b->watch)))
return 1;
break;
case AUDIT_DIR:
if (strcmp(audit_tree_path(a->tree),
audit_tree_path(b->tree)))
return 1;
break;
case AUDIT_FILTERKEY:
/* both filterkeys exist based on above type compare */
if (strcmp(a->filterkey, b->filterkey))
return 1;
break;
default:
if (a->fields[i].val != b->fields[i].val)
return 1;
}
}
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
if (a->mask[i] != b->mask[i])
return 1;
return 0;
}
/* Duplicate LSM field information. The lsm_rule is opaque, so must be
* re-initialized. */
static inline int audit_dupe_lsm_field(struct audit_field *df,
struct audit_field *sf)
{
int ret = 0;
char *lsm_str;
/* our own copy of lsm_str */
lsm_str = kstrdup(sf->lsm_str, GFP_KERNEL);
if (unlikely(!lsm_str))
return -ENOMEM;
df->lsm_str = lsm_str;
/* our own (refreshed) copy of lsm_rule */
ret = security_audit_rule_init(df->type, df->op, df->lsm_str,
(void **)&df->lsm_rule);
/* Keep currently invalid fields around in case they
* become valid after a policy reload. */
if (ret == -EINVAL) {
printk(KERN_WARNING "audit rule for LSM \'%s\' is "
"invalid\n", df->lsm_str);
ret = 0;
}
return ret;
}
/* Duplicate an audit rule. This will be a deep copy with the exception
* of the watch - that pointer is carried over. The LSM specific fields
* will be updated in the copy. The point is to be able to replace the old
* rule with the new rule in the filterlist, then free the old rule.
* The rlist element is undefined; list manipulations are handled apart from
* the initial copy. */
struct audit_entry *audit_dupe_rule(struct audit_krule *old)
{
u32 fcount = old->field_count;
struct audit_entry *entry;
struct audit_krule *new;
char *fk;
int i, err = 0;
entry = audit_init_entry(fcount);
if (unlikely(!entry))
return ERR_PTR(-ENOMEM);
new = &entry->rule;
new->vers_ops = old->vers_ops;
new->flags = old->flags;
new->listnr = old->listnr;
new->action = old->action;
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
new->mask[i] = old->mask[i];
new->prio = old->prio;
new->buflen = old->buflen;
new->inode_f = old->inode_f;
new->field_count = old->field_count;
/*
* note that we are OK with not refcounting here; audit_match_tree()
* never dereferences tree and we can't get false positives there
* since we'd have to have rule gone from the list *and* removed
* before the chunks found by lookup had been allocated, i.e. before
* the beginning of list scan.
*/
new->tree = old->tree;
memcpy(new->fields, old->fields, sizeof(struct audit_field) * fcount);
/* deep copy this information, updating the lsm_rule fields, because
* the originals will all be freed when the old rule is freed. */
for (i = 0; i < fcount; i++) {
switch (new->fields[i].type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
err = audit_dupe_lsm_field(&new->fields[i],
&old->fields[i]);
break;
case AUDIT_FILTERKEY:
fk = kstrdup(old->filterkey, GFP_KERNEL);
if (unlikely(!fk))
err = -ENOMEM;
else
new->filterkey = fk;
}
if (err) {
audit_free_rule(entry);
return ERR_PTR(err);
}
}
if (old->watch) {
audit_get_watch(old->watch);
new->watch = old->watch;
}
return entry;
}
/* Find an existing audit rule.
* Caller must hold audit_filter_mutex to prevent stale rule data. */
static struct audit_entry *audit_find_rule(struct audit_entry *entry,
struct list_head **p)
{
struct audit_entry *e, *found = NULL;
struct list_head *list;
int h;
if (entry->rule.inode_f) {
h = audit_hash_ino(entry->rule.inode_f->val);
*p = list = &audit_inode_hash[h];
} else if (entry->rule.watch) {
/* we don't know the inode number, so must walk entire hash */
for (h = 0; h < AUDIT_INODE_BUCKETS; h++) {
list = &audit_inode_hash[h];
list_for_each_entry(e, list, list)
if (!audit_compare_rule(&entry->rule, &e->rule)) {
found = e;
goto out;
}
}
goto out;
} else {
*p = list = &audit_filter_list[entry->rule.listnr];
}
list_for_each_entry(e, list, list)
if (!audit_compare_rule(&entry->rule, &e->rule)) {
found = e;
goto out;
}
out:
return found;
}
static u64 prio_low = ~0ULL/2;
static u64 prio_high = ~0ULL/2 - 1;
/* Add rule to given filterlist if not a duplicate. */
static inline int audit_add_rule(struct audit_entry *entry)
{
struct audit_entry *e;
struct audit_watch *watch = entry->rule.watch;
struct audit_tree *tree = entry->rule.tree;
struct list_head *list;
int err;
#ifdef CONFIG_AUDITSYSCALL
int dont_count = 0;
/* If either of these, don't count towards total */
if (entry->rule.listnr == AUDIT_FILTER_USER ||
entry->rule.listnr == AUDIT_FILTER_TYPE)
dont_count = 1;
#endif
mutex_lock(&audit_filter_mutex);
e = audit_find_rule(entry, &list);
if (e) {
mutex_unlock(&audit_filter_mutex);
err = -EEXIST;
/* normally audit_add_tree_rule() will free it on failure */
if (tree)
audit_put_tree(tree);
goto error;
}
if (watch) {
/* audit_filter_mutex is dropped and re-taken during this call */
err = audit_add_watch(&entry->rule, &list);
if (err) {
mutex_unlock(&audit_filter_mutex);
goto error;
}
}
if (tree) {
err = audit_add_tree_rule(&entry->rule);
if (err) {
mutex_unlock(&audit_filter_mutex);
goto error;
}
}
entry->rule.prio = ~0ULL;
if (entry->rule.listnr == AUDIT_FILTER_EXIT) {
if (entry->rule.flags & AUDIT_FILTER_PREPEND)
entry->rule.prio = ++prio_high;
else
entry->rule.prio = --prio_low;
}
if (entry->rule.flags & AUDIT_FILTER_PREPEND) {
list_add(&entry->rule.list,
&audit_rules_list[entry->rule.listnr]);
list_add_rcu(&entry->list, list);
entry->rule.flags &= ~AUDIT_FILTER_PREPEND;
} else {
list_add_tail(&entry->rule.list,
&audit_rules_list[entry->rule.listnr]);
list_add_tail_rcu(&entry->list, list);
}
#ifdef CONFIG_AUDITSYSCALL
if (!dont_count)
audit_n_rules++;
if (!audit_match_signal(entry))
audit_signals++;
#endif
mutex_unlock(&audit_filter_mutex);
return 0;
error:
if (watch)
audit_put_watch(watch); /* tmp watch, matches initial get */
return err;
}
/* Remove an existing rule from filterlist. */
static inline int audit_del_rule(struct audit_entry *entry)
{
struct audit_entry *e;
struct audit_watch *watch = entry->rule.watch;
struct audit_tree *tree = entry->rule.tree;
struct list_head *list;
int ret = 0;
#ifdef CONFIG_AUDITSYSCALL
int dont_count = 0;
/* If either of these, don't count towards total */
if (entry->rule.listnr == AUDIT_FILTER_USER ||
entry->rule.listnr == AUDIT_FILTER_TYPE)
dont_count = 1;
#endif
mutex_lock(&audit_filter_mutex);
e = audit_find_rule(entry, &list);
if (!e) {
mutex_unlock(&audit_filter_mutex);
ret = -ENOENT;
goto out;
}
if (e->rule.watch)
audit_remove_watch_rule(&e->rule);
if (e->rule.tree)
audit_remove_tree_rule(&e->rule);
list_del_rcu(&e->list);
list_del(&e->rule.list);
call_rcu(&e->rcu, audit_free_rule_rcu);
#ifdef CONFIG_AUDITSYSCALL
if (!dont_count)
audit_n_rules--;
if (!audit_match_signal(entry))
audit_signals--;
#endif
mutex_unlock(&audit_filter_mutex);
out:
if (watch)
audit_put_watch(watch); /* match initial get */
if (tree)
audit_put_tree(tree); /* that's the temporary one */
return ret;
}
/* List rules using struct audit_rule. Exists for backward
* compatibility with userspace. */
static void audit_list(int pid, int seq, struct sk_buff_head *q)
{
struct sk_buff *skb;
struct audit_krule *r;
int i;
/* This is a blocking read, so use audit_filter_mutex instead of rcu
* iterator to sync with list writers. */
for (i=0; i<AUDIT_NR_FILTERS; i++) {
list_for_each_entry(r, &audit_rules_list[i], list) {
struct audit_rule *rule;
rule = audit_krule_to_rule(r);
if (unlikely(!rule))
break;
skb = audit_make_reply(pid, seq, AUDIT_LIST, 0, 1,
rule, sizeof(*rule));
if (skb)
skb_queue_tail(q, skb);
kfree(rule);
}
}
skb = audit_make_reply(pid, seq, AUDIT_LIST, 1, 1, NULL, 0);
if (skb)
skb_queue_tail(q, skb);
}
/* List rules using struct audit_rule_data. */
static void audit_list_rules(int pid, int seq, struct sk_buff_head *q)
{
struct sk_buff *skb;
struct audit_krule *r;
int i;
/* This is a blocking read, so use audit_filter_mutex instead of rcu
* iterator to sync with list writers. */
for (i=0; i<AUDIT_NR_FILTERS; i++) {
list_for_each_entry(r, &audit_rules_list[i], list) {
struct audit_rule_data *data;
data = audit_krule_to_data(r);
if (unlikely(!data))
break;
skb = audit_make_reply(pid, seq, AUDIT_LIST_RULES, 0, 1,
data, sizeof(*data) + data->buflen);
if (skb)
skb_queue_tail(q, skb);
kfree(data);
}
}
skb = audit_make_reply(pid, seq, AUDIT_LIST_RULES, 1, 1, NULL, 0);
if (skb)
skb_queue_tail(q, skb);
}
/* Log rule additions and removals */
static void audit_log_rule_change(uid_t loginuid, u32 sessionid, u32 sid,
char *action, struct audit_krule *rule,
int res)
{
struct audit_buffer *ab;
if (!audit_enabled)
return;
ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
if (!ab)
return;
audit_log_format(ab, "auid=%u ses=%u", loginuid, sessionid);
if (sid) {
char *ctx = NULL;
u32 len;
if (security_secid_to_secctx(sid, &ctx, &len))
audit_log_format(ab, " ssid=%u", sid);
else {
audit_log_format(ab, " subj=%s", ctx);
security_release_secctx(ctx, len);
}
}
audit_log_format(ab, " op=");
audit_log_string(ab, action);
audit_log_key(ab, rule->filterkey);
audit_log_format(ab, " list=%d res=%d", rule->listnr, res);
audit_log_end(ab);
}
/**
* audit_receive_filter - apply all rules to the specified message type
* @type: audit message type
* @pid: target pid for netlink audit messages
* @uid: target uid for netlink audit messages
* @seq: netlink audit message sequence (serial) number
* @data: payload data
* @datasz: size of payload data
* @loginuid: loginuid of sender
* @sessionid: sessionid for netlink audit message
* @sid: SE Linux Security ID of sender
*/
int audit_receive_filter(int type, int pid, int uid, int seq, void *data,
size_t datasz, uid_t loginuid, u32 sessionid, u32 sid)
{
struct task_struct *tsk;
struct audit_netlink_list *dest;
int err = 0;
struct audit_entry *entry;
switch (type) {
case AUDIT_LIST:
case AUDIT_LIST_RULES:
/* We can't just spew out the rules here because we might fill
* the available socket buffer space and deadlock waiting for
* auditctl to read from it... which isn't ever going to
* happen if we're actually running in the context of auditctl
* trying to _send_ the stuff */
dest = kmalloc(sizeof(struct audit_netlink_list), GFP_KERNEL);
if (!dest)
return -ENOMEM;
dest->pid = pid;
skb_queue_head_init(&dest->q);
mutex_lock(&audit_filter_mutex);
if (type == AUDIT_LIST)
audit_list(pid, seq, &dest->q);
else
audit_list_rules(pid, seq, &dest->q);
mutex_unlock(&audit_filter_mutex);
tsk = kthread_run(audit_send_list, dest, "audit_send_list");
if (IS_ERR(tsk)) {
skb_queue_purge(&dest->q);
kfree(dest);
err = PTR_ERR(tsk);
}
break;
case AUDIT_ADD:
case AUDIT_ADD_RULE:
if (type == AUDIT_ADD)
entry = audit_rule_to_entry(data);
else
entry = audit_data_to_entry(data, datasz);
if (IS_ERR(entry))
return PTR_ERR(entry);
err = audit_add_rule(entry);
audit_log_rule_change(loginuid, sessionid, sid, "add rule",
&entry->rule, !err);
if (err)
audit_free_rule(entry);
break;
case AUDIT_DEL:
case AUDIT_DEL_RULE:
if (type == AUDIT_DEL)
entry = audit_rule_to_entry(data);
else
entry = audit_data_to_entry(data, datasz);
if (IS_ERR(entry))
return PTR_ERR(entry);
err = audit_del_rule(entry);
audit_log_rule_change(loginuid, sessionid, sid, "remove rule",
&entry->rule, !err);
audit_free_rule(entry);
break;
default:
return -EINVAL;
}
return err;
}
int audit_comparator(u32 left, u32 op, u32 right)
{
switch (op) {
case Audit_equal:
return (left == right);
case Audit_not_equal:
return (left != right);
case Audit_lt:
return (left < right);
case Audit_le:
return (left <= right);
case Audit_gt:
return (left > right);
case Audit_ge:
return (left >= right);
case Audit_bitmask:
return (left & right);
case Audit_bittest:
return ((left & right) == right);
default:
BUG();
return 0;
}
}
/* Compare given dentry name with last component in given path,
* return of 0 indicates a match. */
int audit_compare_dname_path(const char *dname, const char *path,
int *dirlen)
{
int dlen, plen;
const char *p;
if (!dname || !path)
return 1;
dlen = strlen(dname);
plen = strlen(path);
if (plen < dlen)
return 1;
/* disregard trailing slashes */
p = path + plen - 1;
while ((*p == '/') && (p > path))
p--;
/* find last path component */
p = p - dlen + 1;
if (p < path)
return 1;
else if (p > path) {
if (*--p != '/')
return 1;
else
p++;
}
/* return length of path's directory component */
if (dirlen)
*dirlen = p - path;
return strncmp(p, dname, dlen);
}
static int audit_filter_user_rules(struct netlink_skb_parms *cb,
struct audit_krule *rule,
enum audit_state *state)
{
int i;
for (i = 0; i < rule->field_count; i++) {
struct audit_field *f = &rule->fields[i];
int result = 0;
u32 sid;
switch (f->type) {
case AUDIT_PID:
result = audit_comparator(cb->creds.pid, f->op, f->val);
break;
case AUDIT_UID:
result = audit_comparator(cb->creds.uid, f->op, f->val);
break;
case AUDIT_GID:
result = audit_comparator(cb->creds.gid, f->op, f->val);
break;
case AUDIT_LOGINUID:
result = audit_comparator(audit_get_loginuid(current),
f->op, f->val);
break;
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
if (f->lsm_rule) {
security_task_getsecid(current, &sid);
result = security_audit_rule_match(sid,
f->type,
f->op,
f->lsm_rule,
NULL);
}
break;
}
if (!result)
return 0;
}
switch (rule->action) {
case AUDIT_NEVER: *state = AUDIT_DISABLED; break;
case AUDIT_ALWAYS: *state = AUDIT_RECORD_CONTEXT; break;
}
return 1;
}
int audit_filter_user(struct netlink_skb_parms *cb)
{
enum audit_state state = AUDIT_DISABLED;
struct audit_entry *e;
int ret = 1;
rcu_read_lock();
list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_USER], list) {
if (audit_filter_user_rules(cb, &e->rule, &state)) {
if (state == AUDIT_DISABLED)
ret = 0;
break;
}
}
rcu_read_unlock();
return ret; /* Audit by default */
}
int audit_filter_type(int type)
{
struct audit_entry *e;
int result = 0;
rcu_read_lock();
if (list_empty(&audit_filter_list[AUDIT_FILTER_TYPE]))
goto unlock_and_return;
list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TYPE],
list) {
int i;
for (i = 0; i < e->rule.field_count; i++) {
struct audit_field *f = &e->rule.fields[i];
if (f->type == AUDIT_MSGTYPE) {
result = audit_comparator(type, f->op, f->val);
if (!result)
break;
}
}
if (result)
goto unlock_and_return;
}
unlock_and_return:
rcu_read_unlock();
return result;
}
static int update_lsm_rule(struct audit_krule *r)
{
struct audit_entry *entry = container_of(r, struct audit_entry, rule);
struct audit_entry *nentry;
int err = 0;
if (!security_audit_rule_known(r))
return 0;
nentry = audit_dupe_rule(r);
if (IS_ERR(nentry)) {
/* save the first error encountered for the
* return value */
err = PTR_ERR(nentry);
audit_panic("error updating LSM filters");
if (r->watch)
list_del(&r->rlist);
list_del_rcu(&entry->list);
list_del(&r->list);
} else {
if (r->watch || r->tree)
list_replace_init(&r->rlist, &nentry->rule.rlist);
list_replace_rcu(&entry->list, &nentry->list);
list_replace(&r->list, &nentry->rule.list);
}
call_rcu(&entry->rcu, audit_free_rule_rcu);
return err;
}
/* This function will re-initialize the lsm_rule field of all applicable rules.
* It will traverse the filter lists serarching for rules that contain LSM
* specific filter fields. When such a rule is found, it is copied, the
* LSM field is re-initialized, and the old rule is replaced with the
* updated rule. */
int audit_update_lsm_rules(void)
{
struct audit_krule *r, *n;
int i, err = 0;
/* audit_filter_mutex synchronizes the writers */
mutex_lock(&audit_filter_mutex);
for (i = 0; i < AUDIT_NR_FILTERS; i++) {
list_for_each_entry_safe(r, n, &audit_rules_list[i], list) {
int res = update_lsm_rule(r);
if (!err)
err = res;
}
}
mutex_unlock(&audit_filter_mutex);
return err;
}
| gpl-2.0 |
sub77/kernel_samsung_matissewifi | fs/ocfs2/refcounttree.c | 4868 | 115751 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* refcounttree.c
*
* Copyright (C) 2009 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/sort.h>
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "inode.h"
#include "alloc.h"
#include "suballoc.h"
#include "journal.h"
#include "uptodate.h"
#include "super.h"
#include "buffer_head_io.h"
#include "blockcheck.h"
#include "refcounttree.h"
#include "sysfile.h"
#include "dlmglue.h"
#include "extent_map.h"
#include "aops.h"
#include "xattr.h"
#include "namei.h"
#include "ocfs2_trace.h"
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/slab.h>
#include <linux/writeback.h>
#include <linux/pagevec.h>
#include <linux/swap.h>
#include <linux/security.h>
#include <linux/fsnotify.h>
#include <linux/quotaops.h>
#include <linux/namei.h>
#include <linux/mount.h>
struct ocfs2_cow_context {
struct inode *inode;
struct file *file;
u32 cow_start;
u32 cow_len;
struct ocfs2_extent_tree data_et;
struct ocfs2_refcount_tree *ref_tree;
struct buffer_head *ref_root_bh;
struct ocfs2_alloc_context *meta_ac;
struct ocfs2_alloc_context *data_ac;
struct ocfs2_cached_dealloc_ctxt dealloc;
void *cow_object;
struct ocfs2_post_refcount *post_refcount;
int extra_credits;
int (*get_clusters)(struct ocfs2_cow_context *context,
u32 v_cluster, u32 *p_cluster,
u32 *num_clusters,
unsigned int *extent_flags);
int (*cow_duplicate_clusters)(handle_t *handle,
struct file *file,
u32 cpos, u32 old_cluster,
u32 new_cluster, u32 new_len);
};
static inline struct ocfs2_refcount_tree *
cache_info_to_refcount(struct ocfs2_caching_info *ci)
{
return container_of(ci, struct ocfs2_refcount_tree, rf_ci);
}
static int ocfs2_validate_refcount_block(struct super_block *sb,
struct buffer_head *bh)
{
int rc;
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)bh->b_data;
trace_ocfs2_validate_refcount_block((unsigned long long)bh->b_blocknr);
BUG_ON(!buffer_uptodate(bh));
/*
* If the ecc fails, we return the error but otherwise
* leave the filesystem running. We know any error is
* local to this block.
*/
rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &rb->rf_check);
if (rc) {
mlog(ML_ERROR, "Checksum failed for refcount block %llu\n",
(unsigned long long)bh->b_blocknr);
return rc;
}
if (!OCFS2_IS_VALID_REFCOUNT_BLOCK(rb)) {
ocfs2_error(sb,
"Refcount block #%llu has bad signature %.*s",
(unsigned long long)bh->b_blocknr, 7,
rb->rf_signature);
return -EINVAL;
}
if (le64_to_cpu(rb->rf_blkno) != bh->b_blocknr) {
ocfs2_error(sb,
"Refcount block #%llu has an invalid rf_blkno "
"of %llu",
(unsigned long long)bh->b_blocknr,
(unsigned long long)le64_to_cpu(rb->rf_blkno));
return -EINVAL;
}
if (le32_to_cpu(rb->rf_fs_generation) != OCFS2_SB(sb)->fs_generation) {
ocfs2_error(sb,
"Refcount block #%llu has an invalid "
"rf_fs_generation of #%u",
(unsigned long long)bh->b_blocknr,
le32_to_cpu(rb->rf_fs_generation));
return -EINVAL;
}
return 0;
}
static int ocfs2_read_refcount_block(struct ocfs2_caching_info *ci,
u64 rb_blkno,
struct buffer_head **bh)
{
int rc;
struct buffer_head *tmp = *bh;
rc = ocfs2_read_block(ci, rb_blkno, &tmp,
ocfs2_validate_refcount_block);
/* If ocfs2_read_block() got us a new bh, pass it up. */
if (!rc && !*bh)
*bh = tmp;
return rc;
}
static u64 ocfs2_refcount_cache_owner(struct ocfs2_caching_info *ci)
{
struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
return rf->rf_blkno;
}
static struct super_block *
ocfs2_refcount_cache_get_super(struct ocfs2_caching_info *ci)
{
struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
return rf->rf_sb;
}
static void ocfs2_refcount_cache_lock(struct ocfs2_caching_info *ci)
{
struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
spin_lock(&rf->rf_lock);
}
static void ocfs2_refcount_cache_unlock(struct ocfs2_caching_info *ci)
{
struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
spin_unlock(&rf->rf_lock);
}
static void ocfs2_refcount_cache_io_lock(struct ocfs2_caching_info *ci)
{
struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
mutex_lock(&rf->rf_io_mutex);
}
static void ocfs2_refcount_cache_io_unlock(struct ocfs2_caching_info *ci)
{
struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
mutex_unlock(&rf->rf_io_mutex);
}
static const struct ocfs2_caching_operations ocfs2_refcount_caching_ops = {
.co_owner = ocfs2_refcount_cache_owner,
.co_get_super = ocfs2_refcount_cache_get_super,
.co_cache_lock = ocfs2_refcount_cache_lock,
.co_cache_unlock = ocfs2_refcount_cache_unlock,
.co_io_lock = ocfs2_refcount_cache_io_lock,
.co_io_unlock = ocfs2_refcount_cache_io_unlock,
};
static struct ocfs2_refcount_tree *
ocfs2_find_refcount_tree(struct ocfs2_super *osb, u64 blkno)
{
struct rb_node *n = osb->osb_rf_lock_tree.rb_node;
struct ocfs2_refcount_tree *tree = NULL;
while (n) {
tree = rb_entry(n, struct ocfs2_refcount_tree, rf_node);
if (blkno < tree->rf_blkno)
n = n->rb_left;
else if (blkno > tree->rf_blkno)
n = n->rb_right;
else
return tree;
}
return NULL;
}
/* osb_lock is already locked. */
static void ocfs2_insert_refcount_tree(struct ocfs2_super *osb,
struct ocfs2_refcount_tree *new)
{
u64 rf_blkno = new->rf_blkno;
struct rb_node *parent = NULL;
struct rb_node **p = &osb->osb_rf_lock_tree.rb_node;
struct ocfs2_refcount_tree *tmp;
while (*p) {
parent = *p;
tmp = rb_entry(parent, struct ocfs2_refcount_tree,
rf_node);
if (rf_blkno < tmp->rf_blkno)
p = &(*p)->rb_left;
else if (rf_blkno > tmp->rf_blkno)
p = &(*p)->rb_right;
else {
/* This should never happen! */
mlog(ML_ERROR, "Duplicate refcount block %llu found!\n",
(unsigned long long)rf_blkno);
BUG();
}
}
rb_link_node(&new->rf_node, parent, p);
rb_insert_color(&new->rf_node, &osb->osb_rf_lock_tree);
}
static void ocfs2_free_refcount_tree(struct ocfs2_refcount_tree *tree)
{
ocfs2_metadata_cache_exit(&tree->rf_ci);
ocfs2_simple_drop_lockres(OCFS2_SB(tree->rf_sb), &tree->rf_lockres);
ocfs2_lock_res_free(&tree->rf_lockres);
kfree(tree);
}
static inline void
ocfs2_erase_refcount_tree_from_list_no_lock(struct ocfs2_super *osb,
struct ocfs2_refcount_tree *tree)
{
rb_erase(&tree->rf_node, &osb->osb_rf_lock_tree);
if (osb->osb_ref_tree_lru && osb->osb_ref_tree_lru == tree)
osb->osb_ref_tree_lru = NULL;
}
static void ocfs2_erase_refcount_tree_from_list(struct ocfs2_super *osb,
struct ocfs2_refcount_tree *tree)
{
spin_lock(&osb->osb_lock);
ocfs2_erase_refcount_tree_from_list_no_lock(osb, tree);
spin_unlock(&osb->osb_lock);
}
static void ocfs2_kref_remove_refcount_tree(struct kref *kref)
{
struct ocfs2_refcount_tree *tree =
container_of(kref, struct ocfs2_refcount_tree, rf_getcnt);
ocfs2_free_refcount_tree(tree);
}
static inline void
ocfs2_refcount_tree_get(struct ocfs2_refcount_tree *tree)
{
kref_get(&tree->rf_getcnt);
}
static inline void
ocfs2_refcount_tree_put(struct ocfs2_refcount_tree *tree)
{
kref_put(&tree->rf_getcnt, ocfs2_kref_remove_refcount_tree);
}
static inline void ocfs2_init_refcount_tree_ci(struct ocfs2_refcount_tree *new,
struct super_block *sb)
{
ocfs2_metadata_cache_init(&new->rf_ci, &ocfs2_refcount_caching_ops);
mutex_init(&new->rf_io_mutex);
new->rf_sb = sb;
spin_lock_init(&new->rf_lock);
}
static inline void ocfs2_init_refcount_tree_lock(struct ocfs2_super *osb,
struct ocfs2_refcount_tree *new,
u64 rf_blkno, u32 generation)
{
init_rwsem(&new->rf_sem);
ocfs2_refcount_lock_res_init(&new->rf_lockres, osb,
rf_blkno, generation);
}
static struct ocfs2_refcount_tree*
ocfs2_allocate_refcount_tree(struct ocfs2_super *osb, u64 rf_blkno)
{
struct ocfs2_refcount_tree *new;
new = kzalloc(sizeof(struct ocfs2_refcount_tree), GFP_NOFS);
if (!new)
return NULL;
new->rf_blkno = rf_blkno;
kref_init(&new->rf_getcnt);
ocfs2_init_refcount_tree_ci(new, osb->sb);
return new;
}
static int ocfs2_get_refcount_tree(struct ocfs2_super *osb, u64 rf_blkno,
struct ocfs2_refcount_tree **ret_tree)
{
int ret = 0;
struct ocfs2_refcount_tree *tree, *new = NULL;
struct buffer_head *ref_root_bh = NULL;
struct ocfs2_refcount_block *ref_rb;
spin_lock(&osb->osb_lock);
if (osb->osb_ref_tree_lru &&
osb->osb_ref_tree_lru->rf_blkno == rf_blkno)
tree = osb->osb_ref_tree_lru;
else
tree = ocfs2_find_refcount_tree(osb, rf_blkno);
if (tree)
goto out;
spin_unlock(&osb->osb_lock);
new = ocfs2_allocate_refcount_tree(osb, rf_blkno);
if (!new) {
ret = -ENOMEM;
mlog_errno(ret);
return ret;
}
/*
* We need the generation to create the refcount tree lock and since
* it isn't changed during the tree modification, we are safe here to
* read without protection.
* We also have to purge the cache after we create the lock since the
* refcount block may have the stale data. It can only be trusted when
* we hold the refcount lock.
*/
ret = ocfs2_read_refcount_block(&new->rf_ci, rf_blkno, &ref_root_bh);
if (ret) {
mlog_errno(ret);
ocfs2_metadata_cache_exit(&new->rf_ci);
kfree(new);
return ret;
}
ref_rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
new->rf_generation = le32_to_cpu(ref_rb->rf_generation);
ocfs2_init_refcount_tree_lock(osb, new, rf_blkno,
new->rf_generation);
ocfs2_metadata_cache_purge(&new->rf_ci);
spin_lock(&osb->osb_lock);
tree = ocfs2_find_refcount_tree(osb, rf_blkno);
if (tree)
goto out;
ocfs2_insert_refcount_tree(osb, new);
tree = new;
new = NULL;
out:
*ret_tree = tree;
osb->osb_ref_tree_lru = tree;
spin_unlock(&osb->osb_lock);
if (new)
ocfs2_free_refcount_tree(new);
brelse(ref_root_bh);
return ret;
}
static int ocfs2_get_refcount_block(struct inode *inode, u64 *ref_blkno)
{
int ret;
struct buffer_head *di_bh = NULL;
struct ocfs2_dinode *di;
ret = ocfs2_read_inode_block(inode, &di_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
BUG_ON(!(OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
di = (struct ocfs2_dinode *)di_bh->b_data;
*ref_blkno = le64_to_cpu(di->i_refcount_loc);
brelse(di_bh);
out:
return ret;
}
static int __ocfs2_lock_refcount_tree(struct ocfs2_super *osb,
struct ocfs2_refcount_tree *tree, int rw)
{
int ret;
ret = ocfs2_refcount_lock(tree, rw);
if (ret) {
mlog_errno(ret);
goto out;
}
if (rw)
down_write(&tree->rf_sem);
else
down_read(&tree->rf_sem);
out:
return ret;
}
/*
* Lock the refcount tree pointed by ref_blkno and return the tree.
* In most case, we lock the tree and read the refcount block.
* So read it here if the caller really needs it.
*
* If the tree has been re-created by other node, it will free the
* old one and re-create it.
*/
int ocfs2_lock_refcount_tree(struct ocfs2_super *osb,
u64 ref_blkno, int rw,
struct ocfs2_refcount_tree **ret_tree,
struct buffer_head **ref_bh)
{
int ret, delete_tree = 0;
struct ocfs2_refcount_tree *tree = NULL;
struct buffer_head *ref_root_bh = NULL;
struct ocfs2_refcount_block *rb;
again:
ret = ocfs2_get_refcount_tree(osb, ref_blkno, &tree);
if (ret) {
mlog_errno(ret);
return ret;
}
ocfs2_refcount_tree_get(tree);
ret = __ocfs2_lock_refcount_tree(osb, tree, rw);
if (ret) {
mlog_errno(ret);
ocfs2_refcount_tree_put(tree);
goto out;
}
ret = ocfs2_read_refcount_block(&tree->rf_ci, tree->rf_blkno,
&ref_root_bh);
if (ret) {
mlog_errno(ret);
ocfs2_unlock_refcount_tree(osb, tree, rw);
ocfs2_refcount_tree_put(tree);
goto out;
}
rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
/*
* If the refcount block has been freed and re-created, we may need
* to recreate the refcount tree also.
*
* Here we just remove the tree from the rb-tree, and the last
* kref holder will unlock and delete this refcount_tree.
* Then we goto "again" and ocfs2_get_refcount_tree will create
* the new refcount tree for us.
*/
if (tree->rf_generation != le32_to_cpu(rb->rf_generation)) {
if (!tree->rf_removed) {
ocfs2_erase_refcount_tree_from_list(osb, tree);
tree->rf_removed = 1;
delete_tree = 1;
}
ocfs2_unlock_refcount_tree(osb, tree, rw);
/*
* We get an extra reference when we create the refcount
* tree, so another put will destroy it.
*/
if (delete_tree)
ocfs2_refcount_tree_put(tree);
brelse(ref_root_bh);
ref_root_bh = NULL;
goto again;
}
*ret_tree = tree;
if (ref_bh) {
*ref_bh = ref_root_bh;
ref_root_bh = NULL;
}
out:
brelse(ref_root_bh);
return ret;
}
void ocfs2_unlock_refcount_tree(struct ocfs2_super *osb,
struct ocfs2_refcount_tree *tree, int rw)
{
if (rw)
up_write(&tree->rf_sem);
else
up_read(&tree->rf_sem);
ocfs2_refcount_unlock(tree, rw);
ocfs2_refcount_tree_put(tree);
}
void ocfs2_purge_refcount_trees(struct ocfs2_super *osb)
{
struct rb_node *node;
struct ocfs2_refcount_tree *tree;
struct rb_root *root = &osb->osb_rf_lock_tree;
while ((node = rb_last(root)) != NULL) {
tree = rb_entry(node, struct ocfs2_refcount_tree, rf_node);
trace_ocfs2_purge_refcount_trees(
(unsigned long long) tree->rf_blkno);
rb_erase(&tree->rf_node, root);
ocfs2_free_refcount_tree(tree);
}
}
/*
* Create a refcount tree for an inode.
* We take for granted that the inode is already locked.
*/
static int ocfs2_create_refcount_tree(struct inode *inode,
struct buffer_head *di_bh)
{
int ret;
handle_t *handle = NULL;
struct ocfs2_alloc_context *meta_ac = NULL;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct buffer_head *new_bh = NULL;
struct ocfs2_refcount_block *rb;
struct ocfs2_refcount_tree *new_tree = NULL, *tree = NULL;
u16 suballoc_bit_start;
u32 num_got;
u64 suballoc_loc, first_blkno;
BUG_ON(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL);
trace_ocfs2_create_refcount_tree(
(unsigned long long)OCFS2_I(inode)->ip_blkno);
ret = ocfs2_reserve_new_metadata_blocks(osb, 1, &meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
handle = ocfs2_start_trans(osb, OCFS2_REFCOUNT_TREE_CREATE_CREDITS);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
ret = ocfs2_claim_metadata(handle, meta_ac, 1, &suballoc_loc,
&suballoc_bit_start, &num_got,
&first_blkno);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
new_tree = ocfs2_allocate_refcount_tree(osb, first_blkno);
if (!new_tree) {
ret = -ENOMEM;
mlog_errno(ret);
goto out_commit;
}
new_bh = sb_getblk(inode->i_sb, first_blkno);
ocfs2_set_new_buffer_uptodate(&new_tree->rf_ci, new_bh);
ret = ocfs2_journal_access_rb(handle, &new_tree->rf_ci, new_bh,
OCFS2_JOURNAL_ACCESS_CREATE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
/* Initialize ocfs2_refcount_block. */
rb = (struct ocfs2_refcount_block *)new_bh->b_data;
memset(rb, 0, inode->i_sb->s_blocksize);
strcpy((void *)rb, OCFS2_REFCOUNT_BLOCK_SIGNATURE);
rb->rf_suballoc_slot = cpu_to_le16(meta_ac->ac_alloc_slot);
rb->rf_suballoc_loc = cpu_to_le64(suballoc_loc);
rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
rb->rf_fs_generation = cpu_to_le32(osb->fs_generation);
rb->rf_blkno = cpu_to_le64(first_blkno);
rb->rf_count = cpu_to_le32(1);
rb->rf_records.rl_count =
cpu_to_le16(ocfs2_refcount_recs_per_rb(osb->sb));
spin_lock(&osb->osb_lock);
rb->rf_generation = osb->s_next_generation++;
spin_unlock(&osb->osb_lock);
ocfs2_journal_dirty(handle, new_bh);
spin_lock(&oi->ip_lock);
oi->ip_dyn_features |= OCFS2_HAS_REFCOUNT_FL;
di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
di->i_refcount_loc = cpu_to_le64(first_blkno);
spin_unlock(&oi->ip_lock);
trace_ocfs2_create_refcount_tree_blkno((unsigned long long)first_blkno);
ocfs2_journal_dirty(handle, di_bh);
/*
* We have to init the tree lock here since it will use
* the generation number to create it.
*/
new_tree->rf_generation = le32_to_cpu(rb->rf_generation);
ocfs2_init_refcount_tree_lock(osb, new_tree, first_blkno,
new_tree->rf_generation);
spin_lock(&osb->osb_lock);
tree = ocfs2_find_refcount_tree(osb, first_blkno);
/*
* We've just created a new refcount tree in this block. If
* we found a refcount tree on the ocfs2_super, it must be
* one we just deleted. We free the old tree before
* inserting the new tree.
*/
BUG_ON(tree && tree->rf_generation == new_tree->rf_generation);
if (tree)
ocfs2_erase_refcount_tree_from_list_no_lock(osb, tree);
ocfs2_insert_refcount_tree(osb, new_tree);
spin_unlock(&osb->osb_lock);
new_tree = NULL;
if (tree)
ocfs2_refcount_tree_put(tree);
out_commit:
ocfs2_commit_trans(osb, handle);
out:
if (new_tree) {
ocfs2_metadata_cache_exit(&new_tree->rf_ci);
kfree(new_tree);
}
brelse(new_bh);
if (meta_ac)
ocfs2_free_alloc_context(meta_ac);
return ret;
}
static int ocfs2_set_refcount_tree(struct inode *inode,
struct buffer_head *di_bh,
u64 refcount_loc)
{
int ret;
handle_t *handle = NULL;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct buffer_head *ref_root_bh = NULL;
struct ocfs2_refcount_block *rb;
struct ocfs2_refcount_tree *ref_tree;
BUG_ON(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL);
ret = ocfs2_lock_refcount_tree(osb, refcount_loc, 1,
&ref_tree, &ref_root_bh);
if (ret) {
mlog_errno(ret);
return ret;
}
handle = ocfs2_start_trans(osb, OCFS2_REFCOUNT_TREE_SET_CREDITS);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
ret = ocfs2_journal_access_rb(handle, &ref_tree->rf_ci, ref_root_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
le32_add_cpu(&rb->rf_count, 1);
ocfs2_journal_dirty(handle, ref_root_bh);
spin_lock(&oi->ip_lock);
oi->ip_dyn_features |= OCFS2_HAS_REFCOUNT_FL;
di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
di->i_refcount_loc = cpu_to_le64(refcount_loc);
spin_unlock(&oi->ip_lock);
ocfs2_journal_dirty(handle, di_bh);
out_commit:
ocfs2_commit_trans(osb, handle);
out:
ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
brelse(ref_root_bh);
return ret;
}
int ocfs2_remove_refcount_tree(struct inode *inode, struct buffer_head *di_bh)
{
int ret, delete_tree = 0;
handle_t *handle = NULL;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_refcount_block *rb;
struct inode *alloc_inode = NULL;
struct buffer_head *alloc_bh = NULL;
struct buffer_head *blk_bh = NULL;
struct ocfs2_refcount_tree *ref_tree;
int credits = OCFS2_REFCOUNT_TREE_REMOVE_CREDITS;
u64 blk = 0, bg_blkno = 0, ref_blkno = le64_to_cpu(di->i_refcount_loc);
u16 bit = 0;
if (!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL))
return 0;
BUG_ON(!ref_blkno);
ret = ocfs2_lock_refcount_tree(osb, ref_blkno, 1, &ref_tree, &blk_bh);
if (ret) {
mlog_errno(ret);
return ret;
}
rb = (struct ocfs2_refcount_block *)blk_bh->b_data;
/*
* If we are the last user, we need to free the block.
* So lock the allocator ahead.
*/
if (le32_to_cpu(rb->rf_count) == 1) {
blk = le64_to_cpu(rb->rf_blkno);
bit = le16_to_cpu(rb->rf_suballoc_bit);
if (rb->rf_suballoc_loc)
bg_blkno = le64_to_cpu(rb->rf_suballoc_loc);
else
bg_blkno = ocfs2_which_suballoc_group(blk, bit);
alloc_inode = ocfs2_get_system_file_inode(osb,
EXTENT_ALLOC_SYSTEM_INODE,
le16_to_cpu(rb->rf_suballoc_slot));
if (!alloc_inode) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
mutex_lock(&alloc_inode->i_mutex);
ret = ocfs2_inode_lock(alloc_inode, &alloc_bh, 1);
if (ret) {
mlog_errno(ret);
goto out_mutex;
}
credits += OCFS2_SUBALLOC_FREE;
}
handle = ocfs2_start_trans(osb, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out_unlock;
}
ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
ret = ocfs2_journal_access_rb(handle, &ref_tree->rf_ci, blk_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
spin_lock(&oi->ip_lock);
oi->ip_dyn_features &= ~OCFS2_HAS_REFCOUNT_FL;
di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
di->i_refcount_loc = 0;
spin_unlock(&oi->ip_lock);
ocfs2_journal_dirty(handle, di_bh);
le32_add_cpu(&rb->rf_count , -1);
ocfs2_journal_dirty(handle, blk_bh);
if (!rb->rf_count) {
delete_tree = 1;
ocfs2_erase_refcount_tree_from_list(osb, ref_tree);
ret = ocfs2_free_suballoc_bits(handle, alloc_inode,
alloc_bh, bit, bg_blkno, 1);
if (ret)
mlog_errno(ret);
}
out_commit:
ocfs2_commit_trans(osb, handle);
out_unlock:
if (alloc_inode) {
ocfs2_inode_unlock(alloc_inode, 1);
brelse(alloc_bh);
}
out_mutex:
if (alloc_inode) {
mutex_unlock(&alloc_inode->i_mutex);
iput(alloc_inode);
}
out:
ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
if (delete_tree)
ocfs2_refcount_tree_put(ref_tree);
brelse(blk_bh);
return ret;
}
static void ocfs2_find_refcount_rec_in_rl(struct ocfs2_caching_info *ci,
struct buffer_head *ref_leaf_bh,
u64 cpos, unsigned int len,
struct ocfs2_refcount_rec *ret_rec,
int *index)
{
int i = 0;
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
struct ocfs2_refcount_rec *rec = NULL;
for (; i < le16_to_cpu(rb->rf_records.rl_used); i++) {
rec = &rb->rf_records.rl_recs[i];
if (le64_to_cpu(rec->r_cpos) +
le32_to_cpu(rec->r_clusters) <= cpos)
continue;
else if (le64_to_cpu(rec->r_cpos) > cpos)
break;
/* ok, cpos fail in this rec. Just return. */
if (ret_rec)
*ret_rec = *rec;
goto out;
}
if (ret_rec) {
/* We meet with a hole here, so fake the rec. */
ret_rec->r_cpos = cpu_to_le64(cpos);
ret_rec->r_refcount = 0;
if (i < le16_to_cpu(rb->rf_records.rl_used) &&
le64_to_cpu(rec->r_cpos) < cpos + len)
ret_rec->r_clusters =
cpu_to_le32(le64_to_cpu(rec->r_cpos) - cpos);
else
ret_rec->r_clusters = cpu_to_le32(len);
}
out:
*index = i;
}
/*
* Try to remove refcount tree. The mechanism is:
* 1) Check whether i_clusters == 0, if no, exit.
* 2) check whether we have i_xattr_loc in dinode. if yes, exit.
* 3) Check whether we have inline xattr stored outside, if yes, exit.
* 4) Remove the tree.
*/
int ocfs2_try_remove_refcount_tree(struct inode *inode,
struct buffer_head *di_bh)
{
int ret;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
down_write(&oi->ip_xattr_sem);
down_write(&oi->ip_alloc_sem);
if (oi->ip_clusters)
goto out;
if ((oi->ip_dyn_features & OCFS2_HAS_XATTR_FL) && di->i_xattr_loc)
goto out;
if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL &&
ocfs2_has_inline_xattr_value_outside(inode, di))
goto out;
ret = ocfs2_remove_refcount_tree(inode, di_bh);
if (ret)
mlog_errno(ret);
out:
up_write(&oi->ip_alloc_sem);
up_write(&oi->ip_xattr_sem);
return 0;
}
/*
* Find the end range for a leaf refcount block indicated by
* el->l_recs[index].e_blkno.
*/
static int ocfs2_get_refcount_cpos_end(struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct ocfs2_extent_block *eb,
struct ocfs2_extent_list *el,
int index, u32 *cpos_end)
{
int ret, i, subtree_root;
u32 cpos;
u64 blkno;
struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
struct ocfs2_path *left_path = NULL, *right_path = NULL;
struct ocfs2_extent_tree et;
struct ocfs2_extent_list *tmp_el;
if (index < le16_to_cpu(el->l_next_free_rec) - 1) {
/*
* We have a extent rec after index, so just use the e_cpos
* of the next extent rec.
*/
*cpos_end = le32_to_cpu(el->l_recs[index+1].e_cpos);
return 0;
}
if (!eb || (eb && !eb->h_next_leaf_blk)) {
/*
* We are the last extent rec, so any high cpos should
* be stored in this leaf refcount block.
*/
*cpos_end = UINT_MAX;
return 0;
}
/*
* If the extent block isn't the last one, we have to find
* the subtree root between this extent block and the next
* leaf extent block and get the corresponding e_cpos from
* the subroot. Otherwise we may corrupt the b-tree.
*/
ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
left_path = ocfs2_new_path_from_et(&et);
if (!left_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
cpos = le32_to_cpu(eb->h_list.l_recs[index].e_cpos);
ret = ocfs2_find_path(ci, left_path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
right_path = ocfs2_new_path_from_path(left_path);
if (!right_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_cpos_for_right_leaf(sb, left_path, &cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(ci, right_path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
subtree_root = ocfs2_find_subtree_root(&et, left_path,
right_path);
tmp_el = left_path->p_node[subtree_root].el;
blkno = left_path->p_node[subtree_root+1].bh->b_blocknr;
for (i = 0; i < le16_to_cpu(tmp_el->l_next_free_rec); i++) {
if (le64_to_cpu(tmp_el->l_recs[i].e_blkno) == blkno) {
*cpos_end = le32_to_cpu(tmp_el->l_recs[i+1].e_cpos);
break;
}
}
BUG_ON(i == le16_to_cpu(tmp_el->l_next_free_rec));
out:
ocfs2_free_path(left_path);
ocfs2_free_path(right_path);
return ret;
}
/*
* Given a cpos and len, try to find the refcount record which contains cpos.
* 1. If cpos can be found in one refcount record, return the record.
* 2. If cpos can't be found, return a fake record which start from cpos
* and end at a small value between cpos+len and start of the next record.
* This fake record has r_refcount = 0.
*/
static int ocfs2_get_refcount_rec(struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
u64 cpos, unsigned int len,
struct ocfs2_refcount_rec *ret_rec,
int *index,
struct buffer_head **ret_bh)
{
int ret = 0, i, found;
u32 low_cpos, uninitialized_var(cpos_end);
struct ocfs2_extent_list *el;
struct ocfs2_extent_rec *rec = NULL;
struct ocfs2_extent_block *eb = NULL;
struct buffer_head *eb_bh = NULL, *ref_leaf_bh = NULL;
struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_root_bh->b_data;
if (!(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL)) {
ocfs2_find_refcount_rec_in_rl(ci, ref_root_bh, cpos, len,
ret_rec, index);
*ret_bh = ref_root_bh;
get_bh(ref_root_bh);
return 0;
}
el = &rb->rf_list;
low_cpos = cpos & OCFS2_32BIT_POS_MASK;
if (el->l_tree_depth) {
ret = ocfs2_find_leaf(ci, el, low_cpos, &eb_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) eb_bh->b_data;
el = &eb->h_list;
if (el->l_tree_depth) {
ocfs2_error(sb,
"refcount tree %llu has non zero tree "
"depth in leaf btree tree block %llu\n",
(unsigned long long)ocfs2_metadata_cache_owner(ci),
(unsigned long long)eb_bh->b_blocknr);
ret = -EROFS;
goto out;
}
}
found = 0;
for (i = le16_to_cpu(el->l_next_free_rec) - 1; i >= 0; i--) {
rec = &el->l_recs[i];
if (le32_to_cpu(rec->e_cpos) <= low_cpos) {
found = 1;
break;
}
}
if (found) {
ret = ocfs2_get_refcount_cpos_end(ci, ref_root_bh,
eb, el, i, &cpos_end);
if (ret) {
mlog_errno(ret);
goto out;
}
if (cpos_end < low_cpos + len)
len = cpos_end - low_cpos;
}
ret = ocfs2_read_refcount_block(ci, le64_to_cpu(rec->e_blkno),
&ref_leaf_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
ocfs2_find_refcount_rec_in_rl(ci, ref_leaf_bh, cpos, len,
ret_rec, index);
*ret_bh = ref_leaf_bh;
out:
brelse(eb_bh);
return ret;
}
enum ocfs2_ref_rec_contig {
REF_CONTIG_NONE = 0,
REF_CONTIG_LEFT,
REF_CONTIG_RIGHT,
REF_CONTIG_LEFTRIGHT,
};
static enum ocfs2_ref_rec_contig
ocfs2_refcount_rec_adjacent(struct ocfs2_refcount_block *rb,
int index)
{
if ((rb->rf_records.rl_recs[index].r_refcount ==
rb->rf_records.rl_recs[index + 1].r_refcount) &&
(le64_to_cpu(rb->rf_records.rl_recs[index].r_cpos) +
le32_to_cpu(rb->rf_records.rl_recs[index].r_clusters) ==
le64_to_cpu(rb->rf_records.rl_recs[index + 1].r_cpos)))
return REF_CONTIG_RIGHT;
return REF_CONTIG_NONE;
}
static enum ocfs2_ref_rec_contig
ocfs2_refcount_rec_contig(struct ocfs2_refcount_block *rb,
int index)
{
enum ocfs2_ref_rec_contig ret = REF_CONTIG_NONE;
if (index < le16_to_cpu(rb->rf_records.rl_used) - 1)
ret = ocfs2_refcount_rec_adjacent(rb, index);
if (index > 0) {
enum ocfs2_ref_rec_contig tmp;
tmp = ocfs2_refcount_rec_adjacent(rb, index - 1);
if (tmp == REF_CONTIG_RIGHT) {
if (ret == REF_CONTIG_RIGHT)
ret = REF_CONTIG_LEFTRIGHT;
else
ret = REF_CONTIG_LEFT;
}
}
return ret;
}
static void ocfs2_rotate_refcount_rec_left(struct ocfs2_refcount_block *rb,
int index)
{
BUG_ON(rb->rf_records.rl_recs[index].r_refcount !=
rb->rf_records.rl_recs[index+1].r_refcount);
le32_add_cpu(&rb->rf_records.rl_recs[index].r_clusters,
le32_to_cpu(rb->rf_records.rl_recs[index+1].r_clusters));
if (index < le16_to_cpu(rb->rf_records.rl_used) - 2)
memmove(&rb->rf_records.rl_recs[index + 1],
&rb->rf_records.rl_recs[index + 2],
sizeof(struct ocfs2_refcount_rec) *
(le16_to_cpu(rb->rf_records.rl_used) - index - 2));
memset(&rb->rf_records.rl_recs[le16_to_cpu(rb->rf_records.rl_used) - 1],
0, sizeof(struct ocfs2_refcount_rec));
le16_add_cpu(&rb->rf_records.rl_used, -1);
}
/*
* Merge the refcount rec if we are contiguous with the adjacent recs.
*/
static void ocfs2_refcount_rec_merge(struct ocfs2_refcount_block *rb,
int index)
{
enum ocfs2_ref_rec_contig contig =
ocfs2_refcount_rec_contig(rb, index);
if (contig == REF_CONTIG_NONE)
return;
if (contig == REF_CONTIG_LEFT || contig == REF_CONTIG_LEFTRIGHT) {
BUG_ON(index == 0);
index--;
}
ocfs2_rotate_refcount_rec_left(rb, index);
if (contig == REF_CONTIG_LEFTRIGHT)
ocfs2_rotate_refcount_rec_left(rb, index);
}
/*
* Change the refcount indexed by "index" in ref_bh.
* If refcount reaches 0, remove it.
*/
static int ocfs2_change_refcount_rec(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_leaf_bh,
int index, int merge, int change)
{
int ret;
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
struct ocfs2_refcount_list *rl = &rb->rf_records;
struct ocfs2_refcount_rec *rec = &rl->rl_recs[index];
ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
trace_ocfs2_change_refcount_rec(
(unsigned long long)ocfs2_metadata_cache_owner(ci),
index, le32_to_cpu(rec->r_refcount), change);
le32_add_cpu(&rec->r_refcount, change);
if (!rec->r_refcount) {
if (index != le16_to_cpu(rl->rl_used) - 1) {
memmove(rec, rec + 1,
(le16_to_cpu(rl->rl_used) - index - 1) *
sizeof(struct ocfs2_refcount_rec));
memset(&rl->rl_recs[le16_to_cpu(rl->rl_used) - 1],
0, sizeof(struct ocfs2_refcount_rec));
}
le16_add_cpu(&rl->rl_used, -1);
} else if (merge)
ocfs2_refcount_rec_merge(rb, index);
ocfs2_journal_dirty(handle, ref_leaf_bh);
out:
return ret;
}
static int ocfs2_expand_inline_ref_root(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct buffer_head **ref_leaf_bh,
struct ocfs2_alloc_context *meta_ac)
{
int ret;
u16 suballoc_bit_start;
u32 num_got;
u64 suballoc_loc, blkno;
struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
struct buffer_head *new_bh = NULL;
struct ocfs2_refcount_block *new_rb;
struct ocfs2_refcount_block *root_rb =
(struct ocfs2_refcount_block *)ref_root_bh->b_data;
ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_claim_metadata(handle, meta_ac, 1, &suballoc_loc,
&suballoc_bit_start, &num_got,
&blkno);
if (ret) {
mlog_errno(ret);
goto out;
}
new_bh = sb_getblk(sb, blkno);
if (new_bh == NULL) {
ret = -EIO;
mlog_errno(ret);
goto out;
}
ocfs2_set_new_buffer_uptodate(ci, new_bh);
ret = ocfs2_journal_access_rb(handle, ci, new_bh,
OCFS2_JOURNAL_ACCESS_CREATE);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* Initialize ocfs2_refcount_block.
* It should contain the same information as the old root.
* so just memcpy it and change the corresponding field.
*/
memcpy(new_bh->b_data, ref_root_bh->b_data, sb->s_blocksize);
new_rb = (struct ocfs2_refcount_block *)new_bh->b_data;
new_rb->rf_suballoc_slot = cpu_to_le16(meta_ac->ac_alloc_slot);
new_rb->rf_suballoc_loc = cpu_to_le64(suballoc_loc);
new_rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
new_rb->rf_blkno = cpu_to_le64(blkno);
new_rb->rf_cpos = cpu_to_le32(0);
new_rb->rf_parent = cpu_to_le64(ref_root_bh->b_blocknr);
new_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_LEAF_FL);
ocfs2_journal_dirty(handle, new_bh);
/* Now change the root. */
memset(&root_rb->rf_list, 0, sb->s_blocksize -
offsetof(struct ocfs2_refcount_block, rf_list));
root_rb->rf_list.l_count = cpu_to_le16(ocfs2_extent_recs_per_rb(sb));
root_rb->rf_clusters = cpu_to_le32(1);
root_rb->rf_list.l_next_free_rec = cpu_to_le16(1);
root_rb->rf_list.l_recs[0].e_blkno = cpu_to_le64(blkno);
root_rb->rf_list.l_recs[0].e_leaf_clusters = cpu_to_le16(1);
root_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_TREE_FL);
ocfs2_journal_dirty(handle, ref_root_bh);
trace_ocfs2_expand_inline_ref_root((unsigned long long)blkno,
le16_to_cpu(new_rb->rf_records.rl_used));
*ref_leaf_bh = new_bh;
new_bh = NULL;
out:
brelse(new_bh);
return ret;
}
static int ocfs2_refcount_rec_no_intersect(struct ocfs2_refcount_rec *prev,
struct ocfs2_refcount_rec *next)
{
if (ocfs2_get_ref_rec_low_cpos(prev) + le32_to_cpu(prev->r_clusters) <=
ocfs2_get_ref_rec_low_cpos(next))
return 1;
return 0;
}
static int cmp_refcount_rec_by_low_cpos(const void *a, const void *b)
{
const struct ocfs2_refcount_rec *l = a, *r = b;
u32 l_cpos = ocfs2_get_ref_rec_low_cpos(l);
u32 r_cpos = ocfs2_get_ref_rec_low_cpos(r);
if (l_cpos > r_cpos)
return 1;
if (l_cpos < r_cpos)
return -1;
return 0;
}
static int cmp_refcount_rec_by_cpos(const void *a, const void *b)
{
const struct ocfs2_refcount_rec *l = a, *r = b;
u64 l_cpos = le64_to_cpu(l->r_cpos);
u64 r_cpos = le64_to_cpu(r->r_cpos);
if (l_cpos > r_cpos)
return 1;
if (l_cpos < r_cpos)
return -1;
return 0;
}
static void swap_refcount_rec(void *a, void *b, int size)
{
struct ocfs2_refcount_rec *l = a, *r = b, tmp;
tmp = *(struct ocfs2_refcount_rec *)l;
*(struct ocfs2_refcount_rec *)l =
*(struct ocfs2_refcount_rec *)r;
*(struct ocfs2_refcount_rec *)r = tmp;
}
/*
* The refcount cpos are ordered by their 64bit cpos,
* But we will use the low 32 bit to be the e_cpos in the b-tree.
* So we need to make sure that this pos isn't intersected with others.
*
* Note: The refcount block is already sorted by their low 32 bit cpos,
* So just try the middle pos first, and we will exit when we find
* the good position.
*/
static int ocfs2_find_refcount_split_pos(struct ocfs2_refcount_list *rl,
u32 *split_pos, int *split_index)
{
int num_used = le16_to_cpu(rl->rl_used);
int delta, middle = num_used / 2;
for (delta = 0; delta < middle; delta++) {
/* Let's check delta earlier than middle */
if (ocfs2_refcount_rec_no_intersect(
&rl->rl_recs[middle - delta - 1],
&rl->rl_recs[middle - delta])) {
*split_index = middle - delta;
break;
}
/* For even counts, don't walk off the end */
if ((middle + delta + 1) == num_used)
continue;
/* Now try delta past middle */
if (ocfs2_refcount_rec_no_intersect(
&rl->rl_recs[middle + delta],
&rl->rl_recs[middle + delta + 1])) {
*split_index = middle + delta + 1;
break;
}
}
if (delta >= middle)
return -ENOSPC;
*split_pos = ocfs2_get_ref_rec_low_cpos(&rl->rl_recs[*split_index]);
return 0;
}
static int ocfs2_divide_leaf_refcount_block(struct buffer_head *ref_leaf_bh,
struct buffer_head *new_bh,
u32 *split_cpos)
{
int split_index = 0, num_moved, ret;
u32 cpos = 0;
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
struct ocfs2_refcount_list *rl = &rb->rf_records;
struct ocfs2_refcount_block *new_rb =
(struct ocfs2_refcount_block *)new_bh->b_data;
struct ocfs2_refcount_list *new_rl = &new_rb->rf_records;
trace_ocfs2_divide_leaf_refcount_block(
(unsigned long long)ref_leaf_bh->b_blocknr,
le16_to_cpu(rl->rl_count), le16_to_cpu(rl->rl_used));
/*
* XXX: Improvement later.
* If we know all the high 32 bit cpos is the same, no need to sort.
*
* In order to make the whole process safe, we do:
* 1. sort the entries by their low 32 bit cpos first so that we can
* find the split cpos easily.
* 2. call ocfs2_insert_extent to insert the new refcount block.
* 3. move the refcount rec to the new block.
* 4. sort the entries by their 64 bit cpos.
* 5. dirty the new_rb and rb.
*/
sort(&rl->rl_recs, le16_to_cpu(rl->rl_used),
sizeof(struct ocfs2_refcount_rec),
cmp_refcount_rec_by_low_cpos, swap_refcount_rec);
ret = ocfs2_find_refcount_split_pos(rl, &cpos, &split_index);
if (ret) {
mlog_errno(ret);
return ret;
}
new_rb->rf_cpos = cpu_to_le32(cpos);
/* move refcount records starting from split_index to the new block. */
num_moved = le16_to_cpu(rl->rl_used) - split_index;
memcpy(new_rl->rl_recs, &rl->rl_recs[split_index],
num_moved * sizeof(struct ocfs2_refcount_rec));
/*ok, remove the entries we just moved over to the other block. */
memset(&rl->rl_recs[split_index], 0,
num_moved * sizeof(struct ocfs2_refcount_rec));
/* change old and new rl_used accordingly. */
le16_add_cpu(&rl->rl_used, -num_moved);
new_rl->rl_used = cpu_to_le16(num_moved);
sort(&rl->rl_recs, le16_to_cpu(rl->rl_used),
sizeof(struct ocfs2_refcount_rec),
cmp_refcount_rec_by_cpos, swap_refcount_rec);
sort(&new_rl->rl_recs, le16_to_cpu(new_rl->rl_used),
sizeof(struct ocfs2_refcount_rec),
cmp_refcount_rec_by_cpos, swap_refcount_rec);
*split_cpos = cpos;
return 0;
}
static int ocfs2_new_leaf_refcount_block(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct buffer_head *ref_leaf_bh,
struct ocfs2_alloc_context *meta_ac)
{
int ret;
u16 suballoc_bit_start;
u32 num_got, new_cpos;
u64 suballoc_loc, blkno;
struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
struct ocfs2_refcount_block *root_rb =
(struct ocfs2_refcount_block *)ref_root_bh->b_data;
struct buffer_head *new_bh = NULL;
struct ocfs2_refcount_block *new_rb;
struct ocfs2_extent_tree ref_et;
BUG_ON(!(le32_to_cpu(root_rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL));
ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_claim_metadata(handle, meta_ac, 1, &suballoc_loc,
&suballoc_bit_start, &num_got,
&blkno);
if (ret) {
mlog_errno(ret);
goto out;
}
new_bh = sb_getblk(sb, blkno);
if (new_bh == NULL) {
ret = -EIO;
mlog_errno(ret);
goto out;
}
ocfs2_set_new_buffer_uptodate(ci, new_bh);
ret = ocfs2_journal_access_rb(handle, ci, new_bh,
OCFS2_JOURNAL_ACCESS_CREATE);
if (ret) {
mlog_errno(ret);
goto out;
}
/* Initialize ocfs2_refcount_block. */
new_rb = (struct ocfs2_refcount_block *)new_bh->b_data;
memset(new_rb, 0, sb->s_blocksize);
strcpy((void *)new_rb, OCFS2_REFCOUNT_BLOCK_SIGNATURE);
new_rb->rf_suballoc_slot = cpu_to_le16(meta_ac->ac_alloc_slot);
new_rb->rf_suballoc_loc = cpu_to_le64(suballoc_loc);
new_rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
new_rb->rf_fs_generation = cpu_to_le32(OCFS2_SB(sb)->fs_generation);
new_rb->rf_blkno = cpu_to_le64(blkno);
new_rb->rf_parent = cpu_to_le64(ref_root_bh->b_blocknr);
new_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_LEAF_FL);
new_rb->rf_records.rl_count =
cpu_to_le16(ocfs2_refcount_recs_per_rb(sb));
new_rb->rf_generation = root_rb->rf_generation;
ret = ocfs2_divide_leaf_refcount_block(ref_leaf_bh, new_bh, &new_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
ocfs2_journal_dirty(handle, ref_leaf_bh);
ocfs2_journal_dirty(handle, new_bh);
ocfs2_init_refcount_extent_tree(&ref_et, ci, ref_root_bh);
trace_ocfs2_new_leaf_refcount_block(
(unsigned long long)new_bh->b_blocknr, new_cpos);
/* Insert the new leaf block with the specific offset cpos. */
ret = ocfs2_insert_extent(handle, &ref_et, new_cpos, new_bh->b_blocknr,
1, 0, meta_ac);
if (ret)
mlog_errno(ret);
out:
brelse(new_bh);
return ret;
}
static int ocfs2_expand_refcount_tree(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct buffer_head *ref_leaf_bh,
struct ocfs2_alloc_context *meta_ac)
{
int ret;
struct buffer_head *expand_bh = NULL;
if (ref_root_bh == ref_leaf_bh) {
/*
* the old root bh hasn't been expanded to a b-tree,
* so expand it first.
*/
ret = ocfs2_expand_inline_ref_root(handle, ci, ref_root_bh,
&expand_bh, meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
} else {
expand_bh = ref_leaf_bh;
get_bh(expand_bh);
}
/* Now add a new refcount block into the tree.*/
ret = ocfs2_new_leaf_refcount_block(handle, ci, ref_root_bh,
expand_bh, meta_ac);
if (ret)
mlog_errno(ret);
out:
brelse(expand_bh);
return ret;
}
/*
* Adjust the extent rec in b-tree representing ref_leaf_bh.
*
* Only called when we have inserted a new refcount rec at index 0
* which means ocfs2_extent_rec.e_cpos may need some change.
*/
static int ocfs2_adjust_refcount_rec(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct buffer_head *ref_leaf_bh,
struct ocfs2_refcount_rec *rec)
{
int ret = 0, i;
u32 new_cpos, old_cpos;
struct ocfs2_path *path = NULL;
struct ocfs2_extent_tree et;
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_root_bh->b_data;
struct ocfs2_extent_list *el;
if (!(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL))
goto out;
rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
old_cpos = le32_to_cpu(rb->rf_cpos);
new_cpos = le64_to_cpu(rec->r_cpos) & OCFS2_32BIT_POS_MASK;
if (old_cpos <= new_cpos)
goto out;
ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
path = ocfs2_new_path_from_et(&et);
if (!path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(ci, path, old_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* 2 more credits, one for the leaf refcount block, one for
* the extent block contains the extent rec.
*/
ret = ocfs2_extend_trans(handle, 2);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_eb(handle, ci, path_leaf_bh(path),
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
/* change the leaf extent block first. */
el = path_leaf_el(path);
for (i = 0; i < le16_to_cpu(el->l_next_free_rec); i++)
if (le32_to_cpu(el->l_recs[i].e_cpos) == old_cpos)
break;
BUG_ON(i == le16_to_cpu(el->l_next_free_rec));
el->l_recs[i].e_cpos = cpu_to_le32(new_cpos);
/* change the r_cpos in the leaf block. */
rb->rf_cpos = cpu_to_le32(new_cpos);
ocfs2_journal_dirty(handle, path_leaf_bh(path));
ocfs2_journal_dirty(handle, ref_leaf_bh);
out:
ocfs2_free_path(path);
return ret;
}
static int ocfs2_insert_refcount_rec(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct buffer_head *ref_leaf_bh,
struct ocfs2_refcount_rec *rec,
int index, int merge,
struct ocfs2_alloc_context *meta_ac)
{
int ret;
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
struct ocfs2_refcount_list *rf_list = &rb->rf_records;
struct buffer_head *new_bh = NULL;
BUG_ON(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL);
if (rf_list->rl_used == rf_list->rl_count) {
u64 cpos = le64_to_cpu(rec->r_cpos);
u32 len = le32_to_cpu(rec->r_clusters);
ret = ocfs2_expand_refcount_tree(handle, ci, ref_root_bh,
ref_leaf_bh, meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
cpos, len, NULL, &index,
&new_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
ref_leaf_bh = new_bh;
rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
rf_list = &rb->rf_records;
}
ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
if (index < le16_to_cpu(rf_list->rl_used))
memmove(&rf_list->rl_recs[index + 1],
&rf_list->rl_recs[index],
(le16_to_cpu(rf_list->rl_used) - index) *
sizeof(struct ocfs2_refcount_rec));
trace_ocfs2_insert_refcount_rec(
(unsigned long long)ref_leaf_bh->b_blocknr, index,
(unsigned long long)le64_to_cpu(rec->r_cpos),
le32_to_cpu(rec->r_clusters), le32_to_cpu(rec->r_refcount));
rf_list->rl_recs[index] = *rec;
le16_add_cpu(&rf_list->rl_used, 1);
if (merge)
ocfs2_refcount_rec_merge(rb, index);
ocfs2_journal_dirty(handle, ref_leaf_bh);
if (index == 0) {
ret = ocfs2_adjust_refcount_rec(handle, ci,
ref_root_bh,
ref_leaf_bh, rec);
if (ret)
mlog_errno(ret);
}
out:
brelse(new_bh);
return ret;
}
/*
* Split the refcount_rec indexed by "index" in ref_leaf_bh.
* This is much simple than our b-tree code.
* split_rec is the new refcount rec we want to insert.
* If split_rec->r_refcount > 0, we are changing the refcount(in case we
* increase refcount or decrease a refcount to non-zero).
* If split_rec->r_refcount == 0, we are punching a hole in current refcount
* rec( in case we decrease a refcount to zero).
*/
static int ocfs2_split_refcount_rec(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct buffer_head *ref_leaf_bh,
struct ocfs2_refcount_rec *split_rec,
int index, int merge,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret, recs_need;
u32 len;
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
struct ocfs2_refcount_list *rf_list = &rb->rf_records;
struct ocfs2_refcount_rec *orig_rec = &rf_list->rl_recs[index];
struct ocfs2_refcount_rec *tail_rec = NULL;
struct buffer_head *new_bh = NULL;
BUG_ON(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL);
trace_ocfs2_split_refcount_rec(le64_to_cpu(orig_rec->r_cpos),
le32_to_cpu(orig_rec->r_clusters),
le32_to_cpu(orig_rec->r_refcount),
le64_to_cpu(split_rec->r_cpos),
le32_to_cpu(split_rec->r_clusters),
le32_to_cpu(split_rec->r_refcount));
/*
* If we just need to split the header or tail clusters,
* no more recs are needed, just split is OK.
* Otherwise we at least need one new recs.
*/
if (!split_rec->r_refcount &&
(split_rec->r_cpos == orig_rec->r_cpos ||
le64_to_cpu(split_rec->r_cpos) +
le32_to_cpu(split_rec->r_clusters) ==
le64_to_cpu(orig_rec->r_cpos) + le32_to_cpu(orig_rec->r_clusters)))
recs_need = 0;
else
recs_need = 1;
/*
* We need one more rec if we split in the middle and the new rec have
* some refcount in it.
*/
if (split_rec->r_refcount &&
(split_rec->r_cpos != orig_rec->r_cpos &&
le64_to_cpu(split_rec->r_cpos) +
le32_to_cpu(split_rec->r_clusters) !=
le64_to_cpu(orig_rec->r_cpos) + le32_to_cpu(orig_rec->r_clusters)))
recs_need++;
/* If the leaf block don't have enough record, expand it. */
if (le16_to_cpu(rf_list->rl_used) + recs_need >
le16_to_cpu(rf_list->rl_count)) {
struct ocfs2_refcount_rec tmp_rec;
u64 cpos = le64_to_cpu(orig_rec->r_cpos);
len = le32_to_cpu(orig_rec->r_clusters);
ret = ocfs2_expand_refcount_tree(handle, ci, ref_root_bh,
ref_leaf_bh, meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* We have to re-get it since now cpos may be moved to
* another leaf block.
*/
ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
cpos, len, &tmp_rec, &index,
&new_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
ref_leaf_bh = new_bh;
rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
rf_list = &rb->rf_records;
orig_rec = &rf_list->rl_recs[index];
}
ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* We have calculated out how many new records we need and store
* in recs_need, so spare enough space first by moving the records
* after "index" to the end.
*/
if (index != le16_to_cpu(rf_list->rl_used) - 1)
memmove(&rf_list->rl_recs[index + 1 + recs_need],
&rf_list->rl_recs[index + 1],
(le16_to_cpu(rf_list->rl_used) - index - 1) *
sizeof(struct ocfs2_refcount_rec));
len = (le64_to_cpu(orig_rec->r_cpos) +
le32_to_cpu(orig_rec->r_clusters)) -
(le64_to_cpu(split_rec->r_cpos) +
le32_to_cpu(split_rec->r_clusters));
/*
* If we have "len", the we will split in the tail and move it
* to the end of the space we have just spared.
*/
if (len) {
tail_rec = &rf_list->rl_recs[index + recs_need];
memcpy(tail_rec, orig_rec, sizeof(struct ocfs2_refcount_rec));
le64_add_cpu(&tail_rec->r_cpos,
le32_to_cpu(tail_rec->r_clusters) - len);
tail_rec->r_clusters = cpu_to_le32(len);
}
/*
* If the split pos isn't the same as the original one, we need to
* split in the head.
*
* Note: We have the chance that split_rec.r_refcount = 0,
* recs_need = 0 and len > 0, which means we just cut the head from
* the orig_rec and in that case we have done some modification in
* orig_rec above, so the check for r_cpos is faked.
*/
if (split_rec->r_cpos != orig_rec->r_cpos && tail_rec != orig_rec) {
len = le64_to_cpu(split_rec->r_cpos) -
le64_to_cpu(orig_rec->r_cpos);
orig_rec->r_clusters = cpu_to_le32(len);
index++;
}
le16_add_cpu(&rf_list->rl_used, recs_need);
if (split_rec->r_refcount) {
rf_list->rl_recs[index] = *split_rec;
trace_ocfs2_split_refcount_rec_insert(
(unsigned long long)ref_leaf_bh->b_blocknr, index,
(unsigned long long)le64_to_cpu(split_rec->r_cpos),
le32_to_cpu(split_rec->r_clusters),
le32_to_cpu(split_rec->r_refcount));
if (merge)
ocfs2_refcount_rec_merge(rb, index);
}
ocfs2_journal_dirty(handle, ref_leaf_bh);
out:
brelse(new_bh);
return ret;
}
static int __ocfs2_increase_refcount(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
u64 cpos, u32 len, int merge,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret = 0, index;
struct buffer_head *ref_leaf_bh = NULL;
struct ocfs2_refcount_rec rec;
unsigned int set_len = 0;
trace_ocfs2_increase_refcount_begin(
(unsigned long long)ocfs2_metadata_cache_owner(ci),
(unsigned long long)cpos, len);
while (len) {
ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
cpos, len, &rec, &index,
&ref_leaf_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
set_len = le32_to_cpu(rec.r_clusters);
/*
* Here we may meet with 3 situations:
*
* 1. If we find an already existing record, and the length
* is the same, cool, we just need to increase the r_refcount
* and it is OK.
* 2. If we find a hole, just insert it with r_refcount = 1.
* 3. If we are in the middle of one extent record, split
* it.
*/
if (rec.r_refcount && le64_to_cpu(rec.r_cpos) == cpos &&
set_len <= len) {
trace_ocfs2_increase_refcount_change(
(unsigned long long)cpos, set_len,
le32_to_cpu(rec.r_refcount));
ret = ocfs2_change_refcount_rec(handle, ci,
ref_leaf_bh, index,
merge, 1);
if (ret) {
mlog_errno(ret);
goto out;
}
} else if (!rec.r_refcount) {
rec.r_refcount = cpu_to_le32(1);
trace_ocfs2_increase_refcount_insert(
(unsigned long long)le64_to_cpu(rec.r_cpos),
set_len);
ret = ocfs2_insert_refcount_rec(handle, ci, ref_root_bh,
ref_leaf_bh,
&rec, index,
merge, meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
} else {
set_len = min((u64)(cpos + len),
le64_to_cpu(rec.r_cpos) + set_len) - cpos;
rec.r_cpos = cpu_to_le64(cpos);
rec.r_clusters = cpu_to_le32(set_len);
le32_add_cpu(&rec.r_refcount, 1);
trace_ocfs2_increase_refcount_split(
(unsigned long long)le64_to_cpu(rec.r_cpos),
set_len, le32_to_cpu(rec.r_refcount));
ret = ocfs2_split_refcount_rec(handle, ci,
ref_root_bh, ref_leaf_bh,
&rec, index, merge,
meta_ac, dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
}
cpos += set_len;
len -= set_len;
brelse(ref_leaf_bh);
ref_leaf_bh = NULL;
}
out:
brelse(ref_leaf_bh);
return ret;
}
static int ocfs2_remove_refcount_extent(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct buffer_head *ref_leaf_bh,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret;
struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
struct ocfs2_extent_tree et;
BUG_ON(rb->rf_records.rl_used);
trace_ocfs2_remove_refcount_extent(
(unsigned long long)ocfs2_metadata_cache_owner(ci),
(unsigned long long)ref_leaf_bh->b_blocknr,
le32_to_cpu(rb->rf_cpos));
ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
ret = ocfs2_remove_extent(handle, &et, le32_to_cpu(rb->rf_cpos),
1, meta_ac, dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
ocfs2_remove_from_cache(ci, ref_leaf_bh);
/*
* add the freed block to the dealloc so that it will be freed
* when we run dealloc.
*/
ret = ocfs2_cache_block_dealloc(dealloc, EXTENT_ALLOC_SYSTEM_INODE,
le16_to_cpu(rb->rf_suballoc_slot),
le64_to_cpu(rb->rf_suballoc_loc),
le64_to_cpu(rb->rf_blkno),
le16_to_cpu(rb->rf_suballoc_bit));
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
le32_add_cpu(&rb->rf_clusters, -1);
/*
* check whether we need to restore the root refcount block if
* there is no leaf extent block at atll.
*/
if (!rb->rf_list.l_next_free_rec) {
BUG_ON(rb->rf_clusters);
trace_ocfs2_restore_refcount_block(
(unsigned long long)ref_root_bh->b_blocknr);
rb->rf_flags = 0;
rb->rf_parent = 0;
rb->rf_cpos = 0;
memset(&rb->rf_records, 0, sb->s_blocksize -
offsetof(struct ocfs2_refcount_block, rf_records));
rb->rf_records.rl_count =
cpu_to_le16(ocfs2_refcount_recs_per_rb(sb));
}
ocfs2_journal_dirty(handle, ref_root_bh);
out:
return ret;
}
int ocfs2_increase_refcount(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
u64 cpos, u32 len,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
return __ocfs2_increase_refcount(handle, ci, ref_root_bh,
cpos, len, 1,
meta_ac, dealloc);
}
static int ocfs2_decrease_refcount_rec(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
struct buffer_head *ref_leaf_bh,
int index, u64 cpos, unsigned int len,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret;
struct ocfs2_refcount_block *rb =
(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
struct ocfs2_refcount_rec *rec = &rb->rf_records.rl_recs[index];
BUG_ON(cpos < le64_to_cpu(rec->r_cpos));
BUG_ON(cpos + len >
le64_to_cpu(rec->r_cpos) + le32_to_cpu(rec->r_clusters));
trace_ocfs2_decrease_refcount_rec(
(unsigned long long)ocfs2_metadata_cache_owner(ci),
(unsigned long long)cpos, len);
if (cpos == le64_to_cpu(rec->r_cpos) &&
len == le32_to_cpu(rec->r_clusters))
ret = ocfs2_change_refcount_rec(handle, ci,
ref_leaf_bh, index, 1, -1);
else {
struct ocfs2_refcount_rec split = *rec;
split.r_cpos = cpu_to_le64(cpos);
split.r_clusters = cpu_to_le32(len);
le32_add_cpu(&split.r_refcount, -1);
ret = ocfs2_split_refcount_rec(handle, ci,
ref_root_bh, ref_leaf_bh,
&split, index, 1,
meta_ac, dealloc);
}
if (ret) {
mlog_errno(ret);
goto out;
}
/* Remove the leaf refcount block if it contains no refcount record. */
if (!rb->rf_records.rl_used && ref_leaf_bh != ref_root_bh) {
ret = ocfs2_remove_refcount_extent(handle, ci, ref_root_bh,
ref_leaf_bh, meta_ac,
dealloc);
if (ret)
mlog_errno(ret);
}
out:
return ret;
}
static int __ocfs2_decrease_refcount(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
u64 cpos, u32 len,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc,
int delete)
{
int ret = 0, index = 0;
struct ocfs2_refcount_rec rec;
unsigned int r_count = 0, r_len;
struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
struct buffer_head *ref_leaf_bh = NULL;
trace_ocfs2_decrease_refcount(
(unsigned long long)ocfs2_metadata_cache_owner(ci),
(unsigned long long)cpos, len, delete);
while (len) {
ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
cpos, len, &rec, &index,
&ref_leaf_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
r_count = le32_to_cpu(rec.r_refcount);
BUG_ON(r_count == 0);
if (!delete)
BUG_ON(r_count > 1);
r_len = min((u64)(cpos + len), le64_to_cpu(rec.r_cpos) +
le32_to_cpu(rec.r_clusters)) - cpos;
ret = ocfs2_decrease_refcount_rec(handle, ci, ref_root_bh,
ref_leaf_bh, index,
cpos, r_len,
meta_ac, dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
if (le32_to_cpu(rec.r_refcount) == 1 && delete) {
ret = ocfs2_cache_cluster_dealloc(dealloc,
ocfs2_clusters_to_blocks(sb, cpos),
r_len);
if (ret) {
mlog_errno(ret);
goto out;
}
}
cpos += r_len;
len -= r_len;
brelse(ref_leaf_bh);
ref_leaf_bh = NULL;
}
out:
brelse(ref_leaf_bh);
return ret;
}
/* Caller must hold refcount tree lock. */
int ocfs2_decrease_refcount(struct inode *inode,
handle_t *handle, u32 cpos, u32 len,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc,
int delete)
{
int ret;
u64 ref_blkno;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct buffer_head *ref_root_bh = NULL;
struct ocfs2_refcount_tree *tree;
BUG_ON(!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
ret = ocfs2_get_refcount_block(inode, &ref_blkno);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb), ref_blkno, &tree);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_read_refcount_block(&tree->rf_ci, tree->rf_blkno,
&ref_root_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = __ocfs2_decrease_refcount(handle, &tree->rf_ci, ref_root_bh,
cpos, len, meta_ac, dealloc, delete);
if (ret)
mlog_errno(ret);
out:
brelse(ref_root_bh);
return ret;
}
/*
* Mark the already-existing extent at cpos as refcounted for len clusters.
* This adds the refcount extent flag.
*
* If the existing extent is larger than the request, initiate a
* split. An attempt will be made at merging with adjacent extents.
*
* The caller is responsible for passing down meta_ac if we'll need it.
*/
static int ocfs2_mark_extent_refcounted(struct inode *inode,
struct ocfs2_extent_tree *et,
handle_t *handle, u32 cpos,
u32 len, u32 phys,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret;
trace_ocfs2_mark_extent_refcounted(OCFS2_I(inode)->ip_blkno,
cpos, len, phys);
if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
ocfs2_error(inode->i_sb, "Inode %lu want to use refcount "
"tree, but the feature bit is not set in the "
"super block.", inode->i_ino);
ret = -EROFS;
goto out;
}
ret = ocfs2_change_extent_flag(handle, et, cpos,
len, phys, meta_ac, dealloc,
OCFS2_EXT_REFCOUNTED, 0);
if (ret)
mlog_errno(ret);
out:
return ret;
}
/*
* Given some contiguous physical clusters, calculate what we need
* for modifying their refcount.
*/
static int ocfs2_calc_refcount_meta_credits(struct super_block *sb,
struct ocfs2_caching_info *ci,
struct buffer_head *ref_root_bh,
u64 start_cpos,
u32 clusters,
int *meta_add,
int *credits)
{
int ret = 0, index, ref_blocks = 0, recs_add = 0;
u64 cpos = start_cpos;
struct ocfs2_refcount_block *rb;
struct ocfs2_refcount_rec rec;
struct buffer_head *ref_leaf_bh = NULL, *prev_bh = NULL;
u32 len;
while (clusters) {
ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
cpos, clusters, &rec,
&index, &ref_leaf_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
if (ref_leaf_bh != prev_bh) {
/*
* Now we encounter a new leaf block, so calculate
* whether we need to extend the old leaf.
*/
if (prev_bh) {
rb = (struct ocfs2_refcount_block *)
prev_bh->b_data;
if (le16_to_cpu(rb->rf_records.rl_used) +
recs_add >
le16_to_cpu(rb->rf_records.rl_count))
ref_blocks++;
}
recs_add = 0;
*credits += 1;
brelse(prev_bh);
prev_bh = ref_leaf_bh;
get_bh(prev_bh);
}
rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
trace_ocfs2_calc_refcount_meta_credits_iterate(
recs_add, (unsigned long long)cpos, clusters,
(unsigned long long)le64_to_cpu(rec.r_cpos),
le32_to_cpu(rec.r_clusters),
le32_to_cpu(rec.r_refcount), index);
len = min((u64)cpos + clusters, le64_to_cpu(rec.r_cpos) +
le32_to_cpu(rec.r_clusters)) - cpos;
/*
* We record all the records which will be inserted to the
* same refcount block, so that we can tell exactly whether
* we need a new refcount block or not.
*
* If we will insert a new one, this is easy and only happens
* during adding refcounted flag to the extent, so we don't
* have a chance of spliting. We just need one record.
*
* If the refcount rec already exists, that would be a little
* complicated. we may have to:
* 1) split at the beginning if the start pos isn't aligned.
* we need 1 more record in this case.
* 2) split int the end if the end pos isn't aligned.
* we need 1 more record in this case.
* 3) split in the middle because of file system fragmentation.
* we need 2 more records in this case(we can't detect this
* beforehand, so always think of the worst case).
*/
if (rec.r_refcount) {
recs_add += 2;
/* Check whether we need a split at the beginning. */
if (cpos == start_cpos &&
cpos != le64_to_cpu(rec.r_cpos))
recs_add++;
/* Check whether we need a split in the end. */
if (cpos + clusters < le64_to_cpu(rec.r_cpos) +
le32_to_cpu(rec.r_clusters))
recs_add++;
} else
recs_add++;
brelse(ref_leaf_bh);
ref_leaf_bh = NULL;
clusters -= len;
cpos += len;
}
if (prev_bh) {
rb = (struct ocfs2_refcount_block *)prev_bh->b_data;
if (le16_to_cpu(rb->rf_records.rl_used) + recs_add >
le16_to_cpu(rb->rf_records.rl_count))
ref_blocks++;
*credits += 1;
}
if (!ref_blocks)
goto out;
*meta_add += ref_blocks;
*credits += ref_blocks;
/*
* So we may need ref_blocks to insert into the tree.
* That also means we need to change the b-tree and add that number
* of records since we never merge them.
* We need one more block for expansion since the new created leaf
* block is also full and needs split.
*/
rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
if (le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL) {
struct ocfs2_extent_tree et;
ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
*meta_add += ocfs2_extend_meta_needed(et.et_root_el);
*credits += ocfs2_calc_extend_credits(sb,
et.et_root_el,
ref_blocks);
} else {
*credits += OCFS2_EXPAND_REFCOUNT_TREE_CREDITS;
*meta_add += 1;
}
out:
trace_ocfs2_calc_refcount_meta_credits(
(unsigned long long)start_cpos, clusters,
*meta_add, *credits);
brelse(ref_leaf_bh);
brelse(prev_bh);
return ret;
}
/*
* For refcount tree, we will decrease some contiguous clusters
* refcount count, so just go through it to see how many blocks
* we gonna touch and whether we need to create new blocks.
*
* Normally the refcount blocks store these refcount should be
* contiguous also, so that we can get the number easily.
* We will at most add split 2 refcount records and 2 more
* refcount blocks, so just check it in a rough way.
*
* Caller must hold refcount tree lock.
*/
int ocfs2_prepare_refcount_change_for_del(struct inode *inode,
u64 refcount_loc,
u64 phys_blkno,
u32 clusters,
int *credits,
int *ref_blocks)
{
int ret;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct buffer_head *ref_root_bh = NULL;
struct ocfs2_refcount_tree *tree;
u64 start_cpos = ocfs2_blocks_to_clusters(inode->i_sb, phys_blkno);
if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
ocfs2_error(inode->i_sb, "Inode %lu want to use refcount "
"tree, but the feature bit is not set in the "
"super block.", inode->i_ino);
ret = -EROFS;
goto out;
}
BUG_ON(!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb),
refcount_loc, &tree);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_read_refcount_block(&tree->rf_ci, refcount_loc,
&ref_root_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_calc_refcount_meta_credits(inode->i_sb,
&tree->rf_ci,
ref_root_bh,
start_cpos, clusters,
ref_blocks, credits);
if (ret) {
mlog_errno(ret);
goto out;
}
trace_ocfs2_prepare_refcount_change_for_del(*ref_blocks, *credits);
out:
brelse(ref_root_bh);
return ret;
}
#define MAX_CONTIG_BYTES 1048576
static inline unsigned int ocfs2_cow_contig_clusters(struct super_block *sb)
{
return ocfs2_clusters_for_bytes(sb, MAX_CONTIG_BYTES);
}
static inline unsigned int ocfs2_cow_contig_mask(struct super_block *sb)
{
return ~(ocfs2_cow_contig_clusters(sb) - 1);
}
/*
* Given an extent that starts at 'start' and an I/O that starts at 'cpos',
* find an offset (start + (n * contig_clusters)) that is closest to cpos
* while still being less than or equal to it.
*
* The goal is to break the extent at a multiple of contig_clusters.
*/
static inline unsigned int ocfs2_cow_align_start(struct super_block *sb,
unsigned int start,
unsigned int cpos)
{
BUG_ON(start > cpos);
return start + ((cpos - start) & ocfs2_cow_contig_mask(sb));
}
/*
* Given a cluster count of len, pad it out so that it is a multiple
* of contig_clusters.
*/
static inline unsigned int ocfs2_cow_align_length(struct super_block *sb,
unsigned int len)
{
unsigned int padded =
(len + (ocfs2_cow_contig_clusters(sb) - 1)) &
ocfs2_cow_contig_mask(sb);
/* Did we wrap? */
if (padded < len)
padded = UINT_MAX;
return padded;
}
/*
* Calculate out the start and number of virtual clusters we need to to CoW.
*
* cpos is vitual start cluster position we want to do CoW in a
* file and write_len is the cluster length.
* max_cpos is the place where we want to stop CoW intentionally.
*
* Normal we will start CoW from the beginning of extent record cotaining cpos.
* We try to break up extents on boundaries of MAX_CONTIG_BYTES so that we
* get good I/O from the resulting extent tree.
*/
static int ocfs2_refcount_cal_cow_clusters(struct inode *inode,
struct ocfs2_extent_list *el,
u32 cpos,
u32 write_len,
u32 max_cpos,
u32 *cow_start,
u32 *cow_len)
{
int ret = 0;
int tree_height = le16_to_cpu(el->l_tree_depth), i;
struct buffer_head *eb_bh = NULL;
struct ocfs2_extent_block *eb = NULL;
struct ocfs2_extent_rec *rec;
unsigned int want_clusters, rec_end = 0;
int contig_clusters = ocfs2_cow_contig_clusters(inode->i_sb);
int leaf_clusters;
BUG_ON(cpos + write_len > max_cpos);
if (tree_height > 0) {
ret = ocfs2_find_leaf(INODE_CACHE(inode), el, cpos, &eb_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) eb_bh->b_data;
el = &eb->h_list;
if (el->l_tree_depth) {
ocfs2_error(inode->i_sb,
"Inode %lu has non zero tree depth in "
"leaf block %llu\n", inode->i_ino,
(unsigned long long)eb_bh->b_blocknr);
ret = -EROFS;
goto out;
}
}
*cow_len = 0;
for (i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
rec = &el->l_recs[i];
if (ocfs2_is_empty_extent(rec)) {
mlog_bug_on_msg(i != 0, "Inode %lu has empty record in "
"index %d\n", inode->i_ino, i);
continue;
}
if (le32_to_cpu(rec->e_cpos) +
le16_to_cpu(rec->e_leaf_clusters) <= cpos)
continue;
if (*cow_len == 0) {
/*
* We should find a refcounted record in the
* first pass.
*/
BUG_ON(!(rec->e_flags & OCFS2_EXT_REFCOUNTED));
*cow_start = le32_to_cpu(rec->e_cpos);
}
/*
* If we encounter a hole, a non-refcounted record or
* pass the max_cpos, stop the search.
*/
if ((!(rec->e_flags & OCFS2_EXT_REFCOUNTED)) ||
(*cow_len && rec_end != le32_to_cpu(rec->e_cpos)) ||
(max_cpos <= le32_to_cpu(rec->e_cpos)))
break;
leaf_clusters = le16_to_cpu(rec->e_leaf_clusters);
rec_end = le32_to_cpu(rec->e_cpos) + leaf_clusters;
if (rec_end > max_cpos) {
rec_end = max_cpos;
leaf_clusters = rec_end - le32_to_cpu(rec->e_cpos);
}
/*
* How many clusters do we actually need from
* this extent? First we see how many we actually
* need to complete the write. If that's smaller
* than contig_clusters, we try for contig_clusters.
*/
if (!*cow_len)
want_clusters = write_len;
else
want_clusters = (cpos + write_len) -
(*cow_start + *cow_len);
if (want_clusters < contig_clusters)
want_clusters = contig_clusters;
/*
* If the write does not cover the whole extent, we
* need to calculate how we're going to split the extent.
* We try to do it on contig_clusters boundaries.
*
* Any extent smaller than contig_clusters will be
* CoWed in its entirety.
*/
if (leaf_clusters <= contig_clusters)
*cow_len += leaf_clusters;
else if (*cow_len || (*cow_start == cpos)) {
/*
* This extent needs to be CoW'd from its
* beginning, so all we have to do is compute
* how many clusters to grab. We align
* want_clusters to the edge of contig_clusters
* to get better I/O.
*/
want_clusters = ocfs2_cow_align_length(inode->i_sb,
want_clusters);
if (leaf_clusters < want_clusters)
*cow_len += leaf_clusters;
else
*cow_len += want_clusters;
} else if ((*cow_start + contig_clusters) >=
(cpos + write_len)) {
/*
* Breaking off contig_clusters at the front
* of the extent will cover our write. That's
* easy.
*/
*cow_len = contig_clusters;
} else if ((rec_end - cpos) <= contig_clusters) {
/*
* Breaking off contig_clusters at the tail of
* this extent will cover cpos.
*/
*cow_start = rec_end - contig_clusters;
*cow_len = contig_clusters;
} else if ((rec_end - cpos) <= want_clusters) {
/*
* While we can't fit the entire write in this
* extent, we know that the write goes from cpos
* to the end of the extent. Break that off.
* We try to break it at some multiple of
* contig_clusters from the front of the extent.
* Failing that (ie, cpos is within
* contig_clusters of the front), we'll CoW the
* entire extent.
*/
*cow_start = ocfs2_cow_align_start(inode->i_sb,
*cow_start, cpos);
*cow_len = rec_end - *cow_start;
} else {
/*
* Ok, the entire write lives in the middle of
* this extent. Let's try to slice the extent up
* nicely. Optimally, our CoW region starts at
* m*contig_clusters from the beginning of the
* extent and goes for n*contig_clusters,
* covering the entire write.
*/
*cow_start = ocfs2_cow_align_start(inode->i_sb,
*cow_start, cpos);
want_clusters = (cpos + write_len) - *cow_start;
want_clusters = ocfs2_cow_align_length(inode->i_sb,
want_clusters);
if (*cow_start + want_clusters <= rec_end)
*cow_len = want_clusters;
else
*cow_len = rec_end - *cow_start;
}
/* Have we covered our entire write yet? */
if ((*cow_start + *cow_len) >= (cpos + write_len))
break;
/*
* If we reach the end of the extent block and don't get enough
* clusters, continue with the next extent block if possible.
*/
if (i + 1 == le16_to_cpu(el->l_next_free_rec) &&
eb && eb->h_next_leaf_blk) {
brelse(eb_bh);
eb_bh = NULL;
ret = ocfs2_read_extent_block(INODE_CACHE(inode),
le64_to_cpu(eb->h_next_leaf_blk),
&eb_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) eb_bh->b_data;
el = &eb->h_list;
i = -1;
}
}
out:
brelse(eb_bh);
return ret;
}
/*
* Prepare meta_ac, data_ac and calculate credits when we want to add some
* num_clusters in data_tree "et" and change the refcount for the old
* clusters(starting form p_cluster) in the refcount tree.
*
* Note:
* 1. since we may split the old tree, so we at most will need num_clusters + 2
* more new leaf records.
* 2. In some case, we may not need to reserve new clusters(e.g, reflink), so
* just give data_ac = NULL.
*/
static int ocfs2_lock_refcount_allocators(struct super_block *sb,
u32 p_cluster, u32 num_clusters,
struct ocfs2_extent_tree *et,
struct ocfs2_caching_info *ref_ci,
struct buffer_head *ref_root_bh,
struct ocfs2_alloc_context **meta_ac,
struct ocfs2_alloc_context **data_ac,
int *credits)
{
int ret = 0, meta_add = 0;
int num_free_extents = ocfs2_num_free_extents(OCFS2_SB(sb), et);
if (num_free_extents < 0) {
ret = num_free_extents;
mlog_errno(ret);
goto out;
}
if (num_free_extents < num_clusters + 2)
meta_add =
ocfs2_extend_meta_needed(et->et_root_el);
*credits += ocfs2_calc_extend_credits(sb, et->et_root_el,
num_clusters + 2);
ret = ocfs2_calc_refcount_meta_credits(sb, ref_ci, ref_root_bh,
p_cluster, num_clusters,
&meta_add, credits);
if (ret) {
mlog_errno(ret);
goto out;
}
trace_ocfs2_lock_refcount_allocators(meta_add, *credits);
ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(sb), meta_add,
meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
if (data_ac) {
ret = ocfs2_reserve_clusters(OCFS2_SB(sb), num_clusters,
data_ac);
if (ret)
mlog_errno(ret);
}
out:
if (ret) {
if (*meta_ac) {
ocfs2_free_alloc_context(*meta_ac);
*meta_ac = NULL;
}
}
return ret;
}
static int ocfs2_clear_cow_buffer(handle_t *handle, struct buffer_head *bh)
{
BUG_ON(buffer_dirty(bh));
clear_buffer_mapped(bh);
return 0;
}
int ocfs2_duplicate_clusters_by_page(handle_t *handle,
struct file *file,
u32 cpos, u32 old_cluster,
u32 new_cluster, u32 new_len)
{
int ret = 0, partial;
struct inode *inode = file->f_path.dentry->d_inode;
struct ocfs2_caching_info *ci = INODE_CACHE(inode);
struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
u64 new_block = ocfs2_clusters_to_blocks(sb, new_cluster);
struct page *page;
pgoff_t page_index;
unsigned int from, to, readahead_pages;
loff_t offset, end, map_end;
struct address_space *mapping = inode->i_mapping;
trace_ocfs2_duplicate_clusters_by_page(cpos, old_cluster,
new_cluster, new_len);
readahead_pages =
(ocfs2_cow_contig_clusters(sb) <<
OCFS2_SB(sb)->s_clustersize_bits) >> PAGE_CACHE_SHIFT;
offset = ((loff_t)cpos) << OCFS2_SB(sb)->s_clustersize_bits;
end = offset + (new_len << OCFS2_SB(sb)->s_clustersize_bits);
/*
* We only duplicate pages until we reach the page contains i_size - 1.
* So trim 'end' to i_size.
*/
if (end > i_size_read(inode))
end = i_size_read(inode);
while (offset < end) {
page_index = offset >> PAGE_CACHE_SHIFT;
map_end = ((loff_t)page_index + 1) << PAGE_CACHE_SHIFT;
if (map_end > end)
map_end = end;
/* from, to is the offset within the page. */
from = offset & (PAGE_CACHE_SIZE - 1);
to = PAGE_CACHE_SIZE;
if (map_end & (PAGE_CACHE_SIZE - 1))
to = map_end & (PAGE_CACHE_SIZE - 1);
page = find_or_create_page(mapping, page_index, GFP_NOFS);
/*
* In case PAGE_CACHE_SIZE <= CLUSTER_SIZE, This page
* can't be dirtied before we CoW it out.
*/
if (PAGE_CACHE_SIZE <= OCFS2_SB(sb)->s_clustersize)
BUG_ON(PageDirty(page));
if (PageReadahead(page)) {
page_cache_async_readahead(mapping,
&file->f_ra, file,
page, page_index,
readahead_pages);
}
if (!PageUptodate(page)) {
ret = block_read_full_page(page, ocfs2_get_block);
if (ret) {
mlog_errno(ret);
goto unlock;
}
lock_page(page);
}
if (page_has_buffers(page)) {
ret = walk_page_buffers(handle, page_buffers(page),
from, to, &partial,
ocfs2_clear_cow_buffer);
if (ret) {
mlog_errno(ret);
goto unlock;
}
}
ocfs2_map_and_dirty_page(inode, handle, from, to,
page, 0, &new_block);
mark_page_accessed(page);
unlock:
unlock_page(page);
page_cache_release(page);
page = NULL;
offset = map_end;
if (ret)
break;
}
return ret;
}
int ocfs2_duplicate_clusters_by_jbd(handle_t *handle,
struct file *file,
u32 cpos, u32 old_cluster,
u32 new_cluster, u32 new_len)
{
int ret = 0;
struct inode *inode = file->f_path.dentry->d_inode;
struct super_block *sb = inode->i_sb;
struct ocfs2_caching_info *ci = INODE_CACHE(inode);
int i, blocks = ocfs2_clusters_to_blocks(sb, new_len);
u64 old_block = ocfs2_clusters_to_blocks(sb, old_cluster);
u64 new_block = ocfs2_clusters_to_blocks(sb, new_cluster);
struct ocfs2_super *osb = OCFS2_SB(sb);
struct buffer_head *old_bh = NULL;
struct buffer_head *new_bh = NULL;
trace_ocfs2_duplicate_clusters_by_page(cpos, old_cluster,
new_cluster, new_len);
for (i = 0; i < blocks; i++, old_block++, new_block++) {
new_bh = sb_getblk(osb->sb, new_block);
if (new_bh == NULL) {
ret = -EIO;
mlog_errno(ret);
break;
}
ocfs2_set_new_buffer_uptodate(ci, new_bh);
ret = ocfs2_read_block(ci, old_block, &old_bh, NULL);
if (ret) {
mlog_errno(ret);
break;
}
ret = ocfs2_journal_access(handle, ci, new_bh,
OCFS2_JOURNAL_ACCESS_CREATE);
if (ret) {
mlog_errno(ret);
break;
}
memcpy(new_bh->b_data, old_bh->b_data, sb->s_blocksize);
ocfs2_journal_dirty(handle, new_bh);
brelse(new_bh);
brelse(old_bh);
new_bh = NULL;
old_bh = NULL;
}
brelse(new_bh);
brelse(old_bh);
return ret;
}
static int ocfs2_clear_ext_refcount(handle_t *handle,
struct ocfs2_extent_tree *et,
u32 cpos, u32 p_cluster, u32 len,
unsigned int ext_flags,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret, index;
struct ocfs2_extent_rec replace_rec;
struct ocfs2_path *path = NULL;
struct ocfs2_extent_list *el;
struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
u64 ino = ocfs2_metadata_cache_owner(et->et_ci);
trace_ocfs2_clear_ext_refcount((unsigned long long)ino,
cpos, len, p_cluster, ext_flags);
memset(&replace_rec, 0, sizeof(replace_rec));
replace_rec.e_cpos = cpu_to_le32(cpos);
replace_rec.e_leaf_clusters = cpu_to_le16(len);
replace_rec.e_blkno = cpu_to_le64(ocfs2_clusters_to_blocks(sb,
p_cluster));
replace_rec.e_flags = ext_flags;
replace_rec.e_flags &= ~OCFS2_EXT_REFCOUNTED;
path = ocfs2_new_path_from_et(et);
if (!path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(et->et_ci, path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
el = path_leaf_el(path);
index = ocfs2_search_extent_list(el, cpos);
if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
ocfs2_error(sb,
"Inode %llu has an extent at cpos %u which can no "
"longer be found.\n",
(unsigned long long)ino, cpos);
ret = -EROFS;
goto out;
}
ret = ocfs2_split_extent(handle, et, path, index,
&replace_rec, meta_ac, dealloc);
if (ret)
mlog_errno(ret);
out:
ocfs2_free_path(path);
return ret;
}
static int ocfs2_replace_clusters(handle_t *handle,
struct ocfs2_cow_context *context,
u32 cpos, u32 old,
u32 new, u32 len,
unsigned int ext_flags)
{
int ret;
struct ocfs2_caching_info *ci = context->data_et.et_ci;
u64 ino = ocfs2_metadata_cache_owner(ci);
trace_ocfs2_replace_clusters((unsigned long long)ino,
cpos, old, new, len, ext_flags);
/*If the old clusters is unwritten, no need to duplicate. */
if (!(ext_flags & OCFS2_EXT_UNWRITTEN)) {
ret = context->cow_duplicate_clusters(handle, context->file,
cpos, old, new, len);
if (ret) {
mlog_errno(ret);
goto out;
}
}
ret = ocfs2_clear_ext_refcount(handle, &context->data_et,
cpos, new, len, ext_flags,
context->meta_ac, &context->dealloc);
if (ret)
mlog_errno(ret);
out:
return ret;
}
int ocfs2_cow_sync_writeback(struct super_block *sb,
struct inode *inode,
u32 cpos, u32 num_clusters)
{
int ret = 0;
loff_t offset, end, map_end;
pgoff_t page_index;
struct page *page;
if (ocfs2_should_order_data(inode))
return 0;
offset = ((loff_t)cpos) << OCFS2_SB(sb)->s_clustersize_bits;
end = offset + (num_clusters << OCFS2_SB(sb)->s_clustersize_bits);
ret = filemap_fdatawrite_range(inode->i_mapping,
offset, end - 1);
if (ret < 0) {
mlog_errno(ret);
return ret;
}
while (offset < end) {
page_index = offset >> PAGE_CACHE_SHIFT;
map_end = ((loff_t)page_index + 1) << PAGE_CACHE_SHIFT;
if (map_end > end)
map_end = end;
page = find_or_create_page(inode->i_mapping,
page_index, GFP_NOFS);
BUG_ON(!page);
wait_on_page_writeback(page);
if (PageError(page)) {
ret = -EIO;
mlog_errno(ret);
} else
mark_page_accessed(page);
unlock_page(page);
page_cache_release(page);
page = NULL;
offset = map_end;
if (ret)
break;
}
return ret;
}
static int ocfs2_di_get_clusters(struct ocfs2_cow_context *context,
u32 v_cluster, u32 *p_cluster,
u32 *num_clusters,
unsigned int *extent_flags)
{
return ocfs2_get_clusters(context->inode, v_cluster, p_cluster,
num_clusters, extent_flags);
}
static int ocfs2_make_clusters_writable(struct super_block *sb,
struct ocfs2_cow_context *context,
u32 cpos, u32 p_cluster,
u32 num_clusters, unsigned int e_flags)
{
int ret, delete, index, credits = 0;
u32 new_bit, new_len, orig_num_clusters;
unsigned int set_len;
struct ocfs2_super *osb = OCFS2_SB(sb);
handle_t *handle;
struct buffer_head *ref_leaf_bh = NULL;
struct ocfs2_caching_info *ref_ci = &context->ref_tree->rf_ci;
struct ocfs2_refcount_rec rec;
trace_ocfs2_make_clusters_writable(cpos, p_cluster,
num_clusters, e_flags);
ret = ocfs2_lock_refcount_allocators(sb, p_cluster, num_clusters,
&context->data_et,
ref_ci,
context->ref_root_bh,
&context->meta_ac,
&context->data_ac, &credits);
if (ret) {
mlog_errno(ret);
return ret;
}
if (context->post_refcount)
credits += context->post_refcount->credits;
credits += context->extra_credits;
handle = ocfs2_start_trans(osb, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
orig_num_clusters = num_clusters;
while (num_clusters) {
ret = ocfs2_get_refcount_rec(ref_ci, context->ref_root_bh,
p_cluster, num_clusters,
&rec, &index, &ref_leaf_bh);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
BUG_ON(!rec.r_refcount);
set_len = min((u64)p_cluster + num_clusters,
le64_to_cpu(rec.r_cpos) +
le32_to_cpu(rec.r_clusters)) - p_cluster;
/*
* There are many different situation here.
* 1. If refcount == 1, remove the flag and don't COW.
* 2. If refcount > 1, allocate clusters.
* Here we may not allocate r_len once at a time, so continue
* until we reach num_clusters.
*/
if (le32_to_cpu(rec.r_refcount) == 1) {
delete = 0;
ret = ocfs2_clear_ext_refcount(handle,
&context->data_et,
cpos, p_cluster,
set_len, e_flags,
context->meta_ac,
&context->dealloc);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
} else {
delete = 1;
ret = __ocfs2_claim_clusters(handle,
context->data_ac,
1, set_len,
&new_bit, &new_len);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
ret = ocfs2_replace_clusters(handle, context,
cpos, p_cluster, new_bit,
new_len, e_flags);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
set_len = new_len;
}
ret = __ocfs2_decrease_refcount(handle, ref_ci,
context->ref_root_bh,
p_cluster, set_len,
context->meta_ac,
&context->dealloc, delete);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
cpos += set_len;
p_cluster += set_len;
num_clusters -= set_len;
brelse(ref_leaf_bh);
ref_leaf_bh = NULL;
}
/* handle any post_cow action. */
if (context->post_refcount && context->post_refcount->func) {
ret = context->post_refcount->func(context->inode, handle,
context->post_refcount->para);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
}
/*
* Here we should write the new page out first if we are
* in write-back mode.
*/
if (context->get_clusters == ocfs2_di_get_clusters) {
ret = ocfs2_cow_sync_writeback(sb, context->inode, cpos,
orig_num_clusters);
if (ret)
mlog_errno(ret);
}
out_commit:
ocfs2_commit_trans(osb, handle);
out:
if (context->data_ac) {
ocfs2_free_alloc_context(context->data_ac);
context->data_ac = NULL;
}
if (context->meta_ac) {
ocfs2_free_alloc_context(context->meta_ac);
context->meta_ac = NULL;
}
brelse(ref_leaf_bh);
return ret;
}
static int ocfs2_replace_cow(struct ocfs2_cow_context *context)
{
int ret = 0;
struct inode *inode = context->inode;
u32 cow_start = context->cow_start, cow_len = context->cow_len;
u32 p_cluster, num_clusters;
unsigned int ext_flags;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
ocfs2_error(inode->i_sb, "Inode %lu want to use refcount "
"tree, but the feature bit is not set in the "
"super block.", inode->i_ino);
return -EROFS;
}
ocfs2_init_dealloc_ctxt(&context->dealloc);
while (cow_len) {
ret = context->get_clusters(context, cow_start, &p_cluster,
&num_clusters, &ext_flags);
if (ret) {
mlog_errno(ret);
break;
}
BUG_ON(!(ext_flags & OCFS2_EXT_REFCOUNTED));
if (cow_len < num_clusters)
num_clusters = cow_len;
ret = ocfs2_make_clusters_writable(inode->i_sb, context,
cow_start, p_cluster,
num_clusters, ext_flags);
if (ret) {
mlog_errno(ret);
break;
}
cow_len -= num_clusters;
cow_start += num_clusters;
}
if (ocfs2_dealloc_has_cluster(&context->dealloc)) {
ocfs2_schedule_truncate_log_flush(osb, 1);
ocfs2_run_deallocs(osb, &context->dealloc);
}
return ret;
}
static void ocfs2_readahead_for_cow(struct inode *inode,
struct file *file,
u32 start, u32 len)
{
struct address_space *mapping;
pgoff_t index;
unsigned long num_pages;
int cs_bits = OCFS2_SB(inode->i_sb)->s_clustersize_bits;
if (!file)
return;
mapping = file->f_mapping;
num_pages = (len << cs_bits) >> PAGE_CACHE_SHIFT;
if (!num_pages)
num_pages = 1;
index = ((loff_t)start << cs_bits) >> PAGE_CACHE_SHIFT;
page_cache_sync_readahead(mapping, &file->f_ra, file,
index, num_pages);
}
/*
* Starting at cpos, try to CoW write_len clusters. Don't CoW
* past max_cpos. This will stop when it runs into a hole or an
* unrefcounted extent.
*/
static int ocfs2_refcount_cow_hunk(struct inode *inode,
struct file *file,
struct buffer_head *di_bh,
u32 cpos, u32 write_len, u32 max_cpos)
{
int ret;
u32 cow_start = 0, cow_len = 0;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
struct buffer_head *ref_root_bh = NULL;
struct ocfs2_refcount_tree *ref_tree;
struct ocfs2_cow_context *context = NULL;
BUG_ON(!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
ret = ocfs2_refcount_cal_cow_clusters(inode, &di->id2.i_list,
cpos, write_len, max_cpos,
&cow_start, &cow_len);
if (ret) {
mlog_errno(ret);
goto out;
}
trace_ocfs2_refcount_cow_hunk(OCFS2_I(inode)->ip_blkno,
cpos, write_len, max_cpos,
cow_start, cow_len);
BUG_ON(cow_len == 0);
ocfs2_readahead_for_cow(inode, file, cow_start, cow_len);
context = kzalloc(sizeof(struct ocfs2_cow_context), GFP_NOFS);
if (!context) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_lock_refcount_tree(osb, le64_to_cpu(di->i_refcount_loc),
1, &ref_tree, &ref_root_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
context->inode = inode;
context->cow_start = cow_start;
context->cow_len = cow_len;
context->ref_tree = ref_tree;
context->ref_root_bh = ref_root_bh;
context->cow_duplicate_clusters = ocfs2_duplicate_clusters_by_page;
context->get_clusters = ocfs2_di_get_clusters;
context->file = file;
ocfs2_init_dinode_extent_tree(&context->data_et,
INODE_CACHE(inode), di_bh);
ret = ocfs2_replace_cow(context);
if (ret)
mlog_errno(ret);
/*
* truncate the extent map here since no matter whether we meet with
* any error during the action, we shouldn't trust cached extent map
* any more.
*/
ocfs2_extent_map_trunc(inode, cow_start);
ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
brelse(ref_root_bh);
out:
kfree(context);
return ret;
}
/*
* CoW any and all clusters between cpos and cpos+write_len.
* Don't CoW past max_cpos. If this returns successfully, all
* clusters between cpos and cpos+write_len are safe to modify.
*/
int ocfs2_refcount_cow(struct inode *inode,
struct file *file,
struct buffer_head *di_bh,
u32 cpos, u32 write_len, u32 max_cpos)
{
int ret = 0;
u32 p_cluster, num_clusters;
unsigned int ext_flags;
while (write_len) {
ret = ocfs2_get_clusters(inode, cpos, &p_cluster,
&num_clusters, &ext_flags);
if (ret) {
mlog_errno(ret);
break;
}
if (write_len < num_clusters)
num_clusters = write_len;
if (ext_flags & OCFS2_EXT_REFCOUNTED) {
ret = ocfs2_refcount_cow_hunk(inode, file, di_bh, cpos,
num_clusters, max_cpos);
if (ret) {
mlog_errno(ret);
break;
}
}
write_len -= num_clusters;
cpos += num_clusters;
}
return ret;
}
static int ocfs2_xattr_value_get_clusters(struct ocfs2_cow_context *context,
u32 v_cluster, u32 *p_cluster,
u32 *num_clusters,
unsigned int *extent_flags)
{
struct inode *inode = context->inode;
struct ocfs2_xattr_value_root *xv = context->cow_object;
return ocfs2_xattr_get_clusters(inode, v_cluster, p_cluster,
num_clusters, &xv->xr_list,
extent_flags);
}
/*
* Given a xattr value root, calculate the most meta/credits we need for
* refcount tree change if we truncate it to 0.
*/
int ocfs2_refcounted_xattr_delete_need(struct inode *inode,
struct ocfs2_caching_info *ref_ci,
struct buffer_head *ref_root_bh,
struct ocfs2_xattr_value_root *xv,
int *meta_add, int *credits)
{
int ret = 0, index, ref_blocks = 0;
u32 p_cluster, num_clusters;
u32 cpos = 0, clusters = le32_to_cpu(xv->xr_clusters);
struct ocfs2_refcount_block *rb;
struct ocfs2_refcount_rec rec;
struct buffer_head *ref_leaf_bh = NULL;
while (cpos < clusters) {
ret = ocfs2_xattr_get_clusters(inode, cpos, &p_cluster,
&num_clusters, &xv->xr_list,
NULL);
if (ret) {
mlog_errno(ret);
goto out;
}
cpos += num_clusters;
while (num_clusters) {
ret = ocfs2_get_refcount_rec(ref_ci, ref_root_bh,
p_cluster, num_clusters,
&rec, &index,
&ref_leaf_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
BUG_ON(!rec.r_refcount);
rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
/*
* We really don't know whether the other clusters is in
* this refcount block or not, so just take the worst
* case that all the clusters are in this block and each
* one will split a refcount rec, so totally we need
* clusters * 2 new refcount rec.
*/
if (le16_to_cpu(rb->rf_records.rl_used) + clusters * 2 >
le16_to_cpu(rb->rf_records.rl_count))
ref_blocks++;
*credits += 1;
brelse(ref_leaf_bh);
ref_leaf_bh = NULL;
if (num_clusters <= le32_to_cpu(rec.r_clusters))
break;
else
num_clusters -= le32_to_cpu(rec.r_clusters);
p_cluster += num_clusters;
}
}
*meta_add += ref_blocks;
if (!ref_blocks)
goto out;
rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
if (le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL)
*credits += OCFS2_EXPAND_REFCOUNT_TREE_CREDITS;
else {
struct ocfs2_extent_tree et;
ocfs2_init_refcount_extent_tree(&et, ref_ci, ref_root_bh);
*credits += ocfs2_calc_extend_credits(inode->i_sb,
et.et_root_el,
ref_blocks);
}
out:
brelse(ref_leaf_bh);
return ret;
}
/*
* Do CoW for xattr.
*/
int ocfs2_refcount_cow_xattr(struct inode *inode,
struct ocfs2_dinode *di,
struct ocfs2_xattr_value_buf *vb,
struct ocfs2_refcount_tree *ref_tree,
struct buffer_head *ref_root_bh,
u32 cpos, u32 write_len,
struct ocfs2_post_refcount *post)
{
int ret;
struct ocfs2_xattr_value_root *xv = vb->vb_xv;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_cow_context *context = NULL;
u32 cow_start, cow_len;
BUG_ON(!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
ret = ocfs2_refcount_cal_cow_clusters(inode, &xv->xr_list,
cpos, write_len, UINT_MAX,
&cow_start, &cow_len);
if (ret) {
mlog_errno(ret);
goto out;
}
BUG_ON(cow_len == 0);
context = kzalloc(sizeof(struct ocfs2_cow_context), GFP_NOFS);
if (!context) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
context->inode = inode;
context->cow_start = cow_start;
context->cow_len = cow_len;
context->ref_tree = ref_tree;
context->ref_root_bh = ref_root_bh;
context->cow_object = xv;
context->cow_duplicate_clusters = ocfs2_duplicate_clusters_by_jbd;
/* We need the extra credits for duplicate_clusters by jbd. */
context->extra_credits =
ocfs2_clusters_to_blocks(inode->i_sb, 1) * cow_len;
context->get_clusters = ocfs2_xattr_value_get_clusters;
context->post_refcount = post;
ocfs2_init_xattr_value_extent_tree(&context->data_et,
INODE_CACHE(inode), vb);
ret = ocfs2_replace_cow(context);
if (ret)
mlog_errno(ret);
out:
kfree(context);
return ret;
}
/*
* Insert a new extent into refcount tree and mark a extent rec
* as refcounted in the dinode tree.
*/
int ocfs2_add_refcount_flag(struct inode *inode,
struct ocfs2_extent_tree *data_et,
struct ocfs2_caching_info *ref_ci,
struct buffer_head *ref_root_bh,
u32 cpos, u32 p_cluster, u32 num_clusters,
struct ocfs2_cached_dealloc_ctxt *dealloc,
struct ocfs2_post_refcount *post)
{
int ret;
handle_t *handle;
int credits = 1, ref_blocks = 0;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_alloc_context *meta_ac = NULL;
ret = ocfs2_calc_refcount_meta_credits(inode->i_sb,
ref_ci, ref_root_bh,
p_cluster, num_clusters,
&ref_blocks, &credits);
if (ret) {
mlog_errno(ret);
goto out;
}
trace_ocfs2_add_refcount_flag(ref_blocks, credits);
if (ref_blocks) {
ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(inode->i_sb),
ref_blocks, &meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
}
if (post)
credits += post->credits;
handle = ocfs2_start_trans(osb, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
ret = ocfs2_mark_extent_refcounted(inode, data_et, handle,
cpos, num_clusters, p_cluster,
meta_ac, dealloc);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
ret = __ocfs2_increase_refcount(handle, ref_ci, ref_root_bh,
p_cluster, num_clusters, 0,
meta_ac, dealloc);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
if (post && post->func) {
ret = post->func(inode, handle, post->para);
if (ret)
mlog_errno(ret);
}
out_commit:
ocfs2_commit_trans(osb, handle);
out:
if (meta_ac)
ocfs2_free_alloc_context(meta_ac);
return ret;
}
static int ocfs2_change_ctime(struct inode *inode,
struct buffer_head *di_bh)
{
int ret;
handle_t *handle;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
handle = ocfs2_start_trans(OCFS2_SB(inode->i_sb),
OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
inode->i_ctime = CURRENT_TIME;
di->i_ctime = cpu_to_le64(inode->i_ctime.tv_sec);
di->i_ctime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
ocfs2_journal_dirty(handle, di_bh);
out_commit:
ocfs2_commit_trans(OCFS2_SB(inode->i_sb), handle);
out:
return ret;
}
static int ocfs2_attach_refcount_tree(struct inode *inode,
struct buffer_head *di_bh)
{
int ret, data_changed = 0;
struct buffer_head *ref_root_bh = NULL;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_refcount_tree *ref_tree;
unsigned int ext_flags;
loff_t size;
u32 cpos, num_clusters, clusters, p_cluster;
struct ocfs2_cached_dealloc_ctxt dealloc;
struct ocfs2_extent_tree di_et;
ocfs2_init_dealloc_ctxt(&dealloc);
if (!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL)) {
ret = ocfs2_create_refcount_tree(inode, di_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
}
BUG_ON(!di->i_refcount_loc);
ret = ocfs2_lock_refcount_tree(osb,
le64_to_cpu(di->i_refcount_loc), 1,
&ref_tree, &ref_root_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL)
goto attach_xattr;
ocfs2_init_dinode_extent_tree(&di_et, INODE_CACHE(inode), di_bh);
size = i_size_read(inode);
clusters = ocfs2_clusters_for_bytes(inode->i_sb, size);
cpos = 0;
while (cpos < clusters) {
ret = ocfs2_get_clusters(inode, cpos, &p_cluster,
&num_clusters, &ext_flags);
if (p_cluster && !(ext_flags & OCFS2_EXT_REFCOUNTED)) {
ret = ocfs2_add_refcount_flag(inode, &di_et,
&ref_tree->rf_ci,
ref_root_bh, cpos,
p_cluster, num_clusters,
&dealloc, NULL);
if (ret) {
mlog_errno(ret);
goto unlock;
}
data_changed = 1;
}
cpos += num_clusters;
}
attach_xattr:
if (oi->ip_dyn_features & OCFS2_HAS_XATTR_FL) {
ret = ocfs2_xattr_attach_refcount_tree(inode, di_bh,
&ref_tree->rf_ci,
ref_root_bh,
&dealloc);
if (ret) {
mlog_errno(ret);
goto unlock;
}
}
if (data_changed) {
ret = ocfs2_change_ctime(inode, di_bh);
if (ret)
mlog_errno(ret);
}
unlock:
ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
brelse(ref_root_bh);
if (!ret && ocfs2_dealloc_has_cluster(&dealloc)) {
ocfs2_schedule_truncate_log_flush(osb, 1);
ocfs2_run_deallocs(osb, &dealloc);
}
out:
/*
* Empty the extent map so that we may get the right extent
* record from the disk.
*/
ocfs2_extent_map_trunc(inode, 0);
return ret;
}
static int ocfs2_add_refcounted_extent(struct inode *inode,
struct ocfs2_extent_tree *et,
struct ocfs2_caching_info *ref_ci,
struct buffer_head *ref_root_bh,
u32 cpos, u32 p_cluster, u32 num_clusters,
unsigned int ext_flags,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret;
handle_t *handle;
int credits = 0;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_alloc_context *meta_ac = NULL;
ret = ocfs2_lock_refcount_allocators(inode->i_sb,
p_cluster, num_clusters,
et, ref_ci,
ref_root_bh, &meta_ac,
NULL, &credits);
if (ret) {
mlog_errno(ret);
goto out;
}
handle = ocfs2_start_trans(osb, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
ret = ocfs2_insert_extent(handle, et, cpos,
ocfs2_clusters_to_blocks(inode->i_sb, p_cluster),
num_clusters, ext_flags, meta_ac);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
ret = ocfs2_increase_refcount(handle, ref_ci, ref_root_bh,
p_cluster, num_clusters,
meta_ac, dealloc);
if (ret)
mlog_errno(ret);
out_commit:
ocfs2_commit_trans(osb, handle);
out:
if (meta_ac)
ocfs2_free_alloc_context(meta_ac);
return ret;
}
static int ocfs2_duplicate_inline_data(struct inode *s_inode,
struct buffer_head *s_bh,
struct inode *t_inode,
struct buffer_head *t_bh)
{
int ret;
handle_t *handle;
struct ocfs2_super *osb = OCFS2_SB(s_inode->i_sb);
struct ocfs2_dinode *s_di = (struct ocfs2_dinode *)s_bh->b_data;
struct ocfs2_dinode *t_di = (struct ocfs2_dinode *)t_bh->b_data;
BUG_ON(!(OCFS2_I(s_inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL));
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_di(handle, INODE_CACHE(t_inode), t_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
t_di->id2.i_data.id_count = s_di->id2.i_data.id_count;
memcpy(t_di->id2.i_data.id_data, s_di->id2.i_data.id_data,
le16_to_cpu(s_di->id2.i_data.id_count));
spin_lock(&OCFS2_I(t_inode)->ip_lock);
OCFS2_I(t_inode)->ip_dyn_features |= OCFS2_INLINE_DATA_FL;
t_di->i_dyn_features = cpu_to_le16(OCFS2_I(t_inode)->ip_dyn_features);
spin_unlock(&OCFS2_I(t_inode)->ip_lock);
ocfs2_journal_dirty(handle, t_bh);
out_commit:
ocfs2_commit_trans(osb, handle);
out:
return ret;
}
static int ocfs2_duplicate_extent_list(struct inode *s_inode,
struct inode *t_inode,
struct buffer_head *t_bh,
struct ocfs2_caching_info *ref_ci,
struct buffer_head *ref_root_bh,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret = 0;
u32 p_cluster, num_clusters, clusters, cpos;
loff_t size;
unsigned int ext_flags;
struct ocfs2_extent_tree et;
ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(t_inode), t_bh);
size = i_size_read(s_inode);
clusters = ocfs2_clusters_for_bytes(s_inode->i_sb, size);
cpos = 0;
while (cpos < clusters) {
ret = ocfs2_get_clusters(s_inode, cpos, &p_cluster,
&num_clusters, &ext_flags);
if (p_cluster) {
ret = ocfs2_add_refcounted_extent(t_inode, &et,
ref_ci, ref_root_bh,
cpos, p_cluster,
num_clusters,
ext_flags,
dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
}
cpos += num_clusters;
}
out:
return ret;
}
/*
* change the new file's attributes to the src.
*
* reflink creates a snapshot of a file, that means the attributes
* must be identical except for three exceptions - nlink, ino, and ctime.
*/
static int ocfs2_complete_reflink(struct inode *s_inode,
struct buffer_head *s_bh,
struct inode *t_inode,
struct buffer_head *t_bh,
bool preserve)
{
int ret;
handle_t *handle;
struct ocfs2_dinode *s_di = (struct ocfs2_dinode *)s_bh->b_data;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)t_bh->b_data;
loff_t size = i_size_read(s_inode);
handle = ocfs2_start_trans(OCFS2_SB(t_inode->i_sb),
OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
return ret;
}
ret = ocfs2_journal_access_di(handle, INODE_CACHE(t_inode), t_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
spin_lock(&OCFS2_I(t_inode)->ip_lock);
OCFS2_I(t_inode)->ip_clusters = OCFS2_I(s_inode)->ip_clusters;
OCFS2_I(t_inode)->ip_attr = OCFS2_I(s_inode)->ip_attr;
OCFS2_I(t_inode)->ip_dyn_features = OCFS2_I(s_inode)->ip_dyn_features;
spin_unlock(&OCFS2_I(t_inode)->ip_lock);
i_size_write(t_inode, size);
t_inode->i_blocks = s_inode->i_blocks;
di->i_xattr_inline_size = s_di->i_xattr_inline_size;
di->i_clusters = s_di->i_clusters;
di->i_size = s_di->i_size;
di->i_dyn_features = s_di->i_dyn_features;
di->i_attr = s_di->i_attr;
if (preserve) {
t_inode->i_uid = s_inode->i_uid;
t_inode->i_gid = s_inode->i_gid;
t_inode->i_mode = s_inode->i_mode;
di->i_uid = s_di->i_uid;
di->i_gid = s_di->i_gid;
di->i_mode = s_di->i_mode;
/*
* update time.
* we want mtime to appear identical to the source and
* update ctime.
*/
t_inode->i_ctime = CURRENT_TIME;
di->i_ctime = cpu_to_le64(t_inode->i_ctime.tv_sec);
di->i_ctime_nsec = cpu_to_le32(t_inode->i_ctime.tv_nsec);
t_inode->i_mtime = s_inode->i_mtime;
di->i_mtime = s_di->i_mtime;
di->i_mtime_nsec = s_di->i_mtime_nsec;
}
ocfs2_journal_dirty(handle, t_bh);
out_commit:
ocfs2_commit_trans(OCFS2_SB(t_inode->i_sb), handle);
return ret;
}
static int ocfs2_create_reflink_node(struct inode *s_inode,
struct buffer_head *s_bh,
struct inode *t_inode,
struct buffer_head *t_bh,
bool preserve)
{
int ret;
struct buffer_head *ref_root_bh = NULL;
struct ocfs2_cached_dealloc_ctxt dealloc;
struct ocfs2_super *osb = OCFS2_SB(s_inode->i_sb);
struct ocfs2_refcount_block *rb;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)s_bh->b_data;
struct ocfs2_refcount_tree *ref_tree;
ocfs2_init_dealloc_ctxt(&dealloc);
ret = ocfs2_set_refcount_tree(t_inode, t_bh,
le64_to_cpu(di->i_refcount_loc));
if (ret) {
mlog_errno(ret);
goto out;
}
if (OCFS2_I(s_inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
ret = ocfs2_duplicate_inline_data(s_inode, s_bh,
t_inode, t_bh);
if (ret)
mlog_errno(ret);
goto out;
}
ret = ocfs2_lock_refcount_tree(osb, le64_to_cpu(di->i_refcount_loc),
1, &ref_tree, &ref_root_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
ret = ocfs2_duplicate_extent_list(s_inode, t_inode, t_bh,
&ref_tree->rf_ci, ref_root_bh,
&dealloc);
if (ret) {
mlog_errno(ret);
goto out_unlock_refcount;
}
out_unlock_refcount:
ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
brelse(ref_root_bh);
out:
if (ocfs2_dealloc_has_cluster(&dealloc)) {
ocfs2_schedule_truncate_log_flush(osb, 1);
ocfs2_run_deallocs(osb, &dealloc);
}
return ret;
}
static int __ocfs2_reflink(struct dentry *old_dentry,
struct buffer_head *old_bh,
struct inode *new_inode,
bool preserve)
{
int ret;
struct inode *inode = old_dentry->d_inode;
struct buffer_head *new_bh = NULL;
if (OCFS2_I(inode)->ip_flags & OCFS2_INODE_SYSTEM_FILE) {
ret = -EINVAL;
mlog_errno(ret);
goto out;
}
ret = filemap_fdatawrite(inode->i_mapping);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_attach_refcount_tree(inode, old_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
mutex_lock_nested(&new_inode->i_mutex, I_MUTEX_CHILD);
ret = ocfs2_inode_lock_nested(new_inode, &new_bh, 1,
OI_LS_REFLINK_TARGET);
if (ret) {
mlog_errno(ret);
goto out_unlock;
}
ret = ocfs2_create_reflink_node(inode, old_bh,
new_inode, new_bh, preserve);
if (ret) {
mlog_errno(ret);
goto inode_unlock;
}
if (OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_XATTR_FL) {
ret = ocfs2_reflink_xattrs(inode, old_bh,
new_inode, new_bh,
preserve);
if (ret) {
mlog_errno(ret);
goto inode_unlock;
}
}
ret = ocfs2_complete_reflink(inode, old_bh,
new_inode, new_bh, preserve);
if (ret)
mlog_errno(ret);
inode_unlock:
ocfs2_inode_unlock(new_inode, 1);
brelse(new_bh);
out_unlock:
mutex_unlock(&new_inode->i_mutex);
out:
if (!ret) {
ret = filemap_fdatawait(inode->i_mapping);
if (ret)
mlog_errno(ret);
}
return ret;
}
static int ocfs2_reflink(struct dentry *old_dentry, struct inode *dir,
struct dentry *new_dentry, bool preserve)
{
int error;
struct inode *inode = old_dentry->d_inode;
struct buffer_head *old_bh = NULL;
struct inode *new_orphan_inode = NULL;
if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb)))
return -EOPNOTSUPP;
error = ocfs2_create_inode_in_orphan(dir, inode->i_mode,
&new_orphan_inode);
if (error) {
mlog_errno(error);
goto out;
}
error = ocfs2_inode_lock(inode, &old_bh, 1);
if (error) {
mlog_errno(error);
goto out;
}
down_write(&OCFS2_I(inode)->ip_xattr_sem);
down_write(&OCFS2_I(inode)->ip_alloc_sem);
error = __ocfs2_reflink(old_dentry, old_bh,
new_orphan_inode, preserve);
up_write(&OCFS2_I(inode)->ip_alloc_sem);
up_write(&OCFS2_I(inode)->ip_xattr_sem);
ocfs2_inode_unlock(inode, 1);
brelse(old_bh);
if (error) {
mlog_errno(error);
goto out;
}
/* If the security isn't preserved, we need to re-initialize them. */
if (!preserve) {
error = ocfs2_init_security_and_acl(dir, new_orphan_inode,
&new_dentry->d_name);
if (error)
mlog_errno(error);
}
out:
if (!error) {
error = ocfs2_mv_orphaned_inode_to_new(dir, new_orphan_inode,
new_dentry);
if (error)
mlog_errno(error);
}
if (new_orphan_inode) {
/*
* We need to open_unlock the inode no matter whether we
* succeed or not, so that other nodes can delete it later.
*/
ocfs2_open_unlock(new_orphan_inode);
if (error)
iput(new_orphan_inode);
}
return error;
}
/*
* Below here are the bits used by OCFS2_IOC_REFLINK() to fake
* sys_reflink(). This will go away when vfs_reflink() exists in
* fs/namei.c.
*/
/* copied from may_create in VFS. */
static inline int ocfs2_may_create(struct inode *dir, struct dentry *child)
{
if (child->d_inode)
return -EEXIST;
if (IS_DEADDIR(dir))
return -ENOENT;
return inode_permission(dir, MAY_WRITE | MAY_EXEC);
}
/**
* ocfs2_vfs_reflink - Create a reference-counted link
*
* @old_dentry: source dentry + inode
* @dir: directory to create the target
* @new_dentry: target dentry
* @preserve: if true, preserve all file attributes
*/
static int ocfs2_vfs_reflink(struct dentry *old_dentry, struct inode *dir,
struct dentry *new_dentry, bool preserve)
{
struct inode *inode = old_dentry->d_inode;
int error;
if (!inode)
return -ENOENT;
error = ocfs2_may_create(dir, new_dentry);
if (error)
return error;
if (dir->i_sb != inode->i_sb)
return -EXDEV;
/*
* A reflink to an append-only or immutable file cannot be created.
*/
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return -EPERM;
/* Only regular files can be reflinked. */
if (!S_ISREG(inode->i_mode))
return -EPERM;
/*
* If the caller wants to preserve ownership, they require the
* rights to do so.
*/
if (preserve) {
if ((current_fsuid() != inode->i_uid) && !capable(CAP_CHOWN))
return -EPERM;
if (!in_group_p(inode->i_gid) && !capable(CAP_CHOWN))
return -EPERM;
}
/*
* If the caller is modifying any aspect of the attributes, they
* are not creating a snapshot. They need read permission on the
* file.
*/
if (!preserve) {
error = inode_permission(inode, MAY_READ);
if (error)
return error;
}
mutex_lock(&inode->i_mutex);
dquot_initialize(dir);
error = ocfs2_reflink(old_dentry, dir, new_dentry, preserve);
mutex_unlock(&inode->i_mutex);
if (!error)
fsnotify_create(dir, new_dentry);
return error;
}
/*
* Most codes are copied from sys_linkat.
*/
int ocfs2_reflink_ioctl(struct inode *inode,
const char __user *oldname,
const char __user *newname,
bool preserve)
{
struct dentry *new_dentry;
struct path old_path, new_path;
int error;
if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb)))
return -EOPNOTSUPP;
error = user_path_at(AT_FDCWD, oldname, 0, &old_path);
if (error) {
mlog_errno(error);
return error;
}
new_dentry = user_path_create(AT_FDCWD, newname, &new_path, 0);
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry)) {
mlog_errno(error);
goto out;
}
error = -EXDEV;
if (old_path.mnt != new_path.mnt) {
mlog_errno(error);
goto out_dput;
}
error = mnt_want_write(new_path.mnt);
if (error) {
mlog_errno(error);
goto out_dput;
}
error = ocfs2_vfs_reflink(old_path.dentry,
new_path.dentry->d_inode,
new_dentry, preserve);
mnt_drop_write(new_path.mnt);
out_dput:
dput(new_dentry);
mutex_unlock(&new_path.dentry->d_inode->i_mutex);
path_put(&new_path);
out:
path_put(&old_path);
return error;
}
| gpl-2.0 |
hsr0/android_kernel_sony_msm7x27a | tools/power/cpupower/utils/idle_monitor/snb_idle.c | 5636 | 4413 | /*
* (C) 2010,2011 Thomas Renninger <trenn@suse.de>, Novell Inc.
*
* Licensed under the terms of the GNU GPL License version 2.
*
* Based on Len Brown's <lenb@kernel.org> turbostat tool.
*/
#if defined(__i386__) || defined(__x86_64__)
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "helpers/helpers.h"
#include "idle_monitor/cpupower-monitor.h"
#define MSR_PKG_C2_RESIDENCY 0x60D
#define MSR_PKG_C7_RESIDENCY 0x3FA
#define MSR_CORE_C7_RESIDENCY 0x3FE
#define MSR_TSC 0x10
enum intel_snb_id { C7 = 0, PC2, PC7, SNB_CSTATE_COUNT, TSC = 0xFFFF };
static int snb_get_count_percent(unsigned int self_id, double *percent,
unsigned int cpu);
static cstate_t snb_cstates[SNB_CSTATE_COUNT] = {
{
.name = "C7",
.desc = N_("Processor Core C7"),
.id = C7,
.range = RANGE_CORE,
.get_count_percent = snb_get_count_percent,
},
{
.name = "PC2",
.desc = N_("Processor Package C2"),
.id = PC2,
.range = RANGE_PACKAGE,
.get_count_percent = snb_get_count_percent,
},
{
.name = "PC7",
.desc = N_("Processor Package C7"),
.id = PC7,
.range = RANGE_PACKAGE,
.get_count_percent = snb_get_count_percent,
},
};
static unsigned long long tsc_at_measure_start;
static unsigned long long tsc_at_measure_end;
static unsigned long long *previous_count[SNB_CSTATE_COUNT];
static unsigned long long *current_count[SNB_CSTATE_COUNT];
/* valid flag for all CPUs. If a MSR read failed it will be zero */
static int *is_valid;
static int snb_get_count(enum intel_snb_id id, unsigned long long *val,
unsigned int cpu)
{
int msr;
switch (id) {
case C7:
msr = MSR_CORE_C7_RESIDENCY;
break;
case PC2:
msr = MSR_PKG_C2_RESIDENCY;
break;
case PC7:
msr = MSR_PKG_C7_RESIDENCY;
break;
case TSC:
msr = MSR_TSC;
break;
default:
return -1;
};
if (read_msr(cpu, msr, val))
return -1;
return 0;
}
static int snb_get_count_percent(unsigned int id, double *percent,
unsigned int cpu)
{
*percent = 0.0;
if (!is_valid[cpu])
return -1;
*percent = (100.0 *
(current_count[id][cpu] - previous_count[id][cpu])) /
(tsc_at_measure_end - tsc_at_measure_start);
dprint("%s: previous: %llu - current: %llu - (%u)\n",
snb_cstates[id].name, previous_count[id][cpu],
current_count[id][cpu], cpu);
dprint("%s: tsc_diff: %llu - count_diff: %llu - percent: %2.f (%u)\n",
snb_cstates[id].name,
(unsigned long long) tsc_at_measure_end - tsc_at_measure_start,
current_count[id][cpu] - previous_count[id][cpu],
*percent, cpu);
return 0;
}
static int snb_start(void)
{
int num, cpu;
unsigned long long val;
for (num = 0; num < SNB_CSTATE_COUNT; num++) {
for (cpu = 0; cpu < cpu_count; cpu++) {
snb_get_count(num, &val, cpu);
previous_count[num][cpu] = val;
}
}
snb_get_count(TSC, &tsc_at_measure_start, 0);
return 0;
}
static int snb_stop(void)
{
unsigned long long val;
int num, cpu;
snb_get_count(TSC, &tsc_at_measure_end, 0);
for (num = 0; num < SNB_CSTATE_COUNT; num++) {
for (cpu = 0; cpu < cpu_count; cpu++) {
is_valid[cpu] = !snb_get_count(num, &val, cpu);
current_count[num][cpu] = val;
}
}
return 0;
}
struct cpuidle_monitor intel_snb_monitor;
static struct cpuidle_monitor *snb_register(void)
{
int num;
if (cpupower_cpu_info.vendor != X86_VENDOR_INTEL
|| cpupower_cpu_info.family != 6)
return NULL;
if (cpupower_cpu_info.model != 0x2A
&& cpupower_cpu_info.model != 0x2D)
return NULL;
is_valid = calloc(cpu_count, sizeof(int));
for (num = 0; num < SNB_CSTATE_COUNT; num++) {
previous_count[num] = calloc(cpu_count,
sizeof(unsigned long long));
current_count[num] = calloc(cpu_count,
sizeof(unsigned long long));
}
intel_snb_monitor.name_len = strlen(intel_snb_monitor.name);
return &intel_snb_monitor;
}
void snb_unregister(void)
{
int num;
free(is_valid);
for (num = 0; num < SNB_CSTATE_COUNT; num++) {
free(previous_count[num]);
free(current_count[num]);
}
}
struct cpuidle_monitor intel_snb_monitor = {
.name = "SandyBridge",
.hw_states = snb_cstates,
.hw_states_num = SNB_CSTATE_COUNT,
.start = snb_start,
.stop = snb_stop,
.do_register = snb_register,
.unregister = snb_unregister,
.needs_root = 1,
.overflow_s = 922000000 /* 922337203 seconds TSC overflow
at 20GHz */
};
#endif /* defined(__i386__) || defined(__x86_64__) */
| gpl-2.0 |
sirkay/sony-msm8960 | tools/power/cpupower/utils/helpers/pci.c | 8452 | 1383 | #if defined(__i386__) || defined(__x86_64__)
#include <helpers/helpers.h>
/*
* pci_acc_init
*
* PCI access helper function depending on libpci
*
* **pacc : if a valid pci_dev is returned
* *pacc must be passed to pci_acc_cleanup to free it
*
* domain: domain
* bus: bus
* slot: slot
* func: func
* vendor: vendor
* device: device
* Pass -1 for one of the six above to match any
*
* Returns :
* struct pci_dev which can be used with pci_{read,write}_* functions
* to access the PCI config space of matching pci devices
*/
struct pci_dev *pci_acc_init(struct pci_access **pacc, int domain, int bus,
int slot, int func, int vendor, int dev)
{
struct pci_filter filter_nb_link = { domain, bus, slot, func,
vendor, dev };
struct pci_dev *device;
*pacc = pci_alloc();
if (*pacc == NULL)
return NULL;
pci_init(*pacc);
pci_scan_bus(*pacc);
for (device = (*pacc)->devices; device; device = device->next) {
if (pci_filter_match(&filter_nb_link, device))
return device;
}
pci_cleanup(*pacc);
return NULL;
}
/* Typically one wants to get a specific slot(device)/func of the root domain
and bus */
struct pci_dev *pci_slot_func_init(struct pci_access **pacc, int slot,
int func)
{
return pci_acc_init(pacc, 0, 0, slot, func, -1, -1);
}
#endif /* defined(__i386__) || defined(__x86_64__) */
| gpl-2.0 |
kozmikkick/kozmikkernel3.8 | net/ax25/ax25_subr.c | 8708 | 7113 | /*
* 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.
*
* Copyright (C) Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk)
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
* Copyright (C) Joerg Reuter DL1BKE (jreuter@yaina.de)
* Copyright (C) Frederic Rible F1OAT (frible@teaser.fr)
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <asm/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
/*
* This routine purges all the queues of frames.
*/
void ax25_clear_queues(ax25_cb *ax25)
{
skb_queue_purge(&ax25->write_queue);
skb_queue_purge(&ax25->ack_queue);
skb_queue_purge(&ax25->reseq_queue);
skb_queue_purge(&ax25->frag_queue);
}
/*
* This routine purges the input queue of those frames that have been
* acknowledged. This replaces the boxes labelled "V(a) <- N(r)" on the
* SDL diagram.
*/
void ax25_frames_acked(ax25_cb *ax25, unsigned short nr)
{
struct sk_buff *skb;
/*
* Remove all the ack-ed frames from the ack queue.
*/
if (ax25->va != nr) {
while (skb_peek(&ax25->ack_queue) != NULL && ax25->va != nr) {
skb = skb_dequeue(&ax25->ack_queue);
kfree_skb(skb);
ax25->va = (ax25->va + 1) % ax25->modulus;
}
}
}
void ax25_requeue_frames(ax25_cb *ax25)
{
struct sk_buff *skb;
/*
* Requeue all the un-ack-ed frames on the output queue to be picked
* up by ax25_kick called from the timer. This arrangement handles the
* possibility of an empty output queue.
*/
while ((skb = skb_dequeue_tail(&ax25->ack_queue)) != NULL)
skb_queue_head(&ax25->write_queue, skb);
}
/*
* Validate that the value of nr is between va and vs. Return true or
* false for testing.
*/
int ax25_validate_nr(ax25_cb *ax25, unsigned short nr)
{
unsigned short vc = ax25->va;
while (vc != ax25->vs) {
if (nr == vc) return 1;
vc = (vc + 1) % ax25->modulus;
}
if (nr == ax25->vs) return 1;
return 0;
}
/*
* This routine is the centralised routine for parsing the control
* information for the different frame formats.
*/
int ax25_decode(ax25_cb *ax25, struct sk_buff *skb, int *ns, int *nr, int *pf)
{
unsigned char *frame;
int frametype = AX25_ILLEGAL;
frame = skb->data;
*ns = *nr = *pf = 0;
if (ax25->modulus == AX25_MODULUS) {
if ((frame[0] & AX25_S) == 0) {
frametype = AX25_I; /* I frame - carries NR/NS/PF */
*ns = (frame[0] >> 1) & 0x07;
*nr = (frame[0] >> 5) & 0x07;
*pf = frame[0] & AX25_PF;
} else if ((frame[0] & AX25_U) == 1) { /* S frame - take out PF/NR */
frametype = frame[0] & 0x0F;
*nr = (frame[0] >> 5) & 0x07;
*pf = frame[0] & AX25_PF;
} else if ((frame[0] & AX25_U) == 3) { /* U frame - take out PF */
frametype = frame[0] & ~AX25_PF;
*pf = frame[0] & AX25_PF;
}
skb_pull(skb, 1);
} else {
if ((frame[0] & AX25_S) == 0) {
frametype = AX25_I; /* I frame - carries NR/NS/PF */
*ns = (frame[0] >> 1) & 0x7F;
*nr = (frame[1] >> 1) & 0x7F;
*pf = frame[1] & AX25_EPF;
skb_pull(skb, 2);
} else if ((frame[0] & AX25_U) == 1) { /* S frame - take out PF/NR */
frametype = frame[0] & 0x0F;
*nr = (frame[1] >> 1) & 0x7F;
*pf = frame[1] & AX25_EPF;
skb_pull(skb, 2);
} else if ((frame[0] & AX25_U) == 3) { /* U frame - take out PF */
frametype = frame[0] & ~AX25_PF;
*pf = frame[0] & AX25_PF;
skb_pull(skb, 1);
}
}
return frametype;
}
/*
* This routine is called when the HDLC layer internally generates a
* command or response for the remote machine ( eg. RR, UA etc. ).
* Only supervisory or unnumbered frames are processed.
*/
void ax25_send_control(ax25_cb *ax25, int frametype, int poll_bit, int type)
{
struct sk_buff *skb;
unsigned char *dptr;
if ((skb = alloc_skb(ax25->ax25_dev->dev->hard_header_len + 2, GFP_ATOMIC)) == NULL)
return;
skb_reserve(skb, ax25->ax25_dev->dev->hard_header_len);
skb_reset_network_header(skb);
/* Assume a response - address structure for DTE */
if (ax25->modulus == AX25_MODULUS) {
dptr = skb_put(skb, 1);
*dptr = frametype;
*dptr |= (poll_bit) ? AX25_PF : 0;
if ((frametype & AX25_U) == AX25_S) /* S frames carry NR */
*dptr |= (ax25->vr << 5);
} else {
if ((frametype & AX25_U) == AX25_U) {
dptr = skb_put(skb, 1);
*dptr = frametype;
*dptr |= (poll_bit) ? AX25_PF : 0;
} else {
dptr = skb_put(skb, 2);
dptr[0] = frametype;
dptr[1] = (ax25->vr << 1);
dptr[1] |= (poll_bit) ? AX25_EPF : 0;
}
}
ax25_transmit_buffer(ax25, skb, type);
}
/*
* Send a 'DM' to an unknown connection attempt, or an invalid caller.
*
* Note: src here is the sender, thus it's the target of the DM
*/
void ax25_return_dm(struct net_device *dev, ax25_address *src, ax25_address *dest, ax25_digi *digi)
{
struct sk_buff *skb;
char *dptr;
ax25_digi retdigi;
if (dev == NULL)
return;
if ((skb = alloc_skb(dev->hard_header_len + 1, GFP_ATOMIC)) == NULL)
return; /* Next SABM will get DM'd */
skb_reserve(skb, dev->hard_header_len);
skb_reset_network_header(skb);
ax25_digi_invert(digi, &retdigi);
dptr = skb_put(skb, 1);
*dptr = AX25_DM | AX25_PF;
/*
* Do the address ourselves
*/
dptr = skb_push(skb, ax25_addr_size(digi));
dptr += ax25_addr_build(dptr, dest, src, &retdigi, AX25_RESPONSE, AX25_MODULUS);
ax25_queue_xmit(skb, dev);
}
/*
* Exponential backoff for AX.25
*/
void ax25_calculate_t1(ax25_cb *ax25)
{
int n, t = 2;
switch (ax25->backoff) {
case 0:
break;
case 1:
t += 2 * ax25->n2count;
break;
case 2:
for (n = 0; n < ax25->n2count; n++)
t *= 2;
if (t > 8) t = 8;
break;
}
ax25->t1 = t * ax25->rtt;
}
/*
* Calculate the Round Trip Time
*/
void ax25_calculate_rtt(ax25_cb *ax25)
{
if (ax25->backoff == 0)
return;
if (ax25_t1timer_running(ax25) && ax25->n2count == 0)
ax25->rtt = (9 * ax25->rtt + ax25->t1 - ax25_display_timer(&ax25->t1timer)) / 10;
if (ax25->rtt < AX25_T1CLAMPLO)
ax25->rtt = AX25_T1CLAMPLO;
if (ax25->rtt > AX25_T1CLAMPHI)
ax25->rtt = AX25_T1CLAMPHI;
}
void ax25_disconnect(ax25_cb *ax25, int reason)
{
ax25_clear_queues(ax25);
ax25_stop_t1timer(ax25);
ax25_stop_t2timer(ax25);
ax25_stop_t3timer(ax25);
ax25_stop_idletimer(ax25);
ax25->state = AX25_STATE_0;
ax25_link_failed(ax25, reason);
if (ax25->sk != NULL) {
local_bh_disable();
bh_lock_sock(ax25->sk);
ax25->sk->sk_state = TCP_CLOSE;
ax25->sk->sk_err = reason;
ax25->sk->sk_shutdown |= SEND_SHUTDOWN;
if (!sock_flag(ax25->sk, SOCK_DEAD)) {
ax25->sk->sk_state_change(ax25->sk);
sock_set_flag(ax25->sk, SOCK_DEAD);
}
bh_unlock_sock(ax25->sk);
local_bh_enable();
}
}
| gpl-2.0 |
CyberGrandChallenge/linux-source-3.13.2-cgc | drivers/scsi/scsi_lib_dma.c | 9476 | 1151 | /*
* SCSI library functions depending on DMA
*/
#include <linux/blkdev.h>
#include <linux/device.h>
#include <linux/export.h>
#include <linux/kernel.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
/**
* scsi_dma_map - perform DMA mapping against command's sg lists
* @cmd: scsi command
*
* Returns the number of sg lists actually used, zero if the sg lists
* is NULL, or -ENOMEM if the mapping failed.
*/
int scsi_dma_map(struct scsi_cmnd *cmd)
{
int nseg = 0;
if (scsi_sg_count(cmd)) {
struct device *dev = cmd->device->host->dma_dev;
nseg = dma_map_sg(dev, scsi_sglist(cmd), scsi_sg_count(cmd),
cmd->sc_data_direction);
if (unlikely(!nseg))
return -ENOMEM;
}
return nseg;
}
EXPORT_SYMBOL(scsi_dma_map);
/**
* scsi_dma_unmap - unmap command's sg lists mapped by scsi_dma_map
* @cmd: scsi command
*/
void scsi_dma_unmap(struct scsi_cmnd *cmd)
{
if (scsi_sg_count(cmd)) {
struct device *dev = cmd->device->host->dma_dev;
dma_unmap_sg(dev, scsi_sglist(cmd), scsi_sg_count(cmd),
cmd->sc_data_direction);
}
}
EXPORT_SYMBOL(scsi_dma_unmap);
| gpl-2.0 |
Chilledheart/glibc | signal/sigandset.c | 5 | 1178 | /* Copyright (C) 1991-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <signal.h>
#define __need_NULL
#include <stddef.h>
/* Combine sets LEFT and RIGHT by logical AND and place result in DEST. */
int
sigandset (sigset_t *dest, const sigset_t *left, const sigset_t *right)
{
if (dest == NULL || left == NULL || right == NULL)
{
__set_errno (EINVAL);
return -1;
}
return __sigandset (dest, left, right);
}
| gpl-2.0 |
TeamExodus/kernel_moto_shamu | drivers/clk/qcom/clock-krait-8974.c | 5 | 25410 | /* Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/rpm-smd-regulator.h>
#include <linux/of.h>
#include <linux/cpumask.h>
#include <linux/clk/msm-clk-provider.h>
#include <linux/clk/msm-clk.h>
#include <linux/clk/msm-clock-generic.h>
#include <soc/qcom/clock-local2.h>
#include <soc/qcom/clock-krait.h>
#include <mach/mmi_soc_info.h>
#include <asm/cputype.h>
#include "clock.h"
/* Clock inputs coming into Krait subsystem */
DEFINE_FIXED_DIV_CLK(hfpll_src_clk, 1, NULL);
DEFINE_FIXED_DIV_CLK(acpu_aux_clk, 2, NULL);
static int hfpll_uv[] = {
RPM_REGULATOR_CORNER_NONE, 0,
RPM_REGULATOR_CORNER_SVS_SOC, 1800000,
RPM_REGULATOR_CORNER_NORMAL, 1800000,
RPM_REGULATOR_CORNER_SUPER_TURBO, 1800000,
};
static DEFINE_VDD_REGULATORS(vdd_hfpll, ARRAY_SIZE(hfpll_uv)/2, 2,
hfpll_uv, NULL);
static unsigned long hfpll_fmax[] = { 0, 998400000, 1996800000, 2900000000UL };
static struct hfpll_data hdata = {
.mode_offset = 0x0,
.l_offset = 0x4,
.m_offset = 0x8,
.n_offset = 0xC,
.user_offset = 0x10,
.config_offset = 0x14,
.status_offset = 0x1C,
.user_val = 0x8,
.low_vco_max_rate = 1248000000,
.min_rate = 537600000UL,
.max_rate = 2900000000UL,
};
static struct hfpll_clk hfpll0_clk = {
.d = &hdata,
.src_rate = 19200000,
.c = {
.parent = &hfpll_src_clk.c,
.dbg_name = "hfpll0_clk",
.ops = &clk_ops_hfpll,
.vdd_class = &vdd_hfpll,
.fmax = hfpll_fmax,
.num_fmax = ARRAY_SIZE(hfpll_fmax),
CLK_INIT(hfpll0_clk.c),
},
};
DEFINE_KPSS_DIV2_CLK(hfpll0_div_clk, &hfpll0_clk.c, 0x4501, true);
static struct hfpll_clk hfpll1_clk = {
.d = &hdata,
.src_rate = 19200000,
.c = {
.parent = &hfpll_src_clk.c,
.dbg_name = "hfpll1_clk",
.ops = &clk_ops_hfpll,
.vdd_class = &vdd_hfpll,
.fmax = hfpll_fmax,
.num_fmax = ARRAY_SIZE(hfpll_fmax),
CLK_INIT(hfpll1_clk.c),
},
};
DEFINE_KPSS_DIV2_CLK(hfpll1_div_clk, &hfpll1_clk.c, 0x5501, true);
static struct hfpll_clk hfpll2_clk = {
.d = &hdata,
.src_rate = 19200000,
.c = {
.parent = &hfpll_src_clk.c,
.dbg_name = "hfpll2_clk",
.ops = &clk_ops_hfpll,
.vdd_class = &vdd_hfpll,
.fmax = hfpll_fmax,
.num_fmax = ARRAY_SIZE(hfpll_fmax),
CLK_INIT(hfpll2_clk.c),
},
};
DEFINE_KPSS_DIV2_CLK(hfpll2_div_clk, &hfpll2_clk.c, 0x6501, true);
static struct hfpll_clk hfpll3_clk = {
.d = &hdata,
.src_rate = 19200000,
.c = {
.parent = &hfpll_src_clk.c,
.dbg_name = "hfpll3_clk",
.ops = &clk_ops_hfpll,
.vdd_class = &vdd_hfpll,
.fmax = hfpll_fmax,
.num_fmax = ARRAY_SIZE(hfpll_fmax),
CLK_INIT(hfpll3_clk.c),
},
};
DEFINE_KPSS_DIV2_CLK(hfpll3_div_clk, &hfpll3_clk.c, 0x7501, true);
static struct hfpll_clk hfpll_l2_clk = {
.d = &hdata,
.src_rate = 19200000,
.c = {
.parent = &hfpll_src_clk.c,
.dbg_name = "hfpll_l2_clk",
.ops = &clk_ops_hfpll,
.vdd_class = &vdd_hfpll,
.fmax = hfpll_fmax,
.num_fmax = ARRAY_SIZE(hfpll_fmax),
CLK_INIT(hfpll_l2_clk.c),
},
};
DEFINE_KPSS_DIV2_CLK(hfpll_l2_div_clk, &hfpll_l2_clk.c, 0x500, false);
#define SEC_MUX_COMMON_DATA \
.safe_parent = &acpu_aux_clk.c, \
.ops = &clk_mux_ops_kpss, \
.mask = 0x3, \
.shift = 2, \
MUX_SRC_LIST( \
{&acpu_aux_clk.c, 2}, \
{NULL /* QSB */, 0}, \
)
static struct mux_clk krait0_sec_mux_clk = {
.offset = 0x4501,
.priv = (void *) true,
SEC_MUX_COMMON_DATA,
.c = {
.dbg_name = "krait0_sec_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(krait0_sec_mux_clk.c),
},
};
static struct mux_clk krait1_sec_mux_clk = {
.offset = 0x5501,
.priv = (void *) true,
SEC_MUX_COMMON_DATA,
.c = {
.dbg_name = "krait1_sec_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(krait1_sec_mux_clk.c),
},
};
static struct mux_clk krait2_sec_mux_clk = {
.offset = 0x6501,
.priv = (void *) true,
SEC_MUX_COMMON_DATA,
.c = {
.dbg_name = "krait2_sec_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(krait2_sec_mux_clk.c),
},
};
static struct mux_clk krait3_sec_mux_clk = {
.offset = 0x7501,
.priv = (void *) true,
SEC_MUX_COMMON_DATA,
.c = {
.dbg_name = "krait3_sec_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(krait3_sec_mux_clk.c),
},
};
static struct mux_clk l2_sec_mux_clk = {
.offset = 0x500,
SEC_MUX_COMMON_DATA,
.c = {
.dbg_name = "l2_sec_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(l2_sec_mux_clk.c),
},
};
#define PRI_MUX_COMMON_DATA \
.ops = &clk_mux_ops_kpss, \
.mask = 0x3, \
.shift = 0
static struct mux_clk krait0_pri_mux_clk = {
.offset = 0x4501,
.priv = (void *) true,
MUX_SRC_LIST(
{ &hfpll0_clk.c, 1 },
{ &hfpll0_div_clk.c, 2 },
{ &krait0_sec_mux_clk.c, 0 },
),
.safe_parent = &krait0_sec_mux_clk.c,
PRI_MUX_COMMON_DATA,
.c = {
.dbg_name = "krait0_pri_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(krait0_pri_mux_clk.c),
},
};
static struct mux_clk krait1_pri_mux_clk = {
.offset = 0x5501,
.priv = (void *) true,
MUX_SRC_LIST(
{ &hfpll1_clk.c, 1 },
{ &hfpll1_div_clk.c, 2 },
{ &krait1_sec_mux_clk.c, 0 },
),
.safe_parent = &krait1_sec_mux_clk.c,
PRI_MUX_COMMON_DATA,
.c = {
.dbg_name = "krait1_pri_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(krait1_pri_mux_clk.c),
},
};
static struct mux_clk krait2_pri_mux_clk = {
.offset = 0x6501,
.priv = (void *) true,
MUX_SRC_LIST(
{ &hfpll2_clk.c, 1 },
{ &hfpll2_div_clk.c, 2 },
{ &krait2_sec_mux_clk.c, 0 },
),
.safe_parent = &krait2_sec_mux_clk.c,
PRI_MUX_COMMON_DATA,
.c = {
.dbg_name = "krait2_pri_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(krait2_pri_mux_clk.c),
},
};
static struct mux_clk krait3_pri_mux_clk = {
.offset = 0x7501,
.priv = (void *) true,
MUX_SRC_LIST(
{ &hfpll3_clk.c, 1 },
{ &hfpll3_div_clk.c, 2 },
{ &krait3_sec_mux_clk.c, 0 },
),
.safe_parent = &krait3_sec_mux_clk.c,
PRI_MUX_COMMON_DATA,
.c = {
.dbg_name = "krait3_pri_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(krait3_pri_mux_clk.c),
},
};
static struct mux_clk l2_pri_mux_clk = {
.offset = 0x500,
MUX_SRC_LIST(
{&hfpll_l2_clk.c, 1 },
{&hfpll_l2_div_clk.c, 2},
{&l2_sec_mux_clk.c, 0}
),
.safe_parent = &l2_sec_mux_clk.c,
PRI_MUX_COMMON_DATA,
.c = {
.dbg_name = "l2_pri_mux_clk",
.ops = &clk_ops_gen_mux,
CLK_INIT(l2_pri_mux_clk.c),
},
};
static struct avs_data avs_table;
static DEFINE_VDD_REGS_INIT(vdd_krait0, 1);
static DEFINE_VDD_REGS_INIT(vdd_krait1, 1);
static DEFINE_VDD_REGS_INIT(vdd_krait2, 1);
static DEFINE_VDD_REGS_INIT(vdd_krait3, 1);
static DEFINE_VDD_REGS_INIT(vdd_l2, 1);
/*
* This clock is mostly a dummy clock in the sense it can't really gate the
* CPU/L2 clocks or affect their frequency. It exists solely to:
*
* - Capture the PVS requirements for each CPU.
* - Implement HW clock gating disable ops needed for measuring the freq of
* Krait/L2 properly.
* - Implement AVS requirement.
*/
struct kpss_core_clk krait0_clk = {
.id = 0,
.avs_tbl = &avs_table,
.c = {
.parent = &krait0_pri_mux_clk.c,
.dbg_name = "krait0_clk",
.ops = &clk_ops_kpss_cpu,
.vdd_class = &vdd_krait0,
CLK_INIT(krait0_clk.c),
},
};
struct kpss_core_clk krait1_clk = {
.id = 1,
.avs_tbl = &avs_table,
.c = {
.parent = &krait1_pri_mux_clk.c,
.dbg_name = "krait1_clk",
.ops = &clk_ops_kpss_cpu,
.vdd_class = &vdd_krait1,
CLK_INIT(krait1_clk.c),
},
};
struct kpss_core_clk krait2_clk = {
.id = 2,
.avs_tbl = &avs_table,
.c = {
.parent = &krait2_pri_mux_clk.c,
.dbg_name = "krait2_clk",
.ops = &clk_ops_kpss_cpu,
.vdd_class = &vdd_krait2,
CLK_INIT(krait2_clk.c),
},
};
struct kpss_core_clk krait3_clk = {
.id = 3,
.avs_tbl = &avs_table,
.c = {
.parent = &krait3_pri_mux_clk.c,
.dbg_name = "krait3_clk",
.ops = &clk_ops_kpss_cpu,
.vdd_class = &vdd_krait3,
CLK_INIT(krait3_clk.c),
},
};
struct kpss_core_clk l2_clk = {
.cp15_iaddr = 0x0500,
.c = {
.parent = &l2_pri_mux_clk.c,
.dbg_name = "l2_clk",
.ops = &clk_ops_kpss_l2,
.vdd_class = &vdd_l2,
CLK_INIT(l2_clk.c),
},
};
static void __iomem *meas_base;
#define L2_CBCR_REG 0x004C
#define GLB_CLK_DIAG 0x001C
DEFINE_FIXED_SLAVE_DIV_CLK(krait0_div_clk, 4, &krait0_clk.c);
DEFINE_FIXED_SLAVE_DIV_CLK(krait1_div_clk, 4, &krait1_clk.c);
DEFINE_FIXED_SLAVE_DIV_CLK(krait2_div_clk, 4, &krait2_clk.c);
DEFINE_FIXED_SLAVE_DIV_CLK(krait3_div_clk, 4, &krait3_clk.c);
DEFINE_FIXED_SLAVE_DIV_CLK(l2_div_clk, 4, &l2_clk.c);
static struct mux_clk kpss_debug_ter_mux = {
.offset = GLB_CLK_DIAG,
.ops = &mux_reg_ops,
.mask = 0x3,
.shift = 8,
MUX_SRC_LIST(
{&krait0_div_clk.c, 0},
{&krait1_div_clk.c, 1},
{&krait2_div_clk.c, 2},
{&krait3_div_clk.c, 3},
),
.rec_set_par = 1,
.base = &meas_base,
.c = {
.dbg_name = "kpss_debug_ter_mux",
.ops = &clk_ops_gen_mux,
CLK_INIT(kpss_debug_ter_mux.c),
},
};
static struct mux_clk kpss_debug_sec_mux = {
.offset = GLB_CLK_DIAG,
.en_offset = L2_CBCR_REG,
.en_reg = 1,
.ops = &mux_reg_ops,
.en_mask = BIT(0),
.mask = 0x7,
.shift = 12,
MUX_SRC_LIST(
{&kpss_debug_ter_mux.c, 0},
{&l2_div_clk.c, 1},
),
.rec_set_par = 1,
.base = &meas_base,
.c = {
.dbg_name = "kpss_debug_sec_mux",
.ops = &clk_ops_gen_mux,
CLK_INIT(kpss_debug_sec_mux.c),
},
};
static struct mux_clk kpss_debug_pri_mux = {
.offset = GLB_CLK_DIAG,
.ops = &mux_reg_ops,
.mask = 0x3,
.shift = 16,
MUX_SRC_LIST(
{&kpss_debug_sec_mux.c, 0},
),
.rec_set_par = 1,
.base = &meas_base,
.c = {
.dbg_name = "kpss_debug_pri_mux",
.ops = &clk_ops_gen_mux,
CLK_INIT(kpss_debug_pri_mux.c),
},
};
static struct clk_lookup kpss_clocks_8974[] = {
CLK_LOOKUP("", hfpll_src_clk.c, ""),
CLK_LOOKUP("", acpu_aux_clk.c, ""),
CLK_LOOKUP("", hfpll0_clk.c, ""),
CLK_LOOKUP("", hfpll0_div_clk.c, ""),
CLK_LOOKUP("", hfpll0_clk.c, ""),
CLK_LOOKUP("", hfpll1_div_clk.c, ""),
CLK_LOOKUP("", hfpll1_clk.c, ""),
CLK_LOOKUP("", hfpll2_div_clk.c, ""),
CLK_LOOKUP("", hfpll2_clk.c, ""),
CLK_LOOKUP("", hfpll3_div_clk.c, ""),
CLK_LOOKUP("", hfpll3_clk.c, ""),
CLK_LOOKUP("", hfpll_l2_div_clk.c, ""),
CLK_LOOKUP("", hfpll_l2_clk.c, ""),
CLK_LOOKUP("", krait0_sec_mux_clk.c, ""),
CLK_LOOKUP("", krait1_sec_mux_clk.c, ""),
CLK_LOOKUP("", krait2_sec_mux_clk.c, ""),
CLK_LOOKUP("", krait3_sec_mux_clk.c, ""),
CLK_LOOKUP("", l2_sec_mux_clk.c, ""),
CLK_LOOKUP("", krait0_pri_mux_clk.c, ""),
CLK_LOOKUP("", krait1_pri_mux_clk.c, ""),
CLK_LOOKUP("", krait2_pri_mux_clk.c, ""),
CLK_LOOKUP("", krait3_pri_mux_clk.c, ""),
CLK_LOOKUP("", l2_pri_mux_clk.c, ""),
CLK_LOOKUP("l2_clk", l2_clk.c, "0.qcom,msm-cpufreq"),
CLK_LOOKUP("cpu0_clk", krait0_clk.c, "0.qcom,msm-cpufreq"),
CLK_LOOKUP("cpu1_clk", krait1_clk.c, "0.qcom,msm-cpufreq"),
CLK_LOOKUP("cpu2_clk", krait2_clk.c, "0.qcom,msm-cpufreq"),
CLK_LOOKUP("cpu3_clk", krait3_clk.c, "0.qcom,msm-cpufreq"),
CLK_LOOKUP("l2_clk", l2_clk.c, "fe805664.qcom,pm"),
CLK_LOOKUP("cpu0_clk", krait0_clk.c, "fe805664.qcom,pm"),
CLK_LOOKUP("cpu1_clk", krait1_clk.c, "fe805664.qcom,pm"),
CLK_LOOKUP("cpu2_clk", krait2_clk.c, "fe805664.qcom,pm"),
CLK_LOOKUP("cpu3_clk", krait3_clk.c, "fe805664.qcom,pm"),
CLK_LOOKUP("kpss_debug_mux", kpss_debug_pri_mux.c,
"fc401880.qcom,cc-debug"),
};
static struct clk *cpu_clk[] = {
&krait0_clk.c,
&krait1_clk.c,
&krait2_clk.c,
&krait3_clk.c,
};
static void get_krait_bin_format_b(struct platform_device *pdev,
int *speed, int *pvs, int *svs_pvs, int *pvs_ver)
{
u32 pte_efuse, redundant_sel;
struct resource *res;
void __iomem *base;
void __iomem *base_svs;
*speed = 0;
*pvs = 0;
*pvs_ver = 0;
*svs_pvs = -1;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "efuse");
if (!res) {
dev_info(&pdev->dev,
"No speed/PVS binning available. Defaulting to 0!\n");
return;
}
base = devm_ioremap(&pdev->dev, res->start, resource_size(res));
if (!base) {
dev_warn(&pdev->dev,
"Unable to read efuse data. Defaulting to 0!\n");
return;
}
pte_efuse = readl_relaxed(base);
redundant_sel = (pte_efuse >> 24) & 0x7;
*speed = pte_efuse & 0x7;
/* 4 bits of PVS are in efuse register bits 31, 8-6. */
*pvs = ((pte_efuse >> 28) & 0x8) | ((pte_efuse >> 6) & 0x7);
*pvs_ver = (pte_efuse >> 4) & 0x3;
switch (redundant_sel) {
case 1:
*speed = (pte_efuse >> 27) & 0xF;
break;
case 2:
*pvs = (pte_efuse >> 27) & 0xF;
break;
}
/* Check SPEED_BIN_BLOW_STATUS */
if (pte_efuse & BIT(3)) {
dev_info(&pdev->dev, "Speed bin: %d\n", *speed);
} else {
dev_warn(&pdev->dev, "Speed bin not set. Defaulting to 0!\n");
*speed = 0;
}
/* Check SVS PVS bin */
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "efuse_svs");
if (res) {
base_svs = devm_ioremap(&pdev->dev, res->start,
resource_size(res));
/* Read the svs pvs value if status bit 28 is valid (set) */
if (!base_svs) {
*svs_pvs = 0;
dev_warn(&pdev->dev,
"Unable to read svs efuse data. Defaulting to 0!\n");
} else {
pte_efuse = readl_relaxed(base_svs);
/*
* Read the svs pvs value if status bit 28 is valid
* 4 bits of SVS PVS are in efuse register bits 27-24
*/
if (pte_efuse & BIT(28))
*svs_pvs = (pte_efuse >> 24) & 0xF;
devm_iounmap(&pdev->dev, base_svs);
}
}
/* Check PVS_BLOW_STATUS */
pte_efuse = readl_relaxed(base + 0x4) & BIT(21);
if (pte_efuse) {
dev_info(&pdev->dev, "PVS bin: %d\n", *pvs);
if (*svs_pvs >= 0)
dev_info(&pdev->dev, "SVS PVS bin: %d\n", *svs_pvs);
} else {
dev_warn(&pdev->dev, "PVS bin not set. Defaulting to 0!\n");
*pvs = 0;
*svs_pvs = -1;
}
dev_info(&pdev->dev, "PVS version: %d\n", *pvs_ver);
devm_iounmap(&pdev->dev, base);
}
static int parse_tbl(struct device *dev, char *prop, int num_cols,
u32 **col1, u32 **col2, u32 **col3)
{
int ret, prop_len, num_rows, i, j, k;
u32 *prop_data;
u32 *col[num_cols];
if (!of_find_property(dev->of_node, prop, &prop_len))
return -EINVAL;
prop_len /= sizeof(*prop_data);
if (prop_len % num_cols || prop_len == 0)
return -EINVAL;
num_rows = prop_len / num_cols;
prop_data = devm_kzalloc(dev, prop_len * sizeof(*prop_data),
GFP_KERNEL);
if (!prop_data)
return -ENOMEM;
for (i = 0; i < num_cols; i++) {
col[i] = devm_kzalloc(dev, num_rows * sizeof(u32), GFP_KERNEL);
if (!col[i])
return -ENOMEM;
}
ret = of_property_read_u32_array(dev->of_node, prop, prop_data,
prop_len);
if (ret)
return ret;
k = 0;
for (i = 0; i < num_rows; i++) {
for (j = 0; j < num_cols; j++)
col[j][i] = prop_data[k++];
}
if (col1)
*col1 = col[0];
if (col2)
*col2 = col[1];
if (col3)
*col3 = col[2];
devm_kfree(dev, prop_data);
return num_rows;
}
static int clk_init_vdd_class(struct device *dev, struct clk *clk, int num,
unsigned long *fmax, int *uv, int *ua)
{
struct clk_vdd_class *vdd = clk->vdd_class;
vdd->level_votes = devm_kzalloc(dev, num * sizeof(int), GFP_KERNEL);
if (!vdd->level_votes) {
dev_err(dev, "Out of memory!\n");
return -ENOMEM;
}
vdd->num_levels = num;
vdd->cur_level = num;
vdd->vdd_uv = uv;
vdd->vdd_ua = ua;
clk->fmax = fmax;
clk->num_fmax = num;
return 0;
}
static int hfpll_base_init(struct platform_device *pdev, struct hfpll_clk *h)
{
struct resource *res;
struct device *dev = &pdev->dev;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, h->c.dbg_name);
if (!res) {
dev_err(dev, "%s base addr not found!\n", h->c.dbg_name);
return -EINVAL;
}
h->base = devm_ioremap(dev, res->start, resource_size(res));
if (!h->base) {
dev_err(dev, "%s ioremap failed!\n", h->c.dbg_name);
return -ENOMEM;
}
return 0;
}
static bool enable_boost;
module_param_named(boost, enable_boost, bool, S_IRUGO | S_IWUSR);
static void krait_update_uv(int *uv, int num, int boost_uv)
{
int i;
switch (read_cpuid_id()) {
case 0x511F04D0: /* KR28M2A20 */
case 0x511F04D1: /* KR28M2A21 */
case 0x510F06F0: /* KR28M4A10 */
for (i = 0; i < num; i++)
uv[i] = max(1150000, uv[i]);
};
if (enable_boost) {
for (i = 0; i < num; i++)
uv[i] += boost_uv;
}
}
static char table_name[] = "qcom,speedXX-pvsXX-bin-vXX";
module_param_string(table_name, table_name, sizeof(table_name), S_IRUGO);
static unsigned int pvs_config_ver;
module_param(pvs_config_ver, uint, S_IRUGO);
static int clock_krait_8974_driver_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct clk *c;
int speed, pvs, svs_pvs, pvs_ver, config_ver, rows, cpu, svs_row = 0;
unsigned long *freq = 0, *svs_freq = 0, cur_rate, aux_rate;
struct resource *res;
int *uv = 0, *ua = 0, *svs_uv = 0, *svs_ua = 0;
u32 *dscr = 0, vco_mask, config_val, svs_fmax;
int ret;
vdd_l2.regulator[0] = devm_regulator_get(dev, "l2-dig");
if (IS_ERR(vdd_l2.regulator[0])) {
dev_err(dev, "Unable to get l2-dig regulator!\n");
return PTR_ERR(vdd_l2.regulator[0]);
}
vdd_hfpll.regulator[0] = devm_regulator_get(dev, "hfpll-dig");
if (IS_ERR(vdd_hfpll.regulator[0])) {
dev_err(dev, "Unable to get hfpll-dig regulator!\n");
return PTR_ERR(vdd_hfpll.regulator[0]);
}
vdd_hfpll.regulator[1] = devm_regulator_get(dev, "hfpll-analog");
if (IS_ERR(vdd_hfpll.regulator[1])) {
dev_err(dev, "Unable to get hfpll-analog regulator!\n");
return PTR_ERR(vdd_hfpll.regulator[1]);
}
vdd_krait0.regulator[0] = devm_regulator_get(dev, "cpu0");
if (IS_ERR(vdd_krait0.regulator[0])) {
dev_err(dev, "Unable to get cpu0 regulator!\n");
return PTR_ERR(vdd_krait0.regulator[0]);
}
vdd_krait1.regulator[0] = devm_regulator_get(dev, "cpu1");
if (IS_ERR(vdd_krait1.regulator[0])) {
dev_err(dev, "Unable to get cpu1 regulator!\n");
return PTR_ERR(vdd_krait1.regulator[0]);
}
vdd_krait2.regulator[0] = devm_regulator_get(dev, "cpu2");
if (IS_ERR(vdd_krait2.regulator[0])) {
dev_err(dev, "Unable to get cpu2 regulator!\n");
return PTR_ERR(vdd_krait2.regulator[0]);
}
vdd_krait3.regulator[0] = devm_regulator_get(dev, "cpu3");
if (IS_ERR(vdd_krait3.regulator[0])) {
dev_err(dev, "Unable to get cpu3 regulator!\n");
return PTR_ERR(vdd_krait3.regulator[0]);
}
c = devm_clk_get(dev, "hfpll_src");
if (IS_ERR(c)) {
dev_err(dev, "Unable to get HFPLL source\n");
return PTR_ERR(c);
}
hfpll_src_clk.c.parent = c;
c = devm_clk_get(dev, "aux_clk");
if (IS_ERR(c)) {
dev_err(dev, "Unable to get AUX source\n");
return PTR_ERR(c);
}
acpu_aux_clk.c.parent = c;
if (hfpll_base_init(pdev, &hfpll0_clk))
return -EINVAL;
if (hfpll_base_init(pdev, &hfpll1_clk))
return -EINVAL;
if (hfpll_base_init(pdev, &hfpll2_clk))
return -EINVAL;
if (hfpll_base_init(pdev, &hfpll3_clk))
return -EINVAL;
if (hfpll_base_init(pdev, &hfpll_l2_clk))
return -EINVAL;
ret = of_property_read_u32(dev->of_node, "qcom,hfpll-config-val",
&config_val);
if (!ret)
hdata.config_val = config_val;
ret = of_property_read_u32(dev->of_node, "qcom,hfpll-user-vco-mask",
&vco_mask);
if (!ret)
hdata.user_vco_mask = vco_mask;
ret = of_property_read_u32(dev->of_node, "qcom,pvs-config-ver",
&config_ver);
if (!ret) {
pvs_config_ver = config_ver;
dev_info(&pdev->dev, "PVS config version: %d\n", config_ver);
}
get_krait_bin_format_b(pdev, &speed, &pvs, &svs_pvs, &pvs_ver);
mmi_acpu_bin_set(&speed, &pvs, &pvs_ver);
snprintf(table_name, ARRAY_SIZE(table_name),
"qcom,speed%d-pvs%d-bin-v%d", speed, pvs, pvs_ver);
rows = parse_tbl(dev, table_name, 3,
(u32 **) &freq, (u32 **) &uv, (u32 **) &ua);
if (rows < 0) {
/* Fall back to most conservative PVS table */
dev_err(dev, "Unable to load voltage plan %s!\n", table_name);
ret = parse_tbl(dev, "qcom,speed0-pvs0-bin-v0", 3,
(u32 **) &freq, (u32 **) &uv, (u32 **) &ua);
if (ret < 0) {
dev_err(dev, "Unable to load safe voltage plan\n");
return rows;
} else {
dev_info(dev, "Safe voltage plan loaded.\n");
pvs = 0;
rows = ret;
}
} else if (svs_pvs >= 0) {
/* Find the split freq for svs fmax */
ret = of_property_read_u32(dev->of_node, "qcom,svs-fmax",
&svs_fmax);
if (ret) {
dev_err(dev, "Unable to find krait fmax for svs\n");
return ret;
}
/* Find the svs fmax freq row */
while ((svs_row < rows) && (freq[svs_row] != svs_fmax))
svs_row++;
if (svs_row == rows) {
dev_err(dev, "Invalid krait fmax for svs\n");
return -EINVAL;
}
snprintf(table_name, ARRAY_SIZE(table_name),
"qcom,speed%d-pvs%d-bin-v%d", speed, svs_pvs, pvs_ver);
rows = parse_tbl(dev, table_name, 3,
(u32 **) &svs_freq, (u32 **) &svs_uv, (u32 **) &svs_ua);
if (rows > 0) {
/* Use the svs voltage data for svs freqs */
while (svs_row >= 0) {
uv[svs_row] = svs_uv[svs_row];
svs_row--;
}
devm_kfree(dev, svs_freq);
devm_kfree(dev, svs_uv);
devm_kfree(dev, svs_ua);
} else {
/* Fall back to most conservative svs pvs table */
dev_err(dev, "Unable to load svs voltage plan %s!\n",
table_name);
snprintf(table_name, ARRAY_SIZE(table_name),
"qcom,speed0-pvs0-bin-v%d", pvs_ver);
rows = parse_tbl(dev, table_name, 3,
(u32 **) &svs_freq, (u32 **) &svs_uv,
(u32 **) &svs_ua);
if (rows < 0) {
dev_err(dev, "Unable to load safe voltage plan.\n");
return rows;
} else {
dev_info(dev, "Safe svs voltage plan loaded.\n");
while (svs_row >= 0) {
uv[svs_row] = svs_uv[svs_row];
svs_row--;
}
devm_kfree(dev, svs_freq);
devm_kfree(dev, svs_uv);
devm_kfree(dev, svs_ua);
}
}
}
krait_update_uv(uv, rows, pvs ? 25000 : 0);
if (clk_init_vdd_class(dev, &krait0_clk.c, rows, freq, uv, ua))
return -ENOMEM;
if (clk_init_vdd_class(dev, &krait1_clk.c, rows, freq, uv, ua))
return -ENOMEM;
if (clk_init_vdd_class(dev, &krait2_clk.c, rows, freq, uv, ua))
return -ENOMEM;
if (clk_init_vdd_class(dev, &krait3_clk.c, rows, freq, uv, ua))
return -ENOMEM;
/* AVS is optional */
rows = parse_tbl(dev, "qcom,avs-tbl", 2, (u32 **) &freq, &dscr, NULL);
if (rows > 0) {
avs_table.rate = freq;
avs_table.dscr = dscr;
avs_table.num = rows;
}
rows = parse_tbl(dev, "qcom,l2-fmax", 2, (u32 **) &freq, (u32 **) &uv,
NULL);
if (rows < 0) {
dev_err(dev, "Unable to find L2 Fmax table!\n");
return rows;
}
if (clk_init_vdd_class(dev, &l2_clk.c, rows, freq, uv, NULL))
return -ENOMEM;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "meas");
if (!res) {
dev_info(&pdev->dev, "Unable to read GLB base.\n");
return -EINVAL;
}
meas_base = devm_ioremap(&pdev->dev, res->start, resource_size(res));
if (!meas_base) {
dev_warn(&pdev->dev, "Unable to map GLB base.\n");
return -ENOMEM;
}
msm_clock_register(kpss_clocks_8974, ARRAY_SIZE(kpss_clocks_8974));
/*
* We don't want the CPU or L2 clocks to be turned off at late init
* if CPUFREQ or HOTPLUG configs are disabled. So, bump up the
* refcount of these clocks. Any cpufreq/hotplug manager can assume
* that the clocks have already been prepared and enabled by the time
* they take over.
*/
for_each_online_cpu(cpu) {
clk_prepare_enable(&l2_clk.c);
WARN(clk_prepare_enable(cpu_clk[cpu]),
"Unable to turn on CPU%d clock", cpu);
}
/*
* Force reinit of HFPLLs and muxes to overwrite any potential
* incorrect configuration of HFPLLs and muxes by the bootloader.
* While at it, also make sure the cores are running at known rates
* and print the current rate.
*
* The clocks are set to aux clock rate first to make sure the
* secondary mux is not sourcing off of QSB. The rate is then set to
* two different rates to force a HFPLL reinit under all
* circumstances.
*/
cur_rate = clk_get_rate(&l2_clk.c);
aux_rate = clk_get_rate(&acpu_aux_clk.c);
if (!cur_rate) {
pr_info("L2 @ unknown rate. Forcing new rate.\n");
cur_rate = aux_rate;
}
clk_set_rate(&l2_clk.c, aux_rate);
clk_set_rate(&l2_clk.c, clk_round_rate(&l2_clk.c, 1));
clk_set_rate(&l2_clk.c, cur_rate);
pr_info("L2 @ %lu KHz\n", clk_get_rate(&l2_clk.c) / 1000);
for_each_possible_cpu(cpu) {
struct clk *c = cpu_clk[cpu];
cur_rate = clk_get_rate(c);
if (!cur_rate) {
pr_info("CPU%d @ unknown rate. Forcing new rate.\n",
cpu);
cur_rate = aux_rate;
}
clk_set_rate(c, aux_rate);
clk_set_rate(c, clk_round_rate(c, 1));
clk_set_rate(c, clk_round_rate(c, cur_rate));
pr_info("CPU%d @ %lu KHz\n", cpu, clk_get_rate(c) / 1000);
}
return 0;
}
static struct of_device_id match_table[] = {
{ .compatible = "qcom,clock-krait-8974" },
{}
};
static struct platform_driver clock_krait_8974_driver = {
.probe = clock_krait_8974_driver_probe,
.driver = {
.name = "clock-krait-8974",
.of_match_table = match_table,
.owner = THIS_MODULE,
},
};
static int __init clock_krait_8974_init(void)
{
return platform_driver_register(&clock_krait_8974_driver);
}
arch_initcall(clock_krait_8974_init);
static void __exit clock_krait_8974_exit(void)
{
platform_driver_unregister(&clock_krait_8974_driver);
}
module_exit(clock_krait_8974_exit);
MODULE_DESCRIPTION("Krait CPU clock driver for 8974");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
ProjectOpenCannibal/android_kernel_lg_geehrc4g | drivers/thermal/msm_thermal.c | 5 | 3921 | /* Copyright (c) 2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/msm_tsens.h>
#include <linux/workqueue.h>
#include <linux/cpu.h>
#include <linux/cpufreq.h>
#include <linux/msm_tsens.h>
#include <linux/msm_thermal.h>
#include <mach/cpufreq.h>
#define DEF_TEMP_SENSOR 0
#define DEF_THERMAL_CHECK_MS 1000
#ifdef CONFIG_MACH_LGE //sync with thermald-8064.conf's temperature. actually 60'C is too low to degrate CPU freqency to 918MHz
#define DEF_ALLOWED_MAX_HIGH 93 //later carefully tune it
#else
#define DEF_ALLOWED_MAX_HIGH 60
#endif
#define DEF_ALLOWED_MAX_FREQ 918000
static int enabled;
static struct msm_thermal_data msm_thermal_info;
static uint32_t limited_max_freq = MSM_CPUFREQ_NO_LIMIT;
static struct delayed_work check_temp_work;
static int update_cpu_max_freq(int cpu, uint32_t max_freq)
{
int ret = 0;
ret = msm_cpufreq_set_freq_limits(cpu, MSM_CPUFREQ_NO_LIMIT, max_freq);
if (ret)
return ret;
ret = cpufreq_update_policy(cpu);
if (ret)
return ret;
limited_max_freq = max_freq;
if (max_freq != MSM_CPUFREQ_NO_LIMIT)
pr_info("msm_thermal: Limiting cpu%d max frequency to %d\n",
cpu, max_freq);
else
pr_info("msm_thermal: Max frequency reset for cpu%d\n", cpu);
return ret;
}
static void check_temp(struct work_struct *work)
{
struct tsens_device tsens_dev;
unsigned long temp = 0;
uint32_t max_freq = limited_max_freq;
int cpu = 0;
int ret = 0;
tsens_dev.sensor_num = msm_thermal_info.sensor_id;
ret = tsens_get_temp(&tsens_dev, &temp);
if (ret) {
pr_debug("msm_thermal: Unable to read TSENS sensor %d\n",
tsens_dev.sensor_num);
goto reschedule;
}
if (temp >= msm_thermal_info.limit_temp)
max_freq = msm_thermal_info.limit_freq;
else if (temp <
msm_thermal_info.limit_temp - msm_thermal_info.temp_hysteresis)
max_freq = MSM_CPUFREQ_NO_LIMIT;
if (max_freq == limited_max_freq)
goto reschedule;
/* Update new limits */
for_each_possible_cpu(cpu) {
ret = update_cpu_max_freq(cpu, max_freq);
if (ret)
pr_debug("Unable to limit cpu%d max freq to %d\n",
cpu, max_freq);
}
reschedule:
if (enabled)
schedule_delayed_work(&check_temp_work,
msecs_to_jiffies(msm_thermal_info.poll_ms));
}
static void disable_msm_thermal(void)
{
int cpu = 0;
/* make sure check_temp is no longer running */
cancel_delayed_work(&check_temp_work);
flush_scheduled_work();
if (limited_max_freq == MSM_CPUFREQ_NO_LIMIT)
return;
for_each_possible_cpu(cpu) {
update_cpu_max_freq(cpu, MSM_CPUFREQ_NO_LIMIT);
}
}
static int set_enabled(const char *val, const struct kernel_param *kp)
{
int ret = 0;
ret = param_set_bool(val, kp);
if (!enabled)
disable_msm_thermal();
else
pr_info("msm_thermal: no action for enabled = %d\n", enabled);
pr_info("msm_thermal: enabled = %d\n", enabled);
return ret;
}
static struct kernel_param_ops module_ops = {
.set = set_enabled,
.get = param_get_bool,
};
module_param_cb(enabled, &module_ops, &enabled, 0644);
MODULE_PARM_DESC(enabled, "enforce thermal limit on cpu");
int __init msm_thermal_init(struct msm_thermal_data *pdata)
{
int ret = 0;
BUG_ON(!pdata);
BUG_ON(pdata->sensor_id >= TSENS_MAX_SENSORS);
memcpy(&msm_thermal_info, pdata, sizeof(struct msm_thermal_data));
enabled = 1;
INIT_DELAYED_WORK(&check_temp_work, check_temp);
schedule_delayed_work(&check_temp_work, 0);
return ret;
}
| gpl-2.0 |
francegabb/mxu1130driver | fs/btrfs/disk-io.c | 5 | 118664 | /*
* Copyright (C) 2007 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/fs.h>
#include <linux/blkdev.h>
#include <linux/scatterlist.h>
#include <linux/swap.h>
#include <linux/radix-tree.h>
#include <linux/writeback.h>
#include <linux/buffer_head.h>
#include <linux/workqueue.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/slab.h>
#include <linux/migrate.h>
#include <linux/ratelimit.h>
#include <linux/uuid.h>
#include <linux/semaphore.h>
#include <asm/unaligned.h>
#include "ctree.h"
#include "disk-io.h"
#include "hash.h"
#include "transaction.h"
#include "btrfs_inode.h"
#include "volumes.h"
#include "print-tree.h"
#include "locking.h"
#include "tree-log.h"
#include "free-space-cache.h"
#include "inode-map.h"
#include "check-integrity.h"
#include "rcu-string.h"
#include "dev-replace.h"
#include "raid56.h"
#include "sysfs.h"
#include "qgroup.h"
#ifdef CONFIG_X86
#include <asm/cpufeature.h>
#endif
static struct extent_io_ops btree_extent_io_ops;
static void end_workqueue_fn(struct btrfs_work *work);
static void free_fs_root(struct btrfs_root *root);
static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
int read_only);
static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
struct btrfs_root *root);
static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
static int btrfs_destroy_marked_extents(struct btrfs_root *root,
struct extent_io_tree *dirty_pages,
int mark);
static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
struct extent_io_tree *pinned_extents);
static int btrfs_cleanup_transaction(struct btrfs_root *root);
static void btrfs_error_commit_super(struct btrfs_root *root);
/*
* btrfs_end_io_wq structs are used to do processing in task context when an IO
* is complete. This is used during reads to verify checksums, and it is used
* by writes to insert metadata for new file extents after IO is complete.
*/
struct btrfs_end_io_wq {
struct bio *bio;
bio_end_io_t *end_io;
void *private;
struct btrfs_fs_info *info;
int error;
enum btrfs_wq_endio_type metadata;
struct list_head list;
struct btrfs_work work;
};
static struct kmem_cache *btrfs_end_io_wq_cache;
int __init btrfs_end_io_wq_init(void)
{
btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
sizeof(struct btrfs_end_io_wq),
0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
NULL);
if (!btrfs_end_io_wq_cache)
return -ENOMEM;
return 0;
}
void btrfs_end_io_wq_exit(void)
{
if (btrfs_end_io_wq_cache)
kmem_cache_destroy(btrfs_end_io_wq_cache);
}
/*
* async submit bios are used to offload expensive checksumming
* onto the worker threads. They checksum file and metadata bios
* just before they are sent down the IO stack.
*/
struct async_submit_bio {
struct inode *inode;
struct bio *bio;
struct list_head list;
extent_submit_bio_hook_t *submit_bio_start;
extent_submit_bio_hook_t *submit_bio_done;
int rw;
int mirror_num;
unsigned long bio_flags;
/*
* bio_offset is optional, can be used if the pages in the bio
* can't tell us where in the file the bio should go
*/
u64 bio_offset;
struct btrfs_work work;
int error;
};
/*
* Lockdep class keys for extent_buffer->lock's in this root. For a given
* eb, the lockdep key is determined by the btrfs_root it belongs to and
* the level the eb occupies in the tree.
*
* Different roots are used for different purposes and may nest inside each
* other and they require separate keysets. As lockdep keys should be
* static, assign keysets according to the purpose of the root as indicated
* by btrfs_root->objectid. This ensures that all special purpose roots
* have separate keysets.
*
* Lock-nesting across peer nodes is always done with the immediate parent
* node locked thus preventing deadlock. As lockdep doesn't know this, use
* subclass to avoid triggering lockdep warning in such cases.
*
* The key is set by the readpage_end_io_hook after the buffer has passed
* csum validation but before the pages are unlocked. It is also set by
* btrfs_init_new_buffer on freshly allocated blocks.
*
* We also add a check to make sure the highest level of the tree is the
* same as our lockdep setup here. If BTRFS_MAX_LEVEL changes, this code
* needs update as well.
*/
#ifdef CONFIG_DEBUG_LOCK_ALLOC
# if BTRFS_MAX_LEVEL != 8
# error
# endif
static struct btrfs_lockdep_keyset {
u64 id; /* root objectid */
const char *name_stem; /* lock name stem */
char names[BTRFS_MAX_LEVEL + 1][20];
struct lock_class_key keys[BTRFS_MAX_LEVEL + 1];
} btrfs_lockdep_keysets[] = {
{ .id = BTRFS_ROOT_TREE_OBJECTID, .name_stem = "root" },
{ .id = BTRFS_EXTENT_TREE_OBJECTID, .name_stem = "extent" },
{ .id = BTRFS_CHUNK_TREE_OBJECTID, .name_stem = "chunk" },
{ .id = BTRFS_DEV_TREE_OBJECTID, .name_stem = "dev" },
{ .id = BTRFS_FS_TREE_OBJECTID, .name_stem = "fs" },
{ .id = BTRFS_CSUM_TREE_OBJECTID, .name_stem = "csum" },
{ .id = BTRFS_QUOTA_TREE_OBJECTID, .name_stem = "quota" },
{ .id = BTRFS_TREE_LOG_OBJECTID, .name_stem = "log" },
{ .id = BTRFS_TREE_RELOC_OBJECTID, .name_stem = "treloc" },
{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID, .name_stem = "dreloc" },
{ .id = BTRFS_UUID_TREE_OBJECTID, .name_stem = "uuid" },
{ .id = 0, .name_stem = "tree" },
};
void __init btrfs_init_lockdep(void)
{
int i, j;
/* initialize lockdep class names */
for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
for (j = 0; j < ARRAY_SIZE(ks->names); j++)
snprintf(ks->names[j], sizeof(ks->names[j]),
"btrfs-%s-%02d", ks->name_stem, j);
}
}
void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
int level)
{
struct btrfs_lockdep_keyset *ks;
BUG_ON(level >= ARRAY_SIZE(ks->keys));
/* find the matching keyset, id 0 is the default entry */
for (ks = btrfs_lockdep_keysets; ks->id; ks++)
if (ks->id == objectid)
break;
lockdep_set_class_and_name(&eb->lock,
&ks->keys[level], ks->names[level]);
}
#endif
/*
* extents on the btree inode are pretty simple, there's one extent
* that covers the entire device
*/
static struct extent_map *btree_get_extent(struct inode *inode,
struct page *page, size_t pg_offset, u64 start, u64 len,
int create)
{
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct extent_map *em;
int ret;
read_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, start, len);
if (em) {
em->bdev =
BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
read_unlock(&em_tree->lock);
goto out;
}
read_unlock(&em_tree->lock);
em = alloc_extent_map();
if (!em) {
em = ERR_PTR(-ENOMEM);
goto out;
}
em->start = 0;
em->len = (u64)-1;
em->block_len = (u64)-1;
em->block_start = 0;
em->bdev = BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em, 0);
if (ret == -EEXIST) {
free_extent_map(em);
em = lookup_extent_mapping(em_tree, start, len);
if (!em)
em = ERR_PTR(-EIO);
} else if (ret) {
free_extent_map(em);
em = ERR_PTR(ret);
}
write_unlock(&em_tree->lock);
out:
return em;
}
u32 btrfs_csum_data(char *data, u32 seed, size_t len)
{
return btrfs_crc32c(seed, data, len);
}
void btrfs_csum_final(u32 crc, char *result)
{
put_unaligned_le32(~crc, result);
}
/*
* compute the csum for a btree block, and either verify it or write it
* into the csum field of the block.
*/
static int csum_tree_block(struct btrfs_root *root, struct extent_buffer *buf,
int verify)
{
u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
char *result = NULL;
unsigned long len;
unsigned long cur_len;
unsigned long offset = BTRFS_CSUM_SIZE;
char *kaddr;
unsigned long map_start;
unsigned long map_len;
int err;
u32 crc = ~(u32)0;
unsigned long inline_result;
len = buf->len - offset;
while (len > 0) {
err = map_private_extent_buffer(buf, offset, 32,
&kaddr, &map_start, &map_len);
if (err)
return 1;
cur_len = min(len, map_len - (offset - map_start));
crc = btrfs_csum_data(kaddr + offset - map_start,
crc, cur_len);
len -= cur_len;
offset += cur_len;
}
if (csum_size > sizeof(inline_result)) {
result = kzalloc(csum_size * sizeof(char), GFP_NOFS);
if (!result)
return 1;
} else {
result = (char *)&inline_result;
}
btrfs_csum_final(crc, result);
if (verify) {
if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
u32 val;
u32 found = 0;
memcpy(&found, result, csum_size);
read_extent_buffer(buf, &val, 0, csum_size);
printk_ratelimited(KERN_INFO
"BTRFS: %s checksum verify failed on %llu wanted %X found %X "
"level %d\n",
root->fs_info->sb->s_id, buf->start,
val, found, btrfs_header_level(buf));
if (result != (char *)&inline_result)
kfree(result);
return 1;
}
} else {
write_extent_buffer(buf, result, 0, csum_size);
}
if (result != (char *)&inline_result)
kfree(result);
return 0;
}
/*
* we can't consider a given block up to date unless the transid of the
* block matches the transid in the parent node's pointer. This is how we
* detect blocks that either didn't get written at all or got written
* in the wrong place.
*/
static int verify_parent_transid(struct extent_io_tree *io_tree,
struct extent_buffer *eb, u64 parent_transid,
int atomic)
{
struct extent_state *cached_state = NULL;
int ret;
bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
return 0;
if (atomic)
return -EAGAIN;
if (need_lock) {
btrfs_tree_read_lock(eb);
btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
}
lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
0, &cached_state);
if (extent_buffer_uptodate(eb) &&
btrfs_header_generation(eb) == parent_transid) {
ret = 0;
goto out;
}
printk_ratelimited(KERN_INFO "BTRFS (device %s): parent transid verify failed on %llu wanted %llu found %llu\n",
eb->fs_info->sb->s_id, eb->start,
parent_transid, btrfs_header_generation(eb));
ret = 1;
/*
* Things reading via commit roots that don't have normal protection,
* like send, can have a really old block in cache that may point at a
* block that has been free'd and re-allocated. So don't clear uptodate
* if we find an eb that is under IO (dirty/writeback) because we could
* end up reading in the stale data and then writing it back out and
* making everybody very sad.
*/
if (!extent_buffer_under_io(eb))
clear_extent_buffer_uptodate(eb);
out:
unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
&cached_state, GFP_NOFS);
if (need_lock)
btrfs_tree_read_unlock_blocking(eb);
return ret;
}
/*
* Return 0 if the superblock checksum type matches the checksum value of that
* algorithm. Pass the raw disk superblock data.
*/
static int btrfs_check_super_csum(char *raw_disk_sb)
{
struct btrfs_super_block *disk_sb =
(struct btrfs_super_block *)raw_disk_sb;
u16 csum_type = btrfs_super_csum_type(disk_sb);
int ret = 0;
if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
u32 crc = ~(u32)0;
const int csum_size = sizeof(crc);
char result[csum_size];
/*
* The super_block structure does not span the whole
* BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
* is filled with zeros and is included in the checkum.
*/
crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
btrfs_csum_final(crc, result);
if (memcmp(raw_disk_sb, result, csum_size))
ret = 1;
if (ret && btrfs_super_generation(disk_sb) < 10) {
printk(KERN_WARNING
"BTRFS: super block crcs don't match, older mkfs detected\n");
ret = 0;
}
}
if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
printk(KERN_ERR "BTRFS: unsupported checksum algorithm %u\n",
csum_type);
ret = 1;
}
return ret;
}
/*
* helper to read a given tree block, doing retries as required when
* the checksums don't match and we have alternate mirrors to try.
*/
static int btree_read_extent_buffer_pages(struct btrfs_root *root,
struct extent_buffer *eb,
u64 start, u64 parent_transid)
{
struct extent_io_tree *io_tree;
int failed = 0;
int ret;
int num_copies = 0;
int mirror_num = 0;
int failed_mirror = 0;
clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
io_tree = &BTRFS_I(root->fs_info->btree_inode)->io_tree;
while (1) {
ret = read_extent_buffer_pages(io_tree, eb, start,
WAIT_COMPLETE,
btree_get_extent, mirror_num);
if (!ret) {
if (!verify_parent_transid(io_tree, eb,
parent_transid, 0))
break;
else
ret = -EIO;
}
/*
* This buffer's crc is fine, but its contents are corrupted, so
* there is no reason to read the other copies, they won't be
* any less wrong.
*/
if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags))
break;
num_copies = btrfs_num_copies(root->fs_info,
eb->start, eb->len);
if (num_copies == 1)
break;
if (!failed_mirror) {
failed = 1;
failed_mirror = eb->read_mirror;
}
mirror_num++;
if (mirror_num == failed_mirror)
mirror_num++;
if (mirror_num > num_copies)
break;
}
if (failed && !ret && failed_mirror)
repair_eb_io_failure(root, eb, failed_mirror);
return ret;
}
/*
* checksum a dirty tree block before IO. This has extra checks to make sure
* we only fill in the checksum field in the first page of a multi-page block
*/
static int csum_dirty_buffer(struct btrfs_root *root, struct page *page)
{
u64 start = page_offset(page);
u64 found_start;
struct extent_buffer *eb;
eb = (struct extent_buffer *)page->private;
if (page != eb->pages[0])
return 0;
found_start = btrfs_header_bytenr(eb);
if (WARN_ON(found_start != start || !PageUptodate(page)))
return 0;
csum_tree_block(root, eb, 0);
return 0;
}
static int check_tree_block_fsid(struct btrfs_root *root,
struct extent_buffer *eb)
{
struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
u8 fsid[BTRFS_UUID_SIZE];
int ret = 1;
read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
while (fs_devices) {
if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
ret = 0;
break;
}
fs_devices = fs_devices->seed;
}
return ret;
}
#define CORRUPT(reason, eb, root, slot) \
btrfs_crit(root->fs_info, "corrupt leaf, %s: block=%llu," \
"root=%llu, slot=%d", reason, \
btrfs_header_bytenr(eb), root->objectid, slot)
static noinline int check_leaf(struct btrfs_root *root,
struct extent_buffer *leaf)
{
struct btrfs_key key;
struct btrfs_key leaf_key;
u32 nritems = btrfs_header_nritems(leaf);
int slot;
if (nritems == 0)
return 0;
/* Check the 0 item */
if (btrfs_item_offset_nr(leaf, 0) + btrfs_item_size_nr(leaf, 0) !=
BTRFS_LEAF_DATA_SIZE(root)) {
CORRUPT("invalid item offset size pair", leaf, root, 0);
return -EIO;
}
/*
* Check to make sure each items keys are in the correct order and their
* offsets make sense. We only have to loop through nritems-1 because
* we check the current slot against the next slot, which verifies the
* next slot's offset+size makes sense and that the current's slot
* offset is correct.
*/
for (slot = 0; slot < nritems - 1; slot++) {
btrfs_item_key_to_cpu(leaf, &leaf_key, slot);
btrfs_item_key_to_cpu(leaf, &key, slot + 1);
/* Make sure the keys are in the right order */
if (btrfs_comp_cpu_keys(&leaf_key, &key) >= 0) {
CORRUPT("bad key order", leaf, root, slot);
return -EIO;
}
/*
* Make sure the offset and ends are right, remember that the
* item data starts at the end of the leaf and grows towards the
* front.
*/
if (btrfs_item_offset_nr(leaf, slot) !=
btrfs_item_end_nr(leaf, slot + 1)) {
CORRUPT("slot offset bad", leaf, root, slot);
return -EIO;
}
/*
* Check to make sure that we don't point outside of the leaf,
* just incase all the items are consistent to eachother, but
* all point outside of the leaf.
*/
if (btrfs_item_end_nr(leaf, slot) >
BTRFS_LEAF_DATA_SIZE(root)) {
CORRUPT("slot end outside of leaf", leaf, root, slot);
return -EIO;
}
}
return 0;
}
static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
u64 phy_offset, struct page *page,
u64 start, u64 end, int mirror)
{
u64 found_start;
int found_level;
struct extent_buffer *eb;
struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
int ret = 0;
int reads_done;
if (!page->private)
goto out;
eb = (struct extent_buffer *)page->private;
/* the pending IO might have been the only thing that kept this buffer
* in memory. Make sure we have a ref for all this other checks
*/
extent_buffer_get(eb);
reads_done = atomic_dec_and_test(&eb->io_pages);
if (!reads_done)
goto err;
eb->read_mirror = mirror;
if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
ret = -EIO;
goto err;
}
found_start = btrfs_header_bytenr(eb);
if (found_start != eb->start) {
printk_ratelimited(KERN_INFO "BTRFS (device %s): bad tree block start "
"%llu %llu\n",
eb->fs_info->sb->s_id, found_start, eb->start);
ret = -EIO;
goto err;
}
if (check_tree_block_fsid(root, eb)) {
printk_ratelimited(KERN_INFO "BTRFS (device %s): bad fsid on block %llu\n",
eb->fs_info->sb->s_id, eb->start);
ret = -EIO;
goto err;
}
found_level = btrfs_header_level(eb);
if (found_level >= BTRFS_MAX_LEVEL) {
btrfs_info(root->fs_info, "bad tree block level %d",
(int)btrfs_header_level(eb));
ret = -EIO;
goto err;
}
btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
eb, found_level);
ret = csum_tree_block(root, eb, 1);
if (ret) {
ret = -EIO;
goto err;
}
/*
* If this is a leaf block and it is corrupt, set the corrupt bit so
* that we don't try and read the other copies of this block, just
* return -EIO.
*/
if (found_level == 0 && check_leaf(root, eb)) {
set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
ret = -EIO;
}
if (!ret)
set_extent_buffer_uptodate(eb);
err:
if (reads_done &&
test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
btree_readahead_hook(root, eb, eb->start, ret);
if (ret) {
/*
* our io error hook is going to dec the io pages
* again, we have to make sure it has something
* to decrement
*/
atomic_inc(&eb->io_pages);
clear_extent_buffer_uptodate(eb);
}
free_extent_buffer(eb);
out:
return ret;
}
static int btree_io_failed_hook(struct page *page, int failed_mirror)
{
struct extent_buffer *eb;
struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
eb = (struct extent_buffer *)page->private;
set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
eb->read_mirror = failed_mirror;
atomic_dec(&eb->io_pages);
if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
btree_readahead_hook(root, eb, eb->start, -EIO);
return -EIO; /* we fixed nothing */
}
static void end_workqueue_bio(struct bio *bio, int err)
{
struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
struct btrfs_fs_info *fs_info;
struct btrfs_workqueue *wq;
btrfs_work_func_t func;
fs_info = end_io_wq->info;
end_io_wq->error = err;
if (bio->bi_rw & REQ_WRITE) {
if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
wq = fs_info->endio_meta_write_workers;
func = btrfs_endio_meta_write_helper;
} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
wq = fs_info->endio_freespace_worker;
func = btrfs_freespace_write_helper;
} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
wq = fs_info->endio_raid56_workers;
func = btrfs_endio_raid56_helper;
} else {
wq = fs_info->endio_write_workers;
func = btrfs_endio_write_helper;
}
} else {
if (unlikely(end_io_wq->metadata ==
BTRFS_WQ_ENDIO_DIO_REPAIR)) {
wq = fs_info->endio_repair_workers;
func = btrfs_endio_repair_helper;
} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
wq = fs_info->endio_raid56_workers;
func = btrfs_endio_raid56_helper;
} else if (end_io_wq->metadata) {
wq = fs_info->endio_meta_workers;
func = btrfs_endio_meta_helper;
} else {
wq = fs_info->endio_workers;
func = btrfs_endio_helper;
}
}
btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
btrfs_queue_work(wq, &end_io_wq->work);
}
int btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
enum btrfs_wq_endio_type metadata)
{
struct btrfs_end_io_wq *end_io_wq;
end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
if (!end_io_wq)
return -ENOMEM;
end_io_wq->private = bio->bi_private;
end_io_wq->end_io = bio->bi_end_io;
end_io_wq->info = info;
end_io_wq->error = 0;
end_io_wq->bio = bio;
end_io_wq->metadata = metadata;
bio->bi_private = end_io_wq;
bio->bi_end_io = end_workqueue_bio;
return 0;
}
unsigned long btrfs_async_submit_limit(struct btrfs_fs_info *info)
{
unsigned long limit = min_t(unsigned long,
info->thread_pool_size,
info->fs_devices->open_devices);
return 256 * limit;
}
static void run_one_async_start(struct btrfs_work *work)
{
struct async_submit_bio *async;
int ret;
async = container_of(work, struct async_submit_bio, work);
ret = async->submit_bio_start(async->inode, async->rw, async->bio,
async->mirror_num, async->bio_flags,
async->bio_offset);
if (ret)
async->error = ret;
}
static void run_one_async_done(struct btrfs_work *work)
{
struct btrfs_fs_info *fs_info;
struct async_submit_bio *async;
int limit;
async = container_of(work, struct async_submit_bio, work);
fs_info = BTRFS_I(async->inode)->root->fs_info;
limit = btrfs_async_submit_limit(fs_info);
limit = limit * 2 / 3;
if (atomic_dec_return(&fs_info->nr_async_submits) < limit &&
waitqueue_active(&fs_info->async_submit_wait))
wake_up(&fs_info->async_submit_wait);
/* If an error occured we just want to clean up the bio and move on */
if (async->error) {
bio_endio(async->bio, async->error);
return;
}
async->submit_bio_done(async->inode, async->rw, async->bio,
async->mirror_num, async->bio_flags,
async->bio_offset);
}
static void run_one_async_free(struct btrfs_work *work)
{
struct async_submit_bio *async;
async = container_of(work, struct async_submit_bio, work);
kfree(async);
}
int btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct inode *inode,
int rw, struct bio *bio, int mirror_num,
unsigned long bio_flags,
u64 bio_offset,
extent_submit_bio_hook_t *submit_bio_start,
extent_submit_bio_hook_t *submit_bio_done)
{
struct async_submit_bio *async;
async = kmalloc(sizeof(*async), GFP_NOFS);
if (!async)
return -ENOMEM;
async->inode = inode;
async->rw = rw;
async->bio = bio;
async->mirror_num = mirror_num;
async->submit_bio_start = submit_bio_start;
async->submit_bio_done = submit_bio_done;
btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
run_one_async_done, run_one_async_free);
async->bio_flags = bio_flags;
async->bio_offset = bio_offset;
async->error = 0;
atomic_inc(&fs_info->nr_async_submits);
if (rw & REQ_SYNC)
btrfs_set_work_high_priority(&async->work);
btrfs_queue_work(fs_info->workers, &async->work);
while (atomic_read(&fs_info->async_submit_draining) &&
atomic_read(&fs_info->nr_async_submits)) {
wait_event(fs_info->async_submit_wait,
(atomic_read(&fs_info->nr_async_submits) == 0));
}
return 0;
}
static int btree_csum_one_bio(struct bio *bio)
{
struct bio_vec *bvec;
struct btrfs_root *root;
int i, ret = 0;
bio_for_each_segment_all(bvec, bio, i) {
root = BTRFS_I(bvec->bv_page->mapping->host)->root;
ret = csum_dirty_buffer(root, bvec->bv_page);
if (ret)
break;
}
return ret;
}
static int __btree_submit_bio_start(struct inode *inode, int rw,
struct bio *bio, int mirror_num,
unsigned long bio_flags,
u64 bio_offset)
{
/*
* when we're called for a write, we're already in the async
* submission context. Just jump into btrfs_map_bio
*/
return btree_csum_one_bio(bio);
}
static int __btree_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
int mirror_num, unsigned long bio_flags,
u64 bio_offset)
{
int ret;
/*
* when we're called for a write, we're already in the async
* submission context. Just jump into btrfs_map_bio
*/
ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio, mirror_num, 1);
if (ret)
bio_endio(bio, ret);
return ret;
}
static int check_async_write(struct inode *inode, unsigned long bio_flags)
{
if (bio_flags & EXTENT_BIO_TREE_LOG)
return 0;
#ifdef CONFIG_X86
if (cpu_has_xmm4_2)
return 0;
#endif
return 1;
}
static int btree_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
int mirror_num, unsigned long bio_flags,
u64 bio_offset)
{
int async = check_async_write(inode, bio_flags);
int ret;
if (!(rw & REQ_WRITE)) {
/*
* called for a read, do the setup so that checksum validation
* can happen in the async kernel threads
*/
ret = btrfs_bio_wq_end_io(BTRFS_I(inode)->root->fs_info,
bio, BTRFS_WQ_ENDIO_METADATA);
if (ret)
goto out_w_error;
ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio,
mirror_num, 0);
} else if (!async) {
ret = btree_csum_one_bio(bio);
if (ret)
goto out_w_error;
ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio,
mirror_num, 0);
} else {
/*
* kthread helpers are used to submit writes so that
* checksumming can happen in parallel across all CPUs
*/
ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
inode, rw, bio, mirror_num, 0,
bio_offset,
__btree_submit_bio_start,
__btree_submit_bio_done);
}
if (ret) {
out_w_error:
bio_endio(bio, ret);
}
return ret;
}
#ifdef CONFIG_MIGRATION
static int btree_migratepage(struct address_space *mapping,
struct page *newpage, struct page *page,
enum migrate_mode mode)
{
/*
* we can't safely write a btree page from here,
* we haven't done the locking hook
*/
if (PageDirty(page))
return -EAGAIN;
/*
* Buffers may be managed in a filesystem specific way.
* We must have no buffers or drop them.
*/
if (page_has_private(page) &&
!try_to_release_page(page, GFP_KERNEL))
return -EAGAIN;
return migrate_page(mapping, newpage, page, mode);
}
#endif
static int btree_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct btrfs_fs_info *fs_info;
int ret;
if (wbc->sync_mode == WB_SYNC_NONE) {
if (wbc->for_kupdate)
return 0;
fs_info = BTRFS_I(mapping->host)->root->fs_info;
/* this is a bit racy, but that's ok */
ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
BTRFS_DIRTY_METADATA_THRESH);
if (ret < 0)
return 0;
}
return btree_write_cache_pages(mapping, wbc);
}
static int btree_readpage(struct file *file, struct page *page)
{
struct extent_io_tree *tree;
tree = &BTRFS_I(page->mapping->host)->io_tree;
return extent_read_full_page(tree, page, btree_get_extent, 0);
}
static int btree_releasepage(struct page *page, gfp_t gfp_flags)
{
if (PageWriteback(page) || PageDirty(page))
return 0;
return try_release_extent_buffer(page);
}
static void btree_invalidatepage(struct page *page, unsigned int offset,
unsigned int length)
{
struct extent_io_tree *tree;
tree = &BTRFS_I(page->mapping->host)->io_tree;
extent_invalidatepage(tree, page, offset);
btree_releasepage(page, GFP_NOFS);
if (PagePrivate(page)) {
btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
"page private not zero on page %llu",
(unsigned long long)page_offset(page));
ClearPagePrivate(page);
set_page_private(page, 0);
page_cache_release(page);
}
}
static int btree_set_page_dirty(struct page *page)
{
#ifdef DEBUG
struct extent_buffer *eb;
BUG_ON(!PagePrivate(page));
eb = (struct extent_buffer *)page->private;
BUG_ON(!eb);
BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
BUG_ON(!atomic_read(&eb->refs));
btrfs_assert_tree_locked(eb);
#endif
return __set_page_dirty_nobuffers(page);
}
static const struct address_space_operations btree_aops = {
.readpage = btree_readpage,
.writepages = btree_writepages,
.releasepage = btree_releasepage,
.invalidatepage = btree_invalidatepage,
#ifdef CONFIG_MIGRATION
.migratepage = btree_migratepage,
#endif
.set_page_dirty = btree_set_page_dirty,
};
void readahead_tree_block(struct btrfs_root *root, u64 bytenr, u32 blocksize)
{
struct extent_buffer *buf = NULL;
struct inode *btree_inode = root->fs_info->btree_inode;
buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
if (!buf)
return;
read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
buf, 0, WAIT_NONE, btree_get_extent, 0);
free_extent_buffer(buf);
}
int reada_tree_block_flagged(struct btrfs_root *root, u64 bytenr, u32 blocksize,
int mirror_num, struct extent_buffer **eb)
{
struct extent_buffer *buf = NULL;
struct inode *btree_inode = root->fs_info->btree_inode;
struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
int ret;
buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
if (!buf)
return 0;
set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
ret = read_extent_buffer_pages(io_tree, buf, 0, WAIT_PAGE_LOCK,
btree_get_extent, mirror_num);
if (ret) {
free_extent_buffer(buf);
return ret;
}
if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
free_extent_buffer(buf);
return -EIO;
} else if (extent_buffer_uptodate(buf)) {
*eb = buf;
} else {
free_extent_buffer(buf);
}
return 0;
}
struct extent_buffer *btrfs_find_tree_block(struct btrfs_root *root,
u64 bytenr)
{
return find_extent_buffer(root->fs_info, bytenr);
}
struct extent_buffer *btrfs_find_create_tree_block(struct btrfs_root *root,
u64 bytenr, u32 blocksize)
{
if (btrfs_test_is_dummy_root(root))
return alloc_test_extent_buffer(root->fs_info, bytenr,
blocksize);
return alloc_extent_buffer(root->fs_info, bytenr, blocksize);
}
int btrfs_write_tree_block(struct extent_buffer *buf)
{
return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
buf->start + buf->len - 1);
}
int btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
{
return filemap_fdatawait_range(buf->pages[0]->mapping,
buf->start, buf->start + buf->len - 1);
}
struct extent_buffer *read_tree_block(struct btrfs_root *root, u64 bytenr,
u64 parent_transid)
{
struct extent_buffer *buf = NULL;
int ret;
buf = btrfs_find_create_tree_block(root, bytenr, root->nodesize);
if (!buf)
return NULL;
ret = btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
if (ret) {
free_extent_buffer(buf);
return NULL;
}
return buf;
}
void clean_tree_block(struct btrfs_trans_handle *trans, struct btrfs_root *root,
struct extent_buffer *buf)
{
struct btrfs_fs_info *fs_info = root->fs_info;
if (btrfs_header_generation(buf) ==
fs_info->running_transaction->transid) {
btrfs_assert_tree_locked(buf);
if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
__percpu_counter_add(&fs_info->dirty_metadata_bytes,
-buf->len,
fs_info->dirty_metadata_batch);
/* ugh, clear_extent_buffer_dirty needs to lock the page */
btrfs_set_lock_blocking(buf);
clear_extent_buffer_dirty(buf);
}
}
}
static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
{
struct btrfs_subvolume_writers *writers;
int ret;
writers = kmalloc(sizeof(*writers), GFP_NOFS);
if (!writers)
return ERR_PTR(-ENOMEM);
ret = percpu_counter_init(&writers->counter, 0, GFP_KERNEL);
if (ret < 0) {
kfree(writers);
return ERR_PTR(ret);
}
init_waitqueue_head(&writers->wait);
return writers;
}
static void
btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
{
percpu_counter_destroy(&writers->counter);
kfree(writers);
}
static void __setup_root(u32 nodesize, u32 sectorsize, u32 stripesize,
struct btrfs_root *root, struct btrfs_fs_info *fs_info,
u64 objectid)
{
root->node = NULL;
root->commit_root = NULL;
root->sectorsize = sectorsize;
root->nodesize = nodesize;
root->stripesize = stripesize;
root->state = 0;
root->orphan_cleanup_state = 0;
root->objectid = objectid;
root->last_trans = 0;
root->highest_objectid = 0;
root->nr_delalloc_inodes = 0;
root->nr_ordered_extents = 0;
root->name = NULL;
root->inode_tree = RB_ROOT;
INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
root->block_rsv = NULL;
root->orphan_block_rsv = NULL;
INIT_LIST_HEAD(&root->dirty_list);
INIT_LIST_HEAD(&root->root_list);
INIT_LIST_HEAD(&root->delalloc_inodes);
INIT_LIST_HEAD(&root->delalloc_root);
INIT_LIST_HEAD(&root->ordered_extents);
INIT_LIST_HEAD(&root->ordered_root);
INIT_LIST_HEAD(&root->logged_list[0]);
INIT_LIST_HEAD(&root->logged_list[1]);
spin_lock_init(&root->orphan_lock);
spin_lock_init(&root->inode_lock);
spin_lock_init(&root->delalloc_lock);
spin_lock_init(&root->ordered_extent_lock);
spin_lock_init(&root->accounting_lock);
spin_lock_init(&root->log_extents_lock[0]);
spin_lock_init(&root->log_extents_lock[1]);
mutex_init(&root->objectid_mutex);
mutex_init(&root->log_mutex);
mutex_init(&root->ordered_extent_mutex);
mutex_init(&root->delalloc_mutex);
init_waitqueue_head(&root->log_writer_wait);
init_waitqueue_head(&root->log_commit_wait[0]);
init_waitqueue_head(&root->log_commit_wait[1]);
INIT_LIST_HEAD(&root->log_ctxs[0]);
INIT_LIST_HEAD(&root->log_ctxs[1]);
atomic_set(&root->log_commit[0], 0);
atomic_set(&root->log_commit[1], 0);
atomic_set(&root->log_writers, 0);
atomic_set(&root->log_batch, 0);
atomic_set(&root->orphan_inodes, 0);
atomic_set(&root->refs, 1);
atomic_set(&root->will_be_snapshoted, 0);
root->log_transid = 0;
root->log_transid_committed = -1;
root->last_log_commit = 0;
if (fs_info)
extent_io_tree_init(&root->dirty_log_pages,
fs_info->btree_inode->i_mapping);
memset(&root->root_key, 0, sizeof(root->root_key));
memset(&root->root_item, 0, sizeof(root->root_item));
memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
memset(&root->root_kobj, 0, sizeof(root->root_kobj));
if (fs_info)
root->defrag_trans_start = fs_info->generation;
else
root->defrag_trans_start = 0;
init_completion(&root->kobj_unregister);
root->root_key.objectid = objectid;
root->anon_dev = 0;
spin_lock_init(&root->root_item_lock);
}
static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info)
{
struct btrfs_root *root = kzalloc(sizeof(*root), GFP_NOFS);
if (root)
root->fs_info = fs_info;
return root;
}
#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
/* Should only be used by the testing infrastructure */
struct btrfs_root *btrfs_alloc_dummy_root(void)
{
struct btrfs_root *root;
root = btrfs_alloc_root(NULL);
if (!root)
return ERR_PTR(-ENOMEM);
__setup_root(4096, 4096, 4096, root, NULL, 1);
set_bit(BTRFS_ROOT_DUMMY_ROOT, &root->state);
root->alloc_bytenr = 0;
return root;
}
#endif
struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info,
u64 objectid)
{
struct extent_buffer *leaf;
struct btrfs_root *tree_root = fs_info->tree_root;
struct btrfs_root *root;
struct btrfs_key key;
int ret = 0;
uuid_le uuid;
root = btrfs_alloc_root(fs_info);
if (!root)
return ERR_PTR(-ENOMEM);
__setup_root(tree_root->nodesize, tree_root->sectorsize,
tree_root->stripesize, root, fs_info, objectid);
root->root_key.objectid = objectid;
root->root_key.type = BTRFS_ROOT_ITEM_KEY;
root->root_key.offset = 0;
leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
if (IS_ERR(leaf)) {
ret = PTR_ERR(leaf);
leaf = NULL;
goto fail;
}
memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
btrfs_set_header_bytenr(leaf, leaf->start);
btrfs_set_header_generation(leaf, trans->transid);
btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
btrfs_set_header_owner(leaf, objectid);
root->node = leaf;
write_extent_buffer(leaf, fs_info->fsid, btrfs_header_fsid(),
BTRFS_FSID_SIZE);
write_extent_buffer(leaf, fs_info->chunk_tree_uuid,
btrfs_header_chunk_tree_uuid(leaf),
BTRFS_UUID_SIZE);
btrfs_mark_buffer_dirty(leaf);
root->commit_root = btrfs_root_node(root);
set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
root->root_item.flags = 0;
root->root_item.byte_limit = 0;
btrfs_set_root_bytenr(&root->root_item, leaf->start);
btrfs_set_root_generation(&root->root_item, trans->transid);
btrfs_set_root_level(&root->root_item, 0);
btrfs_set_root_refs(&root->root_item, 1);
btrfs_set_root_used(&root->root_item, leaf->len);
btrfs_set_root_last_snapshot(&root->root_item, 0);
btrfs_set_root_dirid(&root->root_item, 0);
uuid_le_gen(&uuid);
memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
root->root_item.drop_level = 0;
key.objectid = objectid;
key.type = BTRFS_ROOT_ITEM_KEY;
key.offset = 0;
ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
if (ret)
goto fail;
btrfs_tree_unlock(leaf);
return root;
fail:
if (leaf) {
btrfs_tree_unlock(leaf);
free_extent_buffer(root->commit_root);
free_extent_buffer(leaf);
}
kfree(root);
return ERR_PTR(ret);
}
static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info)
{
struct btrfs_root *root;
struct btrfs_root *tree_root = fs_info->tree_root;
struct extent_buffer *leaf;
root = btrfs_alloc_root(fs_info);
if (!root)
return ERR_PTR(-ENOMEM);
__setup_root(tree_root->nodesize, tree_root->sectorsize,
tree_root->stripesize, root, fs_info,
BTRFS_TREE_LOG_OBJECTID);
root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
root->root_key.type = BTRFS_ROOT_ITEM_KEY;
root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
/*
* DON'T set REF_COWS for log trees
*
* log trees do not get reference counted because they go away
* before a real commit is actually done. They do store pointers
* to file data extents, and those reference counts still get
* updated (along with back refs to the log tree).
*/
leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
NULL, 0, 0, 0);
if (IS_ERR(leaf)) {
kfree(root);
return ERR_CAST(leaf);
}
memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
btrfs_set_header_bytenr(leaf, leaf->start);
btrfs_set_header_generation(leaf, trans->transid);
btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
root->node = leaf;
write_extent_buffer(root->node, root->fs_info->fsid,
btrfs_header_fsid(), BTRFS_FSID_SIZE);
btrfs_mark_buffer_dirty(root->node);
btrfs_tree_unlock(root->node);
return root;
}
int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info)
{
struct btrfs_root *log_root;
log_root = alloc_log_tree(trans, fs_info);
if (IS_ERR(log_root))
return PTR_ERR(log_root);
WARN_ON(fs_info->log_root_tree);
fs_info->log_root_tree = log_root;
return 0;
}
int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
struct btrfs_root *log_root;
struct btrfs_inode_item *inode_item;
log_root = alloc_log_tree(trans, root->fs_info);
if (IS_ERR(log_root))
return PTR_ERR(log_root);
log_root->last_trans = trans->transid;
log_root->root_key.offset = root->root_key.objectid;
inode_item = &log_root->root_item.inode;
btrfs_set_stack_inode_generation(inode_item, 1);
btrfs_set_stack_inode_size(inode_item, 3);
btrfs_set_stack_inode_nlink(inode_item, 1);
btrfs_set_stack_inode_nbytes(inode_item, root->nodesize);
btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
btrfs_set_root_node(&log_root->root_item, log_root->node);
WARN_ON(root->log_root);
root->log_root = log_root;
root->log_transid = 0;
root->log_transid_committed = -1;
root->last_log_commit = 0;
return 0;
}
static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
struct btrfs_key *key)
{
struct btrfs_root *root;
struct btrfs_fs_info *fs_info = tree_root->fs_info;
struct btrfs_path *path;
u64 generation;
int ret;
path = btrfs_alloc_path();
if (!path)
return ERR_PTR(-ENOMEM);
root = btrfs_alloc_root(fs_info);
if (!root) {
ret = -ENOMEM;
goto alloc_fail;
}
__setup_root(tree_root->nodesize, tree_root->sectorsize,
tree_root->stripesize, root, fs_info, key->objectid);
ret = btrfs_find_root(tree_root, key, path,
&root->root_item, &root->root_key);
if (ret) {
if (ret > 0)
ret = -ENOENT;
goto find_fail;
}
generation = btrfs_root_generation(&root->root_item);
root->node = read_tree_block(root, btrfs_root_bytenr(&root->root_item),
generation);
if (!root->node) {
ret = -ENOMEM;
goto find_fail;
} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
ret = -EIO;
goto read_fail;
}
root->commit_root = btrfs_root_node(root);
out:
btrfs_free_path(path);
return root;
read_fail:
free_extent_buffer(root->node);
find_fail:
kfree(root);
alloc_fail:
root = ERR_PTR(ret);
goto out;
}
struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
struct btrfs_key *location)
{
struct btrfs_root *root;
root = btrfs_read_tree_root(tree_root, location);
if (IS_ERR(root))
return root;
if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
set_bit(BTRFS_ROOT_REF_COWS, &root->state);
btrfs_check_and_init_root_item(&root->root_item);
}
return root;
}
int btrfs_init_fs_root(struct btrfs_root *root)
{
int ret;
struct btrfs_subvolume_writers *writers;
root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
GFP_NOFS);
if (!root->free_ino_pinned || !root->free_ino_ctl) {
ret = -ENOMEM;
goto fail;
}
writers = btrfs_alloc_subvolume_writers();
if (IS_ERR(writers)) {
ret = PTR_ERR(writers);
goto fail;
}
root->subv_writers = writers;
btrfs_init_free_ino_ctl(root);
spin_lock_init(&root->ino_cache_lock);
init_waitqueue_head(&root->ino_cache_wait);
ret = get_anon_bdev(&root->anon_dev);
if (ret)
goto free_writers;
return 0;
free_writers:
btrfs_free_subvolume_writers(root->subv_writers);
fail:
kfree(root->free_ino_ctl);
kfree(root->free_ino_pinned);
return ret;
}
static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
u64 root_id)
{
struct btrfs_root *root;
spin_lock(&fs_info->fs_roots_radix_lock);
root = radix_tree_lookup(&fs_info->fs_roots_radix,
(unsigned long)root_id);
spin_unlock(&fs_info->fs_roots_radix_lock);
return root;
}
int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
struct btrfs_root *root)
{
int ret;
ret = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
if (ret)
return ret;
spin_lock(&fs_info->fs_roots_radix_lock);
ret = radix_tree_insert(&fs_info->fs_roots_radix,
(unsigned long)root->root_key.objectid,
root);
if (ret == 0)
set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
spin_unlock(&fs_info->fs_roots_radix_lock);
radix_tree_preload_end();
return ret;
}
struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
struct btrfs_key *location,
bool check_ref)
{
struct btrfs_root *root;
int ret;
if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
return fs_info->tree_root;
if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
return fs_info->extent_root;
if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
return fs_info->chunk_root;
if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
return fs_info->dev_root;
if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
return fs_info->csum_root;
if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
return fs_info->quota_root ? fs_info->quota_root :
ERR_PTR(-ENOENT);
if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
return fs_info->uuid_root ? fs_info->uuid_root :
ERR_PTR(-ENOENT);
again:
root = btrfs_lookup_fs_root(fs_info, location->objectid);
if (root) {
if (check_ref && btrfs_root_refs(&root->root_item) == 0)
return ERR_PTR(-ENOENT);
return root;
}
root = btrfs_read_fs_root(fs_info->tree_root, location);
if (IS_ERR(root))
return root;
if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
ret = -ENOENT;
goto fail;
}
ret = btrfs_init_fs_root(root);
if (ret)
goto fail;
ret = btrfs_find_item(fs_info->tree_root, NULL, BTRFS_ORPHAN_OBJECTID,
location->objectid, BTRFS_ORPHAN_ITEM_KEY, NULL);
if (ret < 0)
goto fail;
if (ret == 0)
set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
ret = btrfs_insert_fs_root(fs_info, root);
if (ret) {
if (ret == -EEXIST) {
free_fs_root(root);
goto again;
}
goto fail;
}
return root;
fail:
free_fs_root(root);
return ERR_PTR(ret);
}
static int btrfs_congested_fn(void *congested_data, int bdi_bits)
{
struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
int ret = 0;
struct btrfs_device *device;
struct backing_dev_info *bdi;
rcu_read_lock();
list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
if (!device->bdev)
continue;
bdi = blk_get_backing_dev_info(device->bdev);
if (bdi_congested(bdi, bdi_bits)) {
ret = 1;
break;
}
}
rcu_read_unlock();
return ret;
}
static int setup_bdi(struct btrfs_fs_info *info, struct backing_dev_info *bdi)
{
int err;
err = bdi_setup_and_register(bdi, "btrfs");
if (err)
return err;
bdi->ra_pages = VM_MAX_READAHEAD * 1024 / PAGE_CACHE_SIZE;
bdi->congested_fn = btrfs_congested_fn;
bdi->congested_data = info;
return 0;
}
/*
* called by the kthread helper functions to finally call the bio end_io
* functions. This is where read checksum verification actually happens
*/
static void end_workqueue_fn(struct btrfs_work *work)
{
struct bio *bio;
struct btrfs_end_io_wq *end_io_wq;
int error;
end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
bio = end_io_wq->bio;
error = end_io_wq->error;
bio->bi_private = end_io_wq->private;
bio->bi_end_io = end_io_wq->end_io;
kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
bio_endio_nodec(bio, error);
}
static int cleaner_kthread(void *arg)
{
struct btrfs_root *root = arg;
int again;
do {
again = 0;
/* Make the cleaner go to sleep early. */
if (btrfs_need_cleaner_sleep(root))
goto sleep;
if (!mutex_trylock(&root->fs_info->cleaner_mutex))
goto sleep;
/*
* Avoid the problem that we change the status of the fs
* during the above check and trylock.
*/
if (btrfs_need_cleaner_sleep(root)) {
mutex_unlock(&root->fs_info->cleaner_mutex);
goto sleep;
}
btrfs_run_delayed_iputs(root);
btrfs_delete_unused_bgs(root->fs_info);
again = btrfs_clean_one_deleted_snapshot(root);
mutex_unlock(&root->fs_info->cleaner_mutex);
/*
* The defragger has dealt with the R/O remount and umount,
* needn't do anything special here.
*/
btrfs_run_defrag_inodes(root->fs_info);
sleep:
if (!try_to_freeze() && !again) {
set_current_state(TASK_INTERRUPTIBLE);
if (!kthread_should_stop())
schedule();
__set_current_state(TASK_RUNNING);
}
} while (!kthread_should_stop());
return 0;
}
static int transaction_kthread(void *arg)
{
struct btrfs_root *root = arg;
struct btrfs_trans_handle *trans;
struct btrfs_transaction *cur;
u64 transid;
unsigned long now;
unsigned long delay;
bool cannot_commit;
do {
cannot_commit = false;
delay = HZ * root->fs_info->commit_interval;
mutex_lock(&root->fs_info->transaction_kthread_mutex);
spin_lock(&root->fs_info->trans_lock);
cur = root->fs_info->running_transaction;
if (!cur) {
spin_unlock(&root->fs_info->trans_lock);
goto sleep;
}
now = get_seconds();
if (cur->state < TRANS_STATE_BLOCKED &&
(now < cur->start_time ||
now - cur->start_time < root->fs_info->commit_interval)) {
spin_unlock(&root->fs_info->trans_lock);
delay = HZ * 5;
goto sleep;
}
transid = cur->transid;
spin_unlock(&root->fs_info->trans_lock);
/* If the file system is aborted, this will always fail. */
trans = btrfs_attach_transaction(root);
if (IS_ERR(trans)) {
if (PTR_ERR(trans) != -ENOENT)
cannot_commit = true;
goto sleep;
}
if (transid == trans->transid) {
btrfs_commit_transaction(trans, root);
} else {
btrfs_end_transaction(trans, root);
}
sleep:
wake_up_process(root->fs_info->cleaner_kthread);
mutex_unlock(&root->fs_info->transaction_kthread_mutex);
if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
&root->fs_info->fs_state)))
btrfs_cleanup_transaction(root);
if (!try_to_freeze()) {
set_current_state(TASK_INTERRUPTIBLE);
if (!kthread_should_stop() &&
(!btrfs_transaction_blocked(root->fs_info) ||
cannot_commit))
schedule_timeout(delay);
__set_current_state(TASK_RUNNING);
}
} while (!kthread_should_stop());
return 0;
}
/*
* this will find the highest generation in the array of
* root backups. The index of the highest array is returned,
* or -1 if we can't find anything.
*
* We check to make sure the array is valid by comparing the
* generation of the latest root in the array with the generation
* in the super block. If they don't match we pitch it.
*/
static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
{
u64 cur;
int newest_index = -1;
struct btrfs_root_backup *root_backup;
int i;
for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
root_backup = info->super_copy->super_roots + i;
cur = btrfs_backup_tree_root_gen(root_backup);
if (cur == newest_gen)
newest_index = i;
}
/* check to see if we actually wrapped around */
if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
root_backup = info->super_copy->super_roots;
cur = btrfs_backup_tree_root_gen(root_backup);
if (cur == newest_gen)
newest_index = 0;
}
return newest_index;
}
/*
* find the oldest backup so we know where to store new entries
* in the backup array. This will set the backup_root_index
* field in the fs_info struct
*/
static void find_oldest_super_backup(struct btrfs_fs_info *info,
u64 newest_gen)
{
int newest_index = -1;
newest_index = find_newest_super_backup(info, newest_gen);
/* if there was garbage in there, just move along */
if (newest_index == -1) {
info->backup_root_index = 0;
} else {
info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
}
}
/*
* copy all the root pointers into the super backup array.
* this will bump the backup pointer by one when it is
* done
*/
static void backup_super_roots(struct btrfs_fs_info *info)
{
int next_backup;
struct btrfs_root_backup *root_backup;
int last_backup;
next_backup = info->backup_root_index;
last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
BTRFS_NUM_BACKUP_ROOTS;
/*
* just overwrite the last backup if we're at the same generation
* this happens only at umount
*/
root_backup = info->super_for_commit->super_roots + last_backup;
if (btrfs_backup_tree_root_gen(root_backup) ==
btrfs_header_generation(info->tree_root->node))
next_backup = last_backup;
root_backup = info->super_for_commit->super_roots + next_backup;
/*
* make sure all of our padding and empty slots get zero filled
* regardless of which ones we use today
*/
memset(root_backup, 0, sizeof(*root_backup));
info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
btrfs_set_backup_tree_root_gen(root_backup,
btrfs_header_generation(info->tree_root->node));
btrfs_set_backup_tree_root_level(root_backup,
btrfs_header_level(info->tree_root->node));
btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
btrfs_set_backup_chunk_root_gen(root_backup,
btrfs_header_generation(info->chunk_root->node));
btrfs_set_backup_chunk_root_level(root_backup,
btrfs_header_level(info->chunk_root->node));
btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
btrfs_set_backup_extent_root_gen(root_backup,
btrfs_header_generation(info->extent_root->node));
btrfs_set_backup_extent_root_level(root_backup,
btrfs_header_level(info->extent_root->node));
/*
* we might commit during log recovery, which happens before we set
* the fs_root. Make sure it is valid before we fill it in.
*/
if (info->fs_root && info->fs_root->node) {
btrfs_set_backup_fs_root(root_backup,
info->fs_root->node->start);
btrfs_set_backup_fs_root_gen(root_backup,
btrfs_header_generation(info->fs_root->node));
btrfs_set_backup_fs_root_level(root_backup,
btrfs_header_level(info->fs_root->node));
}
btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
btrfs_set_backup_dev_root_gen(root_backup,
btrfs_header_generation(info->dev_root->node));
btrfs_set_backup_dev_root_level(root_backup,
btrfs_header_level(info->dev_root->node));
btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
btrfs_set_backup_csum_root_gen(root_backup,
btrfs_header_generation(info->csum_root->node));
btrfs_set_backup_csum_root_level(root_backup,
btrfs_header_level(info->csum_root->node));
btrfs_set_backup_total_bytes(root_backup,
btrfs_super_total_bytes(info->super_copy));
btrfs_set_backup_bytes_used(root_backup,
btrfs_super_bytes_used(info->super_copy));
btrfs_set_backup_num_devices(root_backup,
btrfs_super_num_devices(info->super_copy));
/*
* if we don't copy this out to the super_copy, it won't get remembered
* for the next commit
*/
memcpy(&info->super_copy->super_roots,
&info->super_for_commit->super_roots,
sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
}
/*
* this copies info out of the root backup array and back into
* the in-memory super block. It is meant to help iterate through
* the array, so you send it the number of backups you've already
* tried and the last backup index you used.
*
* this returns -1 when it has tried all the backups
*/
static noinline int next_root_backup(struct btrfs_fs_info *info,
struct btrfs_super_block *super,
int *num_backups_tried, int *backup_index)
{
struct btrfs_root_backup *root_backup;
int newest = *backup_index;
if (*num_backups_tried == 0) {
u64 gen = btrfs_super_generation(super);
newest = find_newest_super_backup(info, gen);
if (newest == -1)
return -1;
*backup_index = newest;
*num_backups_tried = 1;
} else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
/* we've tried all the backups, all done */
return -1;
} else {
/* jump to the next oldest backup */
newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
BTRFS_NUM_BACKUP_ROOTS;
*backup_index = newest;
*num_backups_tried += 1;
}
root_backup = super->super_roots + newest;
btrfs_set_super_generation(super,
btrfs_backup_tree_root_gen(root_backup));
btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
btrfs_set_super_root_level(super,
btrfs_backup_tree_root_level(root_backup));
btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
/*
* fixme: the total bytes and num_devices need to match or we should
* need a fsck
*/
btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
return 0;
}
/* helper to cleanup workers */
static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
{
btrfs_destroy_workqueue(fs_info->fixup_workers);
btrfs_destroy_workqueue(fs_info->delalloc_workers);
btrfs_destroy_workqueue(fs_info->workers);
btrfs_destroy_workqueue(fs_info->endio_workers);
btrfs_destroy_workqueue(fs_info->endio_meta_workers);
btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
btrfs_destroy_workqueue(fs_info->endio_repair_workers);
btrfs_destroy_workqueue(fs_info->rmw_workers);
btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
btrfs_destroy_workqueue(fs_info->endio_write_workers);
btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
btrfs_destroy_workqueue(fs_info->submit_workers);
btrfs_destroy_workqueue(fs_info->delayed_workers);
btrfs_destroy_workqueue(fs_info->caching_workers);
btrfs_destroy_workqueue(fs_info->readahead_workers);
btrfs_destroy_workqueue(fs_info->flush_workers);
btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
btrfs_destroy_workqueue(fs_info->extent_workers);
}
static void free_root_extent_buffers(struct btrfs_root *root)
{
if (root) {
free_extent_buffer(root->node);
free_extent_buffer(root->commit_root);
root->node = NULL;
root->commit_root = NULL;
}
}
/* helper to cleanup tree roots */
static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
{
free_root_extent_buffers(info->tree_root);
free_root_extent_buffers(info->dev_root);
free_root_extent_buffers(info->extent_root);
free_root_extent_buffers(info->csum_root);
free_root_extent_buffers(info->quota_root);
free_root_extent_buffers(info->uuid_root);
if (chunk_root)
free_root_extent_buffers(info->chunk_root);
}
void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
{
int ret;
struct btrfs_root *gang[8];
int i;
while (!list_empty(&fs_info->dead_roots)) {
gang[0] = list_entry(fs_info->dead_roots.next,
struct btrfs_root, root_list);
list_del(&gang[0]->root_list);
if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
btrfs_drop_and_free_fs_root(fs_info, gang[0]);
} else {
free_extent_buffer(gang[0]->node);
free_extent_buffer(gang[0]->commit_root);
btrfs_put_fs_root(gang[0]);
}
}
while (1) {
ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
(void **)gang, 0,
ARRAY_SIZE(gang));
if (!ret)
break;
for (i = 0; i < ret; i++)
btrfs_drop_and_free_fs_root(fs_info, gang[i]);
}
if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
btrfs_free_log_root_tree(NULL, fs_info);
btrfs_destroy_pinned_extent(fs_info->tree_root,
fs_info->pinned_extents);
}
}
int open_ctree(struct super_block *sb,
struct btrfs_fs_devices *fs_devices,
char *options)
{
u32 sectorsize;
u32 nodesize;
u32 stripesize;
u64 generation;
u64 features;
struct btrfs_key location;
struct buffer_head *bh;
struct btrfs_super_block *disk_super;
struct btrfs_fs_info *fs_info = btrfs_sb(sb);
struct btrfs_root *tree_root;
struct btrfs_root *extent_root;
struct btrfs_root *csum_root;
struct btrfs_root *chunk_root;
struct btrfs_root *dev_root;
struct btrfs_root *quota_root;
struct btrfs_root *uuid_root;
struct btrfs_root *log_tree_root;
int ret;
int err = -EINVAL;
int num_backups_tried = 0;
int backup_index = 0;
int max_active;
int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
bool create_uuid_tree;
bool check_uuid_tree;
tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info);
chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info);
if (!tree_root || !chunk_root) {
err = -ENOMEM;
goto fail;
}
ret = init_srcu_struct(&fs_info->subvol_srcu);
if (ret) {
err = ret;
goto fail;
}
ret = setup_bdi(fs_info, &fs_info->bdi);
if (ret) {
err = ret;
goto fail_srcu;
}
ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
if (ret) {
err = ret;
goto fail_bdi;
}
fs_info->dirty_metadata_batch = PAGE_CACHE_SIZE *
(1 + ilog2(nr_cpu_ids));
ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
if (ret) {
err = ret;
goto fail_dirty_metadata_bytes;
}
ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
if (ret) {
err = ret;
goto fail_delalloc_bytes;
}
fs_info->btree_inode = new_inode(sb);
if (!fs_info->btree_inode) {
err = -ENOMEM;
goto fail_bio_counter;
}
mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
INIT_LIST_HEAD(&fs_info->trans_list);
INIT_LIST_HEAD(&fs_info->dead_roots);
INIT_LIST_HEAD(&fs_info->delayed_iputs);
INIT_LIST_HEAD(&fs_info->delalloc_roots);
INIT_LIST_HEAD(&fs_info->caching_block_groups);
spin_lock_init(&fs_info->delalloc_root_lock);
spin_lock_init(&fs_info->trans_lock);
spin_lock_init(&fs_info->fs_roots_radix_lock);
spin_lock_init(&fs_info->delayed_iput_lock);
spin_lock_init(&fs_info->defrag_inodes_lock);
spin_lock_init(&fs_info->free_chunk_lock);
spin_lock_init(&fs_info->tree_mod_seq_lock);
spin_lock_init(&fs_info->super_lock);
spin_lock_init(&fs_info->qgroup_op_lock);
spin_lock_init(&fs_info->buffer_lock);
spin_lock_init(&fs_info->unused_bgs_lock);
rwlock_init(&fs_info->tree_mod_log_lock);
mutex_init(&fs_info->reloc_mutex);
mutex_init(&fs_info->delalloc_root_mutex);
seqlock_init(&fs_info->profiles_lock);
init_completion(&fs_info->kobj_unregister);
INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
INIT_LIST_HEAD(&fs_info->space_info);
INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
INIT_LIST_HEAD(&fs_info->unused_bgs);
btrfs_mapping_init(&fs_info->mapping_tree);
btrfs_init_block_rsv(&fs_info->global_block_rsv,
BTRFS_BLOCK_RSV_GLOBAL);
btrfs_init_block_rsv(&fs_info->delalloc_block_rsv,
BTRFS_BLOCK_RSV_DELALLOC);
btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
BTRFS_BLOCK_RSV_DELOPS);
atomic_set(&fs_info->nr_async_submits, 0);
atomic_set(&fs_info->async_delalloc_pages, 0);
atomic_set(&fs_info->async_submit_draining, 0);
atomic_set(&fs_info->nr_async_bios, 0);
atomic_set(&fs_info->defrag_running, 0);
atomic_set(&fs_info->qgroup_op_seq, 0);
atomic64_set(&fs_info->tree_mod_seq, 0);
fs_info->sb = sb;
fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
fs_info->metadata_ratio = 0;
fs_info->defrag_inodes = RB_ROOT;
fs_info->free_chunk_space = 0;
fs_info->tree_mod_log = RB_ROOT;
fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
fs_info->avg_delayed_ref_runtime = div64_u64(NSEC_PER_SEC, 64);
/* readahead state */
INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_WAIT);
spin_lock_init(&fs_info->reada_lock);
fs_info->thread_pool_size = min_t(unsigned long,
num_online_cpus() + 2, 8);
INIT_LIST_HEAD(&fs_info->ordered_roots);
spin_lock_init(&fs_info->ordered_root_lock);
fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
GFP_NOFS);
if (!fs_info->delayed_root) {
err = -ENOMEM;
goto fail_iput;
}
btrfs_init_delayed_root(fs_info->delayed_root);
mutex_init(&fs_info->scrub_lock);
atomic_set(&fs_info->scrubs_running, 0);
atomic_set(&fs_info->scrub_pause_req, 0);
atomic_set(&fs_info->scrubs_paused, 0);
atomic_set(&fs_info->scrub_cancel_req, 0);
init_waitqueue_head(&fs_info->replace_wait);
init_waitqueue_head(&fs_info->scrub_pause_wait);
fs_info->scrub_workers_refcnt = 0;
#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
fs_info->check_integrity_print_mask = 0;
#endif
spin_lock_init(&fs_info->balance_lock);
mutex_init(&fs_info->balance_mutex);
atomic_set(&fs_info->balance_running, 0);
atomic_set(&fs_info->balance_pause_req, 0);
atomic_set(&fs_info->balance_cancel_req, 0);
fs_info->balance_ctl = NULL;
init_waitqueue_head(&fs_info->balance_wait_q);
btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
sb->s_blocksize = 4096;
sb->s_blocksize_bits = blksize_bits(4096);
sb->s_bdi = &fs_info->bdi;
fs_info->btree_inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
set_nlink(fs_info->btree_inode, 1);
/*
* we set the i_size on the btree inode to the max possible int.
* the real end of the address space is determined by all of
* the devices in the system
*/
fs_info->btree_inode->i_size = OFFSET_MAX;
fs_info->btree_inode->i_mapping->a_ops = &btree_aops;
RB_CLEAR_NODE(&BTRFS_I(fs_info->btree_inode)->rb_node);
extent_io_tree_init(&BTRFS_I(fs_info->btree_inode)->io_tree,
fs_info->btree_inode->i_mapping);
BTRFS_I(fs_info->btree_inode)->io_tree.track_uptodate = 0;
extent_map_tree_init(&BTRFS_I(fs_info->btree_inode)->extent_tree);
BTRFS_I(fs_info->btree_inode)->io_tree.ops = &btree_extent_io_ops;
BTRFS_I(fs_info->btree_inode)->root = tree_root;
memset(&BTRFS_I(fs_info->btree_inode)->location, 0,
sizeof(struct btrfs_key));
set_bit(BTRFS_INODE_DUMMY,
&BTRFS_I(fs_info->btree_inode)->runtime_flags);
btrfs_insert_inode_hash(fs_info->btree_inode);
spin_lock_init(&fs_info->block_group_cache_lock);
fs_info->block_group_cache_tree = RB_ROOT;
fs_info->first_logical_byte = (u64)-1;
extent_io_tree_init(&fs_info->freed_extents[0],
fs_info->btree_inode->i_mapping);
extent_io_tree_init(&fs_info->freed_extents[1],
fs_info->btree_inode->i_mapping);
fs_info->pinned_extents = &fs_info->freed_extents[0];
fs_info->do_barriers = 1;
mutex_init(&fs_info->ordered_operations_mutex);
mutex_init(&fs_info->ordered_extent_flush_mutex);
mutex_init(&fs_info->tree_log_mutex);
mutex_init(&fs_info->chunk_mutex);
mutex_init(&fs_info->transaction_kthread_mutex);
mutex_init(&fs_info->cleaner_mutex);
mutex_init(&fs_info->volume_mutex);
init_rwsem(&fs_info->commit_root_sem);
init_rwsem(&fs_info->cleanup_work_sem);
init_rwsem(&fs_info->subvol_sem);
sema_init(&fs_info->uuid_tree_rescan_sem, 1);
fs_info->dev_replace.lock_owner = 0;
atomic_set(&fs_info->dev_replace.nesting_level, 0);
mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
mutex_init(&fs_info->dev_replace.lock_management_lock);
mutex_init(&fs_info->dev_replace.lock);
spin_lock_init(&fs_info->qgroup_lock);
mutex_init(&fs_info->qgroup_ioctl_lock);
fs_info->qgroup_tree = RB_ROOT;
fs_info->qgroup_op_tree = RB_ROOT;
INIT_LIST_HEAD(&fs_info->dirty_qgroups);
fs_info->qgroup_seq = 1;
fs_info->quota_enabled = 0;
fs_info->pending_quota_state = 0;
fs_info->qgroup_ulist = NULL;
mutex_init(&fs_info->qgroup_rescan_lock);
btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
init_waitqueue_head(&fs_info->transaction_throttle);
init_waitqueue_head(&fs_info->transaction_wait);
init_waitqueue_head(&fs_info->transaction_blocked_wait);
init_waitqueue_head(&fs_info->async_submit_wait);
INIT_LIST_HEAD(&fs_info->pinned_chunks);
ret = btrfs_alloc_stripe_hash_table(fs_info);
if (ret) {
err = ret;
goto fail_alloc;
}
__setup_root(4096, 4096, 4096, tree_root,
fs_info, BTRFS_ROOT_TREE_OBJECTID);
invalidate_bdev(fs_devices->latest_bdev);
/*
* Read super block and check the signature bytes only
*/
bh = btrfs_read_dev_super(fs_devices->latest_bdev);
if (!bh) {
err = -EINVAL;
goto fail_alloc;
}
/*
* We want to check superblock checksum, the type is stored inside.
* Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
*/
if (btrfs_check_super_csum(bh->b_data)) {
printk(KERN_ERR "BTRFS: superblock checksum mismatch\n");
err = -EINVAL;
goto fail_alloc;
}
/*
* super_copy is zeroed at allocation time and we never touch the
* following bytes up to INFO_SIZE, the checksum is calculated from
* the whole block of INFO_SIZE
*/
memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
memcpy(fs_info->super_for_commit, fs_info->super_copy,
sizeof(*fs_info->super_for_commit));
brelse(bh);
memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
ret = btrfs_check_super_valid(fs_info, sb->s_flags & MS_RDONLY);
if (ret) {
printk(KERN_ERR "BTRFS: superblock contains fatal errors\n");
err = -EINVAL;
goto fail_alloc;
}
disk_super = fs_info->super_copy;
if (!btrfs_super_root(disk_super))
goto fail_alloc;
/* check FS state, whether FS is broken. */
if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
/*
* run through our array of backup supers and setup
* our ring pointer to the oldest one
*/
generation = btrfs_super_generation(disk_super);
find_oldest_super_backup(fs_info, generation);
/*
* In the long term, we'll store the compression type in the super
* block, and it'll be used for per file compression control.
*/
fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
ret = btrfs_parse_options(tree_root, options);
if (ret) {
err = ret;
goto fail_alloc;
}
features = btrfs_super_incompat_flags(disk_super) &
~BTRFS_FEATURE_INCOMPAT_SUPP;
if (features) {
printk(KERN_ERR "BTRFS: couldn't mount because of "
"unsupported optional features (%Lx).\n",
features);
err = -EINVAL;
goto fail_alloc;
}
/*
* Leafsize and nodesize were always equal, this is only a sanity check.
*/
if (le32_to_cpu(disk_super->__unused_leafsize) !=
btrfs_super_nodesize(disk_super)) {
printk(KERN_ERR "BTRFS: couldn't mount because metadata "
"blocksizes don't match. node %d leaf %d\n",
btrfs_super_nodesize(disk_super),
le32_to_cpu(disk_super->__unused_leafsize));
err = -EINVAL;
goto fail_alloc;
}
if (btrfs_super_nodesize(disk_super) > BTRFS_MAX_METADATA_BLOCKSIZE) {
printk(KERN_ERR "BTRFS: couldn't mount because metadata "
"blocksize (%d) was too large\n",
btrfs_super_nodesize(disk_super));
err = -EINVAL;
goto fail_alloc;
}
features = btrfs_super_incompat_flags(disk_super);
features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
if (tree_root->fs_info->compress_type == BTRFS_COMPRESS_LZO)
features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
printk(KERN_ERR "BTRFS: has skinny extents\n");
/*
* flag our filesystem as having big metadata blocks if
* they are bigger than the page size
*/
if (btrfs_super_nodesize(disk_super) > PAGE_CACHE_SIZE) {
if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
printk(KERN_INFO "BTRFS: flagging fs with big metadata feature\n");
features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
}
nodesize = btrfs_super_nodesize(disk_super);
sectorsize = btrfs_super_sectorsize(disk_super);
stripesize = btrfs_super_stripesize(disk_super);
fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
/*
* mixed block groups end up with duplicate but slightly offset
* extent buffers for the same range. It leads to corruptions
*/
if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
(sectorsize != nodesize)) {
printk(KERN_WARNING "BTRFS: unequal leaf/node/sector sizes "
"are not allowed for mixed block groups on %s\n",
sb->s_id);
goto fail_alloc;
}
/*
* Needn't use the lock because there is no other task which will
* update the flag.
*/
btrfs_set_super_incompat_flags(disk_super, features);
features = btrfs_super_compat_ro_flags(disk_super) &
~BTRFS_FEATURE_COMPAT_RO_SUPP;
if (!(sb->s_flags & MS_RDONLY) && features) {
printk(KERN_ERR "BTRFS: couldn't mount RDWR because of "
"unsupported option features (%Lx).\n",
features);
err = -EINVAL;
goto fail_alloc;
}
max_active = fs_info->thread_pool_size;
fs_info->workers =
btrfs_alloc_workqueue("worker", flags | WQ_HIGHPRI,
max_active, 16);
fs_info->delalloc_workers =
btrfs_alloc_workqueue("delalloc", flags, max_active, 2);
fs_info->flush_workers =
btrfs_alloc_workqueue("flush_delalloc", flags, max_active, 0);
fs_info->caching_workers =
btrfs_alloc_workqueue("cache", flags, max_active, 0);
/*
* a higher idle thresh on the submit workers makes it much more
* likely that bios will be send down in a sane order to the
* devices
*/
fs_info->submit_workers =
btrfs_alloc_workqueue("submit", flags,
min_t(u64, fs_devices->num_devices,
max_active), 64);
fs_info->fixup_workers =
btrfs_alloc_workqueue("fixup", flags, 1, 0);
/*
* endios are largely parallel and should have a very
* low idle thresh
*/
fs_info->endio_workers =
btrfs_alloc_workqueue("endio", flags, max_active, 4);
fs_info->endio_meta_workers =
btrfs_alloc_workqueue("endio-meta", flags, max_active, 4);
fs_info->endio_meta_write_workers =
btrfs_alloc_workqueue("endio-meta-write", flags, max_active, 2);
fs_info->endio_raid56_workers =
btrfs_alloc_workqueue("endio-raid56", flags, max_active, 4);
fs_info->endio_repair_workers =
btrfs_alloc_workqueue("endio-repair", flags, 1, 0);
fs_info->rmw_workers =
btrfs_alloc_workqueue("rmw", flags, max_active, 2);
fs_info->endio_write_workers =
btrfs_alloc_workqueue("endio-write", flags, max_active, 2);
fs_info->endio_freespace_worker =
btrfs_alloc_workqueue("freespace-write", flags, max_active, 0);
fs_info->delayed_workers =
btrfs_alloc_workqueue("delayed-meta", flags, max_active, 0);
fs_info->readahead_workers =
btrfs_alloc_workqueue("readahead", flags, max_active, 2);
fs_info->qgroup_rescan_workers =
btrfs_alloc_workqueue("qgroup-rescan", flags, 1, 0);
fs_info->extent_workers =
btrfs_alloc_workqueue("extent-refs", flags,
min_t(u64, fs_devices->num_devices,
max_active), 8);
if (!(fs_info->workers && fs_info->delalloc_workers &&
fs_info->submit_workers && fs_info->flush_workers &&
fs_info->endio_workers && fs_info->endio_meta_workers &&
fs_info->endio_meta_write_workers &&
fs_info->endio_repair_workers &&
fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
fs_info->endio_freespace_worker && fs_info->rmw_workers &&
fs_info->caching_workers && fs_info->readahead_workers &&
fs_info->fixup_workers && fs_info->delayed_workers &&
fs_info->extent_workers &&
fs_info->qgroup_rescan_workers)) {
err = -ENOMEM;
goto fail_sb_buffer;
}
fs_info->bdi.ra_pages *= btrfs_super_num_devices(disk_super);
fs_info->bdi.ra_pages = max(fs_info->bdi.ra_pages,
4 * 1024 * 1024 / PAGE_CACHE_SIZE);
tree_root->nodesize = nodesize;
tree_root->sectorsize = sectorsize;
tree_root->stripesize = stripesize;
sb->s_blocksize = sectorsize;
sb->s_blocksize_bits = blksize_bits(sectorsize);
if (btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
printk(KERN_INFO "BTRFS: valid FS not found on %s\n", sb->s_id);
goto fail_sb_buffer;
}
if (sectorsize != PAGE_SIZE) {
printk(KERN_WARNING "BTRFS: Incompatible sector size(%lu) "
"found on %s\n", (unsigned long)sectorsize, sb->s_id);
goto fail_sb_buffer;
}
mutex_lock(&fs_info->chunk_mutex);
ret = btrfs_read_sys_array(tree_root);
mutex_unlock(&fs_info->chunk_mutex);
if (ret) {
printk(KERN_WARNING "BTRFS: failed to read the system "
"array on %s\n", sb->s_id);
goto fail_sb_buffer;
}
generation = btrfs_super_chunk_root_generation(disk_super);
__setup_root(nodesize, sectorsize, stripesize, chunk_root,
fs_info, BTRFS_CHUNK_TREE_OBJECTID);
chunk_root->node = read_tree_block(chunk_root,
btrfs_super_chunk_root(disk_super),
generation);
if (!chunk_root->node ||
!test_bit(EXTENT_BUFFER_UPTODATE, &chunk_root->node->bflags)) {
printk(KERN_WARNING "BTRFS: failed to read chunk root on %s\n",
sb->s_id);
goto fail_tree_roots;
}
btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
chunk_root->commit_root = btrfs_root_node(chunk_root);
read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
ret = btrfs_read_chunk_tree(chunk_root);
if (ret) {
printk(KERN_WARNING "BTRFS: failed to read chunk tree on %s\n",
sb->s_id);
goto fail_tree_roots;
}
/*
* keep the device that is marked to be the target device for the
* dev_replace procedure
*/
btrfs_close_extra_devices(fs_info, fs_devices, 0);
if (!fs_devices->latest_bdev) {
printk(KERN_CRIT "BTRFS: failed to read devices on %s\n",
sb->s_id);
goto fail_tree_roots;
}
retry_root_backup:
generation = btrfs_super_generation(disk_super);
tree_root->node = read_tree_block(tree_root,
btrfs_super_root(disk_super),
generation);
if (!tree_root->node ||
!test_bit(EXTENT_BUFFER_UPTODATE, &tree_root->node->bflags)) {
printk(KERN_WARNING "BTRFS: failed to read tree root on %s\n",
sb->s_id);
goto recovery_tree_root;
}
btrfs_set_root_node(&tree_root->root_item, tree_root->node);
tree_root->commit_root = btrfs_root_node(tree_root);
btrfs_set_root_refs(&tree_root->root_item, 1);
location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
location.type = BTRFS_ROOT_ITEM_KEY;
location.offset = 0;
extent_root = btrfs_read_tree_root(tree_root, &location);
if (IS_ERR(extent_root)) {
ret = PTR_ERR(extent_root);
goto recovery_tree_root;
}
set_bit(BTRFS_ROOT_TRACK_DIRTY, &extent_root->state);
fs_info->extent_root = extent_root;
location.objectid = BTRFS_DEV_TREE_OBJECTID;
dev_root = btrfs_read_tree_root(tree_root, &location);
if (IS_ERR(dev_root)) {
ret = PTR_ERR(dev_root);
goto recovery_tree_root;
}
set_bit(BTRFS_ROOT_TRACK_DIRTY, &dev_root->state);
fs_info->dev_root = dev_root;
btrfs_init_devices_late(fs_info);
location.objectid = BTRFS_CSUM_TREE_OBJECTID;
csum_root = btrfs_read_tree_root(tree_root, &location);
if (IS_ERR(csum_root)) {
ret = PTR_ERR(csum_root);
goto recovery_tree_root;
}
set_bit(BTRFS_ROOT_TRACK_DIRTY, &csum_root->state);
fs_info->csum_root = csum_root;
location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
quota_root = btrfs_read_tree_root(tree_root, &location);
if (!IS_ERR(quota_root)) {
set_bit(BTRFS_ROOT_TRACK_DIRTY, "a_root->state);
fs_info->quota_enabled = 1;
fs_info->pending_quota_state = 1;
fs_info->quota_root = quota_root;
}
location.objectid = BTRFS_UUID_TREE_OBJECTID;
uuid_root = btrfs_read_tree_root(tree_root, &location);
if (IS_ERR(uuid_root)) {
ret = PTR_ERR(uuid_root);
if (ret != -ENOENT)
goto recovery_tree_root;
create_uuid_tree = true;
check_uuid_tree = false;
} else {
set_bit(BTRFS_ROOT_TRACK_DIRTY, &uuid_root->state);
fs_info->uuid_root = uuid_root;
create_uuid_tree = false;
check_uuid_tree =
generation != btrfs_super_uuid_tree_generation(disk_super);
}
fs_info->generation = generation;
fs_info->last_trans_committed = generation;
ret = btrfs_recover_balance(fs_info);
if (ret) {
printk(KERN_WARNING "BTRFS: failed to recover balance\n");
goto fail_block_groups;
}
ret = btrfs_init_dev_stats(fs_info);
if (ret) {
printk(KERN_ERR "BTRFS: failed to init dev_stats: %d\n",
ret);
goto fail_block_groups;
}
ret = btrfs_init_dev_replace(fs_info);
if (ret) {
pr_err("BTRFS: failed to init dev_replace: %d\n", ret);
goto fail_block_groups;
}
btrfs_close_extra_devices(fs_info, fs_devices, 1);
ret = btrfs_sysfs_add_one(fs_info);
if (ret) {
pr_err("BTRFS: failed to init sysfs interface: %d\n", ret);
goto fail_block_groups;
}
ret = btrfs_init_space_info(fs_info);
if (ret) {
printk(KERN_ERR "BTRFS: Failed to initial space info: %d\n", ret);
goto fail_sysfs;
}
ret = btrfs_read_block_groups(extent_root);
if (ret) {
printk(KERN_ERR "BTRFS: Failed to read block groups: %d\n", ret);
goto fail_sysfs;
}
fs_info->num_tolerated_disk_barrier_failures =
btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
if (fs_info->fs_devices->missing_devices >
fs_info->num_tolerated_disk_barrier_failures &&
!(sb->s_flags & MS_RDONLY)) {
printk(KERN_WARNING "BTRFS: "
"too many missing devices, writeable mount is not allowed\n");
goto fail_sysfs;
}
fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
"btrfs-cleaner");
if (IS_ERR(fs_info->cleaner_kthread))
goto fail_sysfs;
fs_info->transaction_kthread = kthread_run(transaction_kthread,
tree_root,
"btrfs-transaction");
if (IS_ERR(fs_info->transaction_kthread))
goto fail_cleaner;
if (!btrfs_test_opt(tree_root, SSD) &&
!btrfs_test_opt(tree_root, NOSSD) &&
!fs_info->fs_devices->rotating) {
printk(KERN_INFO "BTRFS: detected SSD devices, enabling SSD "
"mode\n");
btrfs_set_opt(fs_info->mount_opt, SSD);
}
/*
* Mount does not set all options immediatelly, we can do it now and do
* not have to wait for transaction commit
*/
btrfs_apply_pending_changes(fs_info);
#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
if (btrfs_test_opt(tree_root, CHECK_INTEGRITY)) {
ret = btrfsic_mount(tree_root, fs_devices,
btrfs_test_opt(tree_root,
CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
1 : 0,
fs_info->check_integrity_print_mask);
if (ret)
printk(KERN_WARNING "BTRFS: failed to initialize"
" integrity check module %s\n", sb->s_id);
}
#endif
ret = btrfs_read_qgroup_config(fs_info);
if (ret)
goto fail_trans_kthread;
/* do not make disk changes in broken FS */
if (btrfs_super_log_root(disk_super) != 0) {
u64 bytenr = btrfs_super_log_root(disk_super);
if (fs_devices->rw_devices == 0) {
printk(KERN_WARNING "BTRFS: log replay required "
"on RO media\n");
err = -EIO;
goto fail_qgroup;
}
log_tree_root = btrfs_alloc_root(fs_info);
if (!log_tree_root) {
err = -ENOMEM;
goto fail_qgroup;
}
__setup_root(nodesize, sectorsize, stripesize,
log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
log_tree_root->node = read_tree_block(tree_root, bytenr,
generation + 1);
if (!log_tree_root->node ||
!extent_buffer_uptodate(log_tree_root->node)) {
printk(KERN_ERR "BTRFS: failed to read log tree\n");
free_extent_buffer(log_tree_root->node);
kfree(log_tree_root);
goto fail_qgroup;
}
/* returns with log_tree_root freed on success */
ret = btrfs_recover_log_trees(log_tree_root);
if (ret) {
btrfs_error(tree_root->fs_info, ret,
"Failed to recover log tree");
free_extent_buffer(log_tree_root->node);
kfree(log_tree_root);
goto fail_qgroup;
}
if (sb->s_flags & MS_RDONLY) {
ret = btrfs_commit_super(tree_root);
if (ret)
goto fail_qgroup;
}
}
ret = btrfs_find_orphan_roots(tree_root);
if (ret)
goto fail_qgroup;
if (!(sb->s_flags & MS_RDONLY)) {
ret = btrfs_cleanup_fs_roots(fs_info);
if (ret)
goto fail_qgroup;
mutex_lock(&fs_info->cleaner_mutex);
ret = btrfs_recover_relocation(tree_root);
mutex_unlock(&fs_info->cleaner_mutex);
if (ret < 0) {
printk(KERN_WARNING
"BTRFS: failed to recover relocation\n");
err = -EINVAL;
goto fail_qgroup;
}
}
location.objectid = BTRFS_FS_TREE_OBJECTID;
location.type = BTRFS_ROOT_ITEM_KEY;
location.offset = 0;
fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
if (IS_ERR(fs_info->fs_root)) {
err = PTR_ERR(fs_info->fs_root);
goto fail_qgroup;
}
if (sb->s_flags & MS_RDONLY)
return 0;
down_read(&fs_info->cleanup_work_sem);
if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
(ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
up_read(&fs_info->cleanup_work_sem);
close_ctree(tree_root);
return ret;
}
up_read(&fs_info->cleanup_work_sem);
ret = btrfs_resume_balance_async(fs_info);
if (ret) {
printk(KERN_WARNING "BTRFS: failed to resume balance\n");
close_ctree(tree_root);
return ret;
}
ret = btrfs_resume_dev_replace_async(fs_info);
if (ret) {
pr_warn("BTRFS: failed to resume dev_replace\n");
close_ctree(tree_root);
return ret;
}
btrfs_qgroup_rescan_resume(fs_info);
if (create_uuid_tree) {
pr_info("BTRFS: creating UUID tree\n");
ret = btrfs_create_uuid_tree(fs_info);
if (ret) {
pr_warn("BTRFS: failed to create the UUID tree %d\n",
ret);
close_ctree(tree_root);
return ret;
}
} else if (check_uuid_tree ||
btrfs_test_opt(tree_root, RESCAN_UUID_TREE)) {
pr_info("BTRFS: checking UUID tree\n");
ret = btrfs_check_uuid_tree(fs_info);
if (ret) {
pr_warn("BTRFS: failed to check the UUID tree %d\n",
ret);
close_ctree(tree_root);
return ret;
}
} else {
fs_info->update_uuid_tree_gen = 1;
}
fs_info->open = 1;
return 0;
fail_qgroup:
btrfs_free_qgroup_config(fs_info);
fail_trans_kthread:
kthread_stop(fs_info->transaction_kthread);
btrfs_cleanup_transaction(fs_info->tree_root);
btrfs_free_fs_roots(fs_info);
fail_cleaner:
kthread_stop(fs_info->cleaner_kthread);
/*
* make sure we're done with the btree inode before we stop our
* kthreads
*/
filemap_write_and_wait(fs_info->btree_inode->i_mapping);
fail_sysfs:
btrfs_sysfs_remove_one(fs_info);
fail_block_groups:
btrfs_put_block_group_cache(fs_info);
btrfs_free_block_groups(fs_info);
fail_tree_roots:
free_root_pointers(fs_info, 1);
invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
fail_sb_buffer:
btrfs_stop_all_workers(fs_info);
fail_alloc:
fail_iput:
btrfs_mapping_tree_free(&fs_info->mapping_tree);
iput(fs_info->btree_inode);
fail_bio_counter:
percpu_counter_destroy(&fs_info->bio_counter);
fail_delalloc_bytes:
percpu_counter_destroy(&fs_info->delalloc_bytes);
fail_dirty_metadata_bytes:
percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
fail_bdi:
bdi_destroy(&fs_info->bdi);
fail_srcu:
cleanup_srcu_struct(&fs_info->subvol_srcu);
fail:
btrfs_free_stripe_hash_table(fs_info);
btrfs_close_devices(fs_info->fs_devices);
return err;
recovery_tree_root:
if (!btrfs_test_opt(tree_root, RECOVERY))
goto fail_tree_roots;
free_root_pointers(fs_info, 0);
/* don't use the log in recovery mode, it won't be valid */
btrfs_set_super_log_root(disk_super, 0);
/* we can't trust the free space cache either */
btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
ret = next_root_backup(fs_info, fs_info->super_copy,
&num_backups_tried, &backup_index);
if (ret == -1)
goto fail_block_groups;
goto retry_root_backup;
}
static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
{
if (uptodate) {
set_buffer_uptodate(bh);
} else {
struct btrfs_device *device = (struct btrfs_device *)
bh->b_private;
printk_ratelimited_in_rcu(KERN_WARNING "BTRFS: lost page write due to "
"I/O error on %s\n",
rcu_str_deref(device->name));
/* note, we dont' set_buffer_write_io_error because we have
* our own ways of dealing with the IO errors
*/
clear_buffer_uptodate(bh);
btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
}
unlock_buffer(bh);
put_bh(bh);
}
struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
{
struct buffer_head *bh;
struct buffer_head *latest = NULL;
struct btrfs_super_block *super;
int i;
u64 transid = 0;
u64 bytenr;
/* we would like to check all the supers, but that would make
* a btrfs mount succeed after a mkfs from a different FS.
* So, we need to add a special mount option to scan for
* later supers, using BTRFS_SUPER_MIRROR_MAX instead
*/
for (i = 0; i < 1; i++) {
bytenr = btrfs_sb_offset(i);
if (bytenr + BTRFS_SUPER_INFO_SIZE >=
i_size_read(bdev->bd_inode))
break;
bh = __bread(bdev, bytenr / 4096,
BTRFS_SUPER_INFO_SIZE);
if (!bh)
continue;
super = (struct btrfs_super_block *)bh->b_data;
if (btrfs_super_bytenr(super) != bytenr ||
btrfs_super_magic(super) != BTRFS_MAGIC) {
brelse(bh);
continue;
}
if (!latest || btrfs_super_generation(super) > transid) {
brelse(latest);
latest = bh;
transid = btrfs_super_generation(super);
} else {
brelse(bh);
}
}
return latest;
}
/*
* this should be called twice, once with wait == 0 and
* once with wait == 1. When wait == 0 is done, all the buffer heads
* we write are pinned.
*
* They are released when wait == 1 is done.
* max_mirrors must be the same for both runs, and it indicates how
* many supers on this one device should be written.
*
* max_mirrors == 0 means to write them all.
*/
static int write_dev_supers(struct btrfs_device *device,
struct btrfs_super_block *sb,
int do_barriers, int wait, int max_mirrors)
{
struct buffer_head *bh;
int i;
int ret;
int errors = 0;
u32 crc;
u64 bytenr;
if (max_mirrors == 0)
max_mirrors = BTRFS_SUPER_MIRROR_MAX;
for (i = 0; i < max_mirrors; i++) {
bytenr = btrfs_sb_offset(i);
if (bytenr + BTRFS_SUPER_INFO_SIZE >=
device->commit_total_bytes)
break;
if (wait) {
bh = __find_get_block(device->bdev, bytenr / 4096,
BTRFS_SUPER_INFO_SIZE);
if (!bh) {
errors++;
continue;
}
wait_on_buffer(bh);
if (!buffer_uptodate(bh))
errors++;
/* drop our reference */
brelse(bh);
/* drop the reference from the wait == 0 run */
brelse(bh);
continue;
} else {
btrfs_set_super_bytenr(sb, bytenr);
crc = ~(u32)0;
crc = btrfs_csum_data((char *)sb +
BTRFS_CSUM_SIZE, crc,
BTRFS_SUPER_INFO_SIZE -
BTRFS_CSUM_SIZE);
btrfs_csum_final(crc, sb->csum);
/*
* one reference for us, and we leave it for the
* caller
*/
bh = __getblk(device->bdev, bytenr / 4096,
BTRFS_SUPER_INFO_SIZE);
if (!bh) {
printk(KERN_ERR "BTRFS: couldn't get super "
"buffer head for bytenr %Lu\n", bytenr);
errors++;
continue;
}
memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
/* one reference for submit_bh */
get_bh(bh);
set_buffer_uptodate(bh);
lock_buffer(bh);
bh->b_end_io = btrfs_end_buffer_write_sync;
bh->b_private = device;
}
/*
* we fua the first super. The others we allow
* to go down lazy.
*/
if (i == 0)
ret = btrfsic_submit_bh(WRITE_FUA, bh);
else
ret = btrfsic_submit_bh(WRITE_SYNC, bh);
if (ret)
errors++;
}
return errors < i ? 0 : -1;
}
/*
* endio for the write_dev_flush, this will wake anyone waiting
* for the barrier when it is done
*/
static void btrfs_end_empty_barrier(struct bio *bio, int err)
{
if (err) {
if (err == -EOPNOTSUPP)
set_bit(BIO_EOPNOTSUPP, &bio->bi_flags);
clear_bit(BIO_UPTODATE, &bio->bi_flags);
}
if (bio->bi_private)
complete(bio->bi_private);
bio_put(bio);
}
/*
* trigger flushes for one the devices. If you pass wait == 0, the flushes are
* sent down. With wait == 1, it waits for the previous flush.
*
* any device where the flush fails with eopnotsupp are flagged as not-barrier
* capable
*/
static int write_dev_flush(struct btrfs_device *device, int wait)
{
struct bio *bio;
int ret = 0;
if (device->nobarriers)
return 0;
if (wait) {
bio = device->flush_bio;
if (!bio)
return 0;
wait_for_completion(&device->flush_wait);
if (bio_flagged(bio, BIO_EOPNOTSUPP)) {
printk_in_rcu("BTRFS: disabling barriers on dev %s\n",
rcu_str_deref(device->name));
device->nobarriers = 1;
} else if (!bio_flagged(bio, BIO_UPTODATE)) {
ret = -EIO;
btrfs_dev_stat_inc_and_print(device,
BTRFS_DEV_STAT_FLUSH_ERRS);
}
/* drop the reference from the wait == 0 run */
bio_put(bio);
device->flush_bio = NULL;
return ret;
}
/*
* one reference for us, and we leave it for the
* caller
*/
device->flush_bio = NULL;
bio = btrfs_io_bio_alloc(GFP_NOFS, 0);
if (!bio)
return -ENOMEM;
bio->bi_end_io = btrfs_end_empty_barrier;
bio->bi_bdev = device->bdev;
init_completion(&device->flush_wait);
bio->bi_private = &device->flush_wait;
device->flush_bio = bio;
bio_get(bio);
btrfsic_submit_bio(WRITE_FLUSH, bio);
return 0;
}
/*
* send an empty flush down to each device in parallel,
* then wait for them
*/
static int barrier_all_devices(struct btrfs_fs_info *info)
{
struct list_head *head;
struct btrfs_device *dev;
int errors_send = 0;
int errors_wait = 0;
int ret;
/* send down all the barriers */
head = &info->fs_devices->devices;
list_for_each_entry_rcu(dev, head, dev_list) {
if (dev->missing)
continue;
if (!dev->bdev) {
errors_send++;
continue;
}
if (!dev->in_fs_metadata || !dev->writeable)
continue;
ret = write_dev_flush(dev, 0);
if (ret)
errors_send++;
}
/* wait for all the barriers */
list_for_each_entry_rcu(dev, head, dev_list) {
if (dev->missing)
continue;
if (!dev->bdev) {
errors_wait++;
continue;
}
if (!dev->in_fs_metadata || !dev->writeable)
continue;
ret = write_dev_flush(dev, 1);
if (ret)
errors_wait++;
}
if (errors_send > info->num_tolerated_disk_barrier_failures ||
errors_wait > info->num_tolerated_disk_barrier_failures)
return -EIO;
return 0;
}
int btrfs_calc_num_tolerated_disk_barrier_failures(
struct btrfs_fs_info *fs_info)
{
struct btrfs_ioctl_space_info space;
struct btrfs_space_info *sinfo;
u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
BTRFS_BLOCK_GROUP_SYSTEM,
BTRFS_BLOCK_GROUP_METADATA,
BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
int num_types = 4;
int i;
int c;
int num_tolerated_disk_barrier_failures =
(int)fs_info->fs_devices->num_devices;
for (i = 0; i < num_types; i++) {
struct btrfs_space_info *tmp;
sinfo = NULL;
rcu_read_lock();
list_for_each_entry_rcu(tmp, &fs_info->space_info, list) {
if (tmp->flags == types[i]) {
sinfo = tmp;
break;
}
}
rcu_read_unlock();
if (!sinfo)
continue;
down_read(&sinfo->groups_sem);
for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
if (!list_empty(&sinfo->block_groups[c])) {
u64 flags;
btrfs_get_block_group_info(
&sinfo->block_groups[c], &space);
if (space.total_bytes == 0 ||
space.used_bytes == 0)
continue;
flags = space.flags;
/*
* return
* 0: if dup, single or RAID0 is configured for
* any of metadata, system or data, else
* 1: if RAID5 is configured, or if RAID1 or
* RAID10 is configured and only two mirrors
* are used, else
* 2: if RAID6 is configured, else
* num_mirrors - 1: if RAID1 or RAID10 is
* configured and more than
* 2 mirrors are used.
*/
if (num_tolerated_disk_barrier_failures > 0 &&
((flags & (BTRFS_BLOCK_GROUP_DUP |
BTRFS_BLOCK_GROUP_RAID0)) ||
((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK)
== 0)))
num_tolerated_disk_barrier_failures = 0;
else if (num_tolerated_disk_barrier_failures > 1) {
if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
BTRFS_BLOCK_GROUP_RAID5 |
BTRFS_BLOCK_GROUP_RAID10)) {
num_tolerated_disk_barrier_failures = 1;
} else if (flags &
BTRFS_BLOCK_GROUP_RAID6) {
num_tolerated_disk_barrier_failures = 2;
}
}
}
}
up_read(&sinfo->groups_sem);
}
return num_tolerated_disk_barrier_failures;
}
static int write_all_supers(struct btrfs_root *root, int max_mirrors)
{
struct list_head *head;
struct btrfs_device *dev;
struct btrfs_super_block *sb;
struct btrfs_dev_item *dev_item;
int ret;
int do_barriers;
int max_errors;
int total_errors = 0;
u64 flags;
do_barriers = !btrfs_test_opt(root, NOBARRIER);
backup_super_roots(root->fs_info);
sb = root->fs_info->super_for_commit;
dev_item = &sb->dev_item;
mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
head = &root->fs_info->fs_devices->devices;
max_errors = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
if (do_barriers) {
ret = barrier_all_devices(root->fs_info);
if (ret) {
mutex_unlock(
&root->fs_info->fs_devices->device_list_mutex);
btrfs_error(root->fs_info, ret,
"errors while submitting device barriers.");
return ret;
}
}
list_for_each_entry_rcu(dev, head, dev_list) {
if (!dev->bdev) {
total_errors++;
continue;
}
if (!dev->in_fs_metadata || !dev->writeable)
continue;
btrfs_set_stack_device_generation(dev_item, 0);
btrfs_set_stack_device_type(dev_item, dev->type);
btrfs_set_stack_device_id(dev_item, dev->devid);
btrfs_set_stack_device_total_bytes(dev_item,
dev->commit_total_bytes);
btrfs_set_stack_device_bytes_used(dev_item,
dev->commit_bytes_used);
btrfs_set_stack_device_io_align(dev_item, dev->io_align);
btrfs_set_stack_device_io_width(dev_item, dev->io_width);
btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
flags = btrfs_super_flags(sb);
btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
ret = write_dev_supers(dev, sb, do_barriers, 0, max_mirrors);
if (ret)
total_errors++;
}
if (total_errors > max_errors) {
btrfs_err(root->fs_info, "%d errors while writing supers",
total_errors);
mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
/* FUA is masked off if unsupported and can't be the reason */
btrfs_error(root->fs_info, -EIO,
"%d errors while writing supers", total_errors);
return -EIO;
}
total_errors = 0;
list_for_each_entry_rcu(dev, head, dev_list) {
if (!dev->bdev)
continue;
if (!dev->in_fs_metadata || !dev->writeable)
continue;
ret = write_dev_supers(dev, sb, do_barriers, 1, max_mirrors);
if (ret)
total_errors++;
}
mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
if (total_errors > max_errors) {
btrfs_error(root->fs_info, -EIO,
"%d errors while writing supers", total_errors);
return -EIO;
}
return 0;
}
int write_ctree_super(struct btrfs_trans_handle *trans,
struct btrfs_root *root, int max_mirrors)
{
return write_all_supers(root, max_mirrors);
}
/* Drop a fs root from the radix tree and free it. */
void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
struct btrfs_root *root)
{
spin_lock(&fs_info->fs_roots_radix_lock);
radix_tree_delete(&fs_info->fs_roots_radix,
(unsigned long)root->root_key.objectid);
spin_unlock(&fs_info->fs_roots_radix_lock);
if (btrfs_root_refs(&root->root_item) == 0)
synchronize_srcu(&fs_info->subvol_srcu);
if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
btrfs_free_log(NULL, root);
if (root->free_ino_pinned)
__btrfs_remove_free_space_cache(root->free_ino_pinned);
if (root->free_ino_ctl)
__btrfs_remove_free_space_cache(root->free_ino_ctl);
free_fs_root(root);
}
static void free_fs_root(struct btrfs_root *root)
{
iput(root->ino_cache_inode);
WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
btrfs_free_block_rsv(root, root->orphan_block_rsv);
root->orphan_block_rsv = NULL;
if (root->anon_dev)
free_anon_bdev(root->anon_dev);
if (root->subv_writers)
btrfs_free_subvolume_writers(root->subv_writers);
free_extent_buffer(root->node);
free_extent_buffer(root->commit_root);
kfree(root->free_ino_ctl);
kfree(root->free_ino_pinned);
kfree(root->name);
btrfs_put_fs_root(root);
}
void btrfs_free_fs_root(struct btrfs_root *root)
{
free_fs_root(root);
}
int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
{
u64 root_objectid = 0;
struct btrfs_root *gang[8];
int i = 0;
int err = 0;
unsigned int ret = 0;
int index;
while (1) {
index = srcu_read_lock(&fs_info->subvol_srcu);
ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
(void **)gang, root_objectid,
ARRAY_SIZE(gang));
if (!ret) {
srcu_read_unlock(&fs_info->subvol_srcu, index);
break;
}
root_objectid = gang[ret - 1]->root_key.objectid + 1;
for (i = 0; i < ret; i++) {
/* Avoid to grab roots in dead_roots */
if (btrfs_root_refs(&gang[i]->root_item) == 0) {
gang[i] = NULL;
continue;
}
/* grab all the search result for later use */
gang[i] = btrfs_grab_fs_root(gang[i]);
}
srcu_read_unlock(&fs_info->subvol_srcu, index);
for (i = 0; i < ret; i++) {
if (!gang[i])
continue;
root_objectid = gang[i]->root_key.objectid;
err = btrfs_orphan_cleanup(gang[i]);
if (err)
break;
btrfs_put_fs_root(gang[i]);
}
root_objectid++;
}
/* release the uncleaned roots due to error */
for (; i < ret; i++) {
if (gang[i])
btrfs_put_fs_root(gang[i]);
}
return err;
}
int btrfs_commit_super(struct btrfs_root *root)
{
struct btrfs_trans_handle *trans;
mutex_lock(&root->fs_info->cleaner_mutex);
btrfs_run_delayed_iputs(root);
mutex_unlock(&root->fs_info->cleaner_mutex);
wake_up_process(root->fs_info->cleaner_kthread);
/* wait until ongoing cleanup work done */
down_write(&root->fs_info->cleanup_work_sem);
up_write(&root->fs_info->cleanup_work_sem);
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return PTR_ERR(trans);
return btrfs_commit_transaction(trans, root);
}
void close_ctree(struct btrfs_root *root)
{
struct btrfs_fs_info *fs_info = root->fs_info;
int ret;
fs_info->closing = 1;
smp_mb();
/* wait for the uuid_scan task to finish */
down(&fs_info->uuid_tree_rescan_sem);
/* avoid complains from lockdep et al., set sem back to initial state */
up(&fs_info->uuid_tree_rescan_sem);
/* pause restriper - we want to resume on mount */
btrfs_pause_balance(fs_info);
btrfs_dev_replace_suspend_for_unmount(fs_info);
btrfs_scrub_cancel(fs_info);
/* wait for any defraggers to finish */
wait_event(fs_info->transaction_wait,
(atomic_read(&fs_info->defrag_running) == 0));
/* clear out the rbtree of defraggable inodes */
btrfs_cleanup_defrag_inodes(fs_info);
cancel_work_sync(&fs_info->async_reclaim_work);
if (!(fs_info->sb->s_flags & MS_RDONLY)) {
ret = btrfs_commit_super(root);
if (ret)
btrfs_err(root->fs_info, "commit super ret %d", ret);
}
if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
btrfs_error_commit_super(root);
kthread_stop(fs_info->transaction_kthread);
kthread_stop(fs_info->cleaner_kthread);
fs_info->closing = 2;
smp_mb();
btrfs_free_qgroup_config(root->fs_info);
if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
btrfs_info(root->fs_info, "at unmount delalloc count %lld",
percpu_counter_sum(&fs_info->delalloc_bytes));
}
btrfs_sysfs_remove_one(fs_info);
btrfs_free_fs_roots(fs_info);
btrfs_put_block_group_cache(fs_info);
btrfs_free_block_groups(fs_info);
/*
* we must make sure there is not any read request to
* submit after we stopping all workers.
*/
invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
btrfs_stop_all_workers(fs_info);
fs_info->open = 0;
free_root_pointers(fs_info, 1);
iput(fs_info->btree_inode);
#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
if (btrfs_test_opt(root, CHECK_INTEGRITY))
btrfsic_unmount(root, fs_info->fs_devices);
#endif
btrfs_close_devices(fs_info->fs_devices);
btrfs_mapping_tree_free(&fs_info->mapping_tree);
percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
percpu_counter_destroy(&fs_info->delalloc_bytes);
percpu_counter_destroy(&fs_info->bio_counter);
bdi_destroy(&fs_info->bdi);
cleanup_srcu_struct(&fs_info->subvol_srcu);
btrfs_free_stripe_hash_table(fs_info);
btrfs_free_block_rsv(root, root->orphan_block_rsv);
root->orphan_block_rsv = NULL;
lock_chunks(root);
while (!list_empty(&fs_info->pinned_chunks)) {
struct extent_map *em;
em = list_first_entry(&fs_info->pinned_chunks,
struct extent_map, list);
list_del_init(&em->list);
free_extent_map(em);
}
unlock_chunks(root);
}
int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
int atomic)
{
int ret;
struct inode *btree_inode = buf->pages[0]->mapping->host;
ret = extent_buffer_uptodate(buf);
if (!ret)
return ret;
ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
parent_transid, atomic);
if (ret == -EAGAIN)
return ret;
return !ret;
}
int btrfs_set_buffer_uptodate(struct extent_buffer *buf)
{
return set_extent_buffer_uptodate(buf);
}
void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
{
struct btrfs_root *root;
u64 transid = btrfs_header_generation(buf);
int was_dirty;
#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
/*
* This is a fast path so only do this check if we have sanity tests
* enabled. Normal people shouldn't be marking dummy buffers as dirty
* outside of the sanity tests.
*/
if (unlikely(test_bit(EXTENT_BUFFER_DUMMY, &buf->bflags)))
return;
#endif
root = BTRFS_I(buf->pages[0]->mapping->host)->root;
btrfs_assert_tree_locked(buf);
if (transid != root->fs_info->generation)
WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, "
"found %llu running %llu\n",
buf->start, transid, root->fs_info->generation);
was_dirty = set_extent_buffer_dirty(buf);
if (!was_dirty)
__percpu_counter_add(&root->fs_info->dirty_metadata_bytes,
buf->len,
root->fs_info->dirty_metadata_batch);
#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
if (btrfs_header_level(buf) == 0 && check_leaf(root, buf)) {
btrfs_print_leaf(root, buf);
ASSERT(0);
}
#endif
}
static void __btrfs_btree_balance_dirty(struct btrfs_root *root,
int flush_delayed)
{
/*
* looks as though older kernels can get into trouble with
* this code, they end up stuck in balance_dirty_pages forever
*/
int ret;
if (current->flags & PF_MEMALLOC)
return;
if (flush_delayed)
btrfs_balance_delayed_items(root);
ret = percpu_counter_compare(&root->fs_info->dirty_metadata_bytes,
BTRFS_DIRTY_METADATA_THRESH);
if (ret > 0) {
balance_dirty_pages_ratelimited(
root->fs_info->btree_inode->i_mapping);
}
return;
}
void btrfs_btree_balance_dirty(struct btrfs_root *root)
{
__btrfs_btree_balance_dirty(root, 1);
}
void btrfs_btree_balance_dirty_nodelay(struct btrfs_root *root)
{
__btrfs_btree_balance_dirty(root, 0);
}
int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid)
{
struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
return btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
}
static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
int read_only)
{
struct btrfs_super_block *sb = fs_info->super_copy;
int ret = 0;
if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
printk(KERN_ERR "BTRFS: tree_root level too big: %d >= %d\n",
btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
ret = -EINVAL;
}
if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
printk(KERN_ERR "BTRFS: chunk_root level too big: %d >= %d\n",
btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
ret = -EINVAL;
}
if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
printk(KERN_ERR "BTRFS: log_root level too big: %d >= %d\n",
btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
ret = -EINVAL;
}
/*
* The common minimum, we don't know if we can trust the nodesize/sectorsize
* items yet, they'll be verified later. Issue just a warning.
*/
if (!IS_ALIGNED(btrfs_super_root(sb), 4096))
printk(KERN_WARNING "BTRFS: tree_root block unaligned: %llu\n",
btrfs_super_root(sb));
if (!IS_ALIGNED(btrfs_super_chunk_root(sb), 4096))
printk(KERN_WARNING "BTRFS: chunk_root block unaligned: %llu\n",
btrfs_super_chunk_root(sb));
if (!IS_ALIGNED(btrfs_super_log_root(sb), 4096))
printk(KERN_WARNING "BTRFS: log_root block unaligned: %llu\n",
btrfs_super_log_root(sb));
if (memcmp(fs_info->fsid, sb->dev_item.fsid, BTRFS_UUID_SIZE) != 0) {
printk(KERN_ERR "BTRFS: dev_item UUID does not match fsid: %pU != %pU\n",
fs_info->fsid, sb->dev_item.fsid);
ret = -EINVAL;
}
/*
* Hint to catch really bogus numbers, bitflips or so, more exact checks are
* done later
*/
if (btrfs_super_num_devices(sb) > (1UL << 31))
printk(KERN_WARNING "BTRFS: suspicious number of devices: %llu\n",
btrfs_super_num_devices(sb));
if (btrfs_super_bytenr(sb) != BTRFS_SUPER_INFO_OFFSET) {
printk(KERN_ERR "BTRFS: super offset mismatch %llu != %u\n",
btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
ret = -EINVAL;
}
/*
* The generation is a global counter, we'll trust it more than the others
* but it's still possible that it's the one that's wrong.
*/
if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
printk(KERN_WARNING
"BTRFS: suspicious: generation < chunk_root_generation: %llu < %llu\n",
btrfs_super_generation(sb), btrfs_super_chunk_root_generation(sb));
if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
&& btrfs_super_cache_generation(sb) != (u64)-1)
printk(KERN_WARNING
"BTRFS: suspicious: generation < cache_generation: %llu < %llu\n",
btrfs_super_generation(sb), btrfs_super_cache_generation(sb));
return ret;
}
static void btrfs_error_commit_super(struct btrfs_root *root)
{
mutex_lock(&root->fs_info->cleaner_mutex);
btrfs_run_delayed_iputs(root);
mutex_unlock(&root->fs_info->cleaner_mutex);
down_write(&root->fs_info->cleanup_work_sem);
up_write(&root->fs_info->cleanup_work_sem);
/* cleanup FS via transaction */
btrfs_cleanup_transaction(root);
}
static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
{
struct btrfs_ordered_extent *ordered;
spin_lock(&root->ordered_extent_lock);
/*
* This will just short circuit the ordered completion stuff which will
* make sure the ordered extent gets properly cleaned up.
*/
list_for_each_entry(ordered, &root->ordered_extents,
root_extent_list)
set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
spin_unlock(&root->ordered_extent_lock);
}
static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
{
struct btrfs_root *root;
struct list_head splice;
INIT_LIST_HEAD(&splice);
spin_lock(&fs_info->ordered_root_lock);
list_splice_init(&fs_info->ordered_roots, &splice);
while (!list_empty(&splice)) {
root = list_first_entry(&splice, struct btrfs_root,
ordered_root);
list_move_tail(&root->ordered_root,
&fs_info->ordered_roots);
spin_unlock(&fs_info->ordered_root_lock);
btrfs_destroy_ordered_extents(root);
cond_resched();
spin_lock(&fs_info->ordered_root_lock);
}
spin_unlock(&fs_info->ordered_root_lock);
}
static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
struct btrfs_root *root)
{
struct rb_node *node;
struct btrfs_delayed_ref_root *delayed_refs;
struct btrfs_delayed_ref_node *ref;
int ret = 0;
delayed_refs = &trans->delayed_refs;
spin_lock(&delayed_refs->lock);
if (atomic_read(&delayed_refs->num_entries) == 0) {
spin_unlock(&delayed_refs->lock);
btrfs_info(root->fs_info, "delayed_refs has NO entry");
return ret;
}
while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
struct btrfs_delayed_ref_head *head;
bool pin_bytes = false;
head = rb_entry(node, struct btrfs_delayed_ref_head,
href_node);
if (!mutex_trylock(&head->mutex)) {
atomic_inc(&head->node.refs);
spin_unlock(&delayed_refs->lock);
mutex_lock(&head->mutex);
mutex_unlock(&head->mutex);
btrfs_put_delayed_ref(&head->node);
spin_lock(&delayed_refs->lock);
continue;
}
spin_lock(&head->lock);
while ((node = rb_first(&head->ref_root)) != NULL) {
ref = rb_entry(node, struct btrfs_delayed_ref_node,
rb_node);
ref->in_tree = 0;
rb_erase(&ref->rb_node, &head->ref_root);
atomic_dec(&delayed_refs->num_entries);
btrfs_put_delayed_ref(ref);
}
if (head->must_insert_reserved)
pin_bytes = true;
btrfs_free_delayed_extent_op(head->extent_op);
delayed_refs->num_heads--;
if (head->processing == 0)
delayed_refs->num_heads_ready--;
atomic_dec(&delayed_refs->num_entries);
head->node.in_tree = 0;
rb_erase(&head->href_node, &delayed_refs->href_root);
spin_unlock(&head->lock);
spin_unlock(&delayed_refs->lock);
mutex_unlock(&head->mutex);
if (pin_bytes)
btrfs_pin_extent(root, head->node.bytenr,
head->node.num_bytes, 1);
btrfs_put_delayed_ref(&head->node);
cond_resched();
spin_lock(&delayed_refs->lock);
}
spin_unlock(&delayed_refs->lock);
return ret;
}
static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
{
struct btrfs_inode *btrfs_inode;
struct list_head splice;
INIT_LIST_HEAD(&splice);
spin_lock(&root->delalloc_lock);
list_splice_init(&root->delalloc_inodes, &splice);
while (!list_empty(&splice)) {
btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
delalloc_inodes);
list_del_init(&btrfs_inode->delalloc_inodes);
clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
&btrfs_inode->runtime_flags);
spin_unlock(&root->delalloc_lock);
btrfs_invalidate_inodes(btrfs_inode->root);
spin_lock(&root->delalloc_lock);
}
spin_unlock(&root->delalloc_lock);
}
static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
{
struct btrfs_root *root;
struct list_head splice;
INIT_LIST_HEAD(&splice);
spin_lock(&fs_info->delalloc_root_lock);
list_splice_init(&fs_info->delalloc_roots, &splice);
while (!list_empty(&splice)) {
root = list_first_entry(&splice, struct btrfs_root,
delalloc_root);
list_del_init(&root->delalloc_root);
root = btrfs_grab_fs_root(root);
BUG_ON(!root);
spin_unlock(&fs_info->delalloc_root_lock);
btrfs_destroy_delalloc_inodes(root);
btrfs_put_fs_root(root);
spin_lock(&fs_info->delalloc_root_lock);
}
spin_unlock(&fs_info->delalloc_root_lock);
}
static int btrfs_destroy_marked_extents(struct btrfs_root *root,
struct extent_io_tree *dirty_pages,
int mark)
{
int ret;
struct extent_buffer *eb;
u64 start = 0;
u64 end;
while (1) {
ret = find_first_extent_bit(dirty_pages, start, &start, &end,
mark, NULL);
if (ret)
break;
clear_extent_bits(dirty_pages, start, end, mark, GFP_NOFS);
while (start <= end) {
eb = btrfs_find_tree_block(root, start);
start += root->nodesize;
if (!eb)
continue;
wait_on_extent_buffer_writeback(eb);
if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
&eb->bflags))
clear_extent_buffer_dirty(eb);
free_extent_buffer_stale(eb);
}
}
return ret;
}
static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
struct extent_io_tree *pinned_extents)
{
struct extent_io_tree *unpin;
u64 start;
u64 end;
int ret;
bool loop = true;
unpin = pinned_extents;
again:
while (1) {
ret = find_first_extent_bit(unpin, 0, &start, &end,
EXTENT_DIRTY, NULL);
if (ret)
break;
clear_extent_dirty(unpin, start, end, GFP_NOFS);
btrfs_error_unpin_extent_range(root, start, end);
cond_resched();
}
if (loop) {
if (unpin == &root->fs_info->freed_extents[0])
unpin = &root->fs_info->freed_extents[1];
else
unpin = &root->fs_info->freed_extents[0];
loop = false;
goto again;
}
return 0;
}
static void btrfs_free_pending_ordered(struct btrfs_transaction *cur_trans,
struct btrfs_fs_info *fs_info)
{
struct btrfs_ordered_extent *ordered;
spin_lock(&fs_info->trans_lock);
while (!list_empty(&cur_trans->pending_ordered)) {
ordered = list_first_entry(&cur_trans->pending_ordered,
struct btrfs_ordered_extent,
trans_list);
list_del_init(&ordered->trans_list);
spin_unlock(&fs_info->trans_lock);
btrfs_put_ordered_extent(ordered);
spin_lock(&fs_info->trans_lock);
}
spin_unlock(&fs_info->trans_lock);
}
void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
struct btrfs_root *root)
{
btrfs_destroy_delayed_refs(cur_trans, root);
cur_trans->state = TRANS_STATE_COMMIT_START;
wake_up(&root->fs_info->transaction_blocked_wait);
cur_trans->state = TRANS_STATE_UNBLOCKED;
wake_up(&root->fs_info->transaction_wait);
btrfs_free_pending_ordered(cur_trans, root->fs_info);
btrfs_destroy_delayed_inodes(root);
btrfs_assert_delayed_root_empty(root);
btrfs_destroy_marked_extents(root, &cur_trans->dirty_pages,
EXTENT_DIRTY);
btrfs_destroy_pinned_extent(root,
root->fs_info->pinned_extents);
cur_trans->state =TRANS_STATE_COMPLETED;
wake_up(&cur_trans->commit_wait);
/*
memset(cur_trans, 0, sizeof(*cur_trans));
kmem_cache_free(btrfs_transaction_cachep, cur_trans);
*/
}
static int btrfs_cleanup_transaction(struct btrfs_root *root)
{
struct btrfs_transaction *t;
mutex_lock(&root->fs_info->transaction_kthread_mutex);
spin_lock(&root->fs_info->trans_lock);
while (!list_empty(&root->fs_info->trans_list)) {
t = list_first_entry(&root->fs_info->trans_list,
struct btrfs_transaction, list);
if (t->state >= TRANS_STATE_COMMIT_START) {
atomic_inc(&t->use_count);
spin_unlock(&root->fs_info->trans_lock);
btrfs_wait_for_commit(root, t->transid);
btrfs_put_transaction(t);
spin_lock(&root->fs_info->trans_lock);
continue;
}
if (t == root->fs_info->running_transaction) {
t->state = TRANS_STATE_COMMIT_DOING;
spin_unlock(&root->fs_info->trans_lock);
/*
* We wait for 0 num_writers since we don't hold a trans
* handle open currently for this transaction.
*/
wait_event(t->writer_wait,
atomic_read(&t->num_writers) == 0);
} else {
spin_unlock(&root->fs_info->trans_lock);
}
btrfs_cleanup_one_transaction(t, root);
spin_lock(&root->fs_info->trans_lock);
if (t == root->fs_info->running_transaction)
root->fs_info->running_transaction = NULL;
list_del_init(&t->list);
spin_unlock(&root->fs_info->trans_lock);
btrfs_put_transaction(t);
trace_btrfs_transaction_commit(root);
spin_lock(&root->fs_info->trans_lock);
}
spin_unlock(&root->fs_info->trans_lock);
btrfs_destroy_all_ordered_extents(root->fs_info);
btrfs_destroy_delayed_inodes(root);
btrfs_assert_delayed_root_empty(root);
btrfs_destroy_pinned_extent(root, root->fs_info->pinned_extents);
btrfs_destroy_all_delalloc_inodes(root->fs_info);
mutex_unlock(&root->fs_info->transaction_kthread_mutex);
return 0;
}
static struct extent_io_ops btree_extent_io_ops = {
.readpage_end_io_hook = btree_readpage_end_io_hook,
.readpage_io_failed_hook = btree_io_failed_hook,
.submit_bio_hook = btree_submit_bio_hook,
/* note we're sharing with inode.c for the merge bio hook */
.merge_bio_hook = btrfs_merge_bio_hook,
};
| gpl-2.0 |
aurex-linux/thunar | thunar/thunar-device.c | 5 | 23591 | /*-
* Copyright (c) 2012 Nick Schermer <nick@xfce.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <thunar/thunar-device.h>
#include <thunar/thunar-device-monitor.h>
#include <thunar/thunar-private.h>
#include <thunar/thunar-file.h>
#include <thunar/thunar-notify.h>
typedef gboolean (*AsyncCallbackFinish) (GObject *object,
GAsyncResult *result,
GError **error);
enum
{
PROP_0,
PROP_DEVICE,
PROP_HIDDEN,
PROP_KIND
};
static void thunar_device_finalize (GObject *object);
static void thunar_device_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec);
static void thunar_device_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec);
struct _ThunarDeviceClass
{
GObjectClass __parent__;
};
struct _ThunarDevice
{
GObject __parent__;
/* a GVolume/GMount/GDrive */
gpointer device;
ThunarDeviceKind kind;
/* if the device is the list of hidden names */
guint hidden : 1;
/* added time for sorting */
gint64 stamp;
};
typedef struct
{
/* the device the operation is working on */
ThunarDevice *device;
/* finish function for the async callback */
AsyncCallbackFinish callback_finish;
/* callback for the user */
ThunarDeviceCallback callback;
gpointer user_data;
}
ThunarDeviceOperation;
G_DEFINE_TYPE (ThunarDevice, thunar_device, G_TYPE_OBJECT)
static void
thunar_device_class_init (ThunarDeviceClass *klass)
{
GObjectClass *gobject_class;
gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = thunar_device_finalize;
gobject_class->get_property = thunar_device_get_property;
gobject_class->set_property = thunar_device_set_property;
g_object_class_install_property (gobject_class,
PROP_DEVICE,
g_param_spec_object ("device",
"device",
"device",
G_TYPE_OBJECT,
EXO_PARAM_READWRITE
| G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (gobject_class,
PROP_HIDDEN,
g_param_spec_boolean ("hidden",
"hidden",
"hidden",
FALSE,
EXO_PARAM_READWRITE));
g_object_class_install_property (gobject_class,
PROP_KIND,
g_param_spec_uint ("kind",
"kind",
"kind",
THUNAR_DEVICE_KIND_VOLUME,
THUNAR_DEVICE_KIND_MOUNT_REMOTE,
THUNAR_DEVICE_KIND_VOLUME,
EXO_PARAM_READWRITE
| G_PARAM_CONSTRUCT_ONLY));
}
static void
thunar_device_init (ThunarDevice *device)
{
device->kind = THUNAR_DEVICE_KIND_VOLUME;
device->stamp = g_get_real_time ();
}
static void
thunar_device_finalize (GObject *object)
{
ThunarDevice *device = THUNAR_DEVICE (object);
if (device->device != NULL)
g_object_unref (G_OBJECT (device->device));
(*G_OBJECT_CLASS (thunar_device_parent_class)->finalize) (object);
}
static void
thunar_device_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
ThunarDevice *device = THUNAR_DEVICE (object);
switch (prop_id)
{
case PROP_DEVICE:
g_value_set_object (value, device->device);
break;
case PROP_HIDDEN:
g_value_set_boolean (value, device->hidden);
break;
case PROP_KIND:
g_value_set_uint (value, device->kind);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
thunar_device_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
ThunarDevice *device = THUNAR_DEVICE (object);
switch (prop_id)
{
case PROP_DEVICE:
device->device = g_value_dup_object (value);
_thunar_assert (G_IS_VOLUME (device->device) || G_IS_MOUNT (device->device));
break;
case PROP_HIDDEN:
device->hidden = g_value_get_boolean (value);
break;
case PROP_KIND:
device->kind = g_value_get_uint (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static ThunarDeviceOperation *
thunar_device_operation_new (ThunarDevice *device,
ThunarDeviceCallback callback,
gpointer user_data,
gpointer callback_finish)
{
ThunarDeviceOperation *op;
op = g_slice_new0 (ThunarDeviceOperation);
op->device = g_object_ref (device);
op->callback = callback;
op->callback_finish = callback_finish;
op->user_data = user_data;
return op;
}
static void
thunar_device_operation_finish (GObject *object,
GAsyncResult *result,
gpointer user_data)
{
ThunarDeviceOperation *op = user_data;
GError *error = NULL;
_thunar_return_if_fail (G_IS_OBJECT (object));
_thunar_return_if_fail (G_IS_ASYNC_RESULT (result));
/* remove notification */
thunar_notify_finish (op->device);
/* finish the operation */
if (!(op->callback_finish) (object, result, &error))
{
/* unset the error if a helper program has already interacted with the user */
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED))
g_clear_error (&error);
if (op->callback_finish == (AsyncCallbackFinish) g_volume_mount_finish)
{
/* special handling for mount operation */
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_ALREADY_MOUNTED)
|| g_error_matches (error, G_IO_ERROR, G_IO_ERROR_PENDING))
g_clear_error (&error);
}
}
/* user callback */
(op->callback) (op->device, error, op->user_data);
/* cleanup */
g_clear_error (&error);
g_object_unref (G_OBJECT (op->device));
g_slice_free (ThunarDeviceOperation, op);
}
static void
thunar_device_emit_pre_unmount (ThunarDevice *device,
gboolean all_volumes)
{
ThunarDeviceMonitor *monitor;
GFile *root_file;
root_file = thunar_device_get_root (device);
if (root_file != NULL)
{
/* make sure the pre-unmount event is emitted, this is important
* for the interface */
monitor = thunar_device_monitor_get ();
g_signal_emit_by_name (monitor, "device-pre-unmount", device, root_file);
g_object_unref (monitor);
g_object_unref (root_file);
}
}
gchar *
thunar_device_get_name (const ThunarDevice *device)
{
GFile *mount_point;
gchar *display_name = NULL;
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), NULL);
if (G_IS_VOLUME (device->device))
{
return g_volume_get_name (device->device);
}
else if (G_IS_MOUNT (device->device))
{
/* probably we can make a nicer name for this mount */
mount_point = thunar_device_get_root (device);
if (mount_point != NULL)
{
display_name = thunar_g_file_get_display_name_remote (mount_point);
g_object_unref (mount_point);
}
if (display_name == NULL)
display_name = g_mount_get_name (device->device);
return display_name;
}
else
_thunar_assert_not_reached ();
return NULL;
}
GIcon *
thunar_device_get_icon (const ThunarDevice *device)
{
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), NULL);
if (G_IS_VOLUME (device->device))
return g_volume_get_icon (device->device);
else if (G_IS_MOUNT (device->device))
return g_mount_get_icon (device->device);
else
_thunar_assert_not_reached ();
return NULL;
}
ThunarDeviceKind
thunar_device_get_kind (const ThunarDevice *device)
{
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), THUNAR_DEVICE_KIND_VOLUME);
return device->kind;
}
gchar *
thunar_device_get_identifier (const ThunarDevice *device)
{
gchar *ident = NULL;
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), NULL);
if (G_IS_VOLUME (device->device))
{
ident = g_volume_get_uuid (device->device);
if (ident == NULL)
ident = g_volume_get_identifier (device->device, G_VOLUME_IDENTIFIER_KIND_UUID);
if (ident == NULL)
ident = g_volume_get_name (device->device);
}
else if (G_IS_MOUNT (device->device))
{
ident = g_mount_get_uuid (device->device);
if (ident == NULL)
ident = g_mount_get_name (device->device);
}
else
_thunar_assert_not_reached ();
return ident;
}
gboolean
thunar_device_get_hidden (const ThunarDevice *device)
{
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), FALSE);
return device->hidden;
}
/**
* thunar_device_can_eject:
*
* If the user should see the option to eject this device.
**/
gboolean
thunar_device_can_eject (const ThunarDevice *device)
{
gboolean can_eject = FALSE;
GDrive *drive;
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), FALSE);
if (G_IS_VOLUME (device->device))
{
drive = g_volume_get_drive (device->device);
if (drive != NULL)
{
can_eject = g_drive_can_eject (drive) || g_drive_can_stop (drive);
g_object_unref (drive);
}
else
{
/* check if the volume can eject */
can_eject = g_volume_can_eject (device->device);
}
}
else if (G_IS_MOUNT (device->device))
{
/* eject or unmount because thats for the user the same
* because we prefer volumes over mounts as devices */
can_eject = g_mount_can_eject (device->device) || g_mount_can_unmount (device->device);
}
else
_thunar_assert_not_reached ();
return can_eject;
}
/**
* thunar_device_can_mount:
*
* If the user should see the option to mount this device.
**/
gboolean
thunar_device_can_mount (const ThunarDevice *device)
{
gboolean can_mount = FALSE;
GMount *volume_mount;
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), FALSE);
if (G_IS_VOLUME (device->device))
{
/* only volumes without a mountpoint and mount capability */
volume_mount = g_volume_get_mount (device->device);
if (volume_mount == NULL)
can_mount = g_volume_can_mount (device->device);
else
g_object_unref (volume_mount);
}
else if (G_IS_MOUNT (device->device))
{
/* a mount is already mounted... */
can_mount = FALSE;
}
else
_thunar_assert_not_reached ();
return can_mount;
}
/**
* thunar_device_can_unmount:
*
* If the user should see the option to unmount this device.
**/
gboolean
thunar_device_can_unmount (const ThunarDevice *device)
{
gboolean can_unmount = FALSE;
GMount *volume_mount;
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), FALSE);
if (G_IS_VOLUME (device->device))
{
/* only volumes with a mountpoint and unmount capability */
volume_mount = g_volume_get_mount (device->device);
if (volume_mount != NULL)
{
can_unmount = g_mount_can_unmount (volume_mount);
g_object_unref (volume_mount);
}
}
else if (G_IS_MOUNT (device->device))
{
/* check if the mount can unmount */
can_unmount = g_mount_can_unmount (device->device);
}
else
_thunar_assert_not_reached ();
return can_unmount;
}
gboolean
thunar_device_is_mounted (const ThunarDevice *device)
{
gboolean is_mounted = FALSE;
GMount *volume_mount;
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), FALSE);
if (G_IS_VOLUME (device->device))
{
/* a volume with a mount point is mounted */
volume_mount = g_volume_get_mount (device->device);
if (volume_mount != NULL)
{
is_mounted = TRUE;
g_object_unref (volume_mount);
}
}
else if (G_IS_MOUNT (device->device))
{
/* mounter are always mounted... */
is_mounted = TRUE;
}
else
_thunar_assert_not_reached ();
return is_mounted;
}
GFile *
thunar_device_get_root (const ThunarDevice *device)
{
GFile *root = NULL;
GMount *volume_mount;
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device), NULL);
if (G_IS_VOLUME (device->device))
{
volume_mount = g_volume_get_mount (device->device);
if (volume_mount != NULL)
{
root = g_mount_get_root (volume_mount);
g_object_unref (volume_mount);
}
if (root == NULL)
root = g_volume_get_activation_root (device->device);
}
else if (G_IS_MOUNT (device->device))
{
root = g_mount_get_root (device->device);
}
else
_thunar_assert_not_reached ();
return root;
}
gint
thunar_device_sort (const ThunarDevice *device1,
const ThunarDevice *device2)
{
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device1), 0);
_thunar_return_val_if_fail (THUNAR_IS_DEVICE (device2), 0);
/* sort volumes above mounts */
if (G_OBJECT_TYPE (device1->device) != G_OBJECT_TYPE (device2->device))
return G_IS_VOLUME (device1->device) ? 1 : -1;
/* sort by detect stamp */
return device1->stamp > device2->stamp ? 1 : -1;
}
void
thunar_device_mount (ThunarDevice *device,
GMountOperation *mount_operation,
GCancellable *cancellable,
ThunarDeviceCallback callback,
gpointer user_data)
{
ThunarDeviceOperation *op;
_thunar_return_if_fail (THUNAR_IS_DEVICE (device));
_thunar_return_if_fail (G_IS_MOUNT_OPERATION (mount_operation));
_thunar_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
_thunar_return_if_fail (callback != NULL);
if (G_IS_VOLUME (device->device))
{
op = thunar_device_operation_new (device, callback, user_data,
g_volume_mount_finish);
g_volume_mount (G_VOLUME (device->device),
G_MOUNT_MOUNT_NONE,
mount_operation,
cancellable,
thunar_device_operation_finish,
op);
}
}
/**
* thunar_device_unmount:
*
* Unmount a #ThunarDevice. Don't try to eject.
**/
void
thunar_device_unmount (ThunarDevice *device,
GMountOperation *mount_operation,
GCancellable *cancellable,
ThunarDeviceCallback callback,
gpointer user_data)
{
ThunarDeviceOperation *op;
GMount *mount;
_thunar_return_if_fail (THUNAR_IS_DEVICE (device));
_thunar_return_if_fail (G_IS_MOUNT_OPERATION (mount_operation));
_thunar_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
_thunar_return_if_fail (callback != NULL);
/* get the mount from the volume or use existing mount */
if (G_IS_VOLUME (device->device))
mount = g_volume_get_mount (device->device);
else if (G_IS_MOUNT (device->device))
mount = g_object_ref (device->device);
else
mount = NULL;
if (G_LIKELY (mount != NULL))
{
/* only handle mounts that can be unmounted here */
if (g_mount_can_unmount (mount))
{
/* inform user */
thunar_notify_unmount (device);
/* try unmounting the mount */
thunar_device_emit_pre_unmount (device, FALSE);
op = thunar_device_operation_new (device, callback, user_data,
g_mount_unmount_with_operation_finish);
g_mount_unmount_with_operation (mount,
G_MOUNT_UNMOUNT_NONE,
mount_operation,
cancellable,
thunar_device_operation_finish,
op);
}
g_object_unref (G_OBJECT (mount));
}
}
/**
* thunar_device_unmount:
*
* Try to eject a #ThunarDevice, fall-back to unmounting
**/
void
thunar_device_eject (ThunarDevice *device,
GMountOperation *mount_operation,
GCancellable *cancellable,
ThunarDeviceCallback callback,
gpointer user_data)
{
ThunarDeviceOperation *op;
GMount *mount = NULL;
GVolume *volume;
GDrive *drive;
_thunar_return_if_fail (THUNAR_IS_DEVICE (device));
_thunar_return_if_fail (G_IS_MOUNT_OPERATION (mount_operation));
_thunar_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
_thunar_return_if_fail (callback != NULL);
if (G_IS_VOLUME (device->device))
{
volume = device->device;
drive = g_volume_get_drive (volume);
if (drive != NULL)
{
if (g_drive_can_stop (drive))
{
/* inform user */
thunar_notify_eject (device);
/* try to stop the drive */
thunar_device_emit_pre_unmount (device, TRUE);
op = thunar_device_operation_new (device, callback, user_data,
g_drive_stop_finish);
g_drive_stop (drive,
G_MOUNT_UNMOUNT_NONE,
mount_operation,
cancellable,
thunar_device_operation_finish,
op);
g_object_unref (drive);
/* done */
return;
}
else if (g_drive_can_eject (drive))
{
/* inform user */
thunar_notify_eject (device);
/* try to stop the drive */
thunar_device_emit_pre_unmount (device, TRUE);
op = thunar_device_operation_new (device, callback, user_data,
g_drive_eject_with_operation_finish);
g_drive_eject_with_operation (drive,
G_MOUNT_UNMOUNT_NONE,
mount_operation,
cancellable,
thunar_device_operation_finish,
op);
g_object_unref (drive);
/* done */
return;
}
g_object_unref (drive);
}
if (g_volume_can_eject (volume))
{
/* inform user */
thunar_notify_eject (device);
/* try ejecting the volume */
thunar_device_emit_pre_unmount (device, TRUE);
op = thunar_device_operation_new (device, callback, user_data,
g_volume_eject_with_operation_finish);
g_volume_eject_with_operation (volume,
G_MOUNT_UNMOUNT_NONE,
mount_operation,
cancellable,
thunar_device_operation_finish,
op);
/* done */
return;
}
else
{
/* get the mount and fall-through */
mount = g_volume_get_mount (volume);
}
}
else if (G_IS_MOUNT (device->device))
{
/* set the mount and fall-through */
mount = g_object_ref (device->device);
}
/* handle mounts */
if (mount != NULL)
{
/* distinguish between ejectable and unmountable mounts */
if (g_mount_can_eject (mount))
{
/* inform user */
thunar_notify_eject (device);
/* try ejecting the mount */
thunar_device_emit_pre_unmount (device, FALSE);
op = thunar_device_operation_new (device, callback, user_data,
g_mount_eject_with_operation_finish);
g_mount_eject_with_operation (mount,
G_MOUNT_UNMOUNT_NONE,
mount_operation,
cancellable,
thunar_device_operation_finish,
op);
}
else if (g_mount_can_unmount (mount))
{
/* inform user */
thunar_notify_unmount (device);
/* try unmounting the mount */
thunar_device_emit_pre_unmount (device, FALSE);
op = thunar_device_operation_new (device, callback, user_data,
g_mount_unmount_with_operation_finish);
g_mount_unmount_with_operation (mount,
G_MOUNT_UNMOUNT_NONE,
mount_operation,
cancellable,
thunar_device_operation_finish,
op);
}
g_object_unref (G_OBJECT (mount));
}
}
| gpl-2.0 |
LastAvenger/hurd | trans/hello.c | 5 | 7472 | /* hello.c - A trivial single-file translator
Copyright (C) 1998,1999,2001,02,2006 Free Software Foundation, Inc.
Gordon Matzigkeit <gord@fig.org>, 1999
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.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You 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 _GNU_SOURCE 1
#include <hurd/trivfs.h>
#include <stdio.h>
#include <stdlib.h>
#include <argp.h>
#include <argz.h>
#include <error.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <version.h>
#include "libtrivfs/trivfs_io_S.h"
const char *argp_program_version = STANDARD_HURD_VERSION (hello);
/* The message we return when we are read. */
static const char hello[] = "Hello, world!\n";
static char *contents = (char *) hello;
static size_t contents_len = sizeof hello - 1;
/* Trivfs hooks. */
int trivfs_fstype = FSTYPE_MISC;
int trivfs_fsid = 0;
int trivfs_allow_open = O_READ;
int trivfs_support_read = 1;
int trivfs_support_write = 0;
int trivfs_support_exec = 0;
/* NOTE: This example is not robust: it is possible to trigger some
assertion failures because we don't implement the following:
$ cd /src/hurd/libtrivfs
$ grep -l 'assert.*!trivfs_support_read' *.c |
xargs grep '^trivfs_S_' | sed 's/^[^:]*:\([^ ]*\).*$/\1/'
trivfs_S_io_get_openmodes
trivfs_S_io_clear_some_openmodes
trivfs_S_io_set_some_openmodes
trivfs_S_io_set_all_openmodes
trivfs_S_io_readable
trivfs_S_io_select
$
For that reason, you should run this as an active translator
`settrans -ac testnode /path/to/thello' so that you can see the
error messages when they appear. */
/* A hook for us to keep track of the file descriptor state. */
struct open
{
off_t offs;
};
void
trivfs_modify_stat (struct trivfs_protid *cred, struct stat *st)
{
/* Mark the node as a read-only plain file. */
st->st_mode &= ~(S_IFMT | ALLPERMS);
st->st_mode |= (S_IFREG | S_IRUSR | S_IRGRP | S_IROTH);
st->st_size = contents_len;
}
error_t
trivfs_goaway (struct trivfs_control *cntl, int flags)
{
exit (0);
}
static error_t
open_hook (struct trivfs_peropen *peropen)
{
struct open *op = malloc (sizeof (struct open));
if (op == NULL)
return ENOMEM;
/* Initialize the offset. */
op->offs = 0;
peropen->hook = op;
return 0;
}
static void
close_hook (struct trivfs_peropen *peropen)
{
free (peropen->hook);
}
/* Read data from an IO object. If offset is -1, read from the object
maintained file pointer. If the object is not seekable, offset is
ignored. The amount desired to be read is in AMOUNT. */
error_t
trivfs_S_io_read (struct trivfs_protid *cred,
mach_port_t reply, mach_msg_type_name_t reply_type,
char **data, mach_msg_type_number_t *data_len,
loff_t offs, mach_msg_type_number_t amount)
{
struct open *op;
/* Deny access if they have bad credentials. */
if (! cred)
return EOPNOTSUPP;
else if (! (cred->po->openmodes & O_READ))
return EBADF;
/* Get the offset. */
op = cred->po->hook;
if (offs == -1)
offs = op->offs;
/* Prune the amount they want to read. */
if (offs > contents_len)
offs = contents_len;
if (offs + amount > contents_len)
amount = contents_len - offs;
if (amount > 0)
{
/* Possibly allocate a new buffer. */
if (*data_len < amount)
{
*data = mmap (0, amount, PROT_READ|PROT_WRITE, MAP_ANON, 0, 0);
if (*data == MAP_FAILED)
return ENOMEM;
}
/* Copy the constant data into the buffer. */
memcpy ((char *) *data, contents + offs, amount);
/* Update the saved offset. */
op->offs += amount;
}
*data_len = amount;
return 0;
}
/* Change current read/write offset */
error_t
trivfs_S_io_seek (struct trivfs_protid *cred,
mach_port_t reply, mach_msg_type_name_t reply_type,
off_t offs, int whence, off_t *new_offs)
{
struct open *op;
error_t err = 0;
if (! cred)
return EOPNOTSUPP;
op = cred->po->hook;
switch (whence)
{
case SEEK_CUR:
offs += op->offs;
goto check;
case SEEK_END:
offs += contents_len;
case SEEK_SET:
check:
if (offs >= 0)
{
*new_offs = op->offs = offs;
break;
}
default:
err = EINVAL;
}
return err;
}
/* If this variable is set, it is called every time a new peropen
structure is created and initialized. */
error_t (*trivfs_peropen_create_hook)(struct trivfs_peropen *) = open_hook;
/* If this variable is set, it is called every time a peropen structure
is about to be destroyed. */
void (*trivfs_peropen_destroy_hook) (struct trivfs_peropen *) = close_hook;
/* Options processing. We accept the same options on the command line
and from fsys_set_options. */
static const struct argp_option options[] =
{
{"contents", 'c', "STRING", 0, "Specify the contents of the virtual file"},
{0}
};
static error_t
parse_opt (int opt, char *arg, struct argp_state *state)
{
switch (opt)
{
default:
return ARGP_ERR_UNKNOWN;
case ARGP_KEY_INIT:
case ARGP_KEY_SUCCESS:
case ARGP_KEY_ERROR:
break;
case 'c':
{
char *new = strdup (arg);
if (new == NULL)
return ENOMEM;
if (contents != hello)
free (contents);
contents = new;
contents_len = strlen (new);
break;
}
}
return 0;
}
/* This will be called from libtrivfs to help construct the answer
to an fsys_get_options RPC. */
error_t
trivfs_append_args (struct trivfs_control *fsys,
char **argz, size_t *argz_len)
{
error_t err;
char *opt;
size_t opt_len;
FILE *s;
char *c;
s = open_memstream (&opt, &opt_len);
fprintf (s, "--contents='");
for (c = contents; *c; c++)
switch (*c)
{
case 0x27: /* Single quote. */
fprintf (s, "'\"'\"'");
break;
default:
fprintf (s, "%c", *c);
}
fprintf (s, "'");
fclose (s);
err = argz_add (argz, argz_len, opt);
free (opt);
return err;
}
static struct argp hello_argp =
{ options, parse_opt, 0, "A translator providing a warm greeting." };
/* Setting this variable makes libtrivfs use our argp to
parse options passed in an fsys_set_options RPC. */
struct argp *trivfs_runtime_argp = &hello_argp;
int
main (int argc, char **argv)
{
error_t err;
mach_port_t bootstrap;
struct trivfs_control *fsys;
/* We use the same argp for options available at startup
as for options we'll accept in an fsys_set_options RPC. */
argp_parse (&hello_argp, argc, argv, 0, 0, 0);
task_get_bootstrap_port (mach_task_self (), &bootstrap);
if (bootstrap == MACH_PORT_NULL)
error (1, 0, "Must be started as a translator");
/* Reply to our parent */
err = trivfs_startup (bootstrap, 0, 0, 0, 0, 0, &fsys);
mach_port_deallocate (mach_task_self (), bootstrap);
if (err)
error (3, err, "trivfs_startup");
/* Launch. */
ports_manage_port_operations_one_thread (fsys->pi.bucket, trivfs_demuxer, 0);
return 0;
}
| gpl-2.0 |
atniptw/PonyBuntu | drivers/usb/musb/ux500_dma.c | 261 | 12780 | /*
* drivers/usb/musb/ux500_dma.c
*
* U8500 and U5500 DMA support code
*
* Copyright (C) 2009 STMicroelectronics
* Copyright (C) 2011 ST-Ericsson SA
* Authors:
* Mian Yousaf Kaukab <mian.yousaf.kaukab@stericsson.com>
* Praveena Nadahally <praveen.nadahally@stericsson.com>
* Rajaram Regupathy <ragupathy.rajaram@stericsson.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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/pfn.h>
#include <mach/usb.h>
#include "musb_core.h"
struct ux500_dma_channel {
struct dma_channel channel;
struct ux500_dma_controller *controller;
struct musb_hw_ep *hw_ep;
struct work_struct channel_work;
struct dma_chan *dma_chan;
unsigned int cur_len;
dma_cookie_t cookie;
u8 ch_num;
u8 is_tx;
u8 is_allocated;
};
struct ux500_dma_controller {
struct dma_controller controller;
struct ux500_dma_channel rx_channel[UX500_MUSB_DMA_NUM_RX_CHANNELS];
struct ux500_dma_channel tx_channel[UX500_MUSB_DMA_NUM_TX_CHANNELS];
u32 num_rx_channels;
u32 num_tx_channels;
void *private_data;
dma_addr_t phy_base;
};
/* Work function invoked from DMA callback to handle tx transfers. */
static void ux500_tx_work(struct work_struct *data)
{
struct ux500_dma_channel *ux500_channel = container_of(data,
struct ux500_dma_channel, channel_work);
struct musb_hw_ep *hw_ep = ux500_channel->hw_ep;
struct musb *musb = hw_ep->musb;
unsigned long flags;
dev_dbg(musb->controller, "DMA tx transfer done on hw_ep=%d\n",
hw_ep->epnum);
spin_lock_irqsave(&musb->lock, flags);
ux500_channel->channel.actual_len = ux500_channel->cur_len;
ux500_channel->channel.status = MUSB_DMA_STATUS_FREE;
musb_dma_completion(musb, hw_ep->epnum,
ux500_channel->is_tx);
spin_unlock_irqrestore(&musb->lock, flags);
}
/* Work function invoked from DMA callback to handle rx transfers. */
static void ux500_rx_work(struct work_struct *data)
{
struct ux500_dma_channel *ux500_channel = container_of(data,
struct ux500_dma_channel, channel_work);
struct musb_hw_ep *hw_ep = ux500_channel->hw_ep;
struct musb *musb = hw_ep->musb;
unsigned long flags;
dev_dbg(musb->controller, "DMA rx transfer done on hw_ep=%d\n",
hw_ep->epnum);
spin_lock_irqsave(&musb->lock, flags);
ux500_channel->channel.actual_len = ux500_channel->cur_len;
ux500_channel->channel.status = MUSB_DMA_STATUS_FREE;
musb_dma_completion(musb, hw_ep->epnum,
ux500_channel->is_tx);
spin_unlock_irqrestore(&musb->lock, flags);
}
void ux500_dma_callback(void *private_data)
{
struct dma_channel *channel = (struct dma_channel *)private_data;
struct ux500_dma_channel *ux500_channel = channel->private_data;
schedule_work(&ux500_channel->channel_work);
}
static bool ux500_configure_channel(struct dma_channel *channel,
u16 packet_sz, u8 mode,
dma_addr_t dma_addr, u32 len)
{
struct ux500_dma_channel *ux500_channel = channel->private_data;
struct musb_hw_ep *hw_ep = ux500_channel->hw_ep;
struct dma_chan *dma_chan = ux500_channel->dma_chan;
struct dma_async_tx_descriptor *dma_desc;
enum dma_data_direction direction;
struct scatterlist sg;
struct dma_slave_config slave_conf;
enum dma_slave_buswidth addr_width;
dma_addr_t usb_fifo_addr = (MUSB_FIFO_OFFSET(hw_ep->epnum) +
ux500_channel->controller->phy_base);
struct musb *musb = ux500_channel->controller->private_data;
dev_dbg(musb->controller,
"packet_sz=%d, mode=%d, dma_addr=0x%x, len=%d is_tx=%d\n",
packet_sz, mode, dma_addr, len, ux500_channel->is_tx);
ux500_channel->cur_len = len;
sg_init_table(&sg, 1);
sg_set_page(&sg, pfn_to_page(PFN_DOWN(dma_addr)), len,
offset_in_page(dma_addr));
sg_dma_address(&sg) = dma_addr;
sg_dma_len(&sg) = len;
direction = ux500_channel->is_tx ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
addr_width = (len & 0x3) ? DMA_SLAVE_BUSWIDTH_1_BYTE :
DMA_SLAVE_BUSWIDTH_4_BYTES;
slave_conf.direction = direction;
slave_conf.src_addr = usb_fifo_addr;
slave_conf.src_addr_width = addr_width;
slave_conf.src_maxburst = 16;
slave_conf.dst_addr = usb_fifo_addr;
slave_conf.dst_addr_width = addr_width;
slave_conf.dst_maxburst = 16;
dma_chan->device->device_control(dma_chan, DMA_SLAVE_CONFIG,
(unsigned long) &slave_conf);
dma_desc = dma_chan->device->
device_prep_slave_sg(dma_chan, &sg, 1, direction,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!dma_desc)
return false;
dma_desc->callback = ux500_dma_callback;
dma_desc->callback_param = channel;
ux500_channel->cookie = dma_desc->tx_submit(dma_desc);
dma_async_issue_pending(dma_chan);
return true;
}
static struct dma_channel *ux500_dma_channel_allocate(struct dma_controller *c,
struct musb_hw_ep *hw_ep, u8 is_tx)
{
struct ux500_dma_controller *controller = container_of(c,
struct ux500_dma_controller, controller);
struct ux500_dma_channel *ux500_channel = NULL;
struct musb *musb = controller->private_data;
u8 ch_num = hw_ep->epnum - 1;
u32 max_ch;
/* Max 8 DMA channels (0 - 7). Each DMA channel can only be allocated
* to specified hw_ep. For example DMA channel 0 can only be allocated
* to hw_ep 1 and 9.
*/
if (ch_num > 7)
ch_num -= 8;
max_ch = is_tx ? controller->num_tx_channels :
controller->num_rx_channels;
if (ch_num >= max_ch)
return NULL;
ux500_channel = is_tx ? &(controller->tx_channel[ch_num]) :
&(controller->rx_channel[ch_num]) ;
/* Check if channel is already used. */
if (ux500_channel->is_allocated)
return NULL;
ux500_channel->hw_ep = hw_ep;
ux500_channel->is_allocated = 1;
dev_dbg(musb->controller, "hw_ep=%d, is_tx=0x%x, channel=%d\n",
hw_ep->epnum, is_tx, ch_num);
return &(ux500_channel->channel);
}
static void ux500_dma_channel_release(struct dma_channel *channel)
{
struct ux500_dma_channel *ux500_channel = channel->private_data;
struct musb *musb = ux500_channel->controller->private_data;
dev_dbg(musb->controller, "channel=%d\n", ux500_channel->ch_num);
if (ux500_channel->is_allocated) {
ux500_channel->is_allocated = 0;
channel->status = MUSB_DMA_STATUS_FREE;
channel->actual_len = 0;
}
}
static int ux500_dma_is_compatible(struct dma_channel *channel,
u16 maxpacket, void *buf, u32 length)
{
if ((maxpacket & 0x3) ||
((int)buf & 0x3) ||
(length < 512) ||
(length & 0x3))
return false;
else
return true;
}
static int ux500_dma_channel_program(struct dma_channel *channel,
u16 packet_sz, u8 mode,
dma_addr_t dma_addr, u32 len)
{
int ret;
BUG_ON(channel->status == MUSB_DMA_STATUS_UNKNOWN ||
channel->status == MUSB_DMA_STATUS_BUSY);
if (!ux500_dma_is_compatible(channel, packet_sz, (void *)dma_addr, len))
return false;
channel->status = MUSB_DMA_STATUS_BUSY;
channel->actual_len = 0;
ret = ux500_configure_channel(channel, packet_sz, mode, dma_addr, len);
if (!ret)
channel->status = MUSB_DMA_STATUS_FREE;
return ret;
}
static int ux500_dma_channel_abort(struct dma_channel *channel)
{
struct ux500_dma_channel *ux500_channel = channel->private_data;
struct ux500_dma_controller *controller = ux500_channel->controller;
struct musb *musb = controller->private_data;
void __iomem *epio = musb->endpoints[ux500_channel->hw_ep->epnum].regs;
u16 csr;
dev_dbg(musb->controller, "channel=%d, is_tx=%d\n",
ux500_channel->ch_num, ux500_channel->is_tx);
if (channel->status == MUSB_DMA_STATUS_BUSY) {
if (ux500_channel->is_tx) {
csr = musb_readw(epio, MUSB_TXCSR);
csr &= ~(MUSB_TXCSR_AUTOSET |
MUSB_TXCSR_DMAENAB |
MUSB_TXCSR_DMAMODE);
musb_writew(epio, MUSB_TXCSR, csr);
} else {
csr = musb_readw(epio, MUSB_RXCSR);
csr &= ~(MUSB_RXCSR_AUTOCLEAR |
MUSB_RXCSR_DMAENAB |
MUSB_RXCSR_DMAMODE);
musb_writew(epio, MUSB_RXCSR, csr);
}
ux500_channel->dma_chan->device->
device_control(ux500_channel->dma_chan,
DMA_TERMINATE_ALL, 0);
channel->status = MUSB_DMA_STATUS_FREE;
}
return 0;
}
static int ux500_dma_controller_stop(struct dma_controller *c)
{
struct ux500_dma_controller *controller = container_of(c,
struct ux500_dma_controller, controller);
struct ux500_dma_channel *ux500_channel;
struct dma_channel *channel;
u8 ch_num;
for (ch_num = 0; ch_num < controller->num_rx_channels; ch_num++) {
channel = &controller->rx_channel[ch_num].channel;
ux500_channel = channel->private_data;
ux500_dma_channel_release(channel);
if (ux500_channel->dma_chan)
dma_release_channel(ux500_channel->dma_chan);
}
for (ch_num = 0; ch_num < controller->num_tx_channels; ch_num++) {
channel = &controller->tx_channel[ch_num].channel;
ux500_channel = channel->private_data;
ux500_dma_channel_release(channel);
if (ux500_channel->dma_chan)
dma_release_channel(ux500_channel->dma_chan);
}
return 0;
}
static int ux500_dma_controller_start(struct dma_controller *c)
{
struct ux500_dma_controller *controller = container_of(c,
struct ux500_dma_controller, controller);
struct ux500_dma_channel *ux500_channel = NULL;
struct musb *musb = controller->private_data;
struct device *dev = musb->controller;
struct musb_hdrc_platform_data *plat = dev->platform_data;
struct ux500_musb_board_data *data = plat->board_data;
struct dma_channel *dma_channel = NULL;
u32 ch_num;
u8 dir;
u8 is_tx = 0;
void **param_array;
struct ux500_dma_channel *channel_array;
u32 ch_count;
void (*musb_channel_work)(struct work_struct *);
dma_cap_mask_t mask;
if ((data->num_rx_channels > UX500_MUSB_DMA_NUM_RX_CHANNELS) ||
(data->num_tx_channels > UX500_MUSB_DMA_NUM_TX_CHANNELS))
return -EINVAL;
controller->num_rx_channels = data->num_rx_channels;
controller->num_tx_channels = data->num_tx_channels;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
/* Prepare the loop for RX channels */
channel_array = controller->rx_channel;
ch_count = data->num_rx_channels;
param_array = data->dma_rx_param_array;
musb_channel_work = ux500_rx_work;
for (dir = 0; dir < 2; dir++) {
for (ch_num = 0; ch_num < ch_count; ch_num++) {
ux500_channel = &channel_array[ch_num];
ux500_channel->controller = controller;
ux500_channel->ch_num = ch_num;
ux500_channel->is_tx = is_tx;
dma_channel = &(ux500_channel->channel);
dma_channel->private_data = ux500_channel;
dma_channel->status = MUSB_DMA_STATUS_FREE;
dma_channel->max_len = SZ_16M;
ux500_channel->dma_chan = dma_request_channel(mask,
data->dma_filter,
param_array[ch_num]);
if (!ux500_channel->dma_chan) {
ERR("Dma pipe allocation error dir=%d ch=%d\n",
dir, ch_num);
/* Release already allocated channels */
ux500_dma_controller_stop(c);
return -EBUSY;
}
INIT_WORK(&ux500_channel->channel_work,
musb_channel_work);
}
/* Prepare the loop for TX channels */
channel_array = controller->tx_channel;
ch_count = data->num_tx_channels;
param_array = data->dma_tx_param_array;
musb_channel_work = ux500_tx_work;
is_tx = 1;
}
return 0;
}
void dma_controller_destroy(struct dma_controller *c)
{
struct ux500_dma_controller *controller = container_of(c,
struct ux500_dma_controller, controller);
kfree(controller);
}
struct dma_controller *__init
dma_controller_create(struct musb *musb, void __iomem *base)
{
struct ux500_dma_controller *controller;
struct platform_device *pdev = to_platform_device(musb->controller);
struct resource *iomem;
controller = kzalloc(sizeof(*controller), GFP_KERNEL);
if (!controller)
return NULL;
controller->private_data = musb;
/* Save physical address for DMA controller. */
iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
controller->phy_base = (dma_addr_t) iomem->start;
controller->controller.start = ux500_dma_controller_start;
controller->controller.stop = ux500_dma_controller_stop;
controller->controller.channel_alloc = ux500_dma_channel_allocate;
controller->controller.channel_release = ux500_dma_channel_release;
controller->controller.channel_program = ux500_dma_channel_program;
controller->controller.channel_abort = ux500_dma_channel_abort;
controller->controller.is_compatible = ux500_dma_is_compatible;
return &controller->controller;
}
| gpl-2.0 |
arm10c/linux-stable | sound/soc/tegra/trimslice.c | 517 | 5548 | /*
* trimslice.c - TrimSlice machine ASoC driver
*
* Copyright (C) 2011 - CompuLab, Ltd.
* Author: Mike Rapoport <mike@compulab.co.il>
*
* Based on code copyright/by:
* Author: Stephen Warren <swarren@nvidia.com>
* Copyright (C) 2010-2011 - NVIDIA, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/jack.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include "../codecs/tlv320aic23.h"
#include "tegra_asoc_utils.h"
#define DRV_NAME "tegra-snd-trimslice"
struct tegra_trimslice {
struct tegra_asoc_utils_data util_data;
};
static int trimslice_asoc_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_codec *codec = codec_dai->codec;
struct snd_soc_card *card = codec->card;
struct tegra_trimslice *trimslice = snd_soc_card_get_drvdata(card);
int srate, mclk;
int err;
srate = params_rate(params);
mclk = 128 * srate;
err = tegra_asoc_utils_set_rate(&trimslice->util_data, srate, mclk);
if (err < 0) {
dev_err(card->dev, "Can't configure clocks\n");
return err;
}
err = snd_soc_dai_set_sysclk(codec_dai, 0, mclk,
SND_SOC_CLOCK_IN);
if (err < 0) {
dev_err(card->dev, "codec_dai clock not set\n");
return err;
}
return 0;
}
static struct snd_soc_ops trimslice_asoc_ops = {
.hw_params = trimslice_asoc_hw_params,
};
static const struct snd_soc_dapm_widget trimslice_dapm_widgets[] = {
SND_SOC_DAPM_HP("Line Out", NULL),
SND_SOC_DAPM_LINE("Line In", NULL),
};
static const struct snd_soc_dapm_route trimslice_audio_map[] = {
{"Line Out", NULL, "LOUT"},
{"Line Out", NULL, "ROUT"},
{"LLINEIN", NULL, "Line In"},
{"RLINEIN", NULL, "Line In"},
};
static struct snd_soc_dai_link trimslice_tlv320aic23_dai = {
.name = "TLV320AIC23",
.stream_name = "AIC23",
.codec_dai_name = "tlv320aic23-hifi",
.ops = &trimslice_asoc_ops,
.dai_fmt = SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBS_CFS,
};
static struct snd_soc_card snd_soc_trimslice = {
.name = "tegra-trimslice",
.owner = THIS_MODULE,
.dai_link = &trimslice_tlv320aic23_dai,
.num_links = 1,
.dapm_widgets = trimslice_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(trimslice_dapm_widgets),
.dapm_routes = trimslice_audio_map,
.num_dapm_routes = ARRAY_SIZE(trimslice_audio_map),
.fully_routed = true,
};
static int tegra_snd_trimslice_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct snd_soc_card *card = &snd_soc_trimslice;
struct tegra_trimslice *trimslice;
int ret;
trimslice = devm_kzalloc(&pdev->dev, sizeof(struct tegra_trimslice),
GFP_KERNEL);
if (!trimslice) {
dev_err(&pdev->dev, "Can't allocate tegra_trimslice\n");
return -ENOMEM;
}
card->dev = &pdev->dev;
platform_set_drvdata(pdev, card);
snd_soc_card_set_drvdata(card, trimslice);
trimslice_tlv320aic23_dai.codec_of_node = of_parse_phandle(np,
"nvidia,audio-codec", 0);
if (!trimslice_tlv320aic23_dai.codec_of_node) {
dev_err(&pdev->dev,
"Property 'nvidia,audio-codec' missing or invalid\n");
ret = -EINVAL;
goto err;
}
trimslice_tlv320aic23_dai.cpu_of_node = of_parse_phandle(np,
"nvidia,i2s-controller", 0);
if (!trimslice_tlv320aic23_dai.cpu_of_node) {
dev_err(&pdev->dev,
"Property 'nvidia,i2s-controller' missing or invalid\n");
ret = -EINVAL;
goto err;
}
trimslice_tlv320aic23_dai.platform_of_node =
trimslice_tlv320aic23_dai.cpu_of_node;
ret = tegra_asoc_utils_init(&trimslice->util_data, &pdev->dev);
if (ret)
goto err;
ret = snd_soc_register_card(card);
if (ret) {
dev_err(&pdev->dev, "snd_soc_register_card failed (%d)\n",
ret);
goto err_fini_utils;
}
return 0;
err_fini_utils:
tegra_asoc_utils_fini(&trimslice->util_data);
err:
return ret;
}
static int tegra_snd_trimslice_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
struct tegra_trimslice *trimslice = snd_soc_card_get_drvdata(card);
snd_soc_unregister_card(card);
tegra_asoc_utils_fini(&trimslice->util_data);
return 0;
}
static const struct of_device_id trimslice_of_match[] = {
{ .compatible = "nvidia,tegra-audio-trimslice", },
{},
};
MODULE_DEVICE_TABLE(of, trimslice_of_match);
static struct platform_driver tegra_snd_trimslice_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = trimslice_of_match,
},
.probe = tegra_snd_trimslice_probe,
.remove = tegra_snd_trimslice_remove,
};
module_platform_driver(tegra_snd_trimslice_driver);
MODULE_AUTHOR("Mike Rapoport <mike@compulab.co.il>");
MODULE_DESCRIPTION("Trimslice machine ASoC driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
justsoso8/kernel_zte_n780 | drivers/net/wireless/wl12xx/wl1271_debugfs.c | 517 | 16847 | /*
* This file is part of wl1271
*
* Copyright (C) 2009 Nokia Corporation
*
* Contact: Luciano Coelho <luciano.coelho@nokia.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.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "wl1271_debugfs.h"
#include <linux/skbuff.h>
#include "wl1271.h"
#include "wl1271_acx.h"
#include "wl1271_ps.h"
/* ms */
#define WL1271_DEBUGFS_STATS_LIFETIME 1000
/* debugfs macros idea from mac80211 */
#define DEBUGFS_READONLY_FILE(name, buflen, fmt, value...) \
static ssize_t name## _read(struct file *file, char __user *userbuf, \
size_t count, loff_t *ppos) \
{ \
struct wl1271 *wl = file->private_data; \
char buf[buflen]; \
int res; \
\
res = scnprintf(buf, buflen, fmt "\n", ##value); \
return simple_read_from_buffer(userbuf, count, ppos, buf, res); \
} \
\
static const struct file_operations name## _ops = { \
.read = name## _read, \
.open = wl1271_open_file_generic, \
};
#define DEBUGFS_ADD(name, parent) \
wl->debugfs.name = debugfs_create_file(#name, 0400, parent, \
wl, &name## _ops); \
if (IS_ERR(wl->debugfs.name)) { \
ret = PTR_ERR(wl->debugfs.name); \
wl->debugfs.name = NULL; \
goto out; \
}
#define DEBUGFS_DEL(name) \
do { \
debugfs_remove(wl->debugfs.name); \
wl->debugfs.name = NULL; \
} while (0)
#define DEBUGFS_FWSTATS_FILE(sub, name, buflen, fmt) \
static ssize_t sub## _ ##name## _read(struct file *file, \
char __user *userbuf, \
size_t count, loff_t *ppos) \
{ \
struct wl1271 *wl = file->private_data; \
char buf[buflen]; \
int res; \
\
wl1271_debugfs_update_stats(wl); \
\
res = scnprintf(buf, buflen, fmt "\n", \
wl->stats.fw_stats->sub.name); \
return simple_read_from_buffer(userbuf, count, ppos, buf, res); \
} \
\
static const struct file_operations sub## _ ##name## _ops = { \
.read = sub## _ ##name## _read, \
.open = wl1271_open_file_generic, \
};
#define DEBUGFS_FWSTATS_ADD(sub, name) \
DEBUGFS_ADD(sub## _ ##name, wl->debugfs.fw_statistics)
#define DEBUGFS_FWSTATS_DEL(sub, name) \
DEBUGFS_DEL(sub## _ ##name)
static void wl1271_debugfs_update_stats(struct wl1271 *wl)
{
int ret;
mutex_lock(&wl->mutex);
ret = wl1271_ps_elp_wakeup(wl, false);
if (ret < 0)
goto out;
if (wl->state == WL1271_STATE_ON &&
time_after(jiffies, wl->stats.fw_stats_update +
msecs_to_jiffies(WL1271_DEBUGFS_STATS_LIFETIME))) {
wl1271_acx_statistics(wl, wl->stats.fw_stats);
wl->stats.fw_stats_update = jiffies;
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int wl1271_open_file_generic(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
DEBUGFS_FWSTATS_FILE(tx, internal_desc_overflow, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, out_of_mem, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, hdr_overflow, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, hw_stuck, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, dropped, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, fcs_err, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, xfr_hint_trig, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, path_reset, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, reset_counter, 20, "%u");
DEBUGFS_FWSTATS_FILE(dma, rx_requested, 20, "%u");
DEBUGFS_FWSTATS_FILE(dma, rx_errors, 20, "%u");
DEBUGFS_FWSTATS_FILE(dma, tx_requested, 20, "%u");
DEBUGFS_FWSTATS_FILE(dma, tx_errors, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, cmd_cmplt, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, fiqs, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, rx_headers, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, rx_mem_overflow, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, rx_rdys, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, irqs, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, tx_procs, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, decrypt_done, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, dma0_done, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, dma1_done, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, tx_exch_complete, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, commands, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, rx_procs, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, hw_pm_mode_changes, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, host_acknowledges, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, pci_pm, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, wakeups, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, low_rssi, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, addr_key_count, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, default_key_count, 20, "%u");
/* skipping wep.reserved */
DEBUGFS_FWSTATS_FILE(wep, key_not_found, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, decrypt_fail, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, packets, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, interrupt, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, ps_enter, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, elp_enter, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, missing_bcns, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, wake_on_host, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, wake_on_timer_exp, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, tx_with_ps, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, tx_without_ps, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, rcvd_beacons, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, power_save_off, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, enable_ps, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, disable_ps, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, fix_tsf_ps, 20, "%u");
/* skipping cont_miss_bcns_spread for now */
DEBUGFS_FWSTATS_FILE(pwr, rcvd_awake_beacons, 20, "%u");
DEBUGFS_FWSTATS_FILE(mic, rx_pkts, 20, "%u");
DEBUGFS_FWSTATS_FILE(mic, calc_failure, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, encrypt_fail, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, decrypt_fail, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, encrypt_packets, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, decrypt_packets, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, encrypt_interrupt, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, decrypt_interrupt, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, heart_beat, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, calibration, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, rx_mismatch, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, rx_mem_empty, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, rx_pool, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, oom_late, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, phy_transmit_error, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, tx_stuck, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, pspoll_timeouts, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, upsd_timeouts, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, upsd_max_sptime, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, upsd_max_apturn, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, pspoll_max_apturn, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, pspoll_utilization, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, upsd_utilization, 20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, rx_prep_beacon_drop, 20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, descr_host_int_trig_rx_data, 20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, beacon_buffer_thres_host_int_trig_rx_data,
20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, missed_beacon_host_int_trig_rx_data, 20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, tx_xfr_host_int_trig_rx_data, 20, "%u");
DEBUGFS_READONLY_FILE(retry_count, 20, "%u", wl->stats.retry_count);
DEBUGFS_READONLY_FILE(excessive_retries, 20, "%u",
wl->stats.excessive_retries);
static ssize_t tx_queue_len_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct wl1271 *wl = file->private_data;
u32 queue_len;
char buf[20];
int res;
queue_len = skb_queue_len(&wl->tx_queue);
res = scnprintf(buf, sizeof(buf), "%u\n", queue_len);
return simple_read_from_buffer(userbuf, count, ppos, buf, res);
}
static const struct file_operations tx_queue_len_ops = {
.read = tx_queue_len_read,
.open = wl1271_open_file_generic,
};
static void wl1271_debugfs_delete_files(struct wl1271 *wl)
{
DEBUGFS_FWSTATS_DEL(tx, internal_desc_overflow);
DEBUGFS_FWSTATS_DEL(rx, out_of_mem);
DEBUGFS_FWSTATS_DEL(rx, hdr_overflow);
DEBUGFS_FWSTATS_DEL(rx, hw_stuck);
DEBUGFS_FWSTATS_DEL(rx, dropped);
DEBUGFS_FWSTATS_DEL(rx, fcs_err);
DEBUGFS_FWSTATS_DEL(rx, xfr_hint_trig);
DEBUGFS_FWSTATS_DEL(rx, path_reset);
DEBUGFS_FWSTATS_DEL(rx, reset_counter);
DEBUGFS_FWSTATS_DEL(dma, rx_requested);
DEBUGFS_FWSTATS_DEL(dma, rx_errors);
DEBUGFS_FWSTATS_DEL(dma, tx_requested);
DEBUGFS_FWSTATS_DEL(dma, tx_errors);
DEBUGFS_FWSTATS_DEL(isr, cmd_cmplt);
DEBUGFS_FWSTATS_DEL(isr, fiqs);
DEBUGFS_FWSTATS_DEL(isr, rx_headers);
DEBUGFS_FWSTATS_DEL(isr, rx_mem_overflow);
DEBUGFS_FWSTATS_DEL(isr, rx_rdys);
DEBUGFS_FWSTATS_DEL(isr, irqs);
DEBUGFS_FWSTATS_DEL(isr, tx_procs);
DEBUGFS_FWSTATS_DEL(isr, decrypt_done);
DEBUGFS_FWSTATS_DEL(isr, dma0_done);
DEBUGFS_FWSTATS_DEL(isr, dma1_done);
DEBUGFS_FWSTATS_DEL(isr, tx_exch_complete);
DEBUGFS_FWSTATS_DEL(isr, commands);
DEBUGFS_FWSTATS_DEL(isr, rx_procs);
DEBUGFS_FWSTATS_DEL(isr, hw_pm_mode_changes);
DEBUGFS_FWSTATS_DEL(isr, host_acknowledges);
DEBUGFS_FWSTATS_DEL(isr, pci_pm);
DEBUGFS_FWSTATS_DEL(isr, wakeups);
DEBUGFS_FWSTATS_DEL(isr, low_rssi);
DEBUGFS_FWSTATS_DEL(wep, addr_key_count);
DEBUGFS_FWSTATS_DEL(wep, default_key_count);
/* skipping wep.reserved */
DEBUGFS_FWSTATS_DEL(wep, key_not_found);
DEBUGFS_FWSTATS_DEL(wep, decrypt_fail);
DEBUGFS_FWSTATS_DEL(wep, packets);
DEBUGFS_FWSTATS_DEL(wep, interrupt);
DEBUGFS_FWSTATS_DEL(pwr, ps_enter);
DEBUGFS_FWSTATS_DEL(pwr, elp_enter);
DEBUGFS_FWSTATS_DEL(pwr, missing_bcns);
DEBUGFS_FWSTATS_DEL(pwr, wake_on_host);
DEBUGFS_FWSTATS_DEL(pwr, wake_on_timer_exp);
DEBUGFS_FWSTATS_DEL(pwr, tx_with_ps);
DEBUGFS_FWSTATS_DEL(pwr, tx_without_ps);
DEBUGFS_FWSTATS_DEL(pwr, rcvd_beacons);
DEBUGFS_FWSTATS_DEL(pwr, power_save_off);
DEBUGFS_FWSTATS_DEL(pwr, enable_ps);
DEBUGFS_FWSTATS_DEL(pwr, disable_ps);
DEBUGFS_FWSTATS_DEL(pwr, fix_tsf_ps);
/* skipping cont_miss_bcns_spread for now */
DEBUGFS_FWSTATS_DEL(pwr, rcvd_awake_beacons);
DEBUGFS_FWSTATS_DEL(mic, rx_pkts);
DEBUGFS_FWSTATS_DEL(mic, calc_failure);
DEBUGFS_FWSTATS_DEL(aes, encrypt_fail);
DEBUGFS_FWSTATS_DEL(aes, decrypt_fail);
DEBUGFS_FWSTATS_DEL(aes, encrypt_packets);
DEBUGFS_FWSTATS_DEL(aes, decrypt_packets);
DEBUGFS_FWSTATS_DEL(aes, encrypt_interrupt);
DEBUGFS_FWSTATS_DEL(aes, decrypt_interrupt);
DEBUGFS_FWSTATS_DEL(event, heart_beat);
DEBUGFS_FWSTATS_DEL(event, calibration);
DEBUGFS_FWSTATS_DEL(event, rx_mismatch);
DEBUGFS_FWSTATS_DEL(event, rx_mem_empty);
DEBUGFS_FWSTATS_DEL(event, rx_pool);
DEBUGFS_FWSTATS_DEL(event, oom_late);
DEBUGFS_FWSTATS_DEL(event, phy_transmit_error);
DEBUGFS_FWSTATS_DEL(event, tx_stuck);
DEBUGFS_FWSTATS_DEL(ps, pspoll_timeouts);
DEBUGFS_FWSTATS_DEL(ps, upsd_timeouts);
DEBUGFS_FWSTATS_DEL(ps, upsd_max_sptime);
DEBUGFS_FWSTATS_DEL(ps, upsd_max_apturn);
DEBUGFS_FWSTATS_DEL(ps, pspoll_max_apturn);
DEBUGFS_FWSTATS_DEL(ps, pspoll_utilization);
DEBUGFS_FWSTATS_DEL(ps, upsd_utilization);
DEBUGFS_FWSTATS_DEL(rxpipe, rx_prep_beacon_drop);
DEBUGFS_FWSTATS_DEL(rxpipe, descr_host_int_trig_rx_data);
DEBUGFS_FWSTATS_DEL(rxpipe, beacon_buffer_thres_host_int_trig_rx_data);
DEBUGFS_FWSTATS_DEL(rxpipe, missed_beacon_host_int_trig_rx_data);
DEBUGFS_FWSTATS_DEL(rxpipe, tx_xfr_host_int_trig_rx_data);
DEBUGFS_DEL(tx_queue_len);
DEBUGFS_DEL(retry_count);
DEBUGFS_DEL(excessive_retries);
}
static int wl1271_debugfs_add_files(struct wl1271 *wl)
{
int ret = 0;
DEBUGFS_FWSTATS_ADD(tx, internal_desc_overflow);
DEBUGFS_FWSTATS_ADD(rx, out_of_mem);
DEBUGFS_FWSTATS_ADD(rx, hdr_overflow);
DEBUGFS_FWSTATS_ADD(rx, hw_stuck);
DEBUGFS_FWSTATS_ADD(rx, dropped);
DEBUGFS_FWSTATS_ADD(rx, fcs_err);
DEBUGFS_FWSTATS_ADD(rx, xfr_hint_trig);
DEBUGFS_FWSTATS_ADD(rx, path_reset);
DEBUGFS_FWSTATS_ADD(rx, reset_counter);
DEBUGFS_FWSTATS_ADD(dma, rx_requested);
DEBUGFS_FWSTATS_ADD(dma, rx_errors);
DEBUGFS_FWSTATS_ADD(dma, tx_requested);
DEBUGFS_FWSTATS_ADD(dma, tx_errors);
DEBUGFS_FWSTATS_ADD(isr, cmd_cmplt);
DEBUGFS_FWSTATS_ADD(isr, fiqs);
DEBUGFS_FWSTATS_ADD(isr, rx_headers);
DEBUGFS_FWSTATS_ADD(isr, rx_mem_overflow);
DEBUGFS_FWSTATS_ADD(isr, rx_rdys);
DEBUGFS_FWSTATS_ADD(isr, irqs);
DEBUGFS_FWSTATS_ADD(isr, tx_procs);
DEBUGFS_FWSTATS_ADD(isr, decrypt_done);
DEBUGFS_FWSTATS_ADD(isr, dma0_done);
DEBUGFS_FWSTATS_ADD(isr, dma1_done);
DEBUGFS_FWSTATS_ADD(isr, tx_exch_complete);
DEBUGFS_FWSTATS_ADD(isr, commands);
DEBUGFS_FWSTATS_ADD(isr, rx_procs);
DEBUGFS_FWSTATS_ADD(isr, hw_pm_mode_changes);
DEBUGFS_FWSTATS_ADD(isr, host_acknowledges);
DEBUGFS_FWSTATS_ADD(isr, pci_pm);
DEBUGFS_FWSTATS_ADD(isr, wakeups);
DEBUGFS_FWSTATS_ADD(isr, low_rssi);
DEBUGFS_FWSTATS_ADD(wep, addr_key_count);
DEBUGFS_FWSTATS_ADD(wep, default_key_count);
/* skipping wep.reserved */
DEBUGFS_FWSTATS_ADD(wep, key_not_found);
DEBUGFS_FWSTATS_ADD(wep, decrypt_fail);
DEBUGFS_FWSTATS_ADD(wep, packets);
DEBUGFS_FWSTATS_ADD(wep, interrupt);
DEBUGFS_FWSTATS_ADD(pwr, ps_enter);
DEBUGFS_FWSTATS_ADD(pwr, elp_enter);
DEBUGFS_FWSTATS_ADD(pwr, missing_bcns);
DEBUGFS_FWSTATS_ADD(pwr, wake_on_host);
DEBUGFS_FWSTATS_ADD(pwr, wake_on_timer_exp);
DEBUGFS_FWSTATS_ADD(pwr, tx_with_ps);
DEBUGFS_FWSTATS_ADD(pwr, tx_without_ps);
DEBUGFS_FWSTATS_ADD(pwr, rcvd_beacons);
DEBUGFS_FWSTATS_ADD(pwr, power_save_off);
DEBUGFS_FWSTATS_ADD(pwr, enable_ps);
DEBUGFS_FWSTATS_ADD(pwr, disable_ps);
DEBUGFS_FWSTATS_ADD(pwr, fix_tsf_ps);
/* skipping cont_miss_bcns_spread for now */
DEBUGFS_FWSTATS_ADD(pwr, rcvd_awake_beacons);
DEBUGFS_FWSTATS_ADD(mic, rx_pkts);
DEBUGFS_FWSTATS_ADD(mic, calc_failure);
DEBUGFS_FWSTATS_ADD(aes, encrypt_fail);
DEBUGFS_FWSTATS_ADD(aes, decrypt_fail);
DEBUGFS_FWSTATS_ADD(aes, encrypt_packets);
DEBUGFS_FWSTATS_ADD(aes, decrypt_packets);
DEBUGFS_FWSTATS_ADD(aes, encrypt_interrupt);
DEBUGFS_FWSTATS_ADD(aes, decrypt_interrupt);
DEBUGFS_FWSTATS_ADD(event, heart_beat);
DEBUGFS_FWSTATS_ADD(event, calibration);
DEBUGFS_FWSTATS_ADD(event, rx_mismatch);
DEBUGFS_FWSTATS_ADD(event, rx_mem_empty);
DEBUGFS_FWSTATS_ADD(event, rx_pool);
DEBUGFS_FWSTATS_ADD(event, oom_late);
DEBUGFS_FWSTATS_ADD(event, phy_transmit_error);
DEBUGFS_FWSTATS_ADD(event, tx_stuck);
DEBUGFS_FWSTATS_ADD(ps, pspoll_timeouts);
DEBUGFS_FWSTATS_ADD(ps, upsd_timeouts);
DEBUGFS_FWSTATS_ADD(ps, upsd_max_sptime);
DEBUGFS_FWSTATS_ADD(ps, upsd_max_apturn);
DEBUGFS_FWSTATS_ADD(ps, pspoll_max_apturn);
DEBUGFS_FWSTATS_ADD(ps, pspoll_utilization);
DEBUGFS_FWSTATS_ADD(ps, upsd_utilization);
DEBUGFS_FWSTATS_ADD(rxpipe, rx_prep_beacon_drop);
DEBUGFS_FWSTATS_ADD(rxpipe, descr_host_int_trig_rx_data);
DEBUGFS_FWSTATS_ADD(rxpipe, beacon_buffer_thres_host_int_trig_rx_data);
DEBUGFS_FWSTATS_ADD(rxpipe, missed_beacon_host_int_trig_rx_data);
DEBUGFS_FWSTATS_ADD(rxpipe, tx_xfr_host_int_trig_rx_data);
DEBUGFS_ADD(tx_queue_len, wl->debugfs.rootdir);
DEBUGFS_ADD(retry_count, wl->debugfs.rootdir);
DEBUGFS_ADD(excessive_retries, wl->debugfs.rootdir);
out:
if (ret < 0)
wl1271_debugfs_delete_files(wl);
return ret;
}
void wl1271_debugfs_reset(struct wl1271 *wl)
{
memset(wl->stats.fw_stats, 0, sizeof(*wl->stats.fw_stats));
wl->stats.retry_count = 0;
wl->stats.excessive_retries = 0;
}
int wl1271_debugfs_init(struct wl1271 *wl)
{
int ret;
wl->debugfs.rootdir = debugfs_create_dir(KBUILD_MODNAME, NULL);
if (IS_ERR(wl->debugfs.rootdir)) {
ret = PTR_ERR(wl->debugfs.rootdir);
wl->debugfs.rootdir = NULL;
goto err;
}
wl->debugfs.fw_statistics = debugfs_create_dir("fw-statistics",
wl->debugfs.rootdir);
if (IS_ERR(wl->debugfs.fw_statistics)) {
ret = PTR_ERR(wl->debugfs.fw_statistics);
wl->debugfs.fw_statistics = NULL;
goto err_root;
}
wl->stats.fw_stats = kzalloc(sizeof(*wl->stats.fw_stats),
GFP_KERNEL);
if (!wl->stats.fw_stats) {
ret = -ENOMEM;
goto err_fw;
}
wl->stats.fw_stats_update = jiffies;
ret = wl1271_debugfs_add_files(wl);
if (ret < 0)
goto err_file;
return 0;
err_file:
kfree(wl->stats.fw_stats);
wl->stats.fw_stats = NULL;
err_fw:
debugfs_remove(wl->debugfs.fw_statistics);
wl->debugfs.fw_statistics = NULL;
err_root:
debugfs_remove(wl->debugfs.rootdir);
wl->debugfs.rootdir = NULL;
err:
return ret;
}
void wl1271_debugfs_exit(struct wl1271 *wl)
{
wl1271_debugfs_delete_files(wl);
kfree(wl->stats.fw_stats);
wl->stats.fw_stats = NULL;
debugfs_remove(wl->debugfs.fw_statistics);
wl->debugfs.fw_statistics = NULL;
debugfs_remove(wl->debugfs.rootdir);
wl->debugfs.rootdir = NULL;
}
| gpl-2.0 |
CoRfr/linux | fs/binfmt_elf_fdpic.c | 517 | 48256 | /* binfmt_elf_fdpic.c: FDPIC ELF binary format
*
* Copyright (C) 2003, 2004, 2006 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
* Derived from binfmt_elf.c
*
* 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 <linux/module.h>
#include <linux/fs.h>
#include <linux/stat.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/binfmts.h>
#include <linux/string.h>
#include <linux/file.h>
#include <linux/fcntl.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/security.h>
#include <linux/highmem.h>
#include <linux/highuid.h>
#include <linux/personality.h>
#include <linux/ptrace.h>
#include <linux/init.h>
#include <linux/elf.h>
#include <linux/elf-fdpic.h>
#include <linux/elfcore.h>
#include <linux/coredump.h>
#include <asm/uaccess.h>
#include <asm/param.h>
#include <asm/pgalloc.h>
typedef char *elf_caddr_t;
#if 0
#define kdebug(fmt, ...) printk("FDPIC "fmt"\n" ,##__VA_ARGS__ )
#else
#define kdebug(fmt, ...) do {} while(0)
#endif
#if 0
#define kdcore(fmt, ...) printk("FDPIC "fmt"\n" ,##__VA_ARGS__ )
#else
#define kdcore(fmt, ...) do {} while(0)
#endif
MODULE_LICENSE("GPL");
static int load_elf_fdpic_binary(struct linux_binprm *);
static int elf_fdpic_fetch_phdrs(struct elf_fdpic_params *, struct file *);
static int elf_fdpic_map_file(struct elf_fdpic_params *, struct file *,
struct mm_struct *, const char *);
static int create_elf_fdpic_tables(struct linux_binprm *, struct mm_struct *,
struct elf_fdpic_params *,
struct elf_fdpic_params *);
#ifndef CONFIG_MMU
static int elf_fdpic_transfer_args_to_stack(struct linux_binprm *,
unsigned long *);
static int elf_fdpic_map_file_constdisp_on_uclinux(struct elf_fdpic_params *,
struct file *,
struct mm_struct *);
#endif
static int elf_fdpic_map_file_by_direct_mmap(struct elf_fdpic_params *,
struct file *, struct mm_struct *);
#ifdef CONFIG_ELF_CORE
static int elf_fdpic_core_dump(struct coredump_params *cprm);
#endif
static struct linux_binfmt elf_fdpic_format = {
.module = THIS_MODULE,
.load_binary = load_elf_fdpic_binary,
#ifdef CONFIG_ELF_CORE
.core_dump = elf_fdpic_core_dump,
#endif
.min_coredump = ELF_EXEC_PAGESIZE,
};
static int __init init_elf_fdpic_binfmt(void)
{
register_binfmt(&elf_fdpic_format);
return 0;
}
static void __exit exit_elf_fdpic_binfmt(void)
{
unregister_binfmt(&elf_fdpic_format);
}
core_initcall(init_elf_fdpic_binfmt);
module_exit(exit_elf_fdpic_binfmt);
static int is_elf_fdpic(struct elfhdr *hdr, struct file *file)
{
if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0)
return 0;
if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN)
return 0;
if (!elf_check_arch(hdr) || !elf_check_fdpic(hdr))
return 0;
if (!file->f_op->mmap)
return 0;
return 1;
}
/*****************************************************************************/
/*
* read the program headers table into memory
*/
static int elf_fdpic_fetch_phdrs(struct elf_fdpic_params *params,
struct file *file)
{
struct elf32_phdr *phdr;
unsigned long size;
int retval, loop;
if (params->hdr.e_phentsize != sizeof(struct elf_phdr))
return -ENOMEM;
if (params->hdr.e_phnum > 65536U / sizeof(struct elf_phdr))
return -ENOMEM;
size = params->hdr.e_phnum * sizeof(struct elf_phdr);
params->phdrs = kmalloc(size, GFP_KERNEL);
if (!params->phdrs)
return -ENOMEM;
retval = kernel_read(file, params->hdr.e_phoff,
(char *) params->phdrs, size);
if (unlikely(retval != size))
return retval < 0 ? retval : -ENOEXEC;
/* determine stack size for this binary */
phdr = params->phdrs;
for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
if (phdr->p_type != PT_GNU_STACK)
continue;
if (phdr->p_flags & PF_X)
params->flags |= ELF_FDPIC_FLAG_EXEC_STACK;
else
params->flags |= ELF_FDPIC_FLAG_NOEXEC_STACK;
params->stack_size = phdr->p_memsz;
break;
}
return 0;
}
/*****************************************************************************/
/*
* load an fdpic binary into various bits of memory
*/
static int load_elf_fdpic_binary(struct linux_binprm *bprm)
{
struct elf_fdpic_params exec_params, interp_params;
struct pt_regs *regs = current_pt_regs();
struct elf_phdr *phdr;
unsigned long stack_size, entryaddr;
#ifdef ELF_FDPIC_PLAT_INIT
unsigned long dynaddr;
#endif
#ifndef CONFIG_MMU
unsigned long stack_prot;
#endif
struct file *interpreter = NULL; /* to shut gcc up */
char *interpreter_name = NULL;
int executable_stack;
int retval, i;
kdebug("____ LOAD %d ____", current->pid);
memset(&exec_params, 0, sizeof(exec_params));
memset(&interp_params, 0, sizeof(interp_params));
exec_params.hdr = *(struct elfhdr *) bprm->buf;
exec_params.flags = ELF_FDPIC_FLAG_PRESENT | ELF_FDPIC_FLAG_EXECUTABLE;
/* check that this is a binary we know how to deal with */
retval = -ENOEXEC;
if (!is_elf_fdpic(&exec_params.hdr, bprm->file))
goto error;
/* read the program header table */
retval = elf_fdpic_fetch_phdrs(&exec_params, bprm->file);
if (retval < 0)
goto error;
/* scan for a program header that specifies an interpreter */
phdr = exec_params.phdrs;
for (i = 0; i < exec_params.hdr.e_phnum; i++, phdr++) {
switch (phdr->p_type) {
case PT_INTERP:
retval = -ENOMEM;
if (phdr->p_filesz > PATH_MAX)
goto error;
retval = -ENOENT;
if (phdr->p_filesz < 2)
goto error;
/* read the name of the interpreter into memory */
interpreter_name = kmalloc(phdr->p_filesz, GFP_KERNEL);
if (!interpreter_name)
goto error;
retval = kernel_read(bprm->file,
phdr->p_offset,
interpreter_name,
phdr->p_filesz);
if (unlikely(retval != phdr->p_filesz)) {
if (retval >= 0)
retval = -ENOEXEC;
goto error;
}
retval = -ENOENT;
if (interpreter_name[phdr->p_filesz - 1] != '\0')
goto error;
kdebug("Using ELF interpreter %s", interpreter_name);
/* replace the program with the interpreter */
interpreter = open_exec(interpreter_name);
retval = PTR_ERR(interpreter);
if (IS_ERR(interpreter)) {
interpreter = NULL;
goto error;
}
/*
* If the binary is not readable then enforce
* mm->dumpable = 0 regardless of the interpreter's
* permissions.
*/
would_dump(bprm, interpreter);
retval = kernel_read(interpreter, 0, bprm->buf,
BINPRM_BUF_SIZE);
if (unlikely(retval != BINPRM_BUF_SIZE)) {
if (retval >= 0)
retval = -ENOEXEC;
goto error;
}
interp_params.hdr = *((struct elfhdr *) bprm->buf);
break;
case PT_LOAD:
#ifdef CONFIG_MMU
if (exec_params.load_addr == 0)
exec_params.load_addr = phdr->p_vaddr;
#endif
break;
}
}
if (elf_check_const_displacement(&exec_params.hdr))
exec_params.flags |= ELF_FDPIC_FLAG_CONSTDISP;
/* perform insanity checks on the interpreter */
if (interpreter_name) {
retval = -ELIBBAD;
if (!is_elf_fdpic(&interp_params.hdr, interpreter))
goto error;
interp_params.flags = ELF_FDPIC_FLAG_PRESENT;
/* read the interpreter's program header table */
retval = elf_fdpic_fetch_phdrs(&interp_params, interpreter);
if (retval < 0)
goto error;
}
stack_size = exec_params.stack_size;
if (exec_params.flags & ELF_FDPIC_FLAG_EXEC_STACK)
executable_stack = EXSTACK_ENABLE_X;
else if (exec_params.flags & ELF_FDPIC_FLAG_NOEXEC_STACK)
executable_stack = EXSTACK_DISABLE_X;
else
executable_stack = EXSTACK_DEFAULT;
if (stack_size == 0) {
stack_size = interp_params.stack_size;
if (interp_params.flags & ELF_FDPIC_FLAG_EXEC_STACK)
executable_stack = EXSTACK_ENABLE_X;
else if (interp_params.flags & ELF_FDPIC_FLAG_NOEXEC_STACK)
executable_stack = EXSTACK_DISABLE_X;
else
executable_stack = EXSTACK_DEFAULT;
}
retval = -ENOEXEC;
if (stack_size == 0)
goto error;
if (elf_check_const_displacement(&interp_params.hdr))
interp_params.flags |= ELF_FDPIC_FLAG_CONSTDISP;
/* flush all traces of the currently running executable */
retval = flush_old_exec(bprm);
if (retval)
goto error;
/* there's now no turning back... the old userspace image is dead,
* defunct, deceased, etc. after this point we have to exit via
* error_kill */
set_personality(PER_LINUX_FDPIC);
if (elf_read_implies_exec(&exec_params.hdr, executable_stack))
current->personality |= READ_IMPLIES_EXEC;
setup_new_exec(bprm);
set_binfmt(&elf_fdpic_format);
current->mm->start_code = 0;
current->mm->end_code = 0;
current->mm->start_stack = 0;
current->mm->start_data = 0;
current->mm->end_data = 0;
current->mm->context.exec_fdpic_loadmap = 0;
current->mm->context.interp_fdpic_loadmap = 0;
#ifdef CONFIG_MMU
elf_fdpic_arch_lay_out_mm(&exec_params,
&interp_params,
¤t->mm->start_stack,
¤t->mm->start_brk);
retval = setup_arg_pages(bprm, current->mm->start_stack,
executable_stack);
if (retval < 0) {
send_sig(SIGKILL, current, 0);
goto error_kill;
}
#endif
/* load the executable and interpreter into memory */
retval = elf_fdpic_map_file(&exec_params, bprm->file, current->mm,
"executable");
if (retval < 0)
goto error_kill;
if (interpreter_name) {
retval = elf_fdpic_map_file(&interp_params, interpreter,
current->mm, "interpreter");
if (retval < 0) {
printk(KERN_ERR "Unable to load interpreter\n");
goto error_kill;
}
allow_write_access(interpreter);
fput(interpreter);
interpreter = NULL;
}
#ifdef CONFIG_MMU
if (!current->mm->start_brk)
current->mm->start_brk = current->mm->end_data;
current->mm->brk = current->mm->start_brk =
PAGE_ALIGN(current->mm->start_brk);
#else
/* create a stack and brk area big enough for everyone
* - the brk heap starts at the bottom and works up
* - the stack starts at the top and works down
*/
stack_size = (stack_size + PAGE_SIZE - 1) & PAGE_MASK;
if (stack_size < PAGE_SIZE * 2)
stack_size = PAGE_SIZE * 2;
stack_prot = PROT_READ | PROT_WRITE;
if (executable_stack == EXSTACK_ENABLE_X ||
(executable_stack == EXSTACK_DEFAULT && VM_STACK_FLAGS & VM_EXEC))
stack_prot |= PROT_EXEC;
current->mm->start_brk = vm_mmap(NULL, 0, stack_size, stack_prot,
MAP_PRIVATE | MAP_ANONYMOUS |
MAP_UNINITIALIZED | MAP_GROWSDOWN,
0);
if (IS_ERR_VALUE(current->mm->start_brk)) {
retval = current->mm->start_brk;
current->mm->start_brk = 0;
goto error_kill;
}
current->mm->brk = current->mm->start_brk;
current->mm->context.end_brk = current->mm->start_brk;
current->mm->context.end_brk +=
(stack_size > PAGE_SIZE) ? (stack_size - PAGE_SIZE) : 0;
current->mm->start_stack = current->mm->start_brk + stack_size;
#endif
install_exec_creds(bprm);
if (create_elf_fdpic_tables(bprm, current->mm,
&exec_params, &interp_params) < 0)
goto error_kill;
kdebug("- start_code %lx", current->mm->start_code);
kdebug("- end_code %lx", current->mm->end_code);
kdebug("- start_data %lx", current->mm->start_data);
kdebug("- end_data %lx", current->mm->end_data);
kdebug("- start_brk %lx", current->mm->start_brk);
kdebug("- brk %lx", current->mm->brk);
kdebug("- start_stack %lx", current->mm->start_stack);
#ifdef ELF_FDPIC_PLAT_INIT
/*
* The ABI may specify that certain registers be set up in special
* ways (on i386 %edx is the address of a DT_FINI function, for
* example. This macro performs whatever initialization to
* the regs structure is required.
*/
dynaddr = interp_params.dynamic_addr ?: exec_params.dynamic_addr;
ELF_FDPIC_PLAT_INIT(regs, exec_params.map_addr, interp_params.map_addr,
dynaddr);
#endif
/* everything is now ready... get the userspace context ready to roll */
entryaddr = interp_params.entry_addr ?: exec_params.entry_addr;
start_thread(regs, entryaddr, current->mm->start_stack);
retval = 0;
error:
if (interpreter) {
allow_write_access(interpreter);
fput(interpreter);
}
kfree(interpreter_name);
kfree(exec_params.phdrs);
kfree(exec_params.loadmap);
kfree(interp_params.phdrs);
kfree(interp_params.loadmap);
return retval;
/* unrecoverable error - kill the process */
error_kill:
send_sig(SIGSEGV, current, 0);
goto error;
}
/*****************************************************************************/
#ifndef ELF_BASE_PLATFORM
/*
* AT_BASE_PLATFORM indicates the "real" hardware/microarchitecture.
* If the arch defines ELF_BASE_PLATFORM (in asm/elf.h), the value
* will be copied to the user stack in the same manner as AT_PLATFORM.
*/
#define ELF_BASE_PLATFORM NULL
#endif
/*
* present useful information to the program by shovelling it onto the new
* process's stack
*/
static int create_elf_fdpic_tables(struct linux_binprm *bprm,
struct mm_struct *mm,
struct elf_fdpic_params *exec_params,
struct elf_fdpic_params *interp_params)
{
const struct cred *cred = current_cred();
unsigned long sp, csp, nitems;
elf_caddr_t __user *argv, *envp;
size_t platform_len = 0, len;
char *k_platform, *k_base_platform;
char __user *u_platform, *u_base_platform, *p;
int loop;
int nr; /* reset for each csp adjustment */
#ifdef CONFIG_MMU
/* In some cases (e.g. Hyper-Threading), we want to avoid L1 evictions
* by the processes running on the same package. One thing we can do is
* to shuffle the initial stack for them, so we give the architecture
* an opportunity to do so here.
*/
sp = arch_align_stack(bprm->p);
#else
sp = mm->start_stack;
/* stack the program arguments and environment */
if (elf_fdpic_transfer_args_to_stack(bprm, &sp) < 0)
return -EFAULT;
#endif
/*
* If this architecture has a platform capability string, copy it
* to userspace. In some cases (Sparc), this info is impossible
* for userspace to get any other way, in others (i386) it is
* merely difficult.
*/
k_platform = ELF_PLATFORM;
u_platform = NULL;
if (k_platform) {
platform_len = strlen(k_platform) + 1;
sp -= platform_len;
u_platform = (char __user *) sp;
if (__copy_to_user(u_platform, k_platform, platform_len) != 0)
return -EFAULT;
}
/*
* If this architecture has a "base" platform capability
* string, copy it to userspace.
*/
k_base_platform = ELF_BASE_PLATFORM;
u_base_platform = NULL;
if (k_base_platform) {
platform_len = strlen(k_base_platform) + 1;
sp -= platform_len;
u_base_platform = (char __user *) sp;
if (__copy_to_user(u_base_platform, k_base_platform, platform_len) != 0)
return -EFAULT;
}
sp &= ~7UL;
/* stack the load map(s) */
len = sizeof(struct elf32_fdpic_loadmap);
len += sizeof(struct elf32_fdpic_loadseg) * exec_params->loadmap->nsegs;
sp = (sp - len) & ~7UL;
exec_params->map_addr = sp;
if (copy_to_user((void __user *) sp, exec_params->loadmap, len) != 0)
return -EFAULT;
current->mm->context.exec_fdpic_loadmap = (unsigned long) sp;
if (interp_params->loadmap) {
len = sizeof(struct elf32_fdpic_loadmap);
len += sizeof(struct elf32_fdpic_loadseg) *
interp_params->loadmap->nsegs;
sp = (sp - len) & ~7UL;
interp_params->map_addr = sp;
if (copy_to_user((void __user *) sp, interp_params->loadmap,
len) != 0)
return -EFAULT;
current->mm->context.interp_fdpic_loadmap = (unsigned long) sp;
}
/* force 16 byte _final_ alignment here for generality */
#define DLINFO_ITEMS 15
nitems = 1 + DLINFO_ITEMS + (k_platform ? 1 : 0) +
(k_base_platform ? 1 : 0) + AT_VECTOR_SIZE_ARCH;
if (bprm->interp_flags & BINPRM_FLAGS_EXECFD)
nitems++;
csp = sp;
sp -= nitems * 2 * sizeof(unsigned long);
sp -= (bprm->envc + 1) * sizeof(char *); /* envv[] */
sp -= (bprm->argc + 1) * sizeof(char *); /* argv[] */
sp -= 1 * sizeof(unsigned long); /* argc */
csp -= sp & 15UL;
sp -= sp & 15UL;
/* put the ELF interpreter info on the stack */
#define NEW_AUX_ENT(id, val) \
do { \
struct { unsigned long _id, _val; } __user *ent; \
\
ent = (void __user *) csp; \
__put_user((id), &ent[nr]._id); \
__put_user((val), &ent[nr]._val); \
nr++; \
} while (0)
nr = 0;
csp -= 2 * sizeof(unsigned long);
NEW_AUX_ENT(AT_NULL, 0);
if (k_platform) {
nr = 0;
csp -= 2 * sizeof(unsigned long);
NEW_AUX_ENT(AT_PLATFORM,
(elf_addr_t) (unsigned long) u_platform);
}
if (k_base_platform) {
nr = 0;
csp -= 2 * sizeof(unsigned long);
NEW_AUX_ENT(AT_BASE_PLATFORM,
(elf_addr_t) (unsigned long) u_base_platform);
}
if (bprm->interp_flags & BINPRM_FLAGS_EXECFD) {
nr = 0;
csp -= 2 * sizeof(unsigned long);
NEW_AUX_ENT(AT_EXECFD, bprm->interp_data);
}
nr = 0;
csp -= DLINFO_ITEMS * 2 * sizeof(unsigned long);
NEW_AUX_ENT(AT_HWCAP, ELF_HWCAP);
#ifdef ELF_HWCAP2
NEW_AUX_ENT(AT_HWCAP2, ELF_HWCAP2);
#endif
NEW_AUX_ENT(AT_PAGESZ, PAGE_SIZE);
NEW_AUX_ENT(AT_CLKTCK, CLOCKS_PER_SEC);
NEW_AUX_ENT(AT_PHDR, exec_params->ph_addr);
NEW_AUX_ENT(AT_PHENT, sizeof(struct elf_phdr));
NEW_AUX_ENT(AT_PHNUM, exec_params->hdr.e_phnum);
NEW_AUX_ENT(AT_BASE, interp_params->elfhdr_addr);
NEW_AUX_ENT(AT_FLAGS, 0);
NEW_AUX_ENT(AT_ENTRY, exec_params->entry_addr);
NEW_AUX_ENT(AT_UID, (elf_addr_t) from_kuid_munged(cred->user_ns, cred->uid));
NEW_AUX_ENT(AT_EUID, (elf_addr_t) from_kuid_munged(cred->user_ns, cred->euid));
NEW_AUX_ENT(AT_GID, (elf_addr_t) from_kgid_munged(cred->user_ns, cred->gid));
NEW_AUX_ENT(AT_EGID, (elf_addr_t) from_kgid_munged(cred->user_ns, cred->egid));
NEW_AUX_ENT(AT_SECURE, security_bprm_secureexec(bprm));
NEW_AUX_ENT(AT_EXECFN, bprm->exec);
#ifdef ARCH_DLINFO
nr = 0;
csp -= AT_VECTOR_SIZE_ARCH * 2 * sizeof(unsigned long);
/* ARCH_DLINFO must come last so platform specific code can enforce
* special alignment requirements on the AUXV if necessary (eg. PPC).
*/
ARCH_DLINFO;
#endif
#undef NEW_AUX_ENT
/* allocate room for argv[] and envv[] */
csp -= (bprm->envc + 1) * sizeof(elf_caddr_t);
envp = (elf_caddr_t __user *) csp;
csp -= (bprm->argc + 1) * sizeof(elf_caddr_t);
argv = (elf_caddr_t __user *) csp;
/* stack argc */
csp -= sizeof(unsigned long);
__put_user(bprm->argc, (unsigned long __user *) csp);
BUG_ON(csp != sp);
/* fill in the argv[] array */
#ifdef CONFIG_MMU
current->mm->arg_start = bprm->p;
#else
current->mm->arg_start = current->mm->start_stack -
(MAX_ARG_PAGES * PAGE_SIZE - bprm->p);
#endif
p = (char __user *) current->mm->arg_start;
for (loop = bprm->argc; loop > 0; loop--) {
__put_user((elf_caddr_t) p, argv++);
len = strnlen_user(p, MAX_ARG_STRLEN);
if (!len || len > MAX_ARG_STRLEN)
return -EINVAL;
p += len;
}
__put_user(NULL, argv);
current->mm->arg_end = (unsigned long) p;
/* fill in the envv[] array */
current->mm->env_start = (unsigned long) p;
for (loop = bprm->envc; loop > 0; loop--) {
__put_user((elf_caddr_t)(unsigned long) p, envp++);
len = strnlen_user(p, MAX_ARG_STRLEN);
if (!len || len > MAX_ARG_STRLEN)
return -EINVAL;
p += len;
}
__put_user(NULL, envp);
current->mm->env_end = (unsigned long) p;
mm->start_stack = (unsigned long) sp;
return 0;
}
/*****************************************************************************/
/*
* transfer the program arguments and environment from the holding pages onto
* the stack
*/
#ifndef CONFIG_MMU
static int elf_fdpic_transfer_args_to_stack(struct linux_binprm *bprm,
unsigned long *_sp)
{
unsigned long index, stop, sp;
char *src;
int ret = 0;
stop = bprm->p >> PAGE_SHIFT;
sp = *_sp;
for (index = MAX_ARG_PAGES - 1; index >= stop; index--) {
src = kmap(bprm->page[index]);
sp -= PAGE_SIZE;
if (copy_to_user((void *) sp, src, PAGE_SIZE) != 0)
ret = -EFAULT;
kunmap(bprm->page[index]);
if (ret < 0)
goto out;
}
*_sp = (*_sp - (MAX_ARG_PAGES * PAGE_SIZE - bprm->p)) & ~15;
out:
return ret;
}
#endif
/*****************************************************************************/
/*
* load the appropriate binary image (executable or interpreter) into memory
* - we assume no MMU is available
* - if no other PIC bits are set in params->hdr->e_flags
* - we assume that the LOADable segments in the binary are independently relocatable
* - we assume R/O executable segments are shareable
* - else
* - we assume the loadable parts of the image to require fixed displacement
* - the image is not shareable
*/
static int elf_fdpic_map_file(struct elf_fdpic_params *params,
struct file *file,
struct mm_struct *mm,
const char *what)
{
struct elf32_fdpic_loadmap *loadmap;
#ifdef CONFIG_MMU
struct elf32_fdpic_loadseg *mseg;
#endif
struct elf32_fdpic_loadseg *seg;
struct elf32_phdr *phdr;
unsigned long load_addr, stop;
unsigned nloads, tmp;
size_t size;
int loop, ret;
/* allocate a load map table */
nloads = 0;
for (loop = 0; loop < params->hdr.e_phnum; loop++)
if (params->phdrs[loop].p_type == PT_LOAD)
nloads++;
if (nloads == 0)
return -ELIBBAD;
size = sizeof(*loadmap) + nloads * sizeof(*seg);
loadmap = kzalloc(size, GFP_KERNEL);
if (!loadmap)
return -ENOMEM;
params->loadmap = loadmap;
loadmap->version = ELF32_FDPIC_LOADMAP_VERSION;
loadmap->nsegs = nloads;
load_addr = params->load_addr;
seg = loadmap->segs;
/* map the requested LOADs into the memory space */
switch (params->flags & ELF_FDPIC_FLAG_ARRANGEMENT) {
case ELF_FDPIC_FLAG_CONSTDISP:
case ELF_FDPIC_FLAG_CONTIGUOUS:
#ifndef CONFIG_MMU
ret = elf_fdpic_map_file_constdisp_on_uclinux(params, file, mm);
if (ret < 0)
return ret;
break;
#endif
default:
ret = elf_fdpic_map_file_by_direct_mmap(params, file, mm);
if (ret < 0)
return ret;
break;
}
/* map the entry point */
if (params->hdr.e_entry) {
seg = loadmap->segs;
for (loop = loadmap->nsegs; loop > 0; loop--, seg++) {
if (params->hdr.e_entry >= seg->p_vaddr &&
params->hdr.e_entry < seg->p_vaddr + seg->p_memsz) {
params->entry_addr =
(params->hdr.e_entry - seg->p_vaddr) +
seg->addr;
break;
}
}
}
/* determine where the program header table has wound up if mapped */
stop = params->hdr.e_phoff;
stop += params->hdr.e_phnum * sizeof (struct elf_phdr);
phdr = params->phdrs;
for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
if (phdr->p_type != PT_LOAD)
continue;
if (phdr->p_offset > params->hdr.e_phoff ||
phdr->p_offset + phdr->p_filesz < stop)
continue;
seg = loadmap->segs;
for (loop = loadmap->nsegs; loop > 0; loop--, seg++) {
if (phdr->p_vaddr >= seg->p_vaddr &&
phdr->p_vaddr + phdr->p_filesz <=
seg->p_vaddr + seg->p_memsz) {
params->ph_addr =
(phdr->p_vaddr - seg->p_vaddr) +
seg->addr +
params->hdr.e_phoff - phdr->p_offset;
break;
}
}
break;
}
/* determine where the dynamic section has wound up if there is one */
phdr = params->phdrs;
for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
if (phdr->p_type != PT_DYNAMIC)
continue;
seg = loadmap->segs;
for (loop = loadmap->nsegs; loop > 0; loop--, seg++) {
if (phdr->p_vaddr >= seg->p_vaddr &&
phdr->p_vaddr + phdr->p_memsz <=
seg->p_vaddr + seg->p_memsz) {
params->dynamic_addr =
(phdr->p_vaddr - seg->p_vaddr) +
seg->addr;
/* check the dynamic section contains at least
* one item, and that the last item is a NULL
* entry */
if (phdr->p_memsz == 0 ||
phdr->p_memsz % sizeof(Elf32_Dyn) != 0)
goto dynamic_error;
tmp = phdr->p_memsz / sizeof(Elf32_Dyn);
if (((Elf32_Dyn *)
params->dynamic_addr)[tmp - 1].d_tag != 0)
goto dynamic_error;
break;
}
}
break;
}
/* now elide adjacent segments in the load map on MMU linux
* - on uClinux the holes between may actually be filled with system
* stuff or stuff from other processes
*/
#ifdef CONFIG_MMU
nloads = loadmap->nsegs;
mseg = loadmap->segs;
seg = mseg + 1;
for (loop = 1; loop < nloads; loop++) {
/* see if we have a candidate for merging */
if (seg->p_vaddr - mseg->p_vaddr == seg->addr - mseg->addr) {
load_addr = PAGE_ALIGN(mseg->addr + mseg->p_memsz);
if (load_addr == (seg->addr & PAGE_MASK)) {
mseg->p_memsz +=
load_addr -
(mseg->addr + mseg->p_memsz);
mseg->p_memsz += seg->addr & ~PAGE_MASK;
mseg->p_memsz += seg->p_memsz;
loadmap->nsegs--;
continue;
}
}
mseg++;
if (mseg != seg)
*mseg = *seg;
}
#endif
kdebug("Mapped Object [%s]:", what);
kdebug("- elfhdr : %lx", params->elfhdr_addr);
kdebug("- entry : %lx", params->entry_addr);
kdebug("- PHDR[] : %lx", params->ph_addr);
kdebug("- DYNAMIC[]: %lx", params->dynamic_addr);
seg = loadmap->segs;
for (loop = 0; loop < loadmap->nsegs; loop++, seg++)
kdebug("- LOAD[%d] : %08x-%08x [va=%x ms=%x]",
loop,
seg->addr, seg->addr + seg->p_memsz - 1,
seg->p_vaddr, seg->p_memsz);
return 0;
dynamic_error:
printk("ELF FDPIC %s with invalid DYNAMIC section (inode=%lu)\n",
what, file_inode(file)->i_ino);
return -ELIBBAD;
}
/*****************************************************************************/
/*
* map a file with constant displacement under uClinux
*/
#ifndef CONFIG_MMU
static int elf_fdpic_map_file_constdisp_on_uclinux(
struct elf_fdpic_params *params,
struct file *file,
struct mm_struct *mm)
{
struct elf32_fdpic_loadseg *seg;
struct elf32_phdr *phdr;
unsigned long load_addr, base = ULONG_MAX, top = 0, maddr = 0, mflags;
int loop, ret;
load_addr = params->load_addr;
seg = params->loadmap->segs;
/* determine the bounds of the contiguous overall allocation we must
* make */
phdr = params->phdrs;
for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
if (params->phdrs[loop].p_type != PT_LOAD)
continue;
if (base > phdr->p_vaddr)
base = phdr->p_vaddr;
if (top < phdr->p_vaddr + phdr->p_memsz)
top = phdr->p_vaddr + phdr->p_memsz;
}
/* allocate one big anon block for everything */
mflags = MAP_PRIVATE;
if (params->flags & ELF_FDPIC_FLAG_EXECUTABLE)
mflags |= MAP_EXECUTABLE;
maddr = vm_mmap(NULL, load_addr, top - base,
PROT_READ | PROT_WRITE | PROT_EXEC, mflags, 0);
if (IS_ERR_VALUE(maddr))
return (int) maddr;
if (load_addr != 0)
load_addr += PAGE_ALIGN(top - base);
/* and then load the file segments into it */
phdr = params->phdrs;
for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
if (params->phdrs[loop].p_type != PT_LOAD)
continue;
seg->addr = maddr + (phdr->p_vaddr - base);
seg->p_vaddr = phdr->p_vaddr;
seg->p_memsz = phdr->p_memsz;
ret = read_code(file, seg->addr, phdr->p_offset,
phdr->p_filesz);
if (ret < 0)
return ret;
/* map the ELF header address if in this segment */
if (phdr->p_offset == 0)
params->elfhdr_addr = seg->addr;
/* clear any space allocated but not loaded */
if (phdr->p_filesz < phdr->p_memsz) {
if (clear_user((void *) (seg->addr + phdr->p_filesz),
phdr->p_memsz - phdr->p_filesz))
return -EFAULT;
}
if (mm) {
if (phdr->p_flags & PF_X) {
if (!mm->start_code) {
mm->start_code = seg->addr;
mm->end_code = seg->addr +
phdr->p_memsz;
}
} else if (!mm->start_data) {
mm->start_data = seg->addr;
mm->end_data = seg->addr + phdr->p_memsz;
}
}
seg++;
}
return 0;
}
#endif
/*****************************************************************************/
/*
* map a binary by direct mmap() of the individual PT_LOAD segments
*/
static int elf_fdpic_map_file_by_direct_mmap(struct elf_fdpic_params *params,
struct file *file,
struct mm_struct *mm)
{
struct elf32_fdpic_loadseg *seg;
struct elf32_phdr *phdr;
unsigned long load_addr, delta_vaddr;
int loop, dvset;
load_addr = params->load_addr;
delta_vaddr = 0;
dvset = 0;
seg = params->loadmap->segs;
/* deal with each load segment separately */
phdr = params->phdrs;
for (loop = 0; loop < params->hdr.e_phnum; loop++, phdr++) {
unsigned long maddr, disp, excess, excess1;
int prot = 0, flags;
if (phdr->p_type != PT_LOAD)
continue;
kdebug("[LOAD] va=%lx of=%lx fs=%lx ms=%lx",
(unsigned long) phdr->p_vaddr,
(unsigned long) phdr->p_offset,
(unsigned long) phdr->p_filesz,
(unsigned long) phdr->p_memsz);
/* determine the mapping parameters */
if (phdr->p_flags & PF_R) prot |= PROT_READ;
if (phdr->p_flags & PF_W) prot |= PROT_WRITE;
if (phdr->p_flags & PF_X) prot |= PROT_EXEC;
flags = MAP_PRIVATE | MAP_DENYWRITE;
if (params->flags & ELF_FDPIC_FLAG_EXECUTABLE)
flags |= MAP_EXECUTABLE;
maddr = 0;
switch (params->flags & ELF_FDPIC_FLAG_ARRANGEMENT) {
case ELF_FDPIC_FLAG_INDEPENDENT:
/* PT_LOADs are independently locatable */
break;
case ELF_FDPIC_FLAG_HONOURVADDR:
/* the specified virtual address must be honoured */
maddr = phdr->p_vaddr;
flags |= MAP_FIXED;
break;
case ELF_FDPIC_FLAG_CONSTDISP:
/* constant displacement
* - can be mapped anywhere, but must be mapped as a
* unit
*/
if (!dvset) {
maddr = load_addr;
delta_vaddr = phdr->p_vaddr;
dvset = 1;
} else {
maddr = load_addr + phdr->p_vaddr - delta_vaddr;
flags |= MAP_FIXED;
}
break;
case ELF_FDPIC_FLAG_CONTIGUOUS:
/* contiguity handled later */
break;
default:
BUG();
}
maddr &= PAGE_MASK;
/* create the mapping */
disp = phdr->p_vaddr & ~PAGE_MASK;
maddr = vm_mmap(file, maddr, phdr->p_memsz + disp, prot, flags,
phdr->p_offset - disp);
kdebug("mmap[%d] <file> sz=%lx pr=%x fl=%x of=%lx --> %08lx",
loop, phdr->p_memsz + disp, prot, flags,
phdr->p_offset - disp, maddr);
if (IS_ERR_VALUE(maddr))
return (int) maddr;
if ((params->flags & ELF_FDPIC_FLAG_ARRANGEMENT) ==
ELF_FDPIC_FLAG_CONTIGUOUS)
load_addr += PAGE_ALIGN(phdr->p_memsz + disp);
seg->addr = maddr + disp;
seg->p_vaddr = phdr->p_vaddr;
seg->p_memsz = phdr->p_memsz;
/* map the ELF header address if in this segment */
if (phdr->p_offset == 0)
params->elfhdr_addr = seg->addr;
/* clear the bit between beginning of mapping and beginning of
* PT_LOAD */
if (prot & PROT_WRITE && disp > 0) {
kdebug("clear[%d] ad=%lx sz=%lx", loop, maddr, disp);
if (clear_user((void __user *) maddr, disp))
return -EFAULT;
maddr += disp;
}
/* clear any space allocated but not loaded
* - on uClinux we can just clear the lot
* - on MMU linux we'll get a SIGBUS beyond the last page
* extant in the file
*/
excess = phdr->p_memsz - phdr->p_filesz;
excess1 = PAGE_SIZE - ((maddr + phdr->p_filesz) & ~PAGE_MASK);
#ifdef CONFIG_MMU
if (excess > excess1) {
unsigned long xaddr = maddr + phdr->p_filesz + excess1;
unsigned long xmaddr;
flags |= MAP_FIXED | MAP_ANONYMOUS;
xmaddr = vm_mmap(NULL, xaddr, excess - excess1,
prot, flags, 0);
kdebug("mmap[%d] <anon>"
" ad=%lx sz=%lx pr=%x fl=%x of=0 --> %08lx",
loop, xaddr, excess - excess1, prot, flags,
xmaddr);
if (xmaddr != xaddr)
return -ENOMEM;
}
if (prot & PROT_WRITE && excess1 > 0) {
kdebug("clear[%d] ad=%lx sz=%lx",
loop, maddr + phdr->p_filesz, excess1);
if (clear_user((void __user *) maddr + phdr->p_filesz,
excess1))
return -EFAULT;
}
#else
if (excess > 0) {
kdebug("clear[%d] ad=%lx sz=%lx",
loop, maddr + phdr->p_filesz, excess);
if (clear_user((void *) maddr + phdr->p_filesz, excess))
return -EFAULT;
}
#endif
if (mm) {
if (phdr->p_flags & PF_X) {
if (!mm->start_code) {
mm->start_code = maddr;
mm->end_code = maddr + phdr->p_memsz;
}
} else if (!mm->start_data) {
mm->start_data = maddr;
mm->end_data = maddr + phdr->p_memsz;
}
}
seg++;
}
return 0;
}
/*****************************************************************************/
/*
* ELF-FDPIC core dumper
*
* Modelled on fs/exec.c:aout_core_dump()
* Jeremy Fitzhardinge <jeremy@sw.oz.au>
*
* Modelled on fs/binfmt_elf.c core dumper
*/
#ifdef CONFIG_ELF_CORE
/*
* Decide whether a segment is worth dumping; default is yes to be
* sure (missing info is worse than too much; etc).
* Personally I'd include everything, and use the coredump limit...
*
* I think we should skip something. But I am not sure how. H.J.
*/
static int maydump(struct vm_area_struct *vma, unsigned long mm_flags)
{
int dump_ok;
/* Do not dump I/O mapped devices or special mappings */
if (vma->vm_flags & VM_IO) {
kdcore("%08lx: %08lx: no (IO)", vma->vm_start, vma->vm_flags);
return 0;
}
/* If we may not read the contents, don't allow us to dump
* them either. "dump_write()" can't handle it anyway.
*/
if (!(vma->vm_flags & VM_READ)) {
kdcore("%08lx: %08lx: no (!read)", vma->vm_start, vma->vm_flags);
return 0;
}
/* By default, dump shared memory if mapped from an anonymous file. */
if (vma->vm_flags & VM_SHARED) {
if (file_inode(vma->vm_file)->i_nlink == 0) {
dump_ok = test_bit(MMF_DUMP_ANON_SHARED, &mm_flags);
kdcore("%08lx: %08lx: %s (share)", vma->vm_start,
vma->vm_flags, dump_ok ? "yes" : "no");
return dump_ok;
}
dump_ok = test_bit(MMF_DUMP_MAPPED_SHARED, &mm_flags);
kdcore("%08lx: %08lx: %s (share)", vma->vm_start,
vma->vm_flags, dump_ok ? "yes" : "no");
return dump_ok;
}
#ifdef CONFIG_MMU
/* By default, if it hasn't been written to, don't write it out */
if (!vma->anon_vma) {
dump_ok = test_bit(MMF_DUMP_MAPPED_PRIVATE, &mm_flags);
kdcore("%08lx: %08lx: %s (!anon)", vma->vm_start,
vma->vm_flags, dump_ok ? "yes" : "no");
return dump_ok;
}
#endif
dump_ok = test_bit(MMF_DUMP_ANON_PRIVATE, &mm_flags);
kdcore("%08lx: %08lx: %s", vma->vm_start, vma->vm_flags,
dump_ok ? "yes" : "no");
return dump_ok;
}
/* An ELF note in memory */
struct memelfnote
{
const char *name;
int type;
unsigned int datasz;
void *data;
};
static int notesize(struct memelfnote *en)
{
int sz;
sz = sizeof(struct elf_note);
sz += roundup(strlen(en->name) + 1, 4);
sz += roundup(en->datasz, 4);
return sz;
}
/* #define DEBUG */
static int writenote(struct memelfnote *men, struct coredump_params *cprm)
{
struct elf_note en;
en.n_namesz = strlen(men->name) + 1;
en.n_descsz = men->datasz;
en.n_type = men->type;
return dump_emit(cprm, &en, sizeof(en)) &&
dump_emit(cprm, men->name, en.n_namesz) && dump_align(cprm, 4) &&
dump_emit(cprm, men->data, men->datasz) && dump_align(cprm, 4);
}
static inline void fill_elf_fdpic_header(struct elfhdr *elf, int segs)
{
memcpy(elf->e_ident, ELFMAG, SELFMAG);
elf->e_ident[EI_CLASS] = ELF_CLASS;
elf->e_ident[EI_DATA] = ELF_DATA;
elf->e_ident[EI_VERSION] = EV_CURRENT;
elf->e_ident[EI_OSABI] = ELF_OSABI;
memset(elf->e_ident+EI_PAD, 0, EI_NIDENT-EI_PAD);
elf->e_type = ET_CORE;
elf->e_machine = ELF_ARCH;
elf->e_version = EV_CURRENT;
elf->e_entry = 0;
elf->e_phoff = sizeof(struct elfhdr);
elf->e_shoff = 0;
elf->e_flags = ELF_FDPIC_CORE_EFLAGS;
elf->e_ehsize = sizeof(struct elfhdr);
elf->e_phentsize = sizeof(struct elf_phdr);
elf->e_phnum = segs;
elf->e_shentsize = 0;
elf->e_shnum = 0;
elf->e_shstrndx = 0;
return;
}
static inline void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, loff_t offset)
{
phdr->p_type = PT_NOTE;
phdr->p_offset = offset;
phdr->p_vaddr = 0;
phdr->p_paddr = 0;
phdr->p_filesz = sz;
phdr->p_memsz = 0;
phdr->p_flags = 0;
phdr->p_align = 0;
return;
}
static inline void fill_note(struct memelfnote *note, const char *name, int type,
unsigned int sz, void *data)
{
note->name = name;
note->type = type;
note->datasz = sz;
note->data = data;
return;
}
/*
* fill up all the fields in prstatus from the given task struct, except
* registers which need to be filled up separately.
*/
static void fill_prstatus(struct elf_prstatus *prstatus,
struct task_struct *p, long signr)
{
prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
prstatus->pr_sigpend = p->pending.signal.sig[0];
prstatus->pr_sighold = p->blocked.sig[0];
rcu_read_lock();
prstatus->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
rcu_read_unlock();
prstatus->pr_pid = task_pid_vnr(p);
prstatus->pr_pgrp = task_pgrp_vnr(p);
prstatus->pr_sid = task_session_vnr(p);
if (thread_group_leader(p)) {
struct task_cputime cputime;
/*
* This is the record for the group leader. It shows the
* group-wide total, not its individual thread total.
*/
thread_group_cputime(p, &cputime);
cputime_to_timeval(cputime.utime, &prstatus->pr_utime);
cputime_to_timeval(cputime.stime, &prstatus->pr_stime);
} else {
cputime_t utime, stime;
task_cputime(p, &utime, &stime);
cputime_to_timeval(utime, &prstatus->pr_utime);
cputime_to_timeval(stime, &prstatus->pr_stime);
}
cputime_to_timeval(p->signal->cutime, &prstatus->pr_cutime);
cputime_to_timeval(p->signal->cstime, &prstatus->pr_cstime);
prstatus->pr_exec_fdpic_loadmap = p->mm->context.exec_fdpic_loadmap;
prstatus->pr_interp_fdpic_loadmap = p->mm->context.interp_fdpic_loadmap;
}
static int fill_psinfo(struct elf_prpsinfo *psinfo, struct task_struct *p,
struct mm_struct *mm)
{
const struct cred *cred;
unsigned int i, len;
/* first copy the parameters from user space */
memset(psinfo, 0, sizeof(struct elf_prpsinfo));
len = mm->arg_end - mm->arg_start;
if (len >= ELF_PRARGSZ)
len = ELF_PRARGSZ - 1;
if (copy_from_user(&psinfo->pr_psargs,
(const char __user *) mm->arg_start, len))
return -EFAULT;
for (i = 0; i < len; i++)
if (psinfo->pr_psargs[i] == 0)
psinfo->pr_psargs[i] = ' ';
psinfo->pr_psargs[len] = 0;
rcu_read_lock();
psinfo->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
rcu_read_unlock();
psinfo->pr_pid = task_pid_vnr(p);
psinfo->pr_pgrp = task_pgrp_vnr(p);
psinfo->pr_sid = task_session_vnr(p);
i = p->state ? ffz(~p->state) + 1 : 0;
psinfo->pr_state = i;
psinfo->pr_sname = (i > 5) ? '.' : "RSDTZW"[i];
psinfo->pr_zomb = psinfo->pr_sname == 'Z';
psinfo->pr_nice = task_nice(p);
psinfo->pr_flag = p->flags;
rcu_read_lock();
cred = __task_cred(p);
SET_UID(psinfo->pr_uid, from_kuid_munged(cred->user_ns, cred->uid));
SET_GID(psinfo->pr_gid, from_kgid_munged(cred->user_ns, cred->gid));
rcu_read_unlock();
strncpy(psinfo->pr_fname, p->comm, sizeof(psinfo->pr_fname));
return 0;
}
/* Here is the structure in which status of each thread is captured. */
struct elf_thread_status
{
struct list_head list;
struct elf_prstatus prstatus; /* NT_PRSTATUS */
elf_fpregset_t fpu; /* NT_PRFPREG */
struct task_struct *thread;
#ifdef ELF_CORE_COPY_XFPREGS
elf_fpxregset_t xfpu; /* ELF_CORE_XFPREG_TYPE */
#endif
struct memelfnote notes[3];
int num_notes;
};
/*
* In order to add the specific thread information for the elf file format,
* we need to keep a linked list of every thread's pr_status and then create
* a single section for them in the final core file.
*/
static int elf_dump_thread_status(long signr, struct elf_thread_status *t)
{
struct task_struct *p = t->thread;
int sz = 0;
t->num_notes = 0;
fill_prstatus(&t->prstatus, p, signr);
elf_core_copy_task_regs(p, &t->prstatus.pr_reg);
fill_note(&t->notes[0], "CORE", NT_PRSTATUS, sizeof(t->prstatus),
&t->prstatus);
t->num_notes++;
sz += notesize(&t->notes[0]);
t->prstatus.pr_fpvalid = elf_core_copy_task_fpregs(p, NULL, &t->fpu);
if (t->prstatus.pr_fpvalid) {
fill_note(&t->notes[1], "CORE", NT_PRFPREG, sizeof(t->fpu),
&t->fpu);
t->num_notes++;
sz += notesize(&t->notes[1]);
}
#ifdef ELF_CORE_COPY_XFPREGS
if (elf_core_copy_task_xfpregs(p, &t->xfpu)) {
fill_note(&t->notes[2], "LINUX", ELF_CORE_XFPREG_TYPE,
sizeof(t->xfpu), &t->xfpu);
t->num_notes++;
sz += notesize(&t->notes[2]);
}
#endif
return sz;
}
static void fill_extnum_info(struct elfhdr *elf, struct elf_shdr *shdr4extnum,
elf_addr_t e_shoff, int segs)
{
elf->e_shoff = e_shoff;
elf->e_shentsize = sizeof(*shdr4extnum);
elf->e_shnum = 1;
elf->e_shstrndx = SHN_UNDEF;
memset(shdr4extnum, 0, sizeof(*shdr4extnum));
shdr4extnum->sh_type = SHT_NULL;
shdr4extnum->sh_size = elf->e_shnum;
shdr4extnum->sh_link = elf->e_shstrndx;
shdr4extnum->sh_info = segs;
}
/*
* dump the segments for an MMU process
*/
static bool elf_fdpic_dump_segments(struct coredump_params *cprm)
{
struct vm_area_struct *vma;
for (vma = current->mm->mmap; vma; vma = vma->vm_next) {
unsigned long addr;
if (!maydump(vma, cprm->mm_flags))
continue;
#ifdef CONFIG_MMU
for (addr = vma->vm_start; addr < vma->vm_end;
addr += PAGE_SIZE) {
bool res;
struct page *page = get_dump_page(addr);
if (page) {
void *kaddr = kmap(page);
res = dump_emit(cprm, kaddr, PAGE_SIZE);
kunmap(page);
page_cache_release(page);
} else {
res = dump_skip(cprm, PAGE_SIZE);
}
if (!res)
return false;
}
#else
if (!dump_emit(cprm, (void *) vma->vm_start,
vma->vm_end - vma->vm_start))
return false;
#endif
}
return true;
}
static size_t elf_core_vma_data_size(unsigned long mm_flags)
{
struct vm_area_struct *vma;
size_t size = 0;
for (vma = current->mm->mmap; vma; vma = vma->vm_next)
if (maydump(vma, mm_flags))
size += vma->vm_end - vma->vm_start;
return size;
}
/*
* Actual dumper
*
* This is a two-pass process; first we find the offsets of the bits,
* and then they are actually written out. If we run out of core limit
* we just truncate.
*/
static int elf_fdpic_core_dump(struct coredump_params *cprm)
{
#define NUM_NOTES 6
int has_dumped = 0;
mm_segment_t fs;
int segs;
int i;
struct vm_area_struct *vma;
struct elfhdr *elf = NULL;
loff_t offset = 0, dataoff;
int numnote;
struct memelfnote *notes = NULL;
struct elf_prstatus *prstatus = NULL; /* NT_PRSTATUS */
struct elf_prpsinfo *psinfo = NULL; /* NT_PRPSINFO */
LIST_HEAD(thread_list);
struct list_head *t;
elf_fpregset_t *fpu = NULL;
#ifdef ELF_CORE_COPY_XFPREGS
elf_fpxregset_t *xfpu = NULL;
#endif
int thread_status_size = 0;
elf_addr_t *auxv;
struct elf_phdr *phdr4note = NULL;
struct elf_shdr *shdr4extnum = NULL;
Elf_Half e_phnum;
elf_addr_t e_shoff;
struct core_thread *ct;
struct elf_thread_status *tmp;
/*
* We no longer stop all VM operations.
*
* This is because those proceses that could possibly change map_count
* or the mmap / vma pages are now blocked in do_exit on current
* finishing this core dump.
*
* Only ptrace can touch these memory addresses, but it doesn't change
* the map_count or the pages allocated. So no possibility of crashing
* exists while dumping the mm->vm_next areas to the core file.
*/
/* alloc memory for large data structures: too large to be on stack */
elf = kmalloc(sizeof(*elf), GFP_KERNEL);
if (!elf)
goto cleanup;
prstatus = kzalloc(sizeof(*prstatus), GFP_KERNEL);
if (!prstatus)
goto cleanup;
psinfo = kmalloc(sizeof(*psinfo), GFP_KERNEL);
if (!psinfo)
goto cleanup;
notes = kmalloc(NUM_NOTES * sizeof(struct memelfnote), GFP_KERNEL);
if (!notes)
goto cleanup;
fpu = kmalloc(sizeof(*fpu), GFP_KERNEL);
if (!fpu)
goto cleanup;
#ifdef ELF_CORE_COPY_XFPREGS
xfpu = kmalloc(sizeof(*xfpu), GFP_KERNEL);
if (!xfpu)
goto cleanup;
#endif
for (ct = current->mm->core_state->dumper.next;
ct; ct = ct->next) {
tmp = kzalloc(sizeof(*tmp), GFP_KERNEL);
if (!tmp)
goto cleanup;
tmp->thread = ct->task;
list_add(&tmp->list, &thread_list);
}
list_for_each(t, &thread_list) {
struct elf_thread_status *tmp;
int sz;
tmp = list_entry(t, struct elf_thread_status, list);
sz = elf_dump_thread_status(cprm->siginfo->si_signo, tmp);
thread_status_size += sz;
}
/* now collect the dump for the current */
fill_prstatus(prstatus, current, cprm->siginfo->si_signo);
elf_core_copy_regs(&prstatus->pr_reg, cprm->regs);
segs = current->mm->map_count;
segs += elf_core_extra_phdrs();
/* for notes section */
segs++;
/* If segs > PN_XNUM(0xffff), then e_phnum overflows. To avoid
* this, kernel supports extended numbering. Have a look at
* include/linux/elf.h for further information. */
e_phnum = segs > PN_XNUM ? PN_XNUM : segs;
/* Set up header */
fill_elf_fdpic_header(elf, e_phnum);
has_dumped = 1;
/*
* Set up the notes in similar form to SVR4 core dumps made
* with info from their /proc.
*/
fill_note(notes + 0, "CORE", NT_PRSTATUS, sizeof(*prstatus), prstatus);
fill_psinfo(psinfo, current->group_leader, current->mm);
fill_note(notes + 1, "CORE", NT_PRPSINFO, sizeof(*psinfo), psinfo);
numnote = 2;
auxv = (elf_addr_t *) current->mm->saved_auxv;
i = 0;
do
i += 2;
while (auxv[i - 2] != AT_NULL);
fill_note(¬es[numnote++], "CORE", NT_AUXV,
i * sizeof(elf_addr_t), auxv);
/* Try to dump the FPU. */
if ((prstatus->pr_fpvalid =
elf_core_copy_task_fpregs(current, cprm->regs, fpu)))
fill_note(notes + numnote++,
"CORE", NT_PRFPREG, sizeof(*fpu), fpu);
#ifdef ELF_CORE_COPY_XFPREGS
if (elf_core_copy_task_xfpregs(current, xfpu))
fill_note(notes + numnote++,
"LINUX", ELF_CORE_XFPREG_TYPE, sizeof(*xfpu), xfpu);
#endif
fs = get_fs();
set_fs(KERNEL_DS);
offset += sizeof(*elf); /* Elf header */
offset += segs * sizeof(struct elf_phdr); /* Program headers */
/* Write notes phdr entry */
{
int sz = 0;
for (i = 0; i < numnote; i++)
sz += notesize(notes + i);
sz += thread_status_size;
phdr4note = kmalloc(sizeof(*phdr4note), GFP_KERNEL);
if (!phdr4note)
goto end_coredump;
fill_elf_note_phdr(phdr4note, sz, offset);
offset += sz;
}
/* Page-align dumped data */
dataoff = offset = roundup(offset, ELF_EXEC_PAGESIZE);
offset += elf_core_vma_data_size(cprm->mm_flags);
offset += elf_core_extra_data_size();
e_shoff = offset;
if (e_phnum == PN_XNUM) {
shdr4extnum = kmalloc(sizeof(*shdr4extnum), GFP_KERNEL);
if (!shdr4extnum)
goto end_coredump;
fill_extnum_info(elf, shdr4extnum, e_shoff, segs);
}
offset = dataoff;
if (!dump_emit(cprm, elf, sizeof(*elf)))
goto end_coredump;
if (!dump_emit(cprm, phdr4note, sizeof(*phdr4note)))
goto end_coredump;
/* write program headers for segments dump */
for (vma = current->mm->mmap; vma; vma = vma->vm_next) {
struct elf_phdr phdr;
size_t sz;
sz = vma->vm_end - vma->vm_start;
phdr.p_type = PT_LOAD;
phdr.p_offset = offset;
phdr.p_vaddr = vma->vm_start;
phdr.p_paddr = 0;
phdr.p_filesz = maydump(vma, cprm->mm_flags) ? sz : 0;
phdr.p_memsz = sz;
offset += phdr.p_filesz;
phdr.p_flags = vma->vm_flags & VM_READ ? PF_R : 0;
if (vma->vm_flags & VM_WRITE)
phdr.p_flags |= PF_W;
if (vma->vm_flags & VM_EXEC)
phdr.p_flags |= PF_X;
phdr.p_align = ELF_EXEC_PAGESIZE;
if (!dump_emit(cprm, &phdr, sizeof(phdr)))
goto end_coredump;
}
if (!elf_core_write_extra_phdrs(cprm, offset))
goto end_coredump;
/* write out the notes section */
for (i = 0; i < numnote; i++)
if (!writenote(notes + i, cprm))
goto end_coredump;
/* write out the thread status notes section */
list_for_each(t, &thread_list) {
struct elf_thread_status *tmp =
list_entry(t, struct elf_thread_status, list);
for (i = 0; i < tmp->num_notes; i++)
if (!writenote(&tmp->notes[i], cprm))
goto end_coredump;
}
if (!dump_skip(cprm, dataoff - cprm->written))
goto end_coredump;
if (!elf_fdpic_dump_segments(cprm))
goto end_coredump;
if (!elf_core_write_extra_data(cprm))
goto end_coredump;
if (e_phnum == PN_XNUM) {
if (!dump_emit(cprm, shdr4extnum, sizeof(*shdr4extnum)))
goto end_coredump;
}
if (cprm->file->f_pos != offset) {
/* Sanity check */
printk(KERN_WARNING
"elf_core_dump: file->f_pos (%lld) != offset (%lld)\n",
cprm->file->f_pos, offset);
}
end_coredump:
set_fs(fs);
cleanup:
while (!list_empty(&thread_list)) {
struct list_head *tmp = thread_list.next;
list_del(tmp);
kfree(list_entry(tmp, struct elf_thread_status, list));
}
kfree(phdr4note);
kfree(elf);
kfree(prstatus);
kfree(psinfo);
kfree(notes);
kfree(fpu);
kfree(shdr4extnum);
#ifdef ELF_CORE_COPY_XFPREGS
kfree(xfpu);
#endif
return has_dumped;
#undef NUM_NOTES
}
#endif /* CONFIG_ELF_CORE */
| gpl-2.0 |
STR4NG3R/android_kernel_motorola_msm8226 | drivers/staging/vt6656/dpc.c | 1541 | 55877 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* File: dpc.c
*
* Purpose: handle dpc rx functions
*
* Author: Lyndon Chen
*
* Date: May 20, 2003
*
* Functions:
* device_receive_frame - Rcv 802.11 frame function
* s_bAPModeRxCtl- AP Rcv frame filer Ctl.
* s_bAPModeRxData- AP Rcv data frame handle
* s_bHandleRxEncryption- Rcv decrypted data via on-fly
* s_bHostWepRxEncryption- Rcv encrypted data via host
* s_byGetRateIdx- get rate index
* s_vGetDASA- get data offset
* s_vProcessRxMACHeader- Rcv 802.11 and translate to 802.3
*
* Revision History:
*
*/
#include "device.h"
#include "rxtx.h"
#include "tether.h"
#include "card.h"
#include "bssdb.h"
#include "mac.h"
#include "baseband.h"
#include "michael.h"
#include "tkip.h"
#include "tcrc.h"
#include "wctl.h"
#include "hostap.h"
#include "rf.h"
#include "iowpa.h"
#include "aes_ccmp.h"
#include "datarate.h"
#include "usbpipe.h"
/*--------------------- Static Definitions -------------------------*/
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
//static int msglevel =MSG_LEVEL_DEBUG;
static int msglevel =MSG_LEVEL_INFO;
const BYTE acbyRxRate[MAX_RATE] =
{2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108};
/*--------------------- Static Functions --------------------------*/
/*--------------------- Static Definitions -------------------------*/
/*--------------------- Static Functions --------------------------*/
static BYTE s_byGetRateIdx(BYTE byRate);
static
void
s_vGetDASA(
PBYTE pbyRxBufferAddr,
unsigned int *pcbHeaderSize,
PSEthernetHeader psEthHeader
);
static
void
s_vProcessRxMACHeader (
PSDevice pDevice,
PBYTE pbyRxBufferAddr,
unsigned int cbPacketSize,
BOOL bIsWEP,
BOOL bExtIV,
unsigned int *pcbHeadSize
);
static BOOL s_bAPModeRxCtl(
PSDevice pDevice,
PBYTE pbyFrame,
signed int iSANodeIndex
);
static BOOL s_bAPModeRxData (
PSDevice pDevice,
struct sk_buff *skb,
unsigned int FrameSize,
unsigned int cbHeaderOffset,
signed int iSANodeIndex,
signed int iDANodeIndex
);
static BOOL s_bHandleRxEncryption(
PSDevice pDevice,
PBYTE pbyFrame,
unsigned int FrameSize,
PBYTE pbyRsr,
PBYTE pbyNewRsr,
PSKeyItem * pKeyOut,
int * pbExtIV,
PWORD pwRxTSC15_0,
PDWORD pdwRxTSC47_16
);
static BOOL s_bHostWepRxEncryption(
PSDevice pDevice,
PBYTE pbyFrame,
unsigned int FrameSize,
PBYTE pbyRsr,
BOOL bOnFly,
PSKeyItem pKey,
PBYTE pbyNewRsr,
int * pbExtIV,
PWORD pwRxTSC15_0,
PDWORD pdwRxTSC47_16
);
/*--------------------- Export Variables --------------------------*/
/*+
*
* Description:
* Translate Rcv 802.11 header to 802.3 header with Rx buffer
*
* Parameters:
* In:
* pDevice
* dwRxBufferAddr - Address of Rcv Buffer
* cbPacketSize - Rcv Packet size
* bIsWEP - If Rcv with WEP
* Out:
* pcbHeaderSize - 802.11 header size
*
* Return Value: None
*
-*/
static
void
s_vProcessRxMACHeader (
PSDevice pDevice,
PBYTE pbyRxBufferAddr,
unsigned int cbPacketSize,
BOOL bIsWEP,
BOOL bExtIV,
unsigned int *pcbHeadSize
)
{
PBYTE pbyRxBuffer;
unsigned int cbHeaderSize = 0;
PWORD pwType;
PS802_11Header pMACHeader;
int ii;
pMACHeader = (PS802_11Header) (pbyRxBufferAddr + cbHeaderSize);
s_vGetDASA((PBYTE)pMACHeader, &cbHeaderSize, &pDevice->sRxEthHeader);
if (bIsWEP) {
if (bExtIV) {
// strip IV&ExtIV , add 8 byte
cbHeaderSize += (WLAN_HDR_ADDR3_LEN + 8);
} else {
// strip IV , add 4 byte
cbHeaderSize += (WLAN_HDR_ADDR3_LEN + 4);
}
}
else {
cbHeaderSize += WLAN_HDR_ADDR3_LEN;
};
pbyRxBuffer = (PBYTE) (pbyRxBufferAddr + cbHeaderSize);
if (!compare_ether_addr(pbyRxBuffer, &pDevice->abySNAP_Bridgetunnel[0])) {
cbHeaderSize += 6;
} else if (!compare_ether_addr(pbyRxBuffer, &pDevice->abySNAP_RFC1042[0])) {
cbHeaderSize += 6;
pwType = (PWORD) (pbyRxBufferAddr + cbHeaderSize);
if ((*pwType == cpu_to_be16(ETH_P_IPX)) ||
(*pwType == cpu_to_le16(0xF380))) {
cbHeaderSize -= 8;
pwType = (PWORD) (pbyRxBufferAddr + cbHeaderSize);
if (bIsWEP) {
if (bExtIV) {
*pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN - 8); // 8 is IV&ExtIV
} else {
*pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN - 4); // 4 is IV
}
}
else {
*pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN);
}
}
}
else {
cbHeaderSize -= 2;
pwType = (PWORD) (pbyRxBufferAddr + cbHeaderSize);
if (bIsWEP) {
if (bExtIV) {
*pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN - 8); // 8 is IV&ExtIV
} else {
*pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN - 4); // 4 is IV
}
}
else {
*pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN);
}
}
cbHeaderSize -= (ETH_ALEN * 2);
pbyRxBuffer = (PBYTE) (pbyRxBufferAddr + cbHeaderSize);
for (ii = 0; ii < ETH_ALEN; ii++)
*pbyRxBuffer++ = pDevice->sRxEthHeader.abyDstAddr[ii];
for (ii = 0; ii < ETH_ALEN; ii++)
*pbyRxBuffer++ = pDevice->sRxEthHeader.abySrcAddr[ii];
*pcbHeadSize = cbHeaderSize;
}
static BYTE s_byGetRateIdx(BYTE byRate)
{
BYTE byRateIdx;
for (byRateIdx = 0; byRateIdx <MAX_RATE ; byRateIdx++) {
if (acbyRxRate[byRateIdx%MAX_RATE] == byRate)
return byRateIdx;
}
return 0;
}
static
void
s_vGetDASA (
PBYTE pbyRxBufferAddr,
unsigned int *pcbHeaderSize,
PSEthernetHeader psEthHeader
)
{
unsigned int cbHeaderSize = 0;
PS802_11Header pMACHeader;
int ii;
pMACHeader = (PS802_11Header) (pbyRxBufferAddr + cbHeaderSize);
if ((pMACHeader->wFrameCtl & FC_TODS) == 0) {
if (pMACHeader->wFrameCtl & FC_FROMDS) {
for (ii = 0; ii < ETH_ALEN; ii++) {
psEthHeader->abyDstAddr[ii] =
pMACHeader->abyAddr1[ii];
psEthHeader->abySrcAddr[ii] =
pMACHeader->abyAddr3[ii];
}
} else {
/* IBSS mode */
for (ii = 0; ii < ETH_ALEN; ii++) {
psEthHeader->abyDstAddr[ii] =
pMACHeader->abyAddr1[ii];
psEthHeader->abySrcAddr[ii] =
pMACHeader->abyAddr2[ii];
}
}
} else {
/* Is AP mode.. */
if (pMACHeader->wFrameCtl & FC_FROMDS) {
for (ii = 0; ii < ETH_ALEN; ii++) {
psEthHeader->abyDstAddr[ii] =
pMACHeader->abyAddr3[ii];
psEthHeader->abySrcAddr[ii] =
pMACHeader->abyAddr4[ii];
cbHeaderSize += 6;
}
} else {
for (ii = 0; ii < ETH_ALEN; ii++) {
psEthHeader->abyDstAddr[ii] =
pMACHeader->abyAddr3[ii];
psEthHeader->abySrcAddr[ii] =
pMACHeader->abyAddr2[ii];
}
}
};
*pcbHeaderSize = cbHeaderSize;
}
BOOL
RXbBulkInProcessData (
PSDevice pDevice,
PRCB pRCB,
unsigned long BytesToIndicate
)
{
struct net_device_stats* pStats=&pDevice->stats;
struct sk_buff* skb;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
PSRxMgmtPacket pRxPacket = &(pMgmt->sRxPacket);
PS802_11Header p802_11Header;
PBYTE pbyRsr;
PBYTE pbyNewRsr;
PBYTE pbyRSSI;
PQWORD pqwTSFTime;
PBYTE pbyFrame;
BOOL bDeFragRx = FALSE;
unsigned int cbHeaderOffset;
unsigned int FrameSize;
WORD wEtherType = 0;
signed int iSANodeIndex = -1;
signed int iDANodeIndex = -1;
unsigned int ii;
unsigned int cbIVOffset;
PBYTE pbyRxSts;
PBYTE pbyRxRate;
PBYTE pbySQ;
PBYTE pby3SQ;
unsigned int cbHeaderSize;
PSKeyItem pKey = NULL;
WORD wRxTSC15_0 = 0;
DWORD dwRxTSC47_16 = 0;
SKeyItem STempKey;
// 802.11h RPI
/* signed long ldBm = 0; */
BOOL bIsWEP = FALSE;
BOOL bExtIV = FALSE;
DWORD dwWbkStatus;
PRCB pRCBIndicate = pRCB;
PBYTE pbyDAddress;
PWORD pwPLCP_Length;
BYTE abyVaildRate[MAX_RATE] = {2,4,11,22,12,18,24,36,48,72,96,108};
WORD wPLCPwithPadding;
PS802_11Header pMACHeader;
BOOL bRxeapol_key = FALSE;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"---------- RXbBulkInProcessData---\n");
skb = pRCB->skb;
//[31:16]RcvByteCount ( not include 4-byte Status )
dwWbkStatus = *( (PDWORD)(skb->data) );
FrameSize = (unsigned int)(dwWbkStatus >> 16);
FrameSize += 4;
if (BytesToIndicate != FrameSize) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"---------- WRONG Length 1 \n");
return FALSE;
}
if ((BytesToIndicate > 2372) || (BytesToIndicate <= 40)) {
// Frame Size error drop this packet.
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "---------- WRONG Length 2\n");
return FALSE;
}
pbyDAddress = (PBYTE)(skb->data);
pbyRxSts = pbyDAddress+4;
pbyRxRate = pbyDAddress+5;
//real Frame Size = USBFrameSize -4WbkStatus - 4RxStatus - 8TSF - 4RSR - 4SQ3 - ?Padding
//if SQ3 the range is 24~27, if no SQ3 the range is 20~23
//real Frame size in PLCPLength field.
pwPLCP_Length = (PWORD) (pbyDAddress + 6);
//Fix hardware bug => PLCP_Length error
if ( ((BytesToIndicate - (*pwPLCP_Length)) > 27) ||
((BytesToIndicate - (*pwPLCP_Length)) < 24) ||
(BytesToIndicate < (*pwPLCP_Length)) ) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Wrong PLCP Length %x\n", (int) *pwPLCP_Length);
ASSERT(0);
return FALSE;
}
for ( ii=RATE_1M;ii<MAX_RATE;ii++) {
if ( *pbyRxRate == abyVaildRate[ii] ) {
break;
}
}
if ( ii==MAX_RATE ) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Wrong RxRate %x\n",(int) *pbyRxRate);
return FALSE;
}
wPLCPwithPadding = ( (*pwPLCP_Length / 4) + ( (*pwPLCP_Length % 4) ? 1:0 ) ) *4;
pqwTSFTime = (PQWORD) (pbyDAddress + 8 + wPLCPwithPadding);
if(pDevice->byBBType == BB_TYPE_11G) {
pby3SQ = pbyDAddress + 8 + wPLCPwithPadding + 12;
pbySQ = pby3SQ;
}
else {
pbySQ = pbyDAddress + 8 + wPLCPwithPadding + 8;
pby3SQ = pbySQ;
}
pbyNewRsr = pbyDAddress + 8 + wPLCPwithPadding + 9;
pbyRSSI = pbyDAddress + 8 + wPLCPwithPadding + 10;
pbyRsr = pbyDAddress + 8 + wPLCPwithPadding + 11;
FrameSize = *pwPLCP_Length;
pbyFrame = pbyDAddress + 8;
// update receive statistic counter
STAvUpdateRDStatCounter(&pDevice->scStatistic,
*pbyRsr,
*pbyNewRsr,
*pbyRxSts,
*pbyRxRate,
pbyFrame,
FrameSize
);
pMACHeader = (PS802_11Header) pbyFrame;
//mike add: to judge if current AP is activated?
if ((pMgmt->eCurrMode == WMAC_MODE_STANDBY) ||
(pMgmt->eCurrMode == WMAC_MODE_ESS_STA)) {
if (pMgmt->sNodeDBTable[0].bActive) {
if (!compare_ether_addr(pMgmt->abyCurrBSSID, pMACHeader->abyAddr2)) {
if (pMgmt->sNodeDBTable[0].uInActiveCount != 0)
pMgmt->sNodeDBTable[0].uInActiveCount = 0;
}
}
}
if (!is_multicast_ether_addr(pMACHeader->abyAddr1) && !is_broadcast_ether_addr(pMACHeader->abyAddr1)) {
if ( WCTLbIsDuplicate(&(pDevice->sDupRxCache), (PS802_11Header) pbyFrame) ) {
pDevice->s802_11Counter.FrameDuplicateCount++;
return FALSE;
}
if (compare_ether_addr(pDevice->abyCurrentNetAddr,
pMACHeader->abyAddr1)) {
return FALSE;
}
}
// Use for TKIP MIC
s_vGetDASA(pbyFrame, &cbHeaderSize, &pDevice->sRxEthHeader);
if (!compare_ether_addr((PBYTE)&(pDevice->sRxEthHeader.abySrcAddr[0]),
pDevice->abyCurrentNetAddr))
return FALSE;
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) || (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA)) {
if (IS_CTL_PSPOLL(pbyFrame) || !IS_TYPE_CONTROL(pbyFrame)) {
p802_11Header = (PS802_11Header) (pbyFrame);
// get SA NodeIndex
if (BSSbIsSTAInNodeDB(pDevice, (PBYTE)(p802_11Header->abyAddr2), &iSANodeIndex)) {
pMgmt->sNodeDBTable[iSANodeIndex].ulLastRxJiffer = jiffies;
pMgmt->sNodeDBTable[iSANodeIndex].uInActiveCount = 0;
}
}
}
if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
if (s_bAPModeRxCtl(pDevice, pbyFrame, iSANodeIndex) == TRUE) {
return FALSE;
}
}
if (IS_FC_WEP(pbyFrame)) {
BOOL bRxDecryOK = FALSE;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"rx WEP pkt\n");
bIsWEP = TRUE;
if ((pDevice->bEnableHostWEP) && (iSANodeIndex >= 0)) {
pKey = &STempKey;
pKey->byCipherSuite = pMgmt->sNodeDBTable[iSANodeIndex].byCipherSuite;
pKey->dwKeyIndex = pMgmt->sNodeDBTable[iSANodeIndex].dwKeyIndex;
pKey->uKeyLength = pMgmt->sNodeDBTable[iSANodeIndex].uWepKeyLength;
pKey->dwTSC47_16 = pMgmt->sNodeDBTable[iSANodeIndex].dwTSC47_16;
pKey->wTSC15_0 = pMgmt->sNodeDBTable[iSANodeIndex].wTSC15_0;
memcpy(pKey->abyKey,
&pMgmt->sNodeDBTable[iSANodeIndex].abyWepKey[0],
pKey->uKeyLength
);
bRxDecryOK = s_bHostWepRxEncryption(pDevice,
pbyFrame,
FrameSize,
pbyRsr,
pMgmt->sNodeDBTable[iSANodeIndex].bOnFly,
pKey,
pbyNewRsr,
&bExtIV,
&wRxTSC15_0,
&dwRxTSC47_16);
} else {
bRxDecryOK = s_bHandleRxEncryption(pDevice,
pbyFrame,
FrameSize,
pbyRsr,
pbyNewRsr,
&pKey,
&bExtIV,
&wRxTSC15_0,
&dwRxTSC47_16);
}
if (bRxDecryOK) {
if ((*pbyNewRsr & NEWRSR_DECRYPTOK) == 0) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV Fail\n");
if ( (pMgmt->eAuthenMode == WMAC_AUTH_WPA) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) {
if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_TKIP)) {
pDevice->s802_11Counter.TKIPICVErrors++;
} else if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_CCMP)) {
pDevice->s802_11Counter.CCMPDecryptErrors++;
} else if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_WEP)) {
// pDevice->s802_11Counter.WEPICVErrorCount.QuadPart++;
}
}
return FALSE;
}
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"WEP Func Fail\n");
return FALSE;
}
if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_CCMP))
FrameSize -= 8; // Message Integrity Code
else
FrameSize -= 4; // 4 is ICV
}
//
// RX OK
//
/* remove the FCS/CRC length */
FrameSize -= ETH_FCS_LEN;
if ( !(*pbyRsr & (RSR_ADDRBROAD | RSR_ADDRMULTI)) && // unicast address
(IS_FRAGMENT_PKT((pbyFrame)))
) {
// defragment
bDeFragRx = WCTLbHandleFragment(pDevice, (PS802_11Header) (pbyFrame), FrameSize, bIsWEP, bExtIV);
pDevice->s802_11Counter.ReceivedFragmentCount++;
if (bDeFragRx) {
// defrag complete
// TODO skb, pbyFrame
skb = pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].skb;
FrameSize = pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].cbFrameLength;
pbyFrame = skb->data + 8;
}
else {
return FALSE;
}
}
//
// Management & Control frame Handle
//
if ((IS_TYPE_DATA((pbyFrame))) == FALSE) {
// Handle Control & Manage Frame
if (IS_TYPE_MGMT((pbyFrame))) {
PBYTE pbyData1;
PBYTE pbyData2;
pRxPacket = &(pRCB->sMngPacket);
pRxPacket->p80211Header = (PUWLAN_80211HDR)(pbyFrame);
pRxPacket->cbMPDULen = FrameSize;
pRxPacket->uRSSI = *pbyRSSI;
pRxPacket->bySQ = *pbySQ;
HIDWORD(pRxPacket->qwLocalTSF) = cpu_to_le32(HIDWORD(*pqwTSFTime));
LODWORD(pRxPacket->qwLocalTSF) = cpu_to_le32(LODWORD(*pqwTSFTime));
if (bIsWEP) {
// strip IV
pbyData1 = WLAN_HDR_A3_DATA_PTR(pbyFrame);
pbyData2 = WLAN_HDR_A3_DATA_PTR(pbyFrame) + 4;
for (ii = 0; ii < (FrameSize - 4); ii++) {
*pbyData1 = *pbyData2;
pbyData1++;
pbyData2++;
}
}
pRxPacket->byRxRate = s_byGetRateIdx(*pbyRxRate);
if ( *pbyRxSts == 0 ) {
//Discard beacon packet which channel is 0
if ( (WLAN_GET_FC_FSTYPE((pRxPacket->p80211Header->sA3.wFrameCtl)) == WLAN_FSTYPE_BEACON) ||
(WLAN_GET_FC_FSTYPE((pRxPacket->p80211Header->sA3.wFrameCtl)) == WLAN_FSTYPE_PROBERESP) ) {
return TRUE;
}
}
pRxPacket->byRxChannel = (*pbyRxSts) >> 2;
// hostap Deamon handle 802.11 management
if (pDevice->bEnableHostapd) {
skb->dev = pDevice->apdev;
//skb->data += 4;
//skb->tail += 4;
skb->data += 8;
skb->tail += 8;
skb_put(skb, FrameSize);
skb_reset_mac_header(skb);
skb->pkt_type = PACKET_OTHERHOST;
skb->protocol = htons(ETH_P_802_2);
memset(skb->cb, 0, sizeof(skb->cb));
netif_rx(skb);
return TRUE;
}
//
// Insert the RCB in the Recv Mng list
//
EnqueueRCB(pDevice->FirstRecvMngList, pDevice->LastRecvMngList, pRCBIndicate);
pDevice->NumRecvMngList++;
if ( bDeFragRx == FALSE) {
pRCB->Ref++;
}
if (pDevice->bIsRxMngWorkItemQueued == FALSE) {
pDevice->bIsRxMngWorkItemQueued = TRUE;
tasklet_schedule(&pDevice->RxMngWorkItem);
}
}
else {
// Control Frame
};
return FALSE;
}
else {
if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
//In AP mode, hw only check addr1(BSSID or RA) if equal to local MAC.
if ( !(*pbyRsr & RSR_BSSIDOK)) {
if (bDeFragRx) {
if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
pDevice->dev->name);
}
}
return FALSE;
}
}
else {
// discard DATA packet while not associate || BSSID error
if ((pDevice->bLinkPass == FALSE) ||
!(*pbyRsr & RSR_BSSIDOK)) {
if (bDeFragRx) {
if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
pDevice->dev->name);
}
}
return FALSE;
}
//mike add:station mode check eapol-key challenge--->
{
BYTE Protocol_Version; //802.1x Authentication
BYTE Packet_Type; //802.1x Authentication
BYTE Descriptor_type;
WORD Key_info;
if (bIsWEP)
cbIVOffset = 8;
else
cbIVOffset = 0;
wEtherType = (skb->data[cbIVOffset + 8 + 24 + 6] << 8) |
skb->data[cbIVOffset + 8 + 24 + 6 + 1];
Protocol_Version = skb->data[cbIVOffset + 8 + 24 + 6 + 1 +1];
Packet_Type = skb->data[cbIVOffset + 8 + 24 + 6 + 1 +1+1];
if (wEtherType == ETH_P_PAE) { //Protocol Type in LLC-Header
if(((Protocol_Version==1) ||(Protocol_Version==2)) &&
(Packet_Type==3)) { //802.1x OR eapol-key challenge frame receive
bRxeapol_key = TRUE;
Descriptor_type = skb->data[cbIVOffset + 8 + 24 + 6 + 1 +1+1+1+2];
Key_info = (skb->data[cbIVOffset + 8 + 24 + 6 + 1 +1+1+1+2+1]<<8) |skb->data[cbIVOffset + 8 + 24 + 6 + 1 +1+1+1+2+2] ;
if(Descriptor_type==2) { //RSN
// printk("WPA2_Rx_eapol-key_info<-----:%x\n",Key_info);
}
else if(Descriptor_type==254) {
// printk("WPA_Rx_eapol-key_info<-----:%x\n",Key_info);
}
}
}
}
//mike add:station mode check eapol-key challenge<---
}
}
// Data frame Handle
if (pDevice->bEnablePSMode) {
if (IS_FC_MOREDATA((pbyFrame))) {
if (*pbyRsr & RSR_ADDROK) {
//PSbSendPSPOLL((PSDevice)pDevice);
}
}
else {
if (pMgmt->bInTIMWake == TRUE) {
pMgmt->bInTIMWake = FALSE;
}
}
}
// Now it only supports 802.11g Infrastructure Mode, and support rate must up to 54 Mbps
if (pDevice->bDiversityEnable && (FrameSize>50) &&
(pDevice->eOPMode == OP_MODE_INFRASTRUCTURE) &&
(pDevice->bLinkPass == TRUE)) {
BBvAntennaDiversity(pDevice, s_byGetRateIdx(*pbyRxRate), 0);
}
// ++++++++ For BaseBand Algorithm +++++++++++++++
pDevice->uCurrRSSI = *pbyRSSI;
pDevice->byCurrSQ = *pbySQ;
// todo
/*
if ((*pbyRSSI != 0) &&
(pMgmt->pCurrBSS!=NULL)) {
RFvRSSITodBm(pDevice, *pbyRSSI, &ldBm);
// Moniter if RSSI is too strong.
pMgmt->pCurrBSS->byRSSIStatCnt++;
pMgmt->pCurrBSS->byRSSIStatCnt %= RSSI_STAT_COUNT;
pMgmt->pCurrBSS->ldBmAverage[pMgmt->pCurrBSS->byRSSIStatCnt] = ldBm;
for (ii = 0; ii < RSSI_STAT_COUNT; ii++) {
if (pMgmt->pCurrBSS->ldBmAverage[ii] != 0) {
pMgmt->pCurrBSS->ldBmMAX =
max(pMgmt->pCurrBSS->ldBmAverage[ii], ldBm);
}
}
}
*/
// -----------------------------------------------
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) && (pDevice->bEnable8021x == TRUE)){
BYTE abyMacHdr[24];
// Only 802.1x packet incoming allowed
if (bIsWEP)
cbIVOffset = 8;
else
cbIVOffset = 0;
wEtherType = (skb->data[cbIVOffset + 8 + 24 + 6] << 8) |
skb->data[cbIVOffset + 8 + 24 + 6 + 1];
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wEtherType = %04x \n", wEtherType);
if (wEtherType == ETH_P_PAE) {
skb->dev = pDevice->apdev;
if (bIsWEP == TRUE) {
// strip IV header(8)
memcpy(&abyMacHdr[0], (skb->data + 8), 24);
memcpy((skb->data + 8 + cbIVOffset), &abyMacHdr[0], 24);
}
skb->data += (cbIVOffset + 8);
skb->tail += (cbIVOffset + 8);
skb_put(skb, FrameSize);
skb_reset_mac_header(skb);
skb->pkt_type = PACKET_OTHERHOST;
skb->protocol = htons(ETH_P_802_2);
memset(skb->cb, 0, sizeof(skb->cb));
netif_rx(skb);
return TRUE;
}
// check if 802.1x authorized
if (!(pMgmt->sNodeDBTable[iSANodeIndex].dwFlags & WLAN_STA_AUTHORIZED))
return FALSE;
}
if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_TKIP)) {
if (bIsWEP) {
FrameSize -= 8; //MIC
}
}
//--------------------------------------------------------------------------------
// Soft MIC
if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_TKIP)) {
if (bIsWEP) {
PDWORD pdwMIC_L;
PDWORD pdwMIC_R;
DWORD dwMIC_Priority;
DWORD dwMICKey0 = 0, dwMICKey1 = 0;
DWORD dwLocalMIC_L = 0;
DWORD dwLocalMIC_R = 0;
viawget_wpa_header *wpahdr;
if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
dwMICKey0 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[24]));
dwMICKey1 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[28]));
}
else {
if (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) {
dwMICKey0 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[16]));
dwMICKey1 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[20]));
} else if ((pKey->dwKeyIndex & BIT28) == 0) {
dwMICKey0 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[16]));
dwMICKey1 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[20]));
} else {
dwMICKey0 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[24]));
dwMICKey1 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[28]));
}
}
MIC_vInit(dwMICKey0, dwMICKey1);
MIC_vAppend((PBYTE)&(pDevice->sRxEthHeader.abyDstAddr[0]), 12);
dwMIC_Priority = 0;
MIC_vAppend((PBYTE)&dwMIC_Priority, 4);
// 4 is Rcv buffer header, 24 is MAC Header, and 8 is IV and Ext IV.
MIC_vAppend((PBYTE)(skb->data + 8 + WLAN_HDR_ADDR3_LEN + 8),
FrameSize - WLAN_HDR_ADDR3_LEN - 8);
MIC_vGetMIC(&dwLocalMIC_L, &dwLocalMIC_R);
MIC_vUnInit();
pdwMIC_L = (PDWORD)(skb->data + 8 + FrameSize);
pdwMIC_R = (PDWORD)(skb->data + 8 + FrameSize + 4);
if ((cpu_to_le32(*pdwMIC_L) != dwLocalMIC_L) || (cpu_to_le32(*pdwMIC_R) != dwLocalMIC_R) ||
(pDevice->bRxMICFail == TRUE)) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIC comparison is fail!\n");
pDevice->bRxMICFail = FALSE;
//pDevice->s802_11Counter.TKIPLocalMICFailures.QuadPart++;
pDevice->s802_11Counter.TKIPLocalMICFailures++;
if (bDeFragRx) {
if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
pDevice->dev->name);
}
}
#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
//send event to wpa_supplicant
//if(pDevice->bWPASuppWextEnabled == TRUE)
{
union iwreq_data wrqu;
struct iw_michaelmicfailure ev;
int keyidx = pbyFrame[cbHeaderSize+3] >> 6; //top two-bits
memset(&ev, 0, sizeof(ev));
ev.flags = keyidx & IW_MICFAILURE_KEY_ID;
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
(pMgmt->eCurrState == WMAC_STATE_ASSOC) &&
(*pbyRsr & (RSR_ADDRBROAD | RSR_ADDRMULTI)) == 0) {
ev.flags |= IW_MICFAILURE_PAIRWISE;
} else {
ev.flags |= IW_MICFAILURE_GROUP;
}
ev.src_addr.sa_family = ARPHRD_ETHER;
memcpy(ev.src_addr.sa_data, pMACHeader->abyAddr2, ETH_ALEN);
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.length = sizeof(ev);
PRINT_K("wireless_send_event--->IWEVMICHAELMICFAILURE\n");
wireless_send_event(pDevice->dev, IWEVMICHAELMICFAILURE, &wrqu, (char *)&ev);
}
#endif
if ((pDevice->bWPADEVUp) && (pDevice->skb != NULL)) {
wpahdr = (viawget_wpa_header *)pDevice->skb->data;
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
(pMgmt->eCurrState == WMAC_STATE_ASSOC) &&
(*pbyRsr & (RSR_ADDRBROAD | RSR_ADDRMULTI)) == 0) {
//s802_11_Status.Flags = NDIS_802_11_AUTH_REQUEST_PAIRWISE_ERROR;
wpahdr->type = VIAWGET_PTK_MIC_MSG;
} else {
//s802_11_Status.Flags = NDIS_802_11_AUTH_REQUEST_GROUP_ERROR;
wpahdr->type = VIAWGET_GTK_MIC_MSG;
}
wpahdr->resp_ie_len = 0;
wpahdr->req_ie_len = 0;
skb_put(pDevice->skb, sizeof(viawget_wpa_header));
pDevice->skb->dev = pDevice->wpadev;
skb_reset_mac_header(pDevice->skb);
pDevice->skb->pkt_type = PACKET_HOST;
pDevice->skb->protocol = htons(ETH_P_802_2);
memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
netif_rx(pDevice->skb);
pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
}
return FALSE;
}
}
} //---end of SOFT MIC-----------------------------------------------------------------------
// ++++++++++ Reply Counter Check +++++++++++++
if ((pKey != NULL) && ((pKey->byCipherSuite == KEY_CTL_TKIP) ||
(pKey->byCipherSuite == KEY_CTL_CCMP))) {
if (bIsWEP) {
WORD wLocalTSC15_0 = 0;
DWORD dwLocalTSC47_16 = 0;
unsigned long long RSC = 0;
// endian issues
RSC = *((unsigned long long *) &(pKey->KeyRSC));
wLocalTSC15_0 = (WORD) RSC;
dwLocalTSC47_16 = (DWORD) (RSC>>16);
RSC = dwRxTSC47_16;
RSC <<= 16;
RSC += wRxTSC15_0;
memcpy(&(pKey->KeyRSC), &RSC, sizeof(QWORD));
if ( (pDevice->sMgmtObj.eCurrMode == WMAC_MODE_ESS_STA) &&
(pDevice->sMgmtObj.eCurrState == WMAC_STATE_ASSOC)) {
// check RSC
if ( (wRxTSC15_0 < wLocalTSC15_0) &&
(dwRxTSC47_16 <= dwLocalTSC47_16) &&
!((dwRxTSC47_16 == 0) && (dwLocalTSC47_16 == 0xFFFFFFFF))) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TSC is illegal~~!\n ");
if (pKey->byCipherSuite == KEY_CTL_TKIP)
//pDevice->s802_11Counter.TKIPReplays.QuadPart++;
pDevice->s802_11Counter.TKIPReplays++;
else
//pDevice->s802_11Counter.CCMPReplays.QuadPart++;
pDevice->s802_11Counter.CCMPReplays++;
if (bDeFragRx) {
if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
pDevice->dev->name);
}
}
return FALSE;
}
}
}
} // ----- End of Reply Counter Check --------------------------
s_vProcessRxMACHeader(pDevice, (PBYTE)(skb->data+8), FrameSize, bIsWEP, bExtIV, &cbHeaderOffset);
FrameSize -= cbHeaderOffset;
cbHeaderOffset += 8; // 8 is Rcv buffer header
// Null data, framesize = 12
if (FrameSize < 12)
return FALSE;
if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
if (s_bAPModeRxData(pDevice,
skb,
FrameSize,
cbHeaderOffset,
iSANodeIndex,
iDANodeIndex
) == FALSE) {
if (bDeFragRx) {
if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
pDevice->dev->name);
}
}
return FALSE;
}
}
skb->data += cbHeaderOffset;
skb->tail += cbHeaderOffset;
skb_put(skb, FrameSize);
skb->protocol=eth_type_trans(skb, skb->dev);
skb->ip_summed=CHECKSUM_NONE;
pStats->rx_bytes +=skb->len;
pStats->rx_packets++;
netif_rx(skb);
if (bDeFragRx) {
if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
pDevice->dev->name);
}
return FALSE;
}
return TRUE;
}
static BOOL s_bAPModeRxCtl (
PSDevice pDevice,
PBYTE pbyFrame,
signed int iSANodeIndex
)
{
PS802_11Header p802_11Header;
CMD_STATUS Status;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
if (IS_CTL_PSPOLL(pbyFrame) || !IS_TYPE_CONTROL(pbyFrame)) {
p802_11Header = (PS802_11Header) (pbyFrame);
if (!IS_TYPE_MGMT(pbyFrame)) {
// Data & PS-Poll packet
// check frame class
if (iSANodeIndex > 0) {
// frame class 3 fliter & checking
if (pMgmt->sNodeDBTable[iSANodeIndex].eNodeState < NODE_AUTH) {
// send deauth notification
// reason = (6) class 2 received from nonauth sta
vMgrDeAuthenBeginSta(pDevice,
pMgmt,
(PBYTE)(p802_11Header->abyAddr2),
(WLAN_MGMT_REASON_CLASS2_NONAUTH),
&Status
);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: send vMgrDeAuthenBeginSta 1\n");
return TRUE;
}
if (pMgmt->sNodeDBTable[iSANodeIndex].eNodeState < NODE_ASSOC) {
// send deassoc notification
// reason = (7) class 3 received from nonassoc sta
vMgrDisassocBeginSta(pDevice,
pMgmt,
(PBYTE)(p802_11Header->abyAddr2),
(WLAN_MGMT_REASON_CLASS3_NONASSOC),
&Status
);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: send vMgrDisassocBeginSta 2\n");
return TRUE;
}
if (pMgmt->sNodeDBTable[iSANodeIndex].bPSEnable) {
// delcare received ps-poll event
if (IS_CTL_PSPOLL(pbyFrame)) {
pMgmt->sNodeDBTable[iSANodeIndex].bRxPSPoll = TRUE;
bScheduleCommand((void *) pDevice,
WLAN_CMD_RX_PSPOLL,
NULL);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: WLAN_CMD_RX_PSPOLL 1\n");
}
else {
// check Data PS state
// if PW bit off, send out all PS bufferring packets.
if (!IS_FC_POWERMGT(pbyFrame)) {
pMgmt->sNodeDBTable[iSANodeIndex].bPSEnable = FALSE;
pMgmt->sNodeDBTable[iSANodeIndex].bRxPSPoll = TRUE;
bScheduleCommand((void *) pDevice,
WLAN_CMD_RX_PSPOLL,
NULL);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: WLAN_CMD_RX_PSPOLL 2\n");
}
}
}
else {
if (IS_FC_POWERMGT(pbyFrame)) {
pMgmt->sNodeDBTable[iSANodeIndex].bPSEnable = TRUE;
// Once if STA in PS state, enable multicast bufferring
pMgmt->sNodeDBTable[0].bPSEnable = TRUE;
}
else {
// clear all pending PS frame.
if (pMgmt->sNodeDBTable[iSANodeIndex].wEnQueueCnt > 0) {
pMgmt->sNodeDBTable[iSANodeIndex].bPSEnable = FALSE;
pMgmt->sNodeDBTable[iSANodeIndex].bRxPSPoll = TRUE;
bScheduleCommand((void *) pDevice,
WLAN_CMD_RX_PSPOLL,
NULL);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: WLAN_CMD_RX_PSPOLL 3\n");
}
}
}
}
else {
vMgrDeAuthenBeginSta(pDevice,
pMgmt,
(PBYTE)(p802_11Header->abyAddr2),
(WLAN_MGMT_REASON_CLASS2_NONAUTH),
&Status
);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: send vMgrDeAuthenBeginSta 3\n");
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "BSSID:%pM\n",
p802_11Header->abyAddr3);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "ADDR2:%pM\n",
p802_11Header->abyAddr2);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "ADDR1:%pM\n",
p802_11Header->abyAddr1);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: wFrameCtl= %x\n", p802_11Header->wFrameCtl );
return TRUE;
}
}
}
return FALSE;
}
static BOOL s_bHandleRxEncryption (
PSDevice pDevice,
PBYTE pbyFrame,
unsigned int FrameSize,
PBYTE pbyRsr,
PBYTE pbyNewRsr,
PSKeyItem * pKeyOut,
int * pbExtIV,
PWORD pwRxTSC15_0,
PDWORD pdwRxTSC47_16
)
{
unsigned int PayloadLen = FrameSize;
PBYTE pbyIV;
BYTE byKeyIdx;
PSKeyItem pKey = NULL;
BYTE byDecMode = KEY_CTL_WEP;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
*pwRxTSC15_0 = 0;
*pdwRxTSC47_16 = 0;
pbyIV = pbyFrame + WLAN_HDR_ADDR3_LEN;
if ( WLAN_GET_FC_TODS(*(PWORD)pbyFrame) &&
WLAN_GET_FC_FROMDS(*(PWORD)pbyFrame) ) {
pbyIV += 6; // 6 is 802.11 address4
PayloadLen -= 6;
}
byKeyIdx = (*(pbyIV+3) & 0xc0);
byKeyIdx >>= 6;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\nKeyIdx: %d\n", byKeyIdx);
if ((pMgmt->eAuthenMode == WMAC_AUTH_WPA) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
(pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) {
if (((*pbyRsr & (RSR_ADDRBROAD | RSR_ADDRMULTI)) == 0) &&
(pMgmt->byCSSPK != KEY_CTL_NONE)) {
// unicast pkt use pairwise key
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"unicast pkt\n");
if (KeybGetKey(&(pDevice->sKey), pDevice->abyBSSID, 0xFFFFFFFF, &pKey) == TRUE) {
if (pMgmt->byCSSPK == KEY_CTL_TKIP)
byDecMode = KEY_CTL_TKIP;
else if (pMgmt->byCSSPK == KEY_CTL_CCMP)
byDecMode = KEY_CTL_CCMP;
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"unicast pkt: %d, %p\n", byDecMode, pKey);
} else {
// use group key
KeybGetKey(&(pDevice->sKey), pDevice->abyBSSID, byKeyIdx, &pKey);
if (pMgmt->byCSSGK == KEY_CTL_TKIP)
byDecMode = KEY_CTL_TKIP;
else if (pMgmt->byCSSGK == KEY_CTL_CCMP)
byDecMode = KEY_CTL_CCMP;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"group pkt: %d, %d, %p\n", byKeyIdx, byDecMode, pKey);
}
}
// our WEP only support Default Key
if (pKey == NULL) {
// use default group key
KeybGetKey(&(pDevice->sKey), pDevice->abyBroadcastAddr, byKeyIdx, &pKey);
if (pMgmt->byCSSGK == KEY_CTL_TKIP)
byDecMode = KEY_CTL_TKIP;
else if (pMgmt->byCSSGK == KEY_CTL_CCMP)
byDecMode = KEY_CTL_CCMP;
}
*pKeyOut = pKey;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"AES:%d %d %d\n", pMgmt->byCSSPK, pMgmt->byCSSGK, byDecMode);
if (pKey == NULL) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey == NULL\n");
if (byDecMode == KEY_CTL_WEP) {
// pDevice->s802_11Counter.WEPUndecryptableCount.QuadPart++;
} else if (pDevice->bLinkPass == TRUE) {
// pDevice->s802_11Counter.DecryptFailureCount.QuadPart++;
}
return FALSE;
}
if (byDecMode != pKey->byCipherSuite) {
if (byDecMode == KEY_CTL_WEP) {
// pDevice->s802_11Counter.WEPUndecryptableCount.QuadPart++;
} else if (pDevice->bLinkPass == TRUE) {
// pDevice->s802_11Counter.DecryptFailureCount.QuadPart++;
}
*pKeyOut = NULL;
return FALSE;
}
if (byDecMode == KEY_CTL_WEP) {
// handle WEP
if ((pDevice->byLocalID <= REV_ID_VT3253_A1) ||
(((PSKeyTable)(pKey->pvKeyTable))->bSoftWEP == TRUE)) {
// Software WEP
// 1. 3253A
// 2. WEP 256
PayloadLen -= (WLAN_HDR_ADDR3_LEN + 4 + 4); // 24 is 802.11 header,4 is IV, 4 is crc
memcpy(pDevice->abyPRNG, pbyIV, 3);
memcpy(pDevice->abyPRNG + 3, pKey->abyKey, pKey->uKeyLength);
rc4_init(&pDevice->SBox, pDevice->abyPRNG, pKey->uKeyLength + 3);
rc4_encrypt(&pDevice->SBox, pbyIV+4, pbyIV+4, PayloadLen);
if (ETHbIsBufferCrc32Ok(pbyIV+4, PayloadLen)) {
*pbyNewRsr |= NEWRSR_DECRYPTOK;
}
}
} else if ((byDecMode == KEY_CTL_TKIP) ||
(byDecMode == KEY_CTL_CCMP)) {
// TKIP/AES
PayloadLen -= (WLAN_HDR_ADDR3_LEN + 8 + 4); // 24 is 802.11 header, 8 is IV&ExtIV, 4 is crc
*pdwRxTSC47_16 = cpu_to_le32(*(PDWORD)(pbyIV + 4));
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ExtIV: %x\n", *pdwRxTSC47_16);
if (byDecMode == KEY_CTL_TKIP) {
*pwRxTSC15_0 = cpu_to_le16(MAKEWORD(*(pbyIV+2), *pbyIV));
} else {
*pwRxTSC15_0 = cpu_to_le16(*(PWORD)pbyIV);
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TSC0_15: %x\n", *pwRxTSC15_0);
if ((byDecMode == KEY_CTL_TKIP) &&
(pDevice->byLocalID <= REV_ID_VT3253_A1)) {
// Software TKIP
// 1. 3253 A
PS802_11Header pMACHeader = (PS802_11Header) (pbyFrame);
TKIPvMixKey(pKey->abyKey, pMACHeader->abyAddr2, *pwRxTSC15_0, *pdwRxTSC47_16, pDevice->abyPRNG);
rc4_init(&pDevice->SBox, pDevice->abyPRNG, TKIP_KEY_LEN);
rc4_encrypt(&pDevice->SBox, pbyIV+8, pbyIV+8, PayloadLen);
if (ETHbIsBufferCrc32Ok(pbyIV+8, PayloadLen)) {
*pbyNewRsr |= NEWRSR_DECRYPTOK;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV OK!\n");
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV FAIL!!!\n");
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"PayloadLen = %d\n", PayloadLen);
}
}
}// end of TKIP/AES
if ((*(pbyIV+3) & 0x20) != 0)
*pbExtIV = TRUE;
return TRUE;
}
static BOOL s_bHostWepRxEncryption (
PSDevice pDevice,
PBYTE pbyFrame,
unsigned int FrameSize,
PBYTE pbyRsr,
BOOL bOnFly,
PSKeyItem pKey,
PBYTE pbyNewRsr,
int * pbExtIV,
PWORD pwRxTSC15_0,
PDWORD pdwRxTSC47_16
)
{
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
unsigned int PayloadLen = FrameSize;
PBYTE pbyIV;
BYTE byKeyIdx;
BYTE byDecMode = KEY_CTL_WEP;
PS802_11Header pMACHeader;
*pwRxTSC15_0 = 0;
*pdwRxTSC47_16 = 0;
pbyIV = pbyFrame + WLAN_HDR_ADDR3_LEN;
if ( WLAN_GET_FC_TODS(*(PWORD)pbyFrame) &&
WLAN_GET_FC_FROMDS(*(PWORD)pbyFrame) ) {
pbyIV += 6; // 6 is 802.11 address4
PayloadLen -= 6;
}
byKeyIdx = (*(pbyIV+3) & 0xc0);
byKeyIdx >>= 6;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\nKeyIdx: %d\n", byKeyIdx);
if (pMgmt->byCSSGK == KEY_CTL_TKIP)
byDecMode = KEY_CTL_TKIP;
else if (pMgmt->byCSSGK == KEY_CTL_CCMP)
byDecMode = KEY_CTL_CCMP;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"AES:%d %d %d\n", pMgmt->byCSSPK, pMgmt->byCSSGK, byDecMode);
if (byDecMode != pKey->byCipherSuite) {
if (byDecMode == KEY_CTL_WEP) {
// pDevice->s802_11Counter.WEPUndecryptableCount.QuadPart++;
} else if (pDevice->bLinkPass == TRUE) {
// pDevice->s802_11Counter.DecryptFailureCount.QuadPart++;
}
return FALSE;
}
if (byDecMode == KEY_CTL_WEP) {
// handle WEP
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"byDecMode == KEY_CTL_WEP \n");
if ((pDevice->byLocalID <= REV_ID_VT3253_A1) ||
(((PSKeyTable)(pKey->pvKeyTable))->bSoftWEP == TRUE) ||
(bOnFly == FALSE)) {
// Software WEP
// 1. 3253A
// 2. WEP 256
// 3. NotOnFly
PayloadLen -= (WLAN_HDR_ADDR3_LEN + 4 + 4); // 24 is 802.11 header,4 is IV, 4 is crc
memcpy(pDevice->abyPRNG, pbyIV, 3);
memcpy(pDevice->abyPRNG + 3, pKey->abyKey, pKey->uKeyLength);
rc4_init(&pDevice->SBox, pDevice->abyPRNG, pKey->uKeyLength + 3);
rc4_encrypt(&pDevice->SBox, pbyIV+4, pbyIV+4, PayloadLen);
if (ETHbIsBufferCrc32Ok(pbyIV+4, PayloadLen)) {
*pbyNewRsr |= NEWRSR_DECRYPTOK;
}
}
} else if ((byDecMode == KEY_CTL_TKIP) ||
(byDecMode == KEY_CTL_CCMP)) {
// TKIP/AES
PayloadLen -= (WLAN_HDR_ADDR3_LEN + 8 + 4); // 24 is 802.11 header, 8 is IV&ExtIV, 4 is crc
*pdwRxTSC47_16 = cpu_to_le32(*(PDWORD)(pbyIV + 4));
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ExtIV: %x\n", *pdwRxTSC47_16);
if (byDecMode == KEY_CTL_TKIP) {
*pwRxTSC15_0 = cpu_to_le16(MAKEWORD(*(pbyIV+2), *pbyIV));
} else {
*pwRxTSC15_0 = cpu_to_le16(*(PWORD)pbyIV);
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TSC0_15: %x\n", *pwRxTSC15_0);
if (byDecMode == KEY_CTL_TKIP) {
if ((pDevice->byLocalID <= REV_ID_VT3253_A1) || (bOnFly == FALSE)) {
// Software TKIP
// 1. 3253 A
// 2. NotOnFly
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"soft KEY_CTL_TKIP \n");
pMACHeader = (PS802_11Header) (pbyFrame);
TKIPvMixKey(pKey->abyKey, pMACHeader->abyAddr2, *pwRxTSC15_0, *pdwRxTSC47_16, pDevice->abyPRNG);
rc4_init(&pDevice->SBox, pDevice->abyPRNG, TKIP_KEY_LEN);
rc4_encrypt(&pDevice->SBox, pbyIV+8, pbyIV+8, PayloadLen);
if (ETHbIsBufferCrc32Ok(pbyIV+8, PayloadLen)) {
*pbyNewRsr |= NEWRSR_DECRYPTOK;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV OK!\n");
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV FAIL!!!\n");
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"PayloadLen = %d\n", PayloadLen);
}
}
}
if (byDecMode == KEY_CTL_CCMP) {
if (bOnFly == FALSE) {
// Software CCMP
// NotOnFly
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"soft KEY_CTL_CCMP\n");
if (AESbGenCCMP(pKey->abyKey, pbyFrame, FrameSize)) {
*pbyNewRsr |= NEWRSR_DECRYPTOK;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"CCMP MIC compare OK!\n");
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"CCMP MIC fail!\n");
}
}
}
}// end of TKIP/AES
if ((*(pbyIV+3) & 0x20) != 0)
*pbExtIV = TRUE;
return TRUE;
}
static BOOL s_bAPModeRxData (
PSDevice pDevice,
struct sk_buff *skb,
unsigned int FrameSize,
unsigned int cbHeaderOffset,
signed int iSANodeIndex,
signed int iDANodeIndex
)
{
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
BOOL bRelayAndForward = FALSE;
BOOL bRelayOnly = FALSE;
BYTE byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
WORD wAID;
struct sk_buff* skbcpy = NULL;
if (FrameSize > CB_MAX_BUF_SIZE)
return FALSE;
// check DA
if (is_multicast_ether_addr((PBYTE)(skb->data+cbHeaderOffset))) {
if (pMgmt->sNodeDBTable[0].bPSEnable) {
skbcpy = dev_alloc_skb((int)pDevice->rx_buf_sz);
// if any node in PS mode, buffer packet until DTIM.
if (skbcpy == NULL) {
DBG_PRT(MSG_LEVEL_NOTICE, KERN_INFO "relay multicast no skb available \n");
}
else {
skbcpy->dev = pDevice->dev;
skbcpy->len = FrameSize;
memcpy(skbcpy->data, skb->data+cbHeaderOffset, FrameSize);
skb_queue_tail(&(pMgmt->sNodeDBTable[0].sTxPSQueue), skbcpy);
pMgmt->sNodeDBTable[0].wEnQueueCnt++;
// set tx map
pMgmt->abyPSTxMap[0] |= byMask[0];
}
}
else {
bRelayAndForward = TRUE;
}
}
else {
// check if relay
if (BSSbIsSTAInNodeDB(pDevice, (PBYTE)(skb->data+cbHeaderOffset), &iDANodeIndex)) {
if (pMgmt->sNodeDBTable[iDANodeIndex].eNodeState >= NODE_ASSOC) {
if (pMgmt->sNodeDBTable[iDANodeIndex].bPSEnable) {
// queue this skb until next PS tx, and then release.
skb->data += cbHeaderOffset;
skb->tail += cbHeaderOffset;
skb_put(skb, FrameSize);
skb_queue_tail(&pMgmt->sNodeDBTable[iDANodeIndex].sTxPSQueue, skb);
pMgmt->sNodeDBTable[iDANodeIndex].wEnQueueCnt++;
wAID = pMgmt->sNodeDBTable[iDANodeIndex].wAID;
pMgmt->abyPSTxMap[wAID >> 3] |= byMask[wAID & 7];
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "relay: index= %d, pMgmt->abyPSTxMap[%d]= %d\n",
iDANodeIndex, (wAID >> 3), pMgmt->abyPSTxMap[wAID >> 3]);
return TRUE;
}
else {
bRelayOnly = TRUE;
}
}
}
}
if (bRelayOnly || bRelayAndForward) {
// relay this packet right now
if (bRelayAndForward)
iDANodeIndex = 0;
if ((pDevice->uAssocCount > 1) && (iDANodeIndex >= 0)) {
bRelayPacketSend(pDevice, (PBYTE) (skb->data + cbHeaderOffset),
FrameSize, (unsigned int) iDANodeIndex);
}
if (bRelayOnly)
return FALSE;
}
// none associate, don't forward
if (pDevice->uAssocCount == 0)
return FALSE;
return TRUE;
}
void RXvWorkItem(void *Context)
{
PSDevice pDevice = (PSDevice) Context;
int ntStatus;
PRCB pRCB=NULL;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"---->Rx Polling Thread\n");
spin_lock_irq(&pDevice->lock);
while ((pDevice->Flags & fMP_POST_READS) &&
MP_IS_READY(pDevice) &&
(pDevice->NumRecvFreeList != 0) ) {
pRCB = pDevice->FirstRecvFreeList;
pDevice->NumRecvFreeList--;
ASSERT(pRCB);// cannot be NULL
DequeueRCB(pDevice->FirstRecvFreeList, pDevice->LastRecvFreeList);
ntStatus = PIPEnsBulkInUsbRead(pDevice, pRCB);
}
pDevice->bIsRxWorkItemQueued = FALSE;
spin_unlock_irq(&pDevice->lock);
}
void
RXvFreeRCB(
PRCB pRCB,
BOOL bReAllocSkb
)
{
PSDevice pDevice = (PSDevice)pRCB->pDevice;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"---->RXvFreeRCB\n");
ASSERT(!pRCB->Ref); // should be 0
ASSERT(pRCB->pDevice); // shouldn't be NULL
if (bReAllocSkb == TRUE) {
pRCB->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
// todo error handling
if (pRCB->skb == NULL) {
DBG_PRT(MSG_LEVEL_ERR,KERN_ERR" Failed to re-alloc rx skb\n");
}else {
pRCB->skb->dev = pDevice->dev;
}
}
//
// Insert the RCB back in the Recv free list
//
EnqueueRCB(pDevice->FirstRecvFreeList, pDevice->LastRecvFreeList, pRCB);
pDevice->NumRecvFreeList++;
if ((pDevice->Flags & fMP_POST_READS) && MP_IS_READY(pDevice) &&
(pDevice->bIsRxWorkItemQueued == FALSE) ) {
pDevice->bIsRxWorkItemQueued = TRUE;
tasklet_schedule(&pDevice->ReadWorkItem);
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"<----RXFreeRCB %d %d\n",pDevice->NumRecvFreeList, pDevice->NumRecvMngList);
}
void RXvMngWorkItem(void *Context)
{
PSDevice pDevice = (PSDevice) Context;
PRCB pRCB=NULL;
PSRxMgmtPacket pRxPacket;
BOOL bReAllocSkb = FALSE;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"---->Rx Mng Thread\n");
spin_lock_irq(&pDevice->lock);
while (pDevice->NumRecvMngList!=0)
{
pRCB = pDevice->FirstRecvMngList;
pDevice->NumRecvMngList--;
DequeueRCB(pDevice->FirstRecvMngList, pDevice->LastRecvMngList);
if(!pRCB){
break;
}
ASSERT(pRCB);// cannot be NULL
pRxPacket = &(pRCB->sMngPacket);
vMgrRxManagePacket((void *) pDevice, &(pDevice->sMgmtObj), pRxPacket);
pRCB->Ref--;
if(pRCB->Ref == 0) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"RxvFreeMng %d %d\n",pDevice->NumRecvFreeList, pDevice->NumRecvMngList);
RXvFreeRCB(pRCB, bReAllocSkb);
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Rx Mng Only we have the right to free RCB\n");
}
}
pDevice->bIsRxMngWorkItemQueued = FALSE;
spin_unlock_irq(&pDevice->lock);
}
| gpl-2.0 |
MISL-EBU-System-SW/lsp-public | arch/hexagon/kernel/smp.c | 1541 | 5563 | /*
* SMP support for Hexagon
*
* Copyright (c) 2010-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/percpu.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/spinlock.h>
#include <linux/cpu.h>
#include <asm/time.h> /* timer_interrupt */
#include <asm/hexagon_vm.h>
#define BASE_IPI_IRQ 26
/*
* cpu_possible_mask needs to be filled out prior to setup_per_cpu_areas
* (which is prior to any of our smp_prepare_cpu crap), in order to set
* up the... per_cpu areas.
*/
struct ipi_data {
unsigned long bits;
};
static DEFINE_PER_CPU(struct ipi_data, ipi_data);
static inline void __handle_ipi(unsigned long *ops, struct ipi_data *ipi,
int cpu)
{
unsigned long msg = 0;
do {
msg = find_next_bit(ops, BITS_PER_LONG, msg+1);
switch (msg) {
case IPI_TIMER:
ipi_timer();
break;
case IPI_CALL_FUNC:
generic_smp_call_function_interrupt();
break;
case IPI_CPU_STOP:
/*
* call vmstop()
*/
__vmstop();
break;
case IPI_RESCHEDULE:
scheduler_ipi();
break;
}
} while (msg < BITS_PER_LONG);
}
/* Used for IPI call from other CPU's to unmask int */
void smp_vm_unmask_irq(void *info)
{
__vmintop_locen((long) info);
}
/*
* This is based on Alpha's IPI stuff.
* Supposed to take (int, void*) as args now.
* Specifically, first arg is irq, second is the irq_desc.
*/
irqreturn_t handle_ipi(int irq, void *desc)
{
int cpu = smp_processor_id();
struct ipi_data *ipi = &per_cpu(ipi_data, cpu);
unsigned long ops;
while ((ops = xchg(&ipi->bits, 0)) != 0)
__handle_ipi(&ops, ipi, cpu);
return IRQ_HANDLED;
}
void send_ipi(const struct cpumask *cpumask, enum ipi_message_type msg)
{
unsigned long flags;
unsigned long cpu;
unsigned long retval;
local_irq_save(flags);
for_each_cpu(cpu, cpumask) {
struct ipi_data *ipi = &per_cpu(ipi_data, cpu);
set_bit(msg, &ipi->bits);
/* Possible barrier here */
retval = __vmintop_post(BASE_IPI_IRQ+cpu);
if (retval != 0) {
printk(KERN_ERR "interrupt %ld not configured?\n",
BASE_IPI_IRQ+cpu);
}
}
local_irq_restore(flags);
}
static struct irqaction ipi_intdesc = {
.handler = handle_ipi,
.flags = IRQF_TRIGGER_RISING,
.name = "ipi_handler"
};
void __init smp_prepare_boot_cpu(void)
{
}
/*
* interrupts should already be disabled from the VM
* SP should already be correct; need to set THREADINFO_REG
* to point to current thread info
*/
void start_secondary(void)
{
unsigned int cpu;
unsigned long thread_ptr;
/* Calculate thread_info pointer from stack pointer */
__asm__ __volatile__(
"%0 = SP;\n"
: "=r" (thread_ptr)
);
thread_ptr = thread_ptr & ~(THREAD_SIZE-1);
__asm__ __volatile__(
QUOTED_THREADINFO_REG " = %0;\n"
:
: "r" (thread_ptr)
);
/* Set the memory struct */
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
cpu = smp_processor_id();
setup_irq(BASE_IPI_IRQ + cpu, &ipi_intdesc);
/* Register the clock_event dummy */
setup_percpu_clockdev();
printk(KERN_INFO "%s cpu %d\n", __func__, current_thread_info()->cpu);
notify_cpu_starting(cpu);
set_cpu_online(cpu, true);
local_irq_enable();
cpu_startup_entry(CPUHP_ONLINE);
}
/*
* called once for each present cpu
* apparently starts up the CPU and then
* maintains control until "cpu_online(cpu)" is set.
*/
int __cpu_up(unsigned int cpu, struct task_struct *idle)
{
struct thread_info *thread = (struct thread_info *)idle->stack;
void *stack_start;
thread->cpu = cpu;
/* Boot to the head. */
stack_start = ((void *) thread) + THREAD_SIZE;
__vmstart(start_secondary, stack_start);
while (!cpu_online(cpu))
barrier();
return 0;
}
void __init smp_cpus_done(unsigned int max_cpus)
{
}
void __init smp_prepare_cpus(unsigned int max_cpus)
{
int i;
/*
* should eventually have some sort of machine
* descriptor that has this stuff
*/
/* Right now, let's just fake it. */
for (i = 0; i < max_cpus; i++)
set_cpu_present(i, true);
/* Also need to register the interrupts for IPI */
if (max_cpus > 1)
setup_irq(BASE_IPI_IRQ, &ipi_intdesc);
}
void smp_send_reschedule(int cpu)
{
send_ipi(cpumask_of(cpu), IPI_RESCHEDULE);
}
void smp_send_stop(void)
{
struct cpumask targets;
cpumask_copy(&targets, cpu_online_mask);
cpumask_clear_cpu(smp_processor_id(), &targets);
send_ipi(&targets, IPI_CPU_STOP);
}
void arch_send_call_function_single_ipi(int cpu)
{
send_ipi(cpumask_of(cpu), IPI_CALL_FUNC);
}
void arch_send_call_function_ipi_mask(const struct cpumask *mask)
{
send_ipi(mask, IPI_CALL_FUNC);
}
int setup_profiling_timer(unsigned int multiplier)
{
return -EINVAL;
}
void smp_start_cpus(void)
{
int i;
for (i = 0; i < NR_CPUS; i++)
set_cpu_possible(i, true);
}
| gpl-2.0 |
hubcapsc/orangefs_kmod | arch/powerpc/platforms/powernv/opal-lpc.c | 1541 | 10166 | /*
* PowerNV LPC bus handling.
*
* Copyright 2013 IBM Corp.
*
* 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 <linux/kernel.h>
#include <linux/of.h>
#include <linux/bug.h>
#include <linux/debugfs.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <asm/machdep.h>
#include <asm/firmware.h>
#include <asm/xics.h>
#include <asm/opal.h>
#include <asm/prom.h>
#include <asm/uaccess.h>
#include <asm/debug.h>
static int opal_lpc_chip_id = -1;
static u8 opal_lpc_inb(unsigned long port)
{
int64_t rc;
__be32 data;
if (opal_lpc_chip_id < 0 || port > 0xffff)
return 0xff;
rc = opal_lpc_read(opal_lpc_chip_id, OPAL_LPC_IO, port, &data, 1);
return rc ? 0xff : be32_to_cpu(data);
}
static __le16 __opal_lpc_inw(unsigned long port)
{
int64_t rc;
__be32 data;
if (opal_lpc_chip_id < 0 || port > 0xfffe)
return 0xffff;
if (port & 1)
return (__le16)opal_lpc_inb(port) << 8 | opal_lpc_inb(port + 1);
rc = opal_lpc_read(opal_lpc_chip_id, OPAL_LPC_IO, port, &data, 2);
return rc ? 0xffff : be32_to_cpu(data);
}
static u16 opal_lpc_inw(unsigned long port)
{
return le16_to_cpu(__opal_lpc_inw(port));
}
static __le32 __opal_lpc_inl(unsigned long port)
{
int64_t rc;
__be32 data;
if (opal_lpc_chip_id < 0 || port > 0xfffc)
return 0xffffffff;
if (port & 3)
return (__le32)opal_lpc_inb(port ) << 24 |
(__le32)opal_lpc_inb(port + 1) << 16 |
(__le32)opal_lpc_inb(port + 2) << 8 |
opal_lpc_inb(port + 3);
rc = opal_lpc_read(opal_lpc_chip_id, OPAL_LPC_IO, port, &data, 4);
return rc ? 0xffffffff : be32_to_cpu(data);
}
static u32 opal_lpc_inl(unsigned long port)
{
return le32_to_cpu(__opal_lpc_inl(port));
}
static void opal_lpc_outb(u8 val, unsigned long port)
{
if (opal_lpc_chip_id < 0 || port > 0xffff)
return;
opal_lpc_write(opal_lpc_chip_id, OPAL_LPC_IO, port, val, 1);
}
static void __opal_lpc_outw(__le16 val, unsigned long port)
{
if (opal_lpc_chip_id < 0 || port > 0xfffe)
return;
if (port & 1) {
opal_lpc_outb(val >> 8, port);
opal_lpc_outb(val , port + 1);
return;
}
opal_lpc_write(opal_lpc_chip_id, OPAL_LPC_IO, port, val, 2);
}
static void opal_lpc_outw(u16 val, unsigned long port)
{
__opal_lpc_outw(cpu_to_le16(val), port);
}
static void __opal_lpc_outl(__le32 val, unsigned long port)
{
if (opal_lpc_chip_id < 0 || port > 0xfffc)
return;
if (port & 3) {
opal_lpc_outb(val >> 24, port);
opal_lpc_outb(val >> 16, port + 1);
opal_lpc_outb(val >> 8, port + 2);
opal_lpc_outb(val , port + 3);
return;
}
opal_lpc_write(opal_lpc_chip_id, OPAL_LPC_IO, port, val, 4);
}
static void opal_lpc_outl(u32 val, unsigned long port)
{
__opal_lpc_outl(cpu_to_le32(val), port);
}
static void opal_lpc_insb(unsigned long p, void *b, unsigned long c)
{
u8 *ptr = b;
while(c--)
*(ptr++) = opal_lpc_inb(p);
}
static void opal_lpc_insw(unsigned long p, void *b, unsigned long c)
{
__le16 *ptr = b;
while(c--)
*(ptr++) = __opal_lpc_inw(p);
}
static void opal_lpc_insl(unsigned long p, void *b, unsigned long c)
{
__le32 *ptr = b;
while(c--)
*(ptr++) = __opal_lpc_inl(p);
}
static void opal_lpc_outsb(unsigned long p, const void *b, unsigned long c)
{
const u8 *ptr = b;
while(c--)
opal_lpc_outb(*(ptr++), p);
}
static void opal_lpc_outsw(unsigned long p, const void *b, unsigned long c)
{
const __le16 *ptr = b;
while(c--)
__opal_lpc_outw(*(ptr++), p);
}
static void opal_lpc_outsl(unsigned long p, const void *b, unsigned long c)
{
const __le32 *ptr = b;
while(c--)
__opal_lpc_outl(*(ptr++), p);
}
static const struct ppc_pci_io opal_lpc_io = {
.inb = opal_lpc_inb,
.inw = opal_lpc_inw,
.inl = opal_lpc_inl,
.outb = opal_lpc_outb,
.outw = opal_lpc_outw,
.outl = opal_lpc_outl,
.insb = opal_lpc_insb,
.insw = opal_lpc_insw,
.insl = opal_lpc_insl,
.outsb = opal_lpc_outsb,
.outsw = opal_lpc_outsw,
.outsl = opal_lpc_outsl,
};
#ifdef CONFIG_DEBUG_FS
struct lpc_debugfs_entry {
enum OpalLPCAddressType lpc_type;
};
static ssize_t lpc_debug_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos)
{
struct lpc_debugfs_entry *lpc = filp->private_data;
u32 data, pos, len, todo;
int rc;
if (!access_ok(VERIFY_WRITE, ubuf, count))
return -EFAULT;
todo = count;
while (todo) {
pos = *ppos;
/*
* Select access size based on count and alignment and
* access type. IO and MEM only support byte acceses,
* FW supports all 3.
*/
len = 1;
if (lpc->lpc_type == OPAL_LPC_FW) {
if (todo > 3 && (pos & 3) == 0)
len = 4;
else if (todo > 1 && (pos & 1) == 0)
len = 2;
}
rc = opal_lpc_read(opal_lpc_chip_id, lpc->lpc_type, pos,
&data, len);
if (rc)
return -ENXIO;
/*
* Now there is some trickery with the data returned by OPAL
* as it's the desired data right justified in a 32-bit BE
* word.
*
* This is a very bad interface and I'm to blame for it :-(
*
* So we can't just apply a 32-bit swap to what comes from OPAL,
* because user space expects the *bytes* to be in their proper
* respective positions (ie, LPC position).
*
* So what we really want to do here is to shift data right
* appropriately on a LE kernel.
*
* IE. If the LPC transaction has bytes B0, B1, B2 and B3 in that
* order, we have in memory written to by OPAL at the "data"
* pointer:
*
* Bytes: OPAL "data" LE "data"
* 32-bit: B0 B1 B2 B3 B0B1B2B3 B3B2B1B0
* 16-bit: B0 B1 0000B0B1 B1B00000
* 8-bit: B0 000000B0 B0000000
*
* So a BE kernel will have the leftmost of the above in the MSB
* and rightmost in the LSB and can just then "cast" the u32 "data"
* down to the appropriate quantity and write it.
*
* However, an LE kernel can't. It doesn't need to swap because a
* load from data followed by a store to user are going to preserve
* the byte ordering which is the wire byte order which is what the
* user wants, but in order to "crop" to the right size, we need to
* shift right first.
*/
switch(len) {
case 4:
rc = __put_user((u32)data, (u32 __user *)ubuf);
break;
case 2:
#ifdef __LITTLE_ENDIAN__
data >>= 16;
#endif
rc = __put_user((u16)data, (u16 __user *)ubuf);
break;
default:
#ifdef __LITTLE_ENDIAN__
data >>= 24;
#endif
rc = __put_user((u8)data, (u8 __user *)ubuf);
break;
}
if (rc)
return -EFAULT;
*ppos += len;
ubuf += len;
todo -= len;
}
return count;
}
static ssize_t lpc_debug_write(struct file *filp, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct lpc_debugfs_entry *lpc = filp->private_data;
u32 data, pos, len, todo;
int rc;
if (!access_ok(VERIFY_READ, ubuf, count))
return -EFAULT;
todo = count;
while (todo) {
pos = *ppos;
/*
* Select access size based on count and alignment and
* access type. IO and MEM only support byte acceses,
* FW supports all 3.
*/
len = 1;
if (lpc->lpc_type == OPAL_LPC_FW) {
if (todo > 3 && (pos & 3) == 0)
len = 4;
else if (todo > 1 && (pos & 1) == 0)
len = 2;
}
/*
* Similarly to the read case, we have some trickery here but
* it's different to handle. We need to pass the value to OPAL in
* a register whose layout depends on the access size. We want
* to reproduce the memory layout of the user, however we aren't
* doing a load from user and a store to another memory location
* which would achieve that. Here we pass the value to OPAL via
* a register which is expected to contain the "BE" interpretation
* of the byte sequence. IE: for a 32-bit access, byte 0 should be
* in the MSB. So here we *do* need to byteswap on LE.
*
* User bytes: LE "data" OPAL "data"
* 32-bit: B0 B1 B2 B3 B3B2B1B0 B0B1B2B3
* 16-bit: B0 B1 0000B1B0 0000B0B1
* 8-bit: B0 000000B0 000000B0
*/
switch(len) {
case 4:
rc = __get_user(data, (u32 __user *)ubuf);
data = cpu_to_be32(data);
break;
case 2:
rc = __get_user(data, (u16 __user *)ubuf);
data = cpu_to_be16(data);
break;
default:
rc = __get_user(data, (u8 __user *)ubuf);
break;
}
if (rc)
return -EFAULT;
rc = opal_lpc_write(opal_lpc_chip_id, lpc->lpc_type, pos,
data, len);
if (rc)
return -ENXIO;
*ppos += len;
ubuf += len;
todo -= len;
}
return count;
}
static const struct file_operations lpc_fops = {
.read = lpc_debug_read,
.write = lpc_debug_write,
.open = simple_open,
.llseek = default_llseek,
};
static int opal_lpc_debugfs_create_type(struct dentry *folder,
const char *fname,
enum OpalLPCAddressType type)
{
struct lpc_debugfs_entry *entry;
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return -ENOMEM;
entry->lpc_type = type;
debugfs_create_file(fname, 0600, folder, entry, &lpc_fops);
return 0;
}
static int opal_lpc_init_debugfs(void)
{
struct dentry *root;
int rc = 0;
if (opal_lpc_chip_id < 0)
return -ENODEV;
root = debugfs_create_dir("lpc", powerpc_debugfs_root);
rc |= opal_lpc_debugfs_create_type(root, "io", OPAL_LPC_IO);
rc |= opal_lpc_debugfs_create_type(root, "mem", OPAL_LPC_MEM);
rc |= opal_lpc_debugfs_create_type(root, "fw", OPAL_LPC_FW);
return rc;
}
machine_device_initcall(powernv, opal_lpc_init_debugfs);
#endif /* CONFIG_DEBUG_FS */
void opal_lpc_init(void)
{
struct device_node *np;
/*
* Look for a Power8 LPC bus tagged as "primary",
* we currently support only one though the OPAL APIs
* support any number.
*/
for_each_compatible_node(np, NULL, "ibm,power8-lpc") {
if (!of_device_is_available(np))
continue;
if (!of_get_property(np, "primary", NULL))
continue;
opal_lpc_chip_id = of_get_ibm_chip_id(np);
break;
}
if (opal_lpc_chip_id < 0)
return;
/* Setup special IO ops */
ppc_pci_io = opal_lpc_io;
isa_io_special = true;
pr_info("OPAL: Power8 LPC bus found, chip ID %d\n", opal_lpc_chip_id);
}
| gpl-2.0 |
ztemt/Z9Max_NX510J_V1_kernel | drivers/md/bcache/request.c | 1797 | 35124 | /*
* Main bcache entry point - handle a read or a write request and decide what to
* do with it; the make_request functions are called by the block layer.
*
* Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
* Copyright 2012 Google, Inc.
*/
#include "bcache.h"
#include "btree.h"
#include "debug.h"
#include "request.h"
#include <linux/cgroup.h>
#include <linux/module.h>
#include <linux/hash.h>
#include <linux/random.h>
#include "blk-cgroup.h"
#include <trace/events/bcache.h>
#define CUTOFF_CACHE_ADD 95
#define CUTOFF_CACHE_READA 90
#define CUTOFF_WRITEBACK 50
#define CUTOFF_WRITEBACK_SYNC 75
struct kmem_cache *bch_search_cache;
static void check_should_skip(struct cached_dev *, struct search *);
/* Cgroup interface */
#ifdef CONFIG_CGROUP_BCACHE
static struct bch_cgroup bcache_default_cgroup = { .cache_mode = -1 };
static struct bch_cgroup *cgroup_to_bcache(struct cgroup *cgroup)
{
struct cgroup_subsys_state *css;
return cgroup &&
(css = cgroup_subsys_state(cgroup, bcache_subsys_id))
? container_of(css, struct bch_cgroup, css)
: &bcache_default_cgroup;
}
struct bch_cgroup *bch_bio_to_cgroup(struct bio *bio)
{
struct cgroup_subsys_state *css = bio->bi_css
? cgroup_subsys_state(bio->bi_css->cgroup, bcache_subsys_id)
: task_subsys_state(current, bcache_subsys_id);
return css
? container_of(css, struct bch_cgroup, css)
: &bcache_default_cgroup;
}
static ssize_t cache_mode_read(struct cgroup *cgrp, struct cftype *cft,
struct file *file,
char __user *buf, size_t nbytes, loff_t *ppos)
{
char tmp[1024];
int len = bch_snprint_string_list(tmp, PAGE_SIZE, bch_cache_modes,
cgroup_to_bcache(cgrp)->cache_mode + 1);
if (len < 0)
return len;
return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
}
static int cache_mode_write(struct cgroup *cgrp, struct cftype *cft,
const char *buf)
{
int v = bch_read_string_list(buf, bch_cache_modes);
if (v < 0)
return v;
cgroup_to_bcache(cgrp)->cache_mode = v - 1;
return 0;
}
static u64 bch_verify_read(struct cgroup *cgrp, struct cftype *cft)
{
return cgroup_to_bcache(cgrp)->verify;
}
static int bch_verify_write(struct cgroup *cgrp, struct cftype *cft, u64 val)
{
cgroup_to_bcache(cgrp)->verify = val;
return 0;
}
static u64 bch_cache_hits_read(struct cgroup *cgrp, struct cftype *cft)
{
struct bch_cgroup *bcachecg = cgroup_to_bcache(cgrp);
return atomic_read(&bcachecg->stats.cache_hits);
}
static u64 bch_cache_misses_read(struct cgroup *cgrp, struct cftype *cft)
{
struct bch_cgroup *bcachecg = cgroup_to_bcache(cgrp);
return atomic_read(&bcachecg->stats.cache_misses);
}
static u64 bch_cache_bypass_hits_read(struct cgroup *cgrp,
struct cftype *cft)
{
struct bch_cgroup *bcachecg = cgroup_to_bcache(cgrp);
return atomic_read(&bcachecg->stats.cache_bypass_hits);
}
static u64 bch_cache_bypass_misses_read(struct cgroup *cgrp,
struct cftype *cft)
{
struct bch_cgroup *bcachecg = cgroup_to_bcache(cgrp);
return atomic_read(&bcachecg->stats.cache_bypass_misses);
}
static struct cftype bch_files[] = {
{
.name = "cache_mode",
.read = cache_mode_read,
.write_string = cache_mode_write,
},
{
.name = "verify",
.read_u64 = bch_verify_read,
.write_u64 = bch_verify_write,
},
{
.name = "cache_hits",
.read_u64 = bch_cache_hits_read,
},
{
.name = "cache_misses",
.read_u64 = bch_cache_misses_read,
},
{
.name = "cache_bypass_hits",
.read_u64 = bch_cache_bypass_hits_read,
},
{
.name = "cache_bypass_misses",
.read_u64 = bch_cache_bypass_misses_read,
},
{ } /* terminate */
};
static void init_bch_cgroup(struct bch_cgroup *cg)
{
cg->cache_mode = -1;
}
static struct cgroup_subsys_state *bcachecg_create(struct cgroup *cgroup)
{
struct bch_cgroup *cg;
cg = kzalloc(sizeof(*cg), GFP_KERNEL);
if (!cg)
return ERR_PTR(-ENOMEM);
init_bch_cgroup(cg);
return &cg->css;
}
static void bcachecg_destroy(struct cgroup *cgroup)
{
struct bch_cgroup *cg = cgroup_to_bcache(cgroup);
free_css_id(&bcache_subsys, &cg->css);
kfree(cg);
}
struct cgroup_subsys bcache_subsys = {
.create = bcachecg_create,
.destroy = bcachecg_destroy,
.subsys_id = bcache_subsys_id,
.name = "bcache",
.module = THIS_MODULE,
};
EXPORT_SYMBOL_GPL(bcache_subsys);
#endif
static unsigned cache_mode(struct cached_dev *dc, struct bio *bio)
{
#ifdef CONFIG_CGROUP_BCACHE
int r = bch_bio_to_cgroup(bio)->cache_mode;
if (r >= 0)
return r;
#endif
return BDEV_CACHE_MODE(&dc->sb);
}
static bool verify(struct cached_dev *dc, struct bio *bio)
{
#ifdef CONFIG_CGROUP_BCACHE
if (bch_bio_to_cgroup(bio)->verify)
return true;
#endif
return dc->verify;
}
static void bio_csum(struct bio *bio, struct bkey *k)
{
struct bio_vec *bv;
uint64_t csum = 0;
int i;
bio_for_each_segment(bv, bio, i) {
void *d = kmap(bv->bv_page) + bv->bv_offset;
csum = bch_crc64_update(csum, d, bv->bv_len);
kunmap(bv->bv_page);
}
k->ptr[KEY_PTRS(k)] = csum & (~0ULL >> 1);
}
/* Insert data into cache */
static void bio_invalidate(struct closure *cl)
{
struct btree_op *op = container_of(cl, struct btree_op, cl);
struct bio *bio = op->cache_bio;
pr_debug("invalidating %i sectors from %llu",
bio_sectors(bio), (uint64_t) bio->bi_sector);
while (bio_sectors(bio)) {
unsigned len = min(bio_sectors(bio), 1U << 14);
if (bch_keylist_realloc(&op->keys, 0, op->c))
goto out;
bio->bi_sector += len;
bio->bi_size -= len << 9;
bch_keylist_add(&op->keys,
&KEY(op->inode, bio->bi_sector, len));
}
op->insert_data_done = true;
bio_put(bio);
out:
continue_at(cl, bch_journal, bcache_wq);
}
struct open_bucket {
struct list_head list;
struct task_struct *last;
unsigned sectors_free;
BKEY_PADDED(key);
};
void bch_open_buckets_free(struct cache_set *c)
{
struct open_bucket *b;
while (!list_empty(&c->data_buckets)) {
b = list_first_entry(&c->data_buckets,
struct open_bucket, list);
list_del(&b->list);
kfree(b);
}
}
int bch_open_buckets_alloc(struct cache_set *c)
{
int i;
spin_lock_init(&c->data_bucket_lock);
for (i = 0; i < 6; i++) {
struct open_bucket *b = kzalloc(sizeof(*b), GFP_KERNEL);
if (!b)
return -ENOMEM;
list_add(&b->list, &c->data_buckets);
}
return 0;
}
/*
* We keep multiple buckets open for writes, and try to segregate different
* write streams for better cache utilization: first we look for a bucket where
* the last write to it was sequential with the current write, and failing that
* we look for a bucket that was last used by the same task.
*
* The ideas is if you've got multiple tasks pulling data into the cache at the
* same time, you'll get better cache utilization if you try to segregate their
* data and preserve locality.
*
* For example, say you've starting Firefox at the same time you're copying a
* bunch of files. Firefox will likely end up being fairly hot and stay in the
* cache awhile, but the data you copied might not be; if you wrote all that
* data to the same buckets it'd get invalidated at the same time.
*
* Both of those tasks will be doing fairly random IO so we can't rely on
* detecting sequential IO to segregate their data, but going off of the task
* should be a sane heuristic.
*/
static struct open_bucket *pick_data_bucket(struct cache_set *c,
const struct bkey *search,
struct task_struct *task,
struct bkey *alloc)
{
struct open_bucket *ret, *ret_task = NULL;
list_for_each_entry_reverse(ret, &c->data_buckets, list)
if (!bkey_cmp(&ret->key, search))
goto found;
else if (ret->last == task)
ret_task = ret;
ret = ret_task ?: list_first_entry(&c->data_buckets,
struct open_bucket, list);
found:
if (!ret->sectors_free && KEY_PTRS(alloc)) {
ret->sectors_free = c->sb.bucket_size;
bkey_copy(&ret->key, alloc);
bkey_init(alloc);
}
if (!ret->sectors_free)
ret = NULL;
return ret;
}
/*
* Allocates some space in the cache to write to, and k to point to the newly
* allocated space, and updates KEY_SIZE(k) and KEY_OFFSET(k) (to point to the
* end of the newly allocated space).
*
* May allocate fewer sectors than @sectors, KEY_SIZE(k) indicates how many
* sectors were actually allocated.
*
* If s->writeback is true, will not fail.
*/
static bool bch_alloc_sectors(struct bkey *k, unsigned sectors,
struct search *s)
{
struct cache_set *c = s->op.c;
struct open_bucket *b;
BKEY_PADDED(key) alloc;
struct closure cl, *w = NULL;
unsigned i;
if (s->writeback) {
closure_init_stack(&cl);
w = &cl;
}
/*
* We might have to allocate a new bucket, which we can't do with a
* spinlock held. So if we have to allocate, we drop the lock, allocate
* and then retry. KEY_PTRS() indicates whether alloc points to
* allocated bucket(s).
*/
bkey_init(&alloc.key);
spin_lock(&c->data_bucket_lock);
while (!(b = pick_data_bucket(c, k, s->task, &alloc.key))) {
unsigned watermark = s->op.write_prio
? WATERMARK_MOVINGGC
: WATERMARK_NONE;
spin_unlock(&c->data_bucket_lock);
if (bch_bucket_alloc_set(c, watermark, &alloc.key, 1, w))
return false;
spin_lock(&c->data_bucket_lock);
}
/*
* If we had to allocate, we might race and not need to allocate the
* second time we call find_data_bucket(). If we allocated a bucket but
* didn't use it, drop the refcount bch_bucket_alloc_set() took:
*/
if (KEY_PTRS(&alloc.key))
__bkey_put(c, &alloc.key);
for (i = 0; i < KEY_PTRS(&b->key); i++)
EBUG_ON(ptr_stale(c, &b->key, i));
/* Set up the pointer to the space we're allocating: */
for (i = 0; i < KEY_PTRS(&b->key); i++)
k->ptr[i] = b->key.ptr[i];
sectors = min(sectors, b->sectors_free);
SET_KEY_OFFSET(k, KEY_OFFSET(k) + sectors);
SET_KEY_SIZE(k, sectors);
SET_KEY_PTRS(k, KEY_PTRS(&b->key));
/*
* Move b to the end of the lru, and keep track of what this bucket was
* last used for:
*/
list_move_tail(&b->list, &c->data_buckets);
bkey_copy_key(&b->key, k);
b->last = s->task;
b->sectors_free -= sectors;
for (i = 0; i < KEY_PTRS(&b->key); i++) {
SET_PTR_OFFSET(&b->key, i, PTR_OFFSET(&b->key, i) + sectors);
atomic_long_add(sectors,
&PTR_CACHE(c, &b->key, i)->sectors_written);
}
if (b->sectors_free < c->sb.block_size)
b->sectors_free = 0;
/*
* k takes refcounts on the buckets it points to until it's inserted
* into the btree, but if we're done with this bucket we just transfer
* get_data_bucket()'s refcount.
*/
if (b->sectors_free)
for (i = 0; i < KEY_PTRS(&b->key); i++)
atomic_inc(&PTR_BUCKET(c, &b->key, i)->pin);
spin_unlock(&c->data_bucket_lock);
return true;
}
static void bch_insert_data_error(struct closure *cl)
{
struct btree_op *op = container_of(cl, struct btree_op, cl);
/*
* Our data write just errored, which means we've got a bunch of keys to
* insert that point to data that wasn't succesfully written.
*
* We don't have to insert those keys but we still have to invalidate
* that region of the cache - so, if we just strip off all the pointers
* from the keys we'll accomplish just that.
*/
struct bkey *src = op->keys.bottom, *dst = op->keys.bottom;
while (src != op->keys.top) {
struct bkey *n = bkey_next(src);
SET_KEY_PTRS(src, 0);
bkey_copy(dst, src);
dst = bkey_next(dst);
src = n;
}
op->keys.top = dst;
bch_journal(cl);
}
static void bch_insert_data_endio(struct bio *bio, int error)
{
struct closure *cl = bio->bi_private;
struct btree_op *op = container_of(cl, struct btree_op, cl);
struct search *s = container_of(op, struct search, op);
if (error) {
/* TODO: We could try to recover from this. */
if (s->writeback)
s->error = error;
else if (s->write)
set_closure_fn(cl, bch_insert_data_error, bcache_wq);
else
set_closure_fn(cl, NULL, NULL);
}
bch_bbio_endio(op->c, bio, error, "writing data to cache");
}
static void bch_insert_data_loop(struct closure *cl)
{
struct btree_op *op = container_of(cl, struct btree_op, cl);
struct search *s = container_of(op, struct search, op);
struct bio *bio = op->cache_bio, *n;
if (op->skip)
return bio_invalidate(cl);
if (atomic_sub_return(bio_sectors(bio), &op->c->sectors_to_gc) < 0) {
set_gc_sectors(op->c);
bch_queue_gc(op->c);
}
/*
* Journal writes are marked REQ_FLUSH; if the original write was a
* flush, it'll wait on the journal write.
*/
bio->bi_rw &= ~(REQ_FLUSH|REQ_FUA);
do {
unsigned i;
struct bkey *k;
struct bio_set *split = s->d
? s->d->bio_split : op->c->bio_split;
/* 1 for the device pointer and 1 for the chksum */
if (bch_keylist_realloc(&op->keys,
1 + (op->csum ? 1 : 0),
op->c))
continue_at(cl, bch_journal, bcache_wq);
k = op->keys.top;
bkey_init(k);
SET_KEY_INODE(k, op->inode);
SET_KEY_OFFSET(k, bio->bi_sector);
if (!bch_alloc_sectors(k, bio_sectors(bio), s))
goto err;
n = bch_bio_split(bio, KEY_SIZE(k), GFP_NOIO, split);
if (!n) {
__bkey_put(op->c, k);
continue_at(cl, bch_insert_data_loop, bcache_wq);
}
n->bi_end_io = bch_insert_data_endio;
n->bi_private = cl;
if (s->writeback) {
SET_KEY_DIRTY(k, true);
for (i = 0; i < KEY_PTRS(k); i++)
SET_GC_MARK(PTR_BUCKET(op->c, k, i),
GC_MARK_DIRTY);
}
SET_KEY_CSUM(k, op->csum);
if (KEY_CSUM(k))
bio_csum(n, k);
pr_debug("%s", pkey(k));
bch_keylist_push(&op->keys);
trace_bcache_cache_insert(n, n->bi_sector, n->bi_bdev);
n->bi_rw |= REQ_WRITE;
bch_submit_bbio(n, op->c, k, 0);
} while (n != bio);
op->insert_data_done = true;
continue_at(cl, bch_journal, bcache_wq);
err:
/* bch_alloc_sectors() blocks if s->writeback = true */
BUG_ON(s->writeback);
/*
* But if it's not a writeback write we'd rather just bail out if
* there aren't any buckets ready to write to - it might take awhile and
* we might be starving btree writes for gc or something.
*/
if (s->write) {
/*
* Writethrough write: We can't complete the write until we've
* updated the index. But we don't want to delay the write while
* we wait for buckets to be freed up, so just invalidate the
* rest of the write.
*/
op->skip = true;
return bio_invalidate(cl);
} else {
/*
* From a cache miss, we can just insert the keys for the data
* we have written or bail out if we didn't do anything.
*/
op->insert_data_done = true;
bio_put(bio);
if (!bch_keylist_empty(&op->keys))
continue_at(cl, bch_journal, bcache_wq);
else
closure_return(cl);
}
}
/**
* bch_insert_data - stick some data in the cache
*
* This is the starting point for any data to end up in a cache device; it could
* be from a normal write, or a writeback write, or a write to a flash only
* volume - it's also used by the moving garbage collector to compact data in
* mostly empty buckets.
*
* It first writes the data to the cache, creating a list of keys to be inserted
* (if the data had to be fragmented there will be multiple keys); after the
* data is written it calls bch_journal, and after the keys have been added to
* the next journal write they're inserted into the btree.
*
* It inserts the data in op->cache_bio; bi_sector is used for the key offset,
* and op->inode is used for the key inode.
*
* If op->skip is true, instead of inserting the data it invalidates the region
* of the cache represented by op->cache_bio and op->inode.
*/
void bch_insert_data(struct closure *cl)
{
struct btree_op *op = container_of(cl, struct btree_op, cl);
bch_keylist_init(&op->keys);
bio_get(op->cache_bio);
bch_insert_data_loop(cl);
}
void bch_btree_insert_async(struct closure *cl)
{
struct btree_op *op = container_of(cl, struct btree_op, cl);
struct search *s = container_of(op, struct search, op);
if (bch_btree_insert(op, op->c)) {
s->error = -ENOMEM;
op->insert_data_done = true;
}
if (op->insert_data_done) {
bch_keylist_free(&op->keys);
closure_return(cl);
} else
continue_at(cl, bch_insert_data_loop, bcache_wq);
}
/* Common code for the make_request functions */
static void request_endio(struct bio *bio, int error)
{
struct closure *cl = bio->bi_private;
if (error) {
struct search *s = container_of(cl, struct search, cl);
s->error = error;
/* Only cache read errors are recoverable */
s->recoverable = false;
}
bio_put(bio);
closure_put(cl);
}
void bch_cache_read_endio(struct bio *bio, int error)
{
struct bbio *b = container_of(bio, struct bbio, bio);
struct closure *cl = bio->bi_private;
struct search *s = container_of(cl, struct search, cl);
/*
* If the bucket was reused while our bio was in flight, we might have
* read the wrong data. Set s->error but not error so it doesn't get
* counted against the cache device, but we'll still reread the data
* from the backing device.
*/
if (error)
s->error = error;
else if (ptr_stale(s->op.c, &b->key, 0)) {
atomic_long_inc(&s->op.c->cache_read_races);
s->error = -EINTR;
}
bch_bbio_endio(s->op.c, bio, error, "reading from cache");
}
static void bio_complete(struct search *s)
{
if (s->orig_bio) {
int cpu, rw = bio_data_dir(s->orig_bio);
unsigned long duration = jiffies - s->start_time;
cpu = part_stat_lock();
part_round_stats(cpu, &s->d->disk->part0);
part_stat_add(cpu, &s->d->disk->part0, ticks[rw], duration);
part_stat_unlock();
trace_bcache_request_end(s, s->orig_bio);
bio_endio(s->orig_bio, s->error);
s->orig_bio = NULL;
}
}
static void do_bio_hook(struct search *s)
{
struct bio *bio = &s->bio.bio;
memcpy(bio, s->orig_bio, sizeof(struct bio));
bio->bi_end_io = request_endio;
bio->bi_private = &s->cl;
atomic_set(&bio->bi_cnt, 3);
}
static void search_free(struct closure *cl)
{
struct search *s = container_of(cl, struct search, cl);
bio_complete(s);
if (s->op.cache_bio)
bio_put(s->op.cache_bio);
if (s->unaligned_bvec)
mempool_free(s->bio.bio.bi_io_vec, s->d->unaligned_bvec);
closure_debug_destroy(cl);
mempool_free(s, s->d->c->search);
}
static struct search *search_alloc(struct bio *bio, struct bcache_device *d)
{
struct bio_vec *bv;
struct search *s = mempool_alloc(d->c->search, GFP_NOIO);
memset(s, 0, offsetof(struct search, op.keys));
__closure_init(&s->cl, NULL);
s->op.inode = d->id;
s->op.c = d->c;
s->d = d;
s->op.lock = -1;
s->task = current;
s->orig_bio = bio;
s->write = (bio->bi_rw & REQ_WRITE) != 0;
s->op.flush_journal = (bio->bi_rw & (REQ_FLUSH|REQ_FUA)) != 0;
s->op.skip = (bio->bi_rw & REQ_DISCARD) != 0;
s->recoverable = 1;
s->start_time = jiffies;
do_bio_hook(s);
if (bio->bi_size != bio_segments(bio) * PAGE_SIZE) {
bv = mempool_alloc(d->unaligned_bvec, GFP_NOIO);
memcpy(bv, bio_iovec(bio),
sizeof(struct bio_vec) * bio_segments(bio));
s->bio.bio.bi_io_vec = bv;
s->unaligned_bvec = 1;
}
return s;
}
static void btree_read_async(struct closure *cl)
{
struct btree_op *op = container_of(cl, struct btree_op, cl);
int ret = btree_root(search_recurse, op->c, op);
if (ret == -EAGAIN)
continue_at(cl, btree_read_async, bcache_wq);
closure_return(cl);
}
/* Cached devices */
static void cached_dev_bio_complete(struct closure *cl)
{
struct search *s = container_of(cl, struct search, cl);
struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
search_free(cl);
cached_dev_put(dc);
}
/* Process reads */
static void cached_dev_read_complete(struct closure *cl)
{
struct search *s = container_of(cl, struct search, cl);
if (s->op.insert_collision)
bch_mark_cache_miss_collision(s);
if (s->op.cache_bio) {
int i;
struct bio_vec *bv;
__bio_for_each_segment(bv, s->op.cache_bio, i, 0)
__free_page(bv->bv_page);
}
cached_dev_bio_complete(cl);
}
static void request_read_error(struct closure *cl)
{
struct search *s = container_of(cl, struct search, cl);
struct bio_vec *bv;
int i;
if (s->recoverable) {
/* The cache read failed, but we can retry from the backing
* device.
*/
pr_debug("recovering at sector %llu",
(uint64_t) s->orig_bio->bi_sector);
s->error = 0;
bv = s->bio.bio.bi_io_vec;
do_bio_hook(s);
s->bio.bio.bi_io_vec = bv;
if (!s->unaligned_bvec)
bio_for_each_segment(bv, s->orig_bio, i)
bv->bv_offset = 0, bv->bv_len = PAGE_SIZE;
else
memcpy(s->bio.bio.bi_io_vec,
bio_iovec(s->orig_bio),
sizeof(struct bio_vec) *
bio_segments(s->orig_bio));
/* XXX: invalidate cache */
trace_bcache_read_retry(&s->bio.bio);
closure_bio_submit(&s->bio.bio, &s->cl, s->d);
}
continue_at(cl, cached_dev_read_complete, NULL);
}
static void request_read_done(struct closure *cl)
{
struct search *s = container_of(cl, struct search, cl);
struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
/*
* s->cache_bio != NULL implies that we had a cache miss; cache_bio now
* contains data ready to be inserted into the cache.
*
* First, we copy the data we just read from cache_bio's bounce buffers
* to the buffers the original bio pointed to:
*/
if (s->op.cache_bio) {
struct bio_vec *src, *dst;
unsigned src_offset, dst_offset, bytes;
void *dst_ptr;
bio_reset(s->op.cache_bio);
s->op.cache_bio->bi_sector = s->cache_miss->bi_sector;
s->op.cache_bio->bi_bdev = s->cache_miss->bi_bdev;
s->op.cache_bio->bi_size = s->cache_bio_sectors << 9;
bch_bio_map(s->op.cache_bio, NULL);
src = bio_iovec(s->op.cache_bio);
dst = bio_iovec(s->cache_miss);
src_offset = src->bv_offset;
dst_offset = dst->bv_offset;
dst_ptr = kmap(dst->bv_page);
while (1) {
if (dst_offset == dst->bv_offset + dst->bv_len) {
kunmap(dst->bv_page);
dst++;
if (dst == bio_iovec_idx(s->cache_miss,
s->cache_miss->bi_vcnt))
break;
dst_offset = dst->bv_offset;
dst_ptr = kmap(dst->bv_page);
}
if (src_offset == src->bv_offset + src->bv_len) {
src++;
if (src == bio_iovec_idx(s->op.cache_bio,
s->op.cache_bio->bi_vcnt))
BUG();
src_offset = src->bv_offset;
}
bytes = min(dst->bv_offset + dst->bv_len - dst_offset,
src->bv_offset + src->bv_len - src_offset);
memcpy(dst_ptr + dst_offset,
page_address(src->bv_page) + src_offset,
bytes);
src_offset += bytes;
dst_offset += bytes;
}
bio_put(s->cache_miss);
s->cache_miss = NULL;
}
if (verify(dc, &s->bio.bio) && s->recoverable)
bch_data_verify(s);
bio_complete(s);
if (s->op.cache_bio &&
!test_bit(CACHE_SET_STOPPING, &s->op.c->flags)) {
s->op.type = BTREE_REPLACE;
closure_call(&s->op.cl, bch_insert_data, NULL, cl);
}
continue_at(cl, cached_dev_read_complete, NULL);
}
static void request_read_done_bh(struct closure *cl)
{
struct search *s = container_of(cl, struct search, cl);
struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
bch_mark_cache_accounting(s, !s->cache_miss, s->op.skip);
if (s->error)
continue_at_nobarrier(cl, request_read_error, bcache_wq);
else if (s->op.cache_bio || verify(dc, &s->bio.bio))
continue_at_nobarrier(cl, request_read_done, bcache_wq);
else
continue_at_nobarrier(cl, cached_dev_read_complete, NULL);
}
static int cached_dev_cache_miss(struct btree *b, struct search *s,
struct bio *bio, unsigned sectors)
{
int ret = 0;
unsigned reada;
struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
struct bio *miss;
miss = bch_bio_split(bio, sectors, GFP_NOIO, s->d->bio_split);
if (!miss)
return -EAGAIN;
if (miss == bio)
s->op.lookup_done = true;
miss->bi_end_io = request_endio;
miss->bi_private = &s->cl;
if (s->cache_miss || s->op.skip)
goto out_submit;
if (miss != bio ||
(bio->bi_rw & REQ_RAHEAD) ||
(bio->bi_rw & REQ_META) ||
s->op.c->gc_stats.in_use >= CUTOFF_CACHE_READA)
reada = 0;
else {
reada = min(dc->readahead >> 9,
sectors - bio_sectors(miss));
if (bio_end(miss) + reada > bdev_sectors(miss->bi_bdev))
reada = bdev_sectors(miss->bi_bdev) - bio_end(miss);
}
s->cache_bio_sectors = bio_sectors(miss) + reada;
s->op.cache_bio = bio_alloc_bioset(GFP_NOWAIT,
DIV_ROUND_UP(s->cache_bio_sectors, PAGE_SECTORS),
dc->disk.bio_split);
if (!s->op.cache_bio)
goto out_submit;
s->op.cache_bio->bi_sector = miss->bi_sector;
s->op.cache_bio->bi_bdev = miss->bi_bdev;
s->op.cache_bio->bi_size = s->cache_bio_sectors << 9;
s->op.cache_bio->bi_end_io = request_endio;
s->op.cache_bio->bi_private = &s->cl;
/* btree_search_recurse()'s btree iterator is no good anymore */
ret = -EINTR;
if (!bch_btree_insert_check_key(b, &s->op, s->op.cache_bio))
goto out_put;
bch_bio_map(s->op.cache_bio, NULL);
if (bch_bio_alloc_pages(s->op.cache_bio, __GFP_NOWARN|GFP_NOIO))
goto out_put;
s->cache_miss = miss;
bio_get(s->op.cache_bio);
trace_bcache_cache_miss(s->orig_bio);
closure_bio_submit(s->op.cache_bio, &s->cl, s->d);
return ret;
out_put:
bio_put(s->op.cache_bio);
s->op.cache_bio = NULL;
out_submit:
closure_bio_submit(miss, &s->cl, s->d);
return ret;
}
static void request_read(struct cached_dev *dc, struct search *s)
{
struct closure *cl = &s->cl;
check_should_skip(dc, s);
closure_call(&s->op.cl, btree_read_async, NULL, cl);
continue_at(cl, request_read_done_bh, NULL);
}
/* Process writes */
static void cached_dev_write_complete(struct closure *cl)
{
struct search *s = container_of(cl, struct search, cl);
struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
up_read_non_owner(&dc->writeback_lock);
cached_dev_bio_complete(cl);
}
static bool should_writeback(struct cached_dev *dc, struct bio *bio)
{
unsigned threshold = (bio->bi_rw & REQ_SYNC)
? CUTOFF_WRITEBACK_SYNC
: CUTOFF_WRITEBACK;
return !atomic_read(&dc->disk.detaching) &&
cache_mode(dc, bio) == CACHE_MODE_WRITEBACK &&
dc->disk.c->gc_stats.in_use < threshold;
}
static void request_write(struct cached_dev *dc, struct search *s)
{
struct closure *cl = &s->cl;
struct bio *bio = &s->bio.bio;
struct bkey start, end;
start = KEY(dc->disk.id, bio->bi_sector, 0);
end = KEY(dc->disk.id, bio_end(bio), 0);
bch_keybuf_check_overlapping(&s->op.c->moving_gc_keys, &start, &end);
check_should_skip(dc, s);
down_read_non_owner(&dc->writeback_lock);
if (bch_keybuf_check_overlapping(&dc->writeback_keys, &start, &end)) {
s->op.skip = false;
s->writeback = true;
}
if (bio->bi_rw & REQ_DISCARD)
goto skip;
if (s->op.skip)
goto skip;
if (should_writeback(dc, s->orig_bio))
s->writeback = true;
if (!s->writeback) {
s->op.cache_bio = bio_clone_bioset(bio, GFP_NOIO,
dc->disk.bio_split);
trace_bcache_writethrough(s->orig_bio);
closure_bio_submit(bio, cl, s->d);
} else {
trace_bcache_writeback(s->orig_bio);
bch_writeback_add(dc, bio_sectors(bio));
s->op.cache_bio = bio;
if (bio->bi_rw & REQ_FLUSH) {
/* Also need to send a flush to the backing device */
struct bio *flush = bio_alloc_bioset(GFP_NOIO, 0,
dc->disk.bio_split);
flush->bi_rw = WRITE_FLUSH;
flush->bi_bdev = bio->bi_bdev;
flush->bi_end_io = request_endio;
flush->bi_private = cl;
closure_bio_submit(flush, cl, s->d);
}
}
out:
closure_call(&s->op.cl, bch_insert_data, NULL, cl);
continue_at(cl, cached_dev_write_complete, NULL);
skip:
s->op.skip = true;
s->op.cache_bio = s->orig_bio;
bio_get(s->op.cache_bio);
trace_bcache_write_skip(s->orig_bio);
if ((bio->bi_rw & REQ_DISCARD) &&
!blk_queue_discard(bdev_get_queue(dc->bdev)))
goto out;
closure_bio_submit(bio, cl, s->d);
goto out;
}
static void request_nodata(struct cached_dev *dc, struct search *s)
{
struct closure *cl = &s->cl;
struct bio *bio = &s->bio.bio;
if (bio->bi_rw & REQ_DISCARD) {
request_write(dc, s);
return;
}
if (s->op.flush_journal)
bch_journal_meta(s->op.c, cl);
closure_bio_submit(bio, cl, s->d);
continue_at(cl, cached_dev_bio_complete, NULL);
}
/* Cached devices - read & write stuff */
int bch_get_congested(struct cache_set *c)
{
int i;
if (!c->congested_read_threshold_us &&
!c->congested_write_threshold_us)
return 0;
i = (local_clock_us() - c->congested_last_us) / 1024;
if (i < 0)
return 0;
i += atomic_read(&c->congested);
if (i >= 0)
return 0;
i += CONGESTED_MAX;
return i <= 0 ? 1 : fract_exp_two(i, 6);
}
static void add_sequential(struct task_struct *t)
{
ewma_add(t->sequential_io_avg,
t->sequential_io, 8, 0);
t->sequential_io = 0;
}
static struct hlist_head *iohash(struct cached_dev *dc, uint64_t k)
{
return &dc->io_hash[hash_64(k, RECENT_IO_BITS)];
}
static void check_should_skip(struct cached_dev *dc, struct search *s)
{
struct cache_set *c = s->op.c;
struct bio *bio = &s->bio.bio;
long rand;
int cutoff = bch_get_congested(c);
unsigned mode = cache_mode(dc, bio);
if (atomic_read(&dc->disk.detaching) ||
c->gc_stats.in_use > CUTOFF_CACHE_ADD ||
(bio->bi_rw & REQ_DISCARD))
goto skip;
if (mode == CACHE_MODE_NONE ||
(mode == CACHE_MODE_WRITEAROUND &&
(bio->bi_rw & REQ_WRITE)))
goto skip;
if (bio->bi_sector & (c->sb.block_size - 1) ||
bio_sectors(bio) & (c->sb.block_size - 1)) {
pr_debug("skipping unaligned io");
goto skip;
}
if (!cutoff) {
cutoff = dc->sequential_cutoff >> 9;
if (!cutoff)
goto rescale;
if (mode == CACHE_MODE_WRITEBACK &&
(bio->bi_rw & REQ_WRITE) &&
(bio->bi_rw & REQ_SYNC))
goto rescale;
}
if (dc->sequential_merge) {
struct io *i;
spin_lock(&dc->io_lock);
hlist_for_each_entry(i, iohash(dc, bio->bi_sector), hash)
if (i->last == bio->bi_sector &&
time_before(jiffies, i->jiffies))
goto found;
i = list_first_entry(&dc->io_lru, struct io, lru);
add_sequential(s->task);
i->sequential = 0;
found:
if (i->sequential + bio->bi_size > i->sequential)
i->sequential += bio->bi_size;
i->last = bio_end(bio);
i->jiffies = jiffies + msecs_to_jiffies(5000);
s->task->sequential_io = i->sequential;
hlist_del(&i->hash);
hlist_add_head(&i->hash, iohash(dc, i->last));
list_move_tail(&i->lru, &dc->io_lru);
spin_unlock(&dc->io_lock);
} else {
s->task->sequential_io = bio->bi_size;
add_sequential(s->task);
}
rand = get_random_int();
cutoff -= bitmap_weight(&rand, BITS_PER_LONG);
if (cutoff <= (int) (max(s->task->sequential_io,
s->task->sequential_io_avg) >> 9))
goto skip;
rescale:
bch_rescale_priorities(c, bio_sectors(bio));
return;
skip:
bch_mark_sectors_bypassed(s, bio_sectors(bio));
s->op.skip = true;
}
static void cached_dev_make_request(struct request_queue *q, struct bio *bio)
{
struct search *s;
struct bcache_device *d = bio->bi_bdev->bd_disk->private_data;
struct cached_dev *dc = container_of(d, struct cached_dev, disk);
int cpu, rw = bio_data_dir(bio);
cpu = part_stat_lock();
part_stat_inc(cpu, &d->disk->part0, ios[rw]);
part_stat_add(cpu, &d->disk->part0, sectors[rw], bio_sectors(bio));
part_stat_unlock();
bio->bi_bdev = dc->bdev;
bio->bi_sector += dc->sb.data_offset;
if (cached_dev_get(dc)) {
s = search_alloc(bio, d);
trace_bcache_request_start(s, bio);
if (!bio_has_data(bio))
request_nodata(dc, s);
else if (rw)
request_write(dc, s);
else
request_read(dc, s);
} else {
if ((bio->bi_rw & REQ_DISCARD) &&
!blk_queue_discard(bdev_get_queue(dc->bdev)))
bio_endio(bio, 0);
else
bch_generic_make_request(bio, &d->bio_split_hook);
}
}
static int cached_dev_ioctl(struct bcache_device *d, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct cached_dev *dc = container_of(d, struct cached_dev, disk);
return __blkdev_driver_ioctl(dc->bdev, mode, cmd, arg);
}
static int cached_dev_congested(void *data, int bits)
{
struct bcache_device *d = data;
struct cached_dev *dc = container_of(d, struct cached_dev, disk);
struct request_queue *q = bdev_get_queue(dc->bdev);
int ret = 0;
if (bdi_congested(&q->backing_dev_info, bits))
return 1;
if (cached_dev_get(dc)) {
unsigned i;
struct cache *ca;
for_each_cache(ca, d->c, i) {
q = bdev_get_queue(ca->bdev);
ret |= bdi_congested(&q->backing_dev_info, bits);
}
cached_dev_put(dc);
}
return ret;
}
void bch_cached_dev_request_init(struct cached_dev *dc)
{
struct gendisk *g = dc->disk.disk;
g->queue->make_request_fn = cached_dev_make_request;
g->queue->backing_dev_info.congested_fn = cached_dev_congested;
dc->disk.cache_miss = cached_dev_cache_miss;
dc->disk.ioctl = cached_dev_ioctl;
}
/* Flash backed devices */
static int flash_dev_cache_miss(struct btree *b, struct search *s,
struct bio *bio, unsigned sectors)
{
/* Zero fill bio */
while (bio->bi_idx != bio->bi_vcnt) {
struct bio_vec *bv = bio_iovec(bio);
unsigned j = min(bv->bv_len >> 9, sectors);
void *p = kmap(bv->bv_page);
memset(p + bv->bv_offset, 0, j << 9);
kunmap(bv->bv_page);
bv->bv_len -= j << 9;
bv->bv_offset += j << 9;
if (bv->bv_len)
return 0;
bio->bi_sector += j;
bio->bi_size -= j << 9;
bio->bi_idx++;
sectors -= j;
}
s->op.lookup_done = true;
return 0;
}
static void flash_dev_make_request(struct request_queue *q, struct bio *bio)
{
struct search *s;
struct closure *cl;
struct bcache_device *d = bio->bi_bdev->bd_disk->private_data;
int cpu, rw = bio_data_dir(bio);
cpu = part_stat_lock();
part_stat_inc(cpu, &d->disk->part0, ios[rw]);
part_stat_add(cpu, &d->disk->part0, sectors[rw], bio_sectors(bio));
part_stat_unlock();
s = search_alloc(bio, d);
cl = &s->cl;
bio = &s->bio.bio;
trace_bcache_request_start(s, bio);
if (bio_has_data(bio) && !rw) {
closure_call(&s->op.cl, btree_read_async, NULL, cl);
} else if (bio_has_data(bio) || s->op.skip) {
bch_keybuf_check_overlapping(&s->op.c->moving_gc_keys,
&KEY(d->id, bio->bi_sector, 0),
&KEY(d->id, bio_end(bio), 0));
s->writeback = true;
s->op.cache_bio = bio;
closure_call(&s->op.cl, bch_insert_data, NULL, cl);
} else {
/* No data - probably a cache flush */
if (s->op.flush_journal)
bch_journal_meta(s->op.c, cl);
}
continue_at(cl, search_free, NULL);
}
static int flash_dev_ioctl(struct bcache_device *d, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
return -ENOTTY;
}
static int flash_dev_congested(void *data, int bits)
{
struct bcache_device *d = data;
struct request_queue *q;
struct cache *ca;
unsigned i;
int ret = 0;
for_each_cache(ca, d->c, i) {
q = bdev_get_queue(ca->bdev);
ret |= bdi_congested(&q->backing_dev_info, bits);
}
return ret;
}
void bch_flash_dev_request_init(struct bcache_device *d)
{
struct gendisk *g = d->disk;
g->queue->make_request_fn = flash_dev_make_request;
g->queue->backing_dev_info.congested_fn = flash_dev_congested;
d->cache_miss = flash_dev_cache_miss;
d->ioctl = flash_dev_ioctl;
}
void bch_request_exit(void)
{
#ifdef CONFIG_CGROUP_BCACHE
cgroup_unload_subsys(&bcache_subsys);
#endif
if (bch_search_cache)
kmem_cache_destroy(bch_search_cache);
}
int __init bch_request_init(void)
{
bch_search_cache = KMEM_CACHE(search, 0);
if (!bch_search_cache)
return -ENOMEM;
#ifdef CONFIG_CGROUP_BCACHE
cgroup_load_subsys(&bcache_subsys);
init_bch_cgroup(&bcache_default_cgroup);
cgroup_add_cftypes(&bcache_subsys, bch_files);
#endif
return 0;
}
| gpl-2.0 |
kabata1975/emotion_shamu_kernel | drivers/net/wireless/rtlwifi/rtl8192cu/mac.c | 1797 | 32499 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
****************************************************************************/
#include "../wifi.h"
#include "../pci.h"
#include "../usb.h"
#include "../ps.h"
#include "../cam.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "rf.h"
#include "dm.h"
#include "mac.h"
#include "trx.h"
#include <linux/module.h>
/* macro to shorten lines */
#define LINK_Q ui_link_quality
#define RX_EVM rx_evm_percentage
#define RX_SIGQ rx_mimo_sig_qual
void rtl92c_read_chip_version(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_hal *rtlhal = rtl_hal(rtlpriv);
enum version_8192c chip_version = VERSION_UNKNOWN;
const char *versionid;
u32 value32;
value32 = rtl_read_dword(rtlpriv, REG_SYS_CFG);
if (value32 & TRP_VAUX_EN) {
chip_version = (value32 & TYPE_ID) ? VERSION_TEST_CHIP_92C :
VERSION_TEST_CHIP_88C;
} else {
/* Normal mass production chip. */
chip_version = NORMAL_CHIP;
chip_version |= ((value32 & TYPE_ID) ? CHIP_92C : 0);
chip_version |= ((value32 & VENDOR_ID) ? CHIP_VENDOR_UMC : 0);
/* RTL8723 with BT function. */
chip_version |= ((value32 & BT_FUNC) ? CHIP_8723 : 0);
if (IS_VENDOR_UMC(chip_version))
chip_version |= ((value32 & CHIP_VER_RTL_MASK) ?
CHIP_VENDOR_UMC_B_CUT : 0);
if (IS_92C_SERIAL(chip_version)) {
value32 = rtl_read_dword(rtlpriv, REG_HPON_FSM);
chip_version |= ((CHIP_BONDING_IDENTIFIER(value32) ==
CHIP_BONDING_92C_1T2R) ? CHIP_92C_1T2R : 0);
} else if (IS_8723_SERIES(chip_version)) {
value32 = rtl_read_dword(rtlpriv, REG_GPIO_OUTSTS);
chip_version |= ((value32 & RF_RL_ID) ?
CHIP_8723_DRV_REV : 0);
}
}
rtlhal->version = (enum version_8192c)chip_version;
pr_info("Chip version 0x%x\n", chip_version);
switch (rtlhal->version) {
case VERSION_NORMAL_TSMC_CHIP_92C_1T2R:
versionid = "NORMAL_B_CHIP_92C";
break;
case VERSION_NORMAL_TSMC_CHIP_92C:
versionid = "NORMAL_TSMC_CHIP_92C";
break;
case VERSION_NORMAL_TSMC_CHIP_88C:
versionid = "NORMAL_TSMC_CHIP_88C";
break;
case VERSION_NORMAL_UMC_CHIP_92C_1T2R_A_CUT:
versionid = "NORMAL_UMC_CHIP_i92C_1T2R_A_CUT";
break;
case VERSION_NORMAL_UMC_CHIP_92C_A_CUT:
versionid = "NORMAL_UMC_CHIP_92C_A_CUT";
break;
case VERSION_NORMAL_UMC_CHIP_88C_A_CUT:
versionid = "NORMAL_UMC_CHIP_88C_A_CUT";
break;
case VERSION_NORMAL_UMC_CHIP_92C_1T2R_B_CUT:
versionid = "NORMAL_UMC_CHIP_92C_1T2R_B_CUT";
break;
case VERSION_NORMAL_UMC_CHIP_92C_B_CUT:
versionid = "NORMAL_UMC_CHIP_92C_B_CUT";
break;
case VERSION_NORMAL_UMC_CHIP_88C_B_CUT:
versionid = "NORMAL_UMC_CHIP_88C_B_CUT";
break;
case VERSION_NORMA_UMC_CHIP_8723_1T1R_A_CUT:
versionid = "NORMAL_UMC_CHIP_8723_1T1R_A_CUT";
break;
case VERSION_NORMA_UMC_CHIP_8723_1T1R_B_CUT:
versionid = "NORMAL_UMC_CHIP_8723_1T1R_B_CUT";
break;
case VERSION_TEST_CHIP_92C:
versionid = "TEST_CHIP_92C";
break;
case VERSION_TEST_CHIP_88C:
versionid = "TEST_CHIP_88C";
break;
default:
versionid = "UNKNOWN";
break;
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Chip Version ID: %s\n", versionid);
if (IS_92C_SERIAL(rtlhal->version))
rtlphy->rf_type =
(IS_92C_1T2R(rtlhal->version)) ? RF_1T2R : RF_2T2R;
else
rtlphy->rf_type = RF_1T1R;
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"Chip RF Type: %s\n",
rtlphy->rf_type == RF_2T2R ? "RF_2T2R" : "RF_1T1R");
if (get_rf_type(rtlphy) == RF_1T1R)
rtlpriv->dm.rfpath_rxenable[0] = true;
else
rtlpriv->dm.rfpath_rxenable[0] =
rtlpriv->dm.rfpath_rxenable[1] = true;
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD, "VersionID = 0x%4x\n",
rtlhal->version);
}
/**
* writeLLT - LLT table write access
* @io: io callback
* @address: LLT logical address.
* @data: LLT data content
*
* Realtek hardware access function.
*
*/
bool rtl92c_llt_write(struct ieee80211_hw *hw, u32 address, u32 data)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
bool status = true;
long count = 0;
u32 value = _LLT_INIT_ADDR(address) |
_LLT_INIT_DATA(data) | _LLT_OP(_LLT_WRITE_ACCESS);
rtl_write_dword(rtlpriv, REG_LLT_INIT, value);
do {
value = rtl_read_dword(rtlpriv, REG_LLT_INIT);
if (_LLT_NO_ACTIVE == _LLT_OP_VALUE(value))
break;
if (count > POLLING_LLT_THRESHOLD) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Failed to polling write LLT done at address %d! _LLT_OP_VALUE(%x)\n",
address, _LLT_OP_VALUE(value));
status = false;
break;
}
} while (++count);
return status;
}
/**
* rtl92c_init_LLT_table - Init LLT table
* @io: io callback
* @boundary:
*
* Realtek hardware access function.
*
*/
bool rtl92c_init_llt_table(struct ieee80211_hw *hw, u32 boundary)
{
bool rst = true;
u32 i;
for (i = 0; i < (boundary - 1); i++) {
rst = rtl92c_llt_write(hw, i , i + 1);
if (true != rst) {
pr_err("===> %s #1 fail\n", __func__);
return rst;
}
}
/* end of list */
rst = rtl92c_llt_write(hw, (boundary - 1), 0xFF);
if (true != rst) {
pr_err("===> %s #2 fail\n", __func__);
return rst;
}
/* Make the other pages as ring buffer
* This ring buffer is used as beacon buffer if we config this MAC
* as two MAC transfer.
* Otherwise used as local loopback buffer.
*/
for (i = boundary; i < LLT_LAST_ENTRY_OF_TX_PKT_BUFFER; i++) {
rst = rtl92c_llt_write(hw, i, (i + 1));
if (true != rst) {
pr_err("===> %s #3 fail\n", __func__);
return rst;
}
}
/* Let last entry point to the start entry of ring buffer */
rst = rtl92c_llt_write(hw, LLT_LAST_ENTRY_OF_TX_PKT_BUFFER, boundary);
if (true != rst) {
pr_err("===> %s #4 fail\n", __func__);
return rst;
}
return rst;
}
void rtl92c_set_key(struct ieee80211_hw *hw, u32 key_index,
u8 *p_macaddr, bool is_group, u8 enc_algo,
bool is_wepkey, bool clear_all)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u8 *macaddr = p_macaddr;
u32 entry_id = 0;
bool is_pairwise = false;
static u8 cam_const_addr[4][6] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x03}
};
static u8 cam_const_broad[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
if (clear_all) {
u8 idx = 0;
u8 cam_offset = 0;
u8 clear_number = 5;
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "clear_all\n");
for (idx = 0; idx < clear_number; idx++) {
rtl_cam_mark_invalid(hw, cam_offset + idx);
rtl_cam_empty_entry(hw, cam_offset + idx);
if (idx < 5) {
memset(rtlpriv->sec.key_buf[idx], 0,
MAX_KEY_LEN);
rtlpriv->sec.key_len[idx] = 0;
}
}
} else {
switch (enc_algo) {
case WEP40_ENCRYPTION:
enc_algo = CAM_WEP40;
break;
case WEP104_ENCRYPTION:
enc_algo = CAM_WEP104;
break;
case TKIP_ENCRYPTION:
enc_algo = CAM_TKIP;
break;
case AESCCMP_ENCRYPTION:
enc_algo = CAM_AES;
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"illegal switch case\n");
enc_algo = CAM_TKIP;
break;
}
if (is_wepkey || rtlpriv->sec.use_defaultkey) {
macaddr = cam_const_addr[key_index];
entry_id = key_index;
} else {
if (is_group) {
macaddr = cam_const_broad;
entry_id = key_index;
} else {
if (mac->opmode == NL80211_IFTYPE_AP ||
mac->opmode == NL80211_IFTYPE_MESH_POINT) {
entry_id = rtl_cam_get_free_entry(hw,
p_macaddr);
if (entry_id >= TOTAL_CAM_ENTRY) {
RT_TRACE(rtlpriv, COMP_SEC,
DBG_EMERG,
"Can not find free hw security cam entry\n");
return;
}
} else {
entry_id = CAM_PAIRWISE_KEY_POSITION;
}
key_index = PAIRWISE_KEYIDX;
is_pairwise = true;
}
}
if (rtlpriv->sec.key_len[key_index] == 0) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"delete one entry\n");
if (mac->opmode == NL80211_IFTYPE_AP ||
mac->opmode == NL80211_IFTYPE_MESH_POINT)
rtl_cam_del_entry(hw, p_macaddr);
rtl_cam_delete_one_entry(hw, p_macaddr, entry_id);
} else {
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"The insert KEY length is %d\n",
rtlpriv->sec.key_len[PAIRWISE_KEYIDX]);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"The insert KEY is %x %x\n",
rtlpriv->sec.key_buf[0][0],
rtlpriv->sec.key_buf[0][1]);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"add one entry\n");
if (is_pairwise) {
RT_PRINT_DATA(rtlpriv, COMP_SEC, DBG_LOUD,
"Pairwise Key content",
rtlpriv->sec.pairwise_key,
rtlpriv->sec.
key_len[PAIRWISE_KEYIDX]);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"set Pairwise key\n");
rtl_cam_add_one_entry(hw, macaddr, key_index,
entry_id, enc_algo,
CAM_CONFIG_NO_USEDK,
rtlpriv->sec.
key_buf[key_index]);
} else {
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"set group key\n");
if (mac->opmode == NL80211_IFTYPE_ADHOC) {
rtl_cam_add_one_entry(hw,
rtlefuse->dev_addr,
PAIRWISE_KEYIDX,
CAM_PAIRWISE_KEY_POSITION,
enc_algo,
CAM_CONFIG_NO_USEDK,
rtlpriv->sec.key_buf
[entry_id]);
}
rtl_cam_add_one_entry(hw, macaddr, key_index,
entry_id, enc_algo,
CAM_CONFIG_NO_USEDK,
rtlpriv->sec.key_buf[entry_id]);
}
}
}
}
u32 rtl92c_get_txdma_status(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
return rtl_read_dword(rtlpriv, REG_TXDMA_STATUS);
}
void rtl92c_enable_interrupt(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
if (IS_HARDWARE_TYPE_8192CE(rtlhal)) {
rtl_write_dword(rtlpriv, REG_HIMR, rtlpci->irq_mask[0] &
0xFFFFFFFF);
rtl_write_dword(rtlpriv, REG_HIMRE, rtlpci->irq_mask[1] &
0xFFFFFFFF);
} else {
rtl_write_dword(rtlpriv, REG_HIMR, rtlusb->irq_mask[0] &
0xFFFFFFFF);
rtl_write_dword(rtlpriv, REG_HIMRE, rtlusb->irq_mask[1] &
0xFFFFFFFF);
}
}
void rtl92c_init_interrupt(struct ieee80211_hw *hw)
{
rtl92c_enable_interrupt(hw);
}
void rtl92c_disable_interrupt(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_dword(rtlpriv, REG_HIMR, IMR8190_DISABLED);
rtl_write_dword(rtlpriv, REG_HIMRE, IMR8190_DISABLED);
}
void rtl92c_set_qos(struct ieee80211_hw *hw, int aci)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u32 u4b_ac_param;
rtl92c_dm_init_edca_turbo(hw);
u4b_ac_param = (u32) mac->ac[aci].aifs;
u4b_ac_param |=
((u32) le16_to_cpu(mac->ac[aci].cw_min) & 0xF) <<
AC_PARAM_ECW_MIN_OFFSET;
u4b_ac_param |=
((u32) le16_to_cpu(mac->ac[aci].cw_max) & 0xF) <<
AC_PARAM_ECW_MAX_OFFSET;
u4b_ac_param |= (u32) le16_to_cpu(mac->ac[aci].tx_op) <<
AC_PARAM_TXOP_OFFSET;
RT_TRACE(rtlpriv, COMP_QOS, DBG_LOUD, "queue:%x, ac_param:%x\n",
aci, u4b_ac_param);
switch (aci) {
case AC1_BK:
rtl_write_dword(rtlpriv, REG_EDCA_BK_PARAM, u4b_ac_param);
break;
case AC0_BE:
rtl_write_dword(rtlpriv, REG_EDCA_BE_PARAM, u4b_ac_param);
break;
case AC2_VI:
rtl_write_dword(rtlpriv, REG_EDCA_VI_PARAM, u4b_ac_param);
break;
case AC3_VO:
rtl_write_dword(rtlpriv, REG_EDCA_VO_PARAM, u4b_ac_param);
break;
default:
RT_ASSERT(false, "invalid aci: %d !\n", aci);
break;
}
}
/*-------------------------------------------------------------------------
* HW MAC Address
*-------------------------------------------------------------------------*/
void rtl92c_set_mac_addr(struct ieee80211_hw *hw, const u8 *addr)
{
u32 i;
struct rtl_priv *rtlpriv = rtl_priv(hw);
for (i = 0 ; i < ETH_ALEN ; i++)
rtl_write_byte(rtlpriv, (REG_MACID + i), *(addr+i));
RT_TRACE(rtlpriv, COMP_CMD, DBG_DMESG,
"MAC Address: %02X-%02X-%02X-%02X-%02X-%02X\n",
rtl_read_byte(rtlpriv, REG_MACID),
rtl_read_byte(rtlpriv, REG_MACID+1),
rtl_read_byte(rtlpriv, REG_MACID+2),
rtl_read_byte(rtlpriv, REG_MACID+3),
rtl_read_byte(rtlpriv, REG_MACID+4),
rtl_read_byte(rtlpriv, REG_MACID+5));
}
void rtl92c_init_driver_info_size(struct ieee80211_hw *hw, u8 size)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_byte(rtlpriv, REG_RX_DRVINFO_SZ, size);
}
int rtl92c_set_network_type(struct ieee80211_hw *hw, enum nl80211_iftype type)
{
u8 value;
struct rtl_priv *rtlpriv = rtl_priv(hw);
switch (type) {
case NL80211_IFTYPE_UNSPECIFIED:
value = NT_NO_LINK;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Set Network type to NO LINK!\n");
break;
case NL80211_IFTYPE_ADHOC:
value = NT_LINK_AD_HOC;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Set Network type to Ad Hoc!\n");
break;
case NL80211_IFTYPE_STATION:
value = NT_LINK_AP;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Set Network type to STA!\n");
break;
case NL80211_IFTYPE_AP:
value = NT_AS_AP;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Set Network type to AP!\n");
break;
default:
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Network type %d not supported!\n", type);
return -EOPNOTSUPP;
}
rtl_write_byte(rtlpriv, (REG_CR + 2), value);
return 0;
}
void rtl92c_init_network_type(struct ieee80211_hw *hw)
{
rtl92c_set_network_type(hw, NL80211_IFTYPE_UNSPECIFIED);
}
void rtl92c_init_adaptive_ctrl(struct ieee80211_hw *hw)
{
u16 value16;
u32 value32;
struct rtl_priv *rtlpriv = rtl_priv(hw);
/* Response Rate Set */
value32 = rtl_read_dword(rtlpriv, REG_RRSR);
value32 &= ~RATE_BITMAP_ALL;
value32 |= RATE_RRSR_CCK_ONLY_1M;
rtl_write_dword(rtlpriv, REG_RRSR, value32);
/* SIFS (used in NAV) */
value16 = _SPEC_SIFS_CCK(0x10) | _SPEC_SIFS_OFDM(0x10);
rtl_write_word(rtlpriv, REG_SPEC_SIFS, value16);
/* Retry Limit */
value16 = _LRL(0x30) | _SRL(0x30);
rtl_write_dword(rtlpriv, REG_RL, value16);
}
void rtl92c_init_rate_fallback(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
/* Set Data Auto Rate Fallback Retry Count register. */
rtl_write_dword(rtlpriv, REG_DARFRC, 0x00000000);
rtl_write_dword(rtlpriv, REG_DARFRC+4, 0x10080404);
rtl_write_dword(rtlpriv, REG_RARFRC, 0x04030201);
rtl_write_dword(rtlpriv, REG_RARFRC+4, 0x08070605);
}
static void rtl92c_set_cck_sifs(struct ieee80211_hw *hw, u8 trx_sifs,
u8 ctx_sifs)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_byte(rtlpriv, REG_SIFS_CCK, trx_sifs);
rtl_write_byte(rtlpriv, (REG_SIFS_CCK + 1), ctx_sifs);
}
static void rtl92c_set_ofdm_sifs(struct ieee80211_hw *hw, u8 trx_sifs,
u8 ctx_sifs)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_byte(rtlpriv, REG_SIFS_OFDM, trx_sifs);
rtl_write_byte(rtlpriv, (REG_SIFS_OFDM + 1), ctx_sifs);
}
void rtl92c_init_edca_param(struct ieee80211_hw *hw,
u16 queue, u16 txop, u8 cw_min, u8 cw_max, u8 aifs)
{
/* sequence: VO, VI, BE, BK ==> the same as 92C hardware design.
* referenc : enum nl80211_txq_q or ieee80211_set_wmm_default function.
*/
u32 value;
struct rtl_priv *rtlpriv = rtl_priv(hw);
value = (u32)aifs;
value |= ((u32)cw_min & 0xF) << 8;
value |= ((u32)cw_max & 0xF) << 12;
value |= (u32)txop << 16;
/* 92C hardware register sequence is the same as queue number. */
rtl_write_dword(rtlpriv, (REG_EDCA_VO_PARAM + (queue * 4)), value);
}
void rtl92c_init_edca(struct ieee80211_hw *hw)
{
u16 value16;
struct rtl_priv *rtlpriv = rtl_priv(hw);
/* disable EDCCA count down, to reduce collison and retry */
value16 = rtl_read_word(rtlpriv, REG_RD_CTRL);
value16 |= DIS_EDCA_CNT_DWN;
rtl_write_word(rtlpriv, REG_RD_CTRL, value16);
/* Update SIFS timing. ??????????
* pHalData->SifsTime = 0x0e0e0a0a; */
rtl92c_set_cck_sifs(hw, 0xa, 0xa);
rtl92c_set_ofdm_sifs(hw, 0xe, 0xe);
/* Set CCK/OFDM SIFS to be 10us. */
rtl_write_word(rtlpriv, REG_SIFS_CCK, 0x0a0a);
rtl_write_word(rtlpriv, REG_SIFS_OFDM, 0x1010);
rtl_write_word(rtlpriv, REG_PROT_MODE_CTRL, 0x0204);
rtl_write_dword(rtlpriv, REG_BAR_MODE_CTRL, 0x014004);
/* TXOP */
rtl_write_dword(rtlpriv, REG_EDCA_BE_PARAM, 0x005EA42B);
rtl_write_dword(rtlpriv, REG_EDCA_BK_PARAM, 0x0000A44F);
rtl_write_dword(rtlpriv, REG_EDCA_VI_PARAM, 0x005EA324);
rtl_write_dword(rtlpriv, REG_EDCA_VO_PARAM, 0x002FA226);
/* PIFS */
rtl_write_byte(rtlpriv, REG_PIFS, 0x1C);
/* AGGR BREAK TIME Register */
rtl_write_byte(rtlpriv, REG_AGGR_BREAK_TIME, 0x16);
rtl_write_word(rtlpriv, REG_NAV_PROT_LEN, 0x0040);
rtl_write_byte(rtlpriv, REG_BCNDMATIM, 0x02);
rtl_write_byte(rtlpriv, REG_ATIMWND, 0x02);
}
void rtl92c_init_ampdu_aggregation(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_dword(rtlpriv, REG_AGGLEN_LMT, 0x99997631);
rtl_write_byte(rtlpriv, REG_AGGR_BREAK_TIME, 0x16);
/* init AMPDU aggregation number, tuning for Tx's TP, */
rtl_write_word(rtlpriv, 0x4CA, 0x0708);
}
void rtl92c_init_beacon_max_error(struct ieee80211_hw *hw, bool infra_mode)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_byte(rtlpriv, REG_BCN_MAX_ERR, 0xFF);
}
void rtl92c_init_rdg_setting(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_byte(rtlpriv, REG_RD_CTRL, 0xFF);
rtl_write_word(rtlpriv, REG_RD_NAV_NXT, 0x200);
rtl_write_byte(rtlpriv, REG_RD_RESP_PKT_TH, 0x05);
}
void rtl92c_init_retry_function(struct ieee80211_hw *hw)
{
u8 value8;
struct rtl_priv *rtlpriv = rtl_priv(hw);
value8 = rtl_read_byte(rtlpriv, REG_FWHW_TXQ_CTRL);
value8 |= EN_AMPDU_RTY_NEW;
rtl_write_byte(rtlpriv, REG_FWHW_TXQ_CTRL, value8);
/* Set ACK timeout */
rtl_write_byte(rtlpriv, REG_ACKTO, 0x40);
}
void rtl92c_init_beacon_parameters(struct ieee80211_hw *hw,
enum version_8192c version)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtlpriv);
rtl_write_word(rtlpriv, REG_TBTT_PROHIBIT, 0x6404);/* ms */
rtl_write_byte(rtlpriv, REG_DRVERLYINT, DRIVER_EARLY_INT_TIME);/*ms*/
rtl_write_byte(rtlpriv, REG_BCNDMATIM, BCN_DMA_ATIME_INT_TIME);
if (IS_NORMAL_CHIP(rtlhal->version))
rtl_write_word(rtlpriv, REG_BCNTCFG, 0x660F);
else
rtl_write_word(rtlpriv, REG_BCNTCFG, 0x66FF);
}
void rtl92c_disable_fast_edca(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_word(rtlpriv, REG_FAST_EDCA_CTRL, 0);
}
void rtl92c_set_min_space(struct ieee80211_hw *hw, bool is2T)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 value = is2T ? MAX_MSS_DENSITY_2T : MAX_MSS_DENSITY_1T;
rtl_write_byte(rtlpriv, REG_AMPDU_MIN_SPACE, value);
}
u16 rtl92c_get_mgt_filter(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
return rtl_read_word(rtlpriv, REG_RXFLTMAP0);
}
void rtl92c_set_mgt_filter(struct ieee80211_hw *hw, u16 filter)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_word(rtlpriv, REG_RXFLTMAP0, filter);
}
u16 rtl92c_get_ctrl_filter(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
return rtl_read_word(rtlpriv, REG_RXFLTMAP1);
}
void rtl92c_set_ctrl_filter(struct ieee80211_hw *hw, u16 filter)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_word(rtlpriv, REG_RXFLTMAP1, filter);
}
u16 rtl92c_get_data_filter(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
return rtl_read_word(rtlpriv, REG_RXFLTMAP2);
}
void rtl92c_set_data_filter(struct ieee80211_hw *hw, u16 filter)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_write_word(rtlpriv, REG_RXFLTMAP2, filter);
}
/*==============================================================*/
static u8 _rtl92c_query_rxpwrpercentage(char antpower)
{
if ((antpower <= -100) || (antpower >= 20))
return 0;
else if (antpower >= 0)
return 100;
else
return 100 + antpower;
}
static u8 _rtl92c_evm_db_to_percentage(char value)
{
char ret_val;
ret_val = value;
if (ret_val >= 0)
ret_val = 0;
if (ret_val <= -33)
ret_val = -33;
ret_val = 0 - ret_val;
ret_val *= 3;
if (ret_val == 99)
ret_val = 100;
return ret_val;
}
static long _rtl92c_translate_todbm(struct ieee80211_hw *hw,
u8 signal_strength_index)
{
long signal_power;
signal_power = (long)((signal_strength_index + 1) >> 1);
signal_power -= 95;
return signal_power;
}
static long _rtl92c_signal_scale_mapping(struct ieee80211_hw *hw,
long currsig)
{
long retsig;
if (currsig >= 61 && currsig <= 100)
retsig = 90 + ((currsig - 60) / 4);
else if (currsig >= 41 && currsig <= 60)
retsig = 78 + ((currsig - 40) / 2);
else if (currsig >= 31 && currsig <= 40)
retsig = 66 + (currsig - 30);
else if (currsig >= 21 && currsig <= 30)
retsig = 54 + (currsig - 20);
else if (currsig >= 5 && currsig <= 20)
retsig = 42 + (((currsig - 5) * 2) / 3);
else if (currsig == 4)
retsig = 36;
else if (currsig == 3)
retsig = 27;
else if (currsig == 2)
retsig = 18;
else if (currsig == 1)
retsig = 9;
else
retsig = currsig;
return retsig;
}
static void _rtl92c_query_rxphystatus(struct ieee80211_hw *hw,
struct rtl_stats *pstats,
struct rx_desc_92c *p_desc,
struct rx_fwinfo_92c *p_drvinfo,
bool packet_match_bssid,
bool packet_toself,
bool packet_beacon)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct phy_sts_cck_8192s_t *cck_buf;
s8 rx_pwr_all = 0, rx_pwr[4];
u8 rf_rx_num = 0, evm, pwdb_all;
u8 i, max_spatial_stream;
u32 rssi, total_rssi = 0;
bool in_powersavemode = false;
bool is_cck_rate;
u8 *pdesc = (u8 *)p_desc;
is_cck_rate = RX_HAL_IS_CCK_RATE(p_desc);
pstats->packet_matchbssid = packet_match_bssid;
pstats->packet_toself = packet_toself;
pstats->packet_beacon = packet_beacon;
pstats->is_cck = is_cck_rate;
pstats->RX_SIGQ[0] = -1;
pstats->RX_SIGQ[1] = -1;
if (is_cck_rate) {
u8 report, cck_highpwr;
cck_buf = (struct phy_sts_cck_8192s_t *)p_drvinfo;
if (!in_powersavemode)
cck_highpwr = rtlphy->cck_high_power;
else
cck_highpwr = false;
if (!cck_highpwr) {
u8 cck_agc_rpt = cck_buf->cck_agc_rpt;
report = cck_buf->cck_agc_rpt & 0xc0;
report = report >> 6;
switch (report) {
case 0x3:
rx_pwr_all = -46 - (cck_agc_rpt & 0x3e);
break;
case 0x2:
rx_pwr_all = -26 - (cck_agc_rpt & 0x3e);
break;
case 0x1:
rx_pwr_all = -12 - (cck_agc_rpt & 0x3e);
break;
case 0x0:
rx_pwr_all = 16 - (cck_agc_rpt & 0x3e);
break;
}
} else {
u8 cck_agc_rpt = cck_buf->cck_agc_rpt;
report = p_drvinfo->cfosho[0] & 0x60;
report = report >> 5;
switch (report) {
case 0x3:
rx_pwr_all = -46 - ((cck_agc_rpt & 0x1f) << 1);
break;
case 0x2:
rx_pwr_all = -26 - ((cck_agc_rpt & 0x1f) << 1);
break;
case 0x1:
rx_pwr_all = -12 - ((cck_agc_rpt & 0x1f) << 1);
break;
case 0x0:
rx_pwr_all = 16 - ((cck_agc_rpt & 0x1f) << 1);
break;
}
}
pwdb_all = _rtl92c_query_rxpwrpercentage(rx_pwr_all);
pstats->rx_pwdb_all = pwdb_all;
pstats->recvsignalpower = rx_pwr_all;
if (packet_match_bssid) {
u8 sq;
if (pstats->rx_pwdb_all > 40)
sq = 100;
else {
sq = cck_buf->sq_rpt;
if (sq > 64)
sq = 0;
else if (sq < 20)
sq = 100;
else
sq = ((64 - sq) * 100) / 44;
}
pstats->signalquality = sq;
pstats->RX_SIGQ[0] = sq;
pstats->RX_SIGQ[1] = -1;
}
} else {
rtlpriv->dm.rfpath_rxenable[0] =
rtlpriv->dm.rfpath_rxenable[1] = true;
for (i = RF90_PATH_A; i < RF90_PATH_MAX; i++) {
if (rtlpriv->dm.rfpath_rxenable[i])
rf_rx_num++;
rx_pwr[i] =
((p_drvinfo->gain_trsw[i] & 0x3f) * 2) - 110;
rssi = _rtl92c_query_rxpwrpercentage(rx_pwr[i]);
total_rssi += rssi;
rtlpriv->stats.rx_snr_db[i] =
(long)(p_drvinfo->rxsnr[i] / 2);
if (packet_match_bssid)
pstats->rx_mimo_signalstrength[i] = (u8) rssi;
}
rx_pwr_all = ((p_drvinfo->pwdb_all >> 1) & 0x7f) - 110;
pwdb_all = _rtl92c_query_rxpwrpercentage(rx_pwr_all);
pstats->rx_pwdb_all = pwdb_all;
pstats->rxpower = rx_pwr_all;
pstats->recvsignalpower = rx_pwr_all;
if (GET_RX_DESC_RX_MCS(pdesc) &&
GET_RX_DESC_RX_MCS(pdesc) >= DESC92_RATEMCS8 &&
GET_RX_DESC_RX_MCS(pdesc) <= DESC92_RATEMCS15)
max_spatial_stream = 2;
else
max_spatial_stream = 1;
for (i = 0; i < max_spatial_stream; i++) {
evm = _rtl92c_evm_db_to_percentage(p_drvinfo->rxevm[i]);
if (packet_match_bssid) {
if (i == 0)
pstats->signalquality =
(u8) (evm & 0xff);
pstats->RX_SIGQ[i] =
(u8) (evm & 0xff);
}
}
}
if (is_cck_rate)
pstats->signalstrength =
(u8) (_rtl92c_signal_scale_mapping(hw, pwdb_all));
else if (rf_rx_num != 0)
pstats->signalstrength =
(u8) (_rtl92c_signal_scale_mapping
(hw, total_rssi /= rf_rx_num));
}
static void _rtl92c_process_ui_rssi(struct ieee80211_hw *hw,
struct rtl_stats *pstats)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u8 rfpath;
u32 last_rssi, tmpval;
if (pstats->packet_toself || pstats->packet_beacon) {
rtlpriv->stats.rssi_calculate_cnt++;
if (rtlpriv->stats.ui_rssi.total_num++ >=
PHY_RSSI_SLID_WIN_MAX) {
rtlpriv->stats.ui_rssi.total_num =
PHY_RSSI_SLID_WIN_MAX;
last_rssi =
rtlpriv->stats.ui_rssi.elements[rtlpriv->
stats.ui_rssi.index];
rtlpriv->stats.ui_rssi.total_val -= last_rssi;
}
rtlpriv->stats.ui_rssi.total_val += pstats->signalstrength;
rtlpriv->stats.ui_rssi.elements[rtlpriv->stats.ui_rssi.
index++] = pstats->signalstrength;
if (rtlpriv->stats.ui_rssi.index >= PHY_RSSI_SLID_WIN_MAX)
rtlpriv->stats.ui_rssi.index = 0;
tmpval = rtlpriv->stats.ui_rssi.total_val /
rtlpriv->stats.ui_rssi.total_num;
rtlpriv->stats.signal_strength =
_rtl92c_translate_todbm(hw, (u8) tmpval);
pstats->rssi = rtlpriv->stats.signal_strength;
}
if (!pstats->is_cck && pstats->packet_toself) {
for (rfpath = RF90_PATH_A; rfpath < rtlphy->num_total_rfpath;
rfpath++) {
if (!rtl8192_phy_check_is_legal_rfpath(hw, rfpath))
continue;
if (rtlpriv->stats.rx_rssi_percentage[rfpath] == 0) {
rtlpriv->stats.rx_rssi_percentage[rfpath] =
pstats->rx_mimo_signalstrength[rfpath];
}
if (pstats->rx_mimo_signalstrength[rfpath] >
rtlpriv->stats.rx_rssi_percentage[rfpath]) {
rtlpriv->stats.rx_rssi_percentage[rfpath] =
((rtlpriv->stats.
rx_rssi_percentage[rfpath] *
(RX_SMOOTH_FACTOR - 1)) +
(pstats->rx_mimo_signalstrength[rfpath])) /
(RX_SMOOTH_FACTOR);
rtlpriv->stats.rx_rssi_percentage[rfpath] =
rtlpriv->stats.rx_rssi_percentage[rfpath] +
1;
} else {
rtlpriv->stats.rx_rssi_percentage[rfpath] =
((rtlpriv->stats.
rx_rssi_percentage[rfpath] *
(RX_SMOOTH_FACTOR - 1)) +
(pstats->rx_mimo_signalstrength[rfpath])) /
(RX_SMOOTH_FACTOR);
}
}
}
}
static void _rtl92c_update_rxsignalstatistics(struct ieee80211_hw *hw,
struct rtl_stats *pstats)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
int weighting = 0;
if (rtlpriv->stats.recv_signal_power == 0)
rtlpriv->stats.recv_signal_power = pstats->recvsignalpower;
if (pstats->recvsignalpower > rtlpriv->stats.recv_signal_power)
weighting = 5;
else if (pstats->recvsignalpower < rtlpriv->stats.recv_signal_power)
weighting = (-5);
rtlpriv->stats.recv_signal_power =
(rtlpriv->stats.recv_signal_power * 5 +
pstats->recvsignalpower + weighting) / 6;
}
static void _rtl92c_process_pwdb(struct ieee80211_hw *hw,
struct rtl_stats *pstats)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
long undec_sm_pwdb = 0;
if (mac->opmode == NL80211_IFTYPE_ADHOC) {
return;
} else {
undec_sm_pwdb = rtlpriv->dm.undec_sm_pwdb;
}
if (pstats->packet_toself || pstats->packet_beacon) {
if (undec_sm_pwdb < 0)
undec_sm_pwdb = pstats->rx_pwdb_all;
if (pstats->rx_pwdb_all > (u32) undec_sm_pwdb) {
undec_sm_pwdb = (((undec_sm_pwdb) *
(RX_SMOOTH_FACTOR - 1)) +
(pstats->rx_pwdb_all)) / (RX_SMOOTH_FACTOR);
undec_sm_pwdb += 1;
} else {
undec_sm_pwdb = (((undec_sm_pwdb) *
(RX_SMOOTH_FACTOR - 1)) +
(pstats->rx_pwdb_all)) / (RX_SMOOTH_FACTOR);
}
rtlpriv->dm.undec_sm_pwdb = undec_sm_pwdb;
_rtl92c_update_rxsignalstatistics(hw, pstats);
}
}
static void _rtl92c_process_LINK_Q(struct ieee80211_hw *hw,
struct rtl_stats *pstats)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 last_evm = 0, n_stream, tmpval;
if (pstats->signalquality != 0) {
if (pstats->packet_toself || pstats->packet_beacon) {
if (rtlpriv->stats.LINK_Q.total_num++ >=
PHY_LINKQUALITY_SLID_WIN_MAX) {
rtlpriv->stats.LINK_Q.total_num =
PHY_LINKQUALITY_SLID_WIN_MAX;
last_evm =
rtlpriv->stats.LINK_Q.elements
[rtlpriv->stats.LINK_Q.index];
rtlpriv->stats.LINK_Q.total_val -=
last_evm;
}
rtlpriv->stats.LINK_Q.total_val +=
pstats->signalquality;
rtlpriv->stats.LINK_Q.elements
[rtlpriv->stats.LINK_Q.index++] =
pstats->signalquality;
if (rtlpriv->stats.LINK_Q.index >=
PHY_LINKQUALITY_SLID_WIN_MAX)
rtlpriv->stats.LINK_Q.index = 0;
tmpval = rtlpriv->stats.LINK_Q.total_val /
rtlpriv->stats.LINK_Q.total_num;
rtlpriv->stats.signal_quality = tmpval;
rtlpriv->stats.last_sigstrength_inpercent = tmpval;
for (n_stream = 0; n_stream < 2;
n_stream++) {
if (pstats->RX_SIGQ[n_stream] != -1) {
if (!rtlpriv->stats.RX_EVM[n_stream]) {
rtlpriv->stats.RX_EVM[n_stream]
= pstats->RX_SIGQ[n_stream];
}
rtlpriv->stats.RX_EVM[n_stream] =
((rtlpriv->stats.RX_EVM
[n_stream] *
(RX_SMOOTH_FACTOR - 1)) +
(pstats->RX_SIGQ
[n_stream] * 1)) /
(RX_SMOOTH_FACTOR);
}
}
}
} else {
;
}
}
static void _rtl92c_process_phyinfo(struct ieee80211_hw *hw,
u8 *buffer,
struct rtl_stats *pcurrent_stats)
{
if (!pcurrent_stats->packet_matchbssid &&
!pcurrent_stats->packet_beacon)
return;
_rtl92c_process_ui_rssi(hw, pcurrent_stats);
_rtl92c_process_pwdb(hw, pcurrent_stats);
_rtl92c_process_LINK_Q(hw, pcurrent_stats);
}
void rtl92c_translate_rx_signal_stuff(struct ieee80211_hw *hw,
struct sk_buff *skb,
struct rtl_stats *pstats,
struct rx_desc_92c *pdesc,
struct rx_fwinfo_92c *p_drvinfo)
{
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
struct ieee80211_hdr *hdr;
u8 *tmp_buf;
u8 *praddr;
__le16 fc;
u16 type, cpu_fc;
bool packet_matchbssid, packet_toself, packet_beacon = false;
tmp_buf = skb->data + pstats->rx_drvinfo_size + pstats->rx_bufshift;
hdr = (struct ieee80211_hdr *)tmp_buf;
fc = hdr->frame_control;
cpu_fc = le16_to_cpu(fc);
type = WLAN_FC_GET_TYPE(fc);
praddr = hdr->addr1;
packet_matchbssid =
((IEEE80211_FTYPE_CTL != type) &&
ether_addr_equal(mac->bssid,
(cpu_fc & IEEE80211_FCTL_TODS) ? hdr->addr1 :
(cpu_fc & IEEE80211_FCTL_FROMDS) ? hdr->addr2 :
hdr->addr3) &&
(!pstats->hwerror) && (!pstats->crc) && (!pstats->icv));
packet_toself = packet_matchbssid &&
ether_addr_equal(praddr, rtlefuse->dev_addr);
if (ieee80211_is_beacon(fc))
packet_beacon = true;
_rtl92c_query_rxphystatus(hw, pstats, pdesc, p_drvinfo,
packet_matchbssid, packet_toself,
packet_beacon);
_rtl92c_process_phyinfo(hw, tmp_buf, pstats);
}
| gpl-2.0 |
jakew02/android_kernel_lge_v10 | drivers/i2c/muxes/i2c-mux-pca954x.c | 2053 | 6939 | /*
* I2C multiplexer
*
* Copyright (c) 2008-2009 Rodolfo Giometti <giometti@linux.it>
* Copyright (c) 2008-2009 Eurotech S.p.A. <info@eurotech.it>
*
* This module supports the PCA954x series of I2C multiplexer/switch chips
* made by Philips Semiconductors.
* This includes the:
* PCA9540, PCA9542, PCA9543, PCA9544, PCA9545, PCA9546, PCA9547
* and PCA9548.
*
* These chips are all controlled via the I2C bus itself, and all have a
* single 8-bit register. The upstream "parent" bus fans out to two,
* four, or eight downstream busses or channels; which of these
* are selected is determined by the chip type and register contents. A
* mux can select only one sub-bus at a time; a switch can select any
* combination simultaneously.
*
* Based on:
* pca954x.c from Kumar Gala <galak@kernel.crashing.org>
* Copyright (C) 2006
*
* Based on:
* pca954x.c from Ken Harrenstien
* Copyright (C) 2004 Google, Inc. (Ken Harrenstien)
*
* Based on:
* i2c-virtual_cb.c from Brian Kuschak <bkuschak@yahoo.com>
* and
* pca9540.c from Jean Delvare <khali@linux-fr.org>.
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/i2c-mux.h>
#include <linux/i2c/pca954x.h>
#define PCA954X_MAX_NCHANS 8
enum pca_type {
pca_9540,
pca_9542,
pca_9543,
pca_9544,
pca_9545,
pca_9546,
pca_9547,
pca_9548,
};
struct pca954x {
enum pca_type type;
struct i2c_adapter *virt_adaps[PCA954X_MAX_NCHANS];
u8 last_chan; /* last register value */
};
struct chip_desc {
u8 nchans;
u8 enable; /* used for muxes only */
enum muxtype {
pca954x_ismux = 0,
pca954x_isswi
} muxtype;
};
/* Provide specs for the PCA954x types we know about */
static const struct chip_desc chips[] = {
[pca_9540] = {
.nchans = 2,
.enable = 0x4,
.muxtype = pca954x_ismux,
},
[pca_9543] = {
.nchans = 2,
.muxtype = pca954x_isswi,
},
[pca_9544] = {
.nchans = 4,
.enable = 0x4,
.muxtype = pca954x_ismux,
},
[pca_9545] = {
.nchans = 4,
.muxtype = pca954x_isswi,
},
[pca_9547] = {
.nchans = 8,
.enable = 0x8,
.muxtype = pca954x_ismux,
},
[pca_9548] = {
.nchans = 8,
.muxtype = pca954x_isswi,
},
};
static const struct i2c_device_id pca954x_id[] = {
{ "pca9540", pca_9540 },
{ "pca9542", pca_9540 },
{ "pca9543", pca_9543 },
{ "pca9544", pca_9544 },
{ "pca9545", pca_9545 },
{ "pca9546", pca_9545 },
{ "pca9547", pca_9547 },
{ "pca9548", pca_9548 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pca954x_id);
/* Write to mux register. Don't use i2c_transfer()/i2c_smbus_xfer()
for this as they will try to lock adapter a second time */
static int pca954x_reg_write(struct i2c_adapter *adap,
struct i2c_client *client, u8 val)
{
int ret = -ENODEV;
if (adap->algo->master_xfer) {
struct i2c_msg msg;
char buf[1];
msg.addr = client->addr;
msg.flags = 0;
msg.len = 1;
buf[0] = val;
msg.buf = buf;
ret = adap->algo->master_xfer(adap, &msg, 1);
} else {
union i2c_smbus_data data;
ret = adap->algo->smbus_xfer(adap, client->addr,
client->flags,
I2C_SMBUS_WRITE,
val, I2C_SMBUS_BYTE, &data);
}
return ret;
}
static int pca954x_select_chan(struct i2c_adapter *adap,
void *client, u32 chan)
{
struct pca954x *data = i2c_get_clientdata(client);
const struct chip_desc *chip = &chips[data->type];
u8 regval;
int ret = 0;
/* we make switches look like muxes, not sure how to be smarter */
if (chip->muxtype == pca954x_ismux)
regval = chan | chip->enable;
else
regval = 1 << chan;
/* Only select the channel if its different from the last channel */
if (data->last_chan != regval) {
ret = pca954x_reg_write(adap, client, regval);
data->last_chan = regval;
}
return ret;
}
static int pca954x_deselect_mux(struct i2c_adapter *adap,
void *client, u32 chan)
{
struct pca954x *data = i2c_get_clientdata(client);
/* Deselect active channel */
data->last_chan = 0;
return pca954x_reg_write(adap, client, data->last_chan);
}
/*
* I2C init/probing/exit functions
*/
static int pca954x_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adap = to_i2c_adapter(client->dev.parent);
struct pca954x_platform_data *pdata = client->dev.platform_data;
int num, force, class;
struct pca954x *data;
int ret = -ENODEV;
if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_BYTE))
goto err;
data = kzalloc(sizeof(struct pca954x), GFP_KERNEL);
if (!data) {
ret = -ENOMEM;
goto err;
}
i2c_set_clientdata(client, data);
/* Write the mux register at addr to verify
* that the mux is in fact present. This also
* initializes the mux to disconnected state.
*/
if (i2c_smbus_write_byte(client, 0) < 0) {
dev_warn(&client->dev, "probe failed\n");
goto exit_free;
}
data->type = id->driver_data;
data->last_chan = 0; /* force the first selection */
/* Now create an adapter for each channel */
for (num = 0; num < chips[data->type].nchans; num++) {
force = 0; /* dynamic adap number */
class = 0; /* no class by default */
if (pdata) {
if (num < pdata->num_modes) {
/* force static number */
force = pdata->modes[num].adap_id;
class = pdata->modes[num].class;
} else
/* discard unconfigured channels */
break;
}
data->virt_adaps[num] =
i2c_add_mux_adapter(adap, &client->dev, client,
force, num, class, pca954x_select_chan,
(pdata && pdata->modes[num].deselect_on_exit)
? pca954x_deselect_mux : NULL);
if (data->virt_adaps[num] == NULL) {
ret = -ENODEV;
dev_err(&client->dev,
"failed to register multiplexed adapter"
" %d as bus %d\n", num, force);
goto virt_reg_failed;
}
}
dev_info(&client->dev,
"registered %d multiplexed busses for I2C %s %s\n",
num, chips[data->type].muxtype == pca954x_ismux
? "mux" : "switch", client->name);
return 0;
virt_reg_failed:
for (num--; num >= 0; num--)
i2c_del_mux_adapter(data->virt_adaps[num]);
exit_free:
kfree(data);
err:
return ret;
}
static int pca954x_remove(struct i2c_client *client)
{
struct pca954x *data = i2c_get_clientdata(client);
const struct chip_desc *chip = &chips[data->type];
int i;
for (i = 0; i < chip->nchans; ++i)
if (data->virt_adaps[i]) {
i2c_del_mux_adapter(data->virt_adaps[i]);
data->virt_adaps[i] = NULL;
}
kfree(data);
return 0;
}
static struct i2c_driver pca954x_driver = {
.driver = {
.name = "pca954x",
.owner = THIS_MODULE,
},
.probe = pca954x_probe,
.remove = pca954x_remove,
.id_table = pca954x_id,
};
module_i2c_driver(pca954x_driver);
MODULE_AUTHOR("Rodolfo Giometti <giometti@linux.it>");
MODULE_DESCRIPTION("PCA954x I2C mux/switch driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
felixsch/linux | arch/mips/lasat/picvue.c | 2309 | 4353 | /*
* Picvue PVC160206 display driver
*
* Brian Murphy <brian@murphy.dk>
*
*/
#include <linux/kernel.h>
#include <linux/delay.h>
#include <asm/bootinfo.h>
#include <asm/lasat/lasat.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/string.h>
#include "picvue.h"
#define PVC_BUSY 0x80
#define PVC_NLINES 2
#define PVC_DISPMEM 80
#define PVC_LINELEN PVC_DISPMEM / PVC_NLINES
struct pvc_defs *picvue;
static void pvc_reg_write(u32 val)
{
*picvue->reg = val;
}
static u32 pvc_reg_read(void)
{
u32 tmp = *picvue->reg;
return tmp;
}
static void pvc_write_byte(u32 data, u8 byte)
{
data |= picvue->e;
pvc_reg_write(data);
data &= ~picvue->data_mask;
data |= byte << picvue->data_shift;
pvc_reg_write(data);
ndelay(220);
pvc_reg_write(data & ~picvue->e);
ndelay(220);
}
static u8 pvc_read_byte(u32 data)
{
u8 byte;
data |= picvue->e;
pvc_reg_write(data);
ndelay(220);
byte = (pvc_reg_read() & picvue->data_mask) >> picvue->data_shift;
data &= ~picvue->e;
pvc_reg_write(data);
ndelay(220);
return byte;
}
static u8 pvc_read_data(void)
{
u32 data = pvc_reg_read();
u8 byte;
data |= picvue->rw;
data &= ~picvue->rs;
pvc_reg_write(data);
ndelay(40);
byte = pvc_read_byte(data);
data |= picvue->rs;
pvc_reg_write(data);
return byte;
}
#define TIMEOUT 1000
static int pvc_wait(void)
{
int i = TIMEOUT;
int err = 0;
while ((pvc_read_data() & PVC_BUSY) && i)
i--;
if (i == 0)
err = -ETIME;
return err;
}
#define MODE_INST 0
#define MODE_DATA 1
static void pvc_write(u8 byte, int mode)
{
u32 data = pvc_reg_read();
data &= ~picvue->rw;
if (mode == MODE_DATA)
data |= picvue->rs;
else
data &= ~picvue->rs;
pvc_reg_write(data);
ndelay(40);
pvc_write_byte(data, byte);
if (mode == MODE_DATA)
data &= ~picvue->rs;
else
data |= picvue->rs;
pvc_reg_write(data);
pvc_wait();
}
void pvc_write_string(const unsigned char *str, u8 addr, int line)
{
int i = 0;
if (line > 0 && (PVC_NLINES > 1))
addr += 0x40 * line;
pvc_write(0x80 | addr, MODE_INST);
while (*str != 0 && i < PVC_LINELEN) {
pvc_write(*str++, MODE_DATA);
i++;
}
}
void pvc_write_string_centered(const unsigned char *str, int line)
{
int len = strlen(str);
u8 addr;
if (len > PVC_VISIBLE_CHARS)
addr = 0;
else
addr = (PVC_VISIBLE_CHARS - strlen(str))/2;
pvc_write_string(str, addr, line);
}
void pvc_dump_string(const unsigned char *str)
{
int len = strlen(str);
pvc_write_string(str, 0, 0);
if (len > PVC_VISIBLE_CHARS)
pvc_write_string(&str[PVC_VISIBLE_CHARS], 0, 1);
}
#define BM_SIZE 8
#define MAX_PROGRAMMABLE_CHARS 8
int pvc_program_cg(int charnum, u8 bitmap[BM_SIZE])
{
int i;
int addr;
if (charnum > MAX_PROGRAMMABLE_CHARS)
return -ENOENT;
addr = charnum * 8;
pvc_write(0x40 | addr, MODE_INST);
for (i = 0; i < BM_SIZE; i++)
pvc_write(bitmap[i], MODE_DATA);
return 0;
}
#define FUNC_SET_CMD 0x20
#define EIGHT_BYTE (1 << 4)
#define FOUR_BYTE 0
#define TWO_LINES (1 << 3)
#define ONE_LINE 0
#define LARGE_FONT (1 << 2)
#define SMALL_FONT 0
static void pvc_funcset(u8 cmd)
{
pvc_write(FUNC_SET_CMD | (cmd & (EIGHT_BYTE|TWO_LINES|LARGE_FONT)),
MODE_INST);
}
#define ENTRYMODE_CMD 0x4
#define AUTO_INC (1 << 1)
#define AUTO_DEC 0
#define CURSOR_FOLLOWS_DISP (1 << 0)
static void pvc_entrymode(u8 cmd)
{
pvc_write(ENTRYMODE_CMD | (cmd & (AUTO_INC|CURSOR_FOLLOWS_DISP)),
MODE_INST);
}
#define DISP_CNT_CMD 0x08
#define DISP_OFF 0
#define DISP_ON (1 << 2)
#define CUR_ON (1 << 1)
#define CUR_BLINK (1 << 0)
void pvc_dispcnt(u8 cmd)
{
pvc_write(DISP_CNT_CMD | (cmd & (DISP_ON|CUR_ON|CUR_BLINK)), MODE_INST);
}
#define MOVE_CMD 0x10
#define DISPLAY (1 << 3)
#define CURSOR 0
#define RIGHT (1 << 2)
#define LEFT 0
void pvc_move(u8 cmd)
{
pvc_write(MOVE_CMD | (cmd & (DISPLAY|RIGHT)), MODE_INST);
}
#define CLEAR_CMD 0x1
void pvc_clear(void)
{
pvc_write(CLEAR_CMD, MODE_INST);
}
#define HOME_CMD 0x2
void pvc_home(void)
{
pvc_write(HOME_CMD, MODE_INST);
}
int pvc_init(void)
{
u8 cmd = EIGHT_BYTE;
if (PVC_NLINES == 2)
cmd |= (SMALL_FONT|TWO_LINES);
else
cmd |= (LARGE_FONT|ONE_LINE);
pvc_funcset(cmd);
pvc_dispcnt(DISP_ON);
pvc_entrymode(AUTO_INC);
pvc_clear();
pvc_write_string_centered("Display", 0);
pvc_write_string_centered("Initialized", 1);
return 0;
}
module_init(pvc_init);
MODULE_LICENSE("GPL");
| gpl-2.0 |
montekki/linux-2.6-acedia | drivers/net/arcnet/com90io.c | 2821 | 11098 | /*
* Linux ARCnet driver - COM90xx chipset (IO-mapped buffers)
*
* Written 1997 by David Woodhouse.
* Written 1994-1999 by Avery Pennarun.
* Written 1999-2000 by Martin Mares <mj@ucw.cz>.
* Derived from skeleton.c by Donald Becker.
*
* Special thanks to Contemporary Controls, Inc. (www.ccontrols.com)
* for sponsoring the further development of this driver.
*
* **********************
*
* The original copyright of skeleton.c was as follows:
*
* skeleton.c Written 1993 by Donald Becker.
* Copyright 1993 United States Government as represented by the
* Director, National Security Agency. This software may only be used
* and distributed according to the terms of the GNU General Public License as
* modified by SRC, incorporated herein by reference.
*
* **********************
*
* For more details, see drivers/net/arcnet.c
*
* **********************
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/bootmem.h>
#include <linux/init.h>
#include <asm/io.h>
#include <linux/arcdevice.h>
#define VERSION "arcnet: COM90xx IO-mapped mode support (by David Woodhouse et el.)\n"
/* Internal function declarations */
static int com90io_found(struct net_device *dev);
static void com90io_command(struct net_device *dev, int command);
static int com90io_status(struct net_device *dev);
static void com90io_setmask(struct net_device *dev, int mask);
static int com90io_reset(struct net_device *dev, int really_reset);
static void com90io_copy_to_card(struct net_device *dev, int bufnum, int offset,
void *buf, int count);
static void com90io_copy_from_card(struct net_device *dev, int bufnum, int offset,
void *buf, int count);
/* Handy defines for ARCnet specific stuff */
/* The number of low I/O ports used by the card. */
#define ARCNET_TOTAL_SIZE 16
/* COM 9026 controller chip --> ARCnet register addresses */
#define _INTMASK (ioaddr+0) /* writable */
#define _STATUS (ioaddr+0) /* readable */
#define _COMMAND (ioaddr+1) /* writable, returns random vals on read (?) */
#define _RESET (ioaddr+8) /* software reset (on read) */
#define _MEMDATA (ioaddr+12) /* Data port for IO-mapped memory */
#define _ADDR_HI (ioaddr+15) /* Control registers for said */
#define _ADDR_LO (ioaddr+14)
#define _CONFIG (ioaddr+2) /* Configuration register */
#undef ASTATUS
#undef ACOMMAND
#undef AINTMASK
#define ASTATUS() inb(_STATUS)
#define ACOMMAND(cmd) outb((cmd),_COMMAND)
#define AINTMASK(msk) outb((msk),_INTMASK)
#define SETCONF() outb((lp->config),_CONFIG)
/****************************************************************************
* *
* IO-mapped operation routines *
* *
****************************************************************************/
#undef ONE_AT_A_TIME_TX
#undef ONE_AT_A_TIME_RX
static u_char get_buffer_byte(struct net_device *dev, unsigned offset)
{
int ioaddr = dev->base_addr;
outb(offset >> 8, _ADDR_HI);
outb(offset & 0xff, _ADDR_LO);
return inb(_MEMDATA);
}
#ifdef ONE_AT_A_TIME_TX
static void put_buffer_byte(struct net_device *dev, unsigned offset, u_char datum)
{
int ioaddr = dev->base_addr;
outb(offset >> 8, _ADDR_HI);
outb(offset & 0xff, _ADDR_LO);
outb(datum, _MEMDATA);
}
#endif
static void get_whole_buffer(struct net_device *dev, unsigned offset, unsigned length, char *dest)
{
int ioaddr = dev->base_addr;
outb((offset >> 8) | AUTOINCflag, _ADDR_HI);
outb(offset & 0xff, _ADDR_LO);
while (length--)
#ifdef ONE_AT_A_TIME_RX
*(dest++) = get_buffer_byte(dev, offset++);
#else
*(dest++) = inb(_MEMDATA);
#endif
}
static void put_whole_buffer(struct net_device *dev, unsigned offset, unsigned length, char *dest)
{
int ioaddr = dev->base_addr;
outb((offset >> 8) | AUTOINCflag, _ADDR_HI);
outb(offset & 0xff, _ADDR_LO);
while (length--)
#ifdef ONE_AT_A_TIME_TX
put_buffer_byte(dev, offset++, *(dest++));
#else
outb(*(dest++), _MEMDATA);
#endif
}
/*
* We cannot probe for an IO mapped card either, although we can check that
* it's where we were told it was, and even autoirq
*/
static int __init com90io_probe(struct net_device *dev)
{
int ioaddr = dev->base_addr, status;
unsigned long airqmask;
BUGLVL(D_NORMAL) printk(VERSION);
BUGLVL(D_NORMAL) printk("E-mail me if you actually test this driver, please!\n");
if (!ioaddr) {
BUGMSG(D_NORMAL, "No autoprobe for IO mapped cards; you "
"must specify the base address!\n");
return -ENODEV;
}
if (!request_region(ioaddr, ARCNET_TOTAL_SIZE, "com90io probe")) {
BUGMSG(D_INIT_REASONS, "IO request_region %x-%x failed.\n",
ioaddr, ioaddr + ARCNET_TOTAL_SIZE - 1);
return -ENXIO;
}
if (ASTATUS() == 0xFF) {
BUGMSG(D_INIT_REASONS, "IO address %x empty\n", ioaddr);
goto err_out;
}
inb(_RESET);
mdelay(RESETtime);
status = ASTATUS();
if ((status & 0x9D) != (NORXflag | RECONflag | TXFREEflag | RESETflag)) {
BUGMSG(D_INIT_REASONS, "Status invalid (%Xh).\n", status);
goto err_out;
}
BUGMSG(D_INIT_REASONS, "Status after reset: %X\n", status);
ACOMMAND(CFLAGScmd | RESETclear | CONFIGclear);
BUGMSG(D_INIT_REASONS, "Status after reset acknowledged: %X\n", status);
status = ASTATUS();
if (status & RESETflag) {
BUGMSG(D_INIT_REASONS, "Eternal reset (status=%Xh)\n", status);
goto err_out;
}
outb((0x16 | IOMAPflag) & ~ENABLE16flag, _CONFIG);
/* Read first loc'n of memory */
outb(AUTOINCflag, _ADDR_HI);
outb(0, _ADDR_LO);
if ((status = inb(_MEMDATA)) != 0xd1) {
BUGMSG(D_INIT_REASONS, "Signature byte not found"
" (%Xh instead).\n", status);
goto err_out;
}
if (!dev->irq) {
/*
* if we do this, we're sure to get an IRQ since the
* card has just reset and the NORXflag is on until
* we tell it to start receiving.
*/
airqmask = probe_irq_on();
outb(NORXflag, _INTMASK);
udelay(1);
outb(0, _INTMASK);
dev->irq = probe_irq_off(airqmask);
if ((int)dev->irq <= 0) {
BUGMSG(D_INIT_REASONS, "Autoprobe IRQ failed\n");
goto err_out;
}
}
release_region(ioaddr, ARCNET_TOTAL_SIZE); /* end of probing */
return com90io_found(dev);
err_out:
release_region(ioaddr, ARCNET_TOTAL_SIZE);
return -ENODEV;
}
/* Set up the struct net_device associated with this card. Called after
* probing succeeds.
*/
static int __init com90io_found(struct net_device *dev)
{
struct arcnet_local *lp;
int ioaddr = dev->base_addr;
int err;
/* Reserve the irq */
if (request_irq(dev->irq, arcnet_interrupt, 0, "arcnet (COM90xx-IO)", dev)) {
BUGMSG(D_NORMAL, "Can't get IRQ %d!\n", dev->irq);
return -ENODEV;
}
/* Reserve the I/O region */
if (!request_region(dev->base_addr, ARCNET_TOTAL_SIZE, "arcnet (COM90xx-IO)")) {
free_irq(dev->irq, dev);
return -EBUSY;
}
lp = netdev_priv(dev);
lp->card_name = "COM90xx I/O";
lp->hw.command = com90io_command;
lp->hw.status = com90io_status;
lp->hw.intmask = com90io_setmask;
lp->hw.reset = com90io_reset;
lp->hw.owner = THIS_MODULE;
lp->hw.copy_to_card = com90io_copy_to_card;
lp->hw.copy_from_card = com90io_copy_from_card;
lp->config = (0x16 | IOMAPflag) & ~ENABLE16flag;
SETCONF();
/* get and check the station ID from offset 1 in shmem */
dev->dev_addr[0] = get_buffer_byte(dev, 1);
err = register_netdev(dev);
if (err) {
outb((inb(_CONFIG) & ~IOMAPflag), _CONFIG);
free_irq(dev->irq, dev);
release_region(dev->base_addr, ARCNET_TOTAL_SIZE);
return err;
}
BUGMSG(D_NORMAL, "COM90IO: station %02Xh found at %03lXh, IRQ %d.\n",
dev->dev_addr[0], dev->base_addr, dev->irq);
return 0;
}
/*
* Do a hardware reset on the card, and set up necessary registers.
*
* This should be called as little as possible, because it disrupts the
* token on the network (causes a RECON) and requires a significant delay.
*
* However, it does make sure the card is in a defined state.
*/
static int com90io_reset(struct net_device *dev, int really_reset)
{
struct arcnet_local *lp = netdev_priv(dev);
short ioaddr = dev->base_addr;
BUGMSG(D_INIT, "Resetting %s (status=%02Xh)\n", dev->name, ASTATUS());
if (really_reset) {
/* reset the card */
inb(_RESET);
mdelay(RESETtime);
}
/* Set the thing to IO-mapped, 8-bit mode */
lp->config = (0x1C | IOMAPflag) & ~ENABLE16flag;
SETCONF();
ACOMMAND(CFLAGScmd | RESETclear); /* clear flags & end reset */
ACOMMAND(CFLAGScmd | CONFIGclear);
/* verify that the ARCnet signature byte is present */
if (get_buffer_byte(dev, 0) != TESTvalue) {
BUGMSG(D_NORMAL, "reset failed: TESTvalue not present.\n");
return 1;
}
/* enable extended (512-byte) packets */
ACOMMAND(CONFIGcmd | EXTconf);
/* done! return success. */
return 0;
}
static void com90io_command(struct net_device *dev, int cmd)
{
short ioaddr = dev->base_addr;
ACOMMAND(cmd);
}
static int com90io_status(struct net_device *dev)
{
short ioaddr = dev->base_addr;
return ASTATUS();
}
static void com90io_setmask(struct net_device *dev, int mask)
{
short ioaddr = dev->base_addr;
AINTMASK(mask);
}
static void com90io_copy_to_card(struct net_device *dev, int bufnum, int offset,
void *buf, int count)
{
TIME("put_whole_buffer", count, put_whole_buffer(dev, bufnum * 512 + offset, count, buf));
}
static void com90io_copy_from_card(struct net_device *dev, int bufnum, int offset,
void *buf, int count)
{
TIME("get_whole_buffer", count, get_whole_buffer(dev, bufnum * 512 + offset, count, buf));
}
static int io; /* use the insmod io= irq= shmem= options */
static int irq;
static char device[9]; /* use eg. device=arc1 to change name */
module_param(io, int, 0);
module_param(irq, int, 0);
module_param_string(device, device, sizeof(device), 0);
MODULE_LICENSE("GPL");
#ifndef MODULE
static int __init com90io_setup(char *s)
{
int ints[4];
s = get_options(s, 4, ints);
if (!ints[0])
return 0;
switch (ints[0]) {
default: /* ERROR */
printk("com90io: Too many arguments.\n");
case 2: /* IRQ */
irq = ints[2];
case 1: /* IO address */
io = ints[1];
}
if (*s)
snprintf(device, sizeof(device), "%s", s);
return 1;
}
__setup("com90io=", com90io_setup);
#endif
static struct net_device *my_dev;
static int __init com90io_init(void)
{
struct net_device *dev;
int err;
dev = alloc_arcdev(device);
if (!dev)
return -ENOMEM;
dev->base_addr = io;
dev->irq = irq;
if (dev->irq == 2)
dev->irq = 9;
err = com90io_probe(dev);
if (err) {
free_netdev(dev);
return err;
}
my_dev = dev;
return 0;
}
static void __exit com90io_exit(void)
{
struct net_device *dev = my_dev;
int ioaddr = dev->base_addr;
unregister_netdev(dev);
/* Set the thing back to MMAP mode, in case the old driver is loaded later */
outb((inb(_CONFIG) & ~IOMAPflag), _CONFIG);
free_irq(dev->irq, dev);
release_region(dev->base_addr, ARCNET_TOTAL_SIZE);
free_netdev(dev);
}
module_init(com90io_init)
module_exit(com90io_exit)
| gpl-2.0 |
chinghanyu/Cognet-RPi-linux | drivers/staging/wlan-ng/p80211req.c | 2821 | 7872 | /* src/p80211/p80211req.c
*
* Request/Indication/MacMgmt interface handling functions
*
* Copyright (C) 1999 AbsoluteValue Systems, Inc. All Rights Reserved.
* --------------------------------------------------------------------
*
* linux-wlan
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License version 2 (the "GPL"), in which
* case the provisions of the GPL are applicable instead of the
* above. If you wish to allow the use of your version of this file
* only under the terms of the GPL and not to allow others to use
* your version of this file under the MPL, indicate your decision
* by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* --------------------------------------------------------------------
*
* Inquiries regarding the linux-wlan Open Source project can be
* made directly to:
*
* AbsoluteValue Systems Inc.
* info@linux-wlan.com
* http://www.linux-wlan.com
*
* --------------------------------------------------------------------
*
* Portions of the development of this software were funded by
* Intersil Corporation as part of PRISM(R) chipset product development.
*
* --------------------------------------------------------------------
*
* This file contains the functions, types, and macros to support the
* MLME request interface that's implemented via the device ioctls.
*
* --------------------------------------------------------------------
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <linux/wireless.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <net/sock.h>
#include <linux/netlink.h>
#include "p80211types.h"
#include "p80211hdr.h"
#include "p80211mgmt.h"
#include "p80211conv.h"
#include "p80211msg.h"
#include "p80211netdev.h"
#include "p80211ioctl.h"
#include "p80211metadef.h"
#include "p80211metastruct.h"
#include "p80211req.h"
static void p80211req_handlemsg(wlandevice_t *wlandev, struct p80211msg *msg);
static void p80211req_mibset_mibget(wlandevice_t *wlandev,
struct p80211msg_dot11req_mibget *mib_msg,
int isget);
/*----------------------------------------------------------------
* p80211req_dorequest
*
* Handles an MLME reqest/confirm message.
*
* Arguments:
* wlandev WLAN device struct
* msgbuf Buffer containing a request message
*
* Returns:
* 0 on success, an errno otherwise
*
* Call context:
* Potentially blocks the caller, so it's a good idea to
* not call this function from an interrupt context.
----------------------------------------------------------------*/
int p80211req_dorequest(wlandevice_t *wlandev, u8 *msgbuf)
{
int result = 0;
struct p80211msg *msg = (struct p80211msg *) msgbuf;
/* Check to make sure the MSD is running */
if (!((wlandev->msdstate == WLAN_MSD_HWPRESENT &&
msg->msgcode == DIDmsg_lnxreq_ifstate) ||
wlandev->msdstate == WLAN_MSD_RUNNING ||
wlandev->msdstate == WLAN_MSD_FWLOAD)) {
return -ENODEV;
}
/* Check Permissions */
if (!capable(CAP_NET_ADMIN) &&
(msg->msgcode != DIDmsg_dot11req_mibget)) {
printk(KERN_ERR
"%s: only dot11req_mibget allowed for non-root.\n",
wlandev->name);
return -EPERM;
}
/* Check for busy status */
if (test_and_set_bit(1, &(wlandev->request_pending)))
return -EBUSY;
/* Allow p80211 to look at msg and handle if desired. */
/* So far, all p80211 msgs are immediate, no waitq/timer necessary */
/* This may change. */
p80211req_handlemsg(wlandev, msg);
/* Pass it down to wlandev via wlandev->mlmerequest */
if (wlandev->mlmerequest != NULL)
wlandev->mlmerequest(wlandev, msg);
clear_bit(1, &(wlandev->request_pending));
return result; /* if result==0, msg->status still may contain an err */
}
/*----------------------------------------------------------------
* p80211req_handlemsg
*
* p80211 message handler. Primarily looks for messages that
* belong to p80211 and then dispatches the appropriate response.
* TODO: we don't do anything yet. Once the linuxMIB is better
* defined we'll need a get/set handler.
*
* Arguments:
* wlandev WLAN device struct
* msg message structure
*
* Returns:
* nothing (any results are set in the status field of the msg)
*
* Call context:
* Process thread
----------------------------------------------------------------*/
static void p80211req_handlemsg(wlandevice_t *wlandev, struct p80211msg *msg)
{
switch (msg->msgcode) {
case DIDmsg_lnxreq_hostwep:{
struct p80211msg_lnxreq_hostwep *req =
(struct p80211msg_lnxreq_hostwep *) msg;
wlandev->hostwep &=
~(HOSTWEP_DECRYPT | HOSTWEP_ENCRYPT);
if (req->decrypt.data == P80211ENUM_truth_true)
wlandev->hostwep |= HOSTWEP_DECRYPT;
if (req->encrypt.data == P80211ENUM_truth_true)
wlandev->hostwep |= HOSTWEP_ENCRYPT;
break;
}
case DIDmsg_dot11req_mibget:
case DIDmsg_dot11req_mibset:{
int isget = (msg->msgcode == DIDmsg_dot11req_mibget);
struct p80211msg_dot11req_mibget *mib_msg =
(struct p80211msg_dot11req_mibget *) msg;
p80211req_mibset_mibget(wlandev, mib_msg, isget);
break;
}
} /* switch msg->msgcode */
}
static void p80211req_mibset_mibget(wlandevice_t *wlandev,
struct p80211msg_dot11req_mibget *mib_msg,
int isget)
{
p80211itemd_t *mibitem = (p80211itemd_t *) mib_msg->mibattribute.data;
p80211pstrd_t *pstr = (p80211pstrd_t *) mibitem->data;
u8 *key = mibitem->data + sizeof(p80211pstrd_t);
switch (mibitem->did) {
case DIDmib_dot11smt_dot11WEPDefaultKeysTable_dot11WEPDefaultKey0:{
if (!isget)
wep_change_key(wlandev, 0, key, pstr->len);
break;
}
case DIDmib_dot11smt_dot11WEPDefaultKeysTable_dot11WEPDefaultKey1:{
if (!isget)
wep_change_key(wlandev, 1, key, pstr->len);
break;
}
case DIDmib_dot11smt_dot11WEPDefaultKeysTable_dot11WEPDefaultKey2:{
if (!isget)
wep_change_key(wlandev, 2, key, pstr->len);
break;
}
case DIDmib_dot11smt_dot11WEPDefaultKeysTable_dot11WEPDefaultKey3:{
if (!isget)
wep_change_key(wlandev, 3, key, pstr->len);
break;
}
case DIDmib_dot11smt_dot11PrivacyTable_dot11WEPDefaultKeyID:{
u32 *data = (u32 *) mibitem->data;
if (isget) {
*data = wlandev->hostwep & HOSTWEP_DEFAULTKEY_MASK;
} else {
wlandev->hostwep &= ~(HOSTWEP_DEFAULTKEY_MASK);
wlandev->hostwep |= (*data & HOSTWEP_DEFAULTKEY_MASK);
}
break;
}
case DIDmib_dot11smt_dot11PrivacyTable_dot11PrivacyInvoked:{
u32 *data = (u32 *) mibitem->data;
if (isget) {
if (wlandev->hostwep & HOSTWEP_PRIVACYINVOKED)
*data = P80211ENUM_truth_true;
else
*data = P80211ENUM_truth_false;
} else {
wlandev->hostwep &= ~(HOSTWEP_PRIVACYINVOKED);
if (*data == P80211ENUM_truth_true)
wlandev->hostwep |= HOSTWEP_PRIVACYINVOKED;
}
break;
}
case DIDmib_dot11smt_dot11PrivacyTable_dot11ExcludeUnencrypted:{
u32 *data = (u32 *) mibitem->data;
if (isget) {
if (wlandev->hostwep & HOSTWEP_EXCLUDEUNENCRYPTED)
*data = P80211ENUM_truth_true;
else
*data = P80211ENUM_truth_false;
} else {
wlandev->hostwep &= ~(HOSTWEP_EXCLUDEUNENCRYPTED);
if (*data == P80211ENUM_truth_true)
wlandev->hostwep |= HOSTWEP_EXCLUDEUNENCRYPTED;
}
break;
}
}
}
| gpl-2.0 |
iamthedarkone/Nexus-S-Kernel | sound/pci/cs5535audio/cs5535audio.c | 3589 | 10564 | /*
* Driver for audio on multifunction CS5535/6 companion device
* Copyright (C) Jaya Kumar
*
* Based on Jaroslav Kysela and Takashi Iwai's examples.
* This work was sponsored by CIS(M) Sdn Bhd.
*
* 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/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/moduleparam.h>
#include <asm/io.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/rawmidi.h>
#include <sound/ac97_codec.h>
#include <sound/initval.h>
#include <sound/asoundef.h>
#include "cs5535audio.h"
#define DRIVER_NAME "cs5535audio"
static char *ac97_quirk;
module_param(ac97_quirk, charp, 0444);
MODULE_PARM_DESC(ac97_quirk, "AC'97 board specific workarounds.");
static struct ac97_quirk ac97_quirks[] __devinitdata = {
#if 0 /* Not yet confirmed if all 5536 boards are HP only */
{
.subvendor = PCI_VENDOR_ID_AMD,
.subdevice = PCI_DEVICE_ID_AMD_CS5536_AUDIO,
.name = "AMD RDK",
.type = AC97_TUNE_HP_ONLY
},
#endif
{}
};
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for " DRIVER_NAME);
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for " DRIVER_NAME);
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable " DRIVER_NAME);
static DEFINE_PCI_DEVICE_TABLE(snd_cs5535audio_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_CS5535_AUDIO) },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_AUDIO) },
{}
};
MODULE_DEVICE_TABLE(pci, snd_cs5535audio_ids);
static void wait_till_cmd_acked(struct cs5535audio *cs5535au, unsigned long timeout)
{
unsigned int tmp;
do {
tmp = cs_readl(cs5535au, ACC_CODEC_CNTL);
if (!(tmp & CMD_NEW))
break;
udelay(1);
} while (--timeout);
if (!timeout)
snd_printk(KERN_ERR "Failure writing to cs5535 codec\n");
}
static unsigned short snd_cs5535audio_codec_read(struct cs5535audio *cs5535au,
unsigned short reg)
{
unsigned int regdata;
unsigned int timeout;
unsigned int val;
regdata = ((unsigned int) reg) << 24;
regdata |= ACC_CODEC_CNTL_RD_CMD;
regdata |= CMD_NEW;
cs_writel(cs5535au, ACC_CODEC_CNTL, regdata);
wait_till_cmd_acked(cs5535au, 50);
timeout = 50;
do {
val = cs_readl(cs5535au, ACC_CODEC_STATUS);
if ((val & STS_NEW) && reg == (val >> 24))
break;
udelay(1);
} while (--timeout);
if (!timeout)
snd_printk(KERN_ERR "Failure reading codec reg 0x%x,"
"Last value=0x%x\n", reg, val);
return (unsigned short) val;
}
static void snd_cs5535audio_codec_write(struct cs5535audio *cs5535au,
unsigned short reg, unsigned short val)
{
unsigned int regdata;
regdata = ((unsigned int) reg) << 24;
regdata |= val;
regdata &= CMD_MASK;
regdata |= CMD_NEW;
regdata &= ACC_CODEC_CNTL_WR_CMD;
cs_writel(cs5535au, ACC_CODEC_CNTL, regdata);
wait_till_cmd_acked(cs5535au, 50);
}
static void snd_cs5535audio_ac97_codec_write(struct snd_ac97 *ac97,
unsigned short reg, unsigned short val)
{
struct cs5535audio *cs5535au = ac97->private_data;
snd_cs5535audio_codec_write(cs5535au, reg, val);
}
static unsigned short snd_cs5535audio_ac97_codec_read(struct snd_ac97 *ac97,
unsigned short reg)
{
struct cs5535audio *cs5535au = ac97->private_data;
return snd_cs5535audio_codec_read(cs5535au, reg);
}
static int __devinit snd_cs5535audio_mixer(struct cs5535audio *cs5535au)
{
struct snd_card *card = cs5535au->card;
struct snd_ac97_bus *pbus;
struct snd_ac97_template ac97;
int err;
static struct snd_ac97_bus_ops ops = {
.write = snd_cs5535audio_ac97_codec_write,
.read = snd_cs5535audio_ac97_codec_read,
};
if ((err = snd_ac97_bus(card, 0, &ops, NULL, &pbus)) < 0)
return err;
memset(&ac97, 0, sizeof(ac97));
ac97.scaps = AC97_SCAP_AUDIO | AC97_SCAP_SKIP_MODEM
| AC97_SCAP_POWER_SAVE;
ac97.private_data = cs5535au;
ac97.pci = cs5535au->pci;
/* set any OLPC-specific scaps */
olpc_prequirks(card, &ac97);
if ((err = snd_ac97_mixer(pbus, &ac97, &cs5535au->ac97)) < 0) {
snd_printk(KERN_ERR "mixer failed\n");
return err;
}
snd_ac97_tune_hardware(cs5535au->ac97, ac97_quirks, ac97_quirk);
err = olpc_quirks(card, cs5535au->ac97);
if (err < 0) {
snd_printk(KERN_ERR "olpc quirks failed\n");
return err;
}
return 0;
}
static void process_bm0_irq(struct cs5535audio *cs5535au)
{
u8 bm_stat;
spin_lock(&cs5535au->reg_lock);
bm_stat = cs_readb(cs5535au, ACC_BM0_STATUS);
spin_unlock(&cs5535au->reg_lock);
if (bm_stat & EOP) {
struct cs5535audio_dma *dma;
dma = cs5535au->playback_substream->runtime->private_data;
snd_pcm_period_elapsed(cs5535au->playback_substream);
} else {
snd_printk(KERN_ERR "unexpected bm0 irq src, bm_stat=%x\n",
bm_stat);
}
}
static void process_bm1_irq(struct cs5535audio *cs5535au)
{
u8 bm_stat;
spin_lock(&cs5535au->reg_lock);
bm_stat = cs_readb(cs5535au, ACC_BM1_STATUS);
spin_unlock(&cs5535au->reg_lock);
if (bm_stat & EOP) {
struct cs5535audio_dma *dma;
dma = cs5535au->capture_substream->runtime->private_data;
snd_pcm_period_elapsed(cs5535au->capture_substream);
}
}
static irqreturn_t snd_cs5535audio_interrupt(int irq, void *dev_id)
{
u16 acc_irq_stat;
unsigned char count;
struct cs5535audio *cs5535au = dev_id;
if (cs5535au == NULL)
return IRQ_NONE;
acc_irq_stat = cs_readw(cs5535au, ACC_IRQ_STATUS);
if (!acc_irq_stat)
return IRQ_NONE;
for (count = 0; count < 4; count++) {
if (acc_irq_stat & (1 << count)) {
switch (count) {
case IRQ_STS:
cs_readl(cs5535au, ACC_GPIO_STATUS);
break;
case WU_IRQ_STS:
cs_readl(cs5535au, ACC_GPIO_STATUS);
break;
case BM0_IRQ_STS:
process_bm0_irq(cs5535au);
break;
case BM1_IRQ_STS:
process_bm1_irq(cs5535au);
break;
default:
snd_printk(KERN_ERR "Unexpected irq src: "
"0x%x\n", acc_irq_stat);
break;
}
}
}
return IRQ_HANDLED;
}
static int snd_cs5535audio_free(struct cs5535audio *cs5535au)
{
synchronize_irq(cs5535au->irq);
pci_set_power_state(cs5535au->pci, 3);
if (cs5535au->irq >= 0)
free_irq(cs5535au->irq, cs5535au);
pci_release_regions(cs5535au->pci);
pci_disable_device(cs5535au->pci);
kfree(cs5535au);
return 0;
}
static int snd_cs5535audio_dev_free(struct snd_device *device)
{
struct cs5535audio *cs5535au = device->device_data;
return snd_cs5535audio_free(cs5535au);
}
static int __devinit snd_cs5535audio_create(struct snd_card *card,
struct pci_dev *pci,
struct cs5535audio **rcs5535au)
{
struct cs5535audio *cs5535au;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_cs5535audio_dev_free,
};
*rcs5535au = NULL;
if ((err = pci_enable_device(pci)) < 0)
return err;
if (pci_set_dma_mask(pci, DMA_BIT_MASK(32)) < 0 ||
pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(32)) < 0) {
printk(KERN_WARNING "unable to get 32bit dma\n");
err = -ENXIO;
goto pcifail;
}
cs5535au = kzalloc(sizeof(*cs5535au), GFP_KERNEL);
if (cs5535au == NULL) {
err = -ENOMEM;
goto pcifail;
}
spin_lock_init(&cs5535au->reg_lock);
cs5535au->card = card;
cs5535au->pci = pci;
cs5535au->irq = -1;
if ((err = pci_request_regions(pci, "CS5535 Audio")) < 0) {
kfree(cs5535au);
goto pcifail;
}
cs5535au->port = pci_resource_start(pci, 0);
if (request_irq(pci->irq, snd_cs5535audio_interrupt,
IRQF_SHARED, "CS5535 Audio", cs5535au)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
err = -EBUSY;
goto sndfail;
}
cs5535au->irq = pci->irq;
pci_set_master(pci);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
cs5535au, &ops)) < 0)
goto sndfail;
snd_card_set_dev(card, &pci->dev);
*rcs5535au = cs5535au;
return 0;
sndfail: /* leave the device alive, just kill the snd */
snd_cs5535audio_free(cs5535au);
return err;
pcifail:
pci_disable_device(pci);
return err;
}
static int __devinit snd_cs5535audio_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct cs5535audio *cs5535au;
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
if ((err = snd_cs5535audio_create(card, pci, &cs5535au)) < 0)
goto probefail_out;
card->private_data = cs5535au;
if ((err = snd_cs5535audio_mixer(cs5535au)) < 0)
goto probefail_out;
if ((err = snd_cs5535audio_pcm(cs5535au)) < 0)
goto probefail_out;
strcpy(card->driver, DRIVER_NAME);
strcpy(card->shortname, "CS5535 Audio");
sprintf(card->longname, "%s %s at 0x%lx, irq %i",
card->shortname, card->driver,
cs5535au->port, cs5535au->irq);
if ((err = snd_card_register(card)) < 0)
goto probefail_out;
pci_set_drvdata(pci, card);
dev++;
return 0;
probefail_out:
snd_card_free(card);
return err;
}
static void __devexit snd_cs5535audio_remove(struct pci_dev *pci)
{
olpc_quirks_cleanup();
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
static struct pci_driver driver = {
.name = DRIVER_NAME,
.id_table = snd_cs5535audio_ids,
.probe = snd_cs5535audio_probe,
.remove = __devexit_p(snd_cs5535audio_remove),
#ifdef CONFIG_PM
.suspend = snd_cs5535audio_suspend,
.resume = snd_cs5535audio_resume,
#endif
};
static int __init alsa_card_cs5535audio_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_cs5535audio_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_cs5535audio_init)
module_exit(alsa_card_cs5535audio_exit)
MODULE_AUTHOR("Jaya Kumar");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("CS5535 Audio");
MODULE_SUPPORTED_DEVICE("CS5535 Audio");
| gpl-2.0 |
nobodyAtall/msm7x30-3.4.x-nAa | sound/soc/samsung/spdif.c | 4869 | 11966 | /* sound/soc/samsung/spdif.c
*
* ALSA SoC Audio Layer - Samsung S/PDIF Controller driver
*
* Copyright (c) 2010 Samsung Electronics Co. Ltd
* http://www.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 <linux/clk.h>
#include <linux/io.h>
#include <linux/module.h>
#include <sound/soc.h>
#include <sound/pcm_params.h>
#include <plat/audio.h>
#include <mach/dma.h>
#include "dma.h"
#include "spdif.h"
/* Registers */
#define CLKCON 0x00
#define CON 0x04
#define BSTAS 0x08
#define CSTAS 0x0C
#define DATA_OUTBUF 0x10
#define DCNT 0x14
#define BSTAS_S 0x18
#define DCNT_S 0x1C
#define CLKCTL_MASK 0x7
#define CLKCTL_MCLK_EXT (0x1 << 2)
#define CLKCTL_PWR_ON (0x1 << 0)
#define CON_MASK 0x3ffffff
#define CON_FIFO_TH_SHIFT 19
#define CON_FIFO_TH_MASK (0x7 << 19)
#define CON_USERDATA_23RDBIT (0x1 << 12)
#define CON_SW_RESET (0x1 << 5)
#define CON_MCLKDIV_MASK (0x3 << 3)
#define CON_MCLKDIV_256FS (0x0 << 3)
#define CON_MCLKDIV_384FS (0x1 << 3)
#define CON_MCLKDIV_512FS (0x2 << 3)
#define CON_PCM_MASK (0x3 << 1)
#define CON_PCM_16BIT (0x0 << 1)
#define CON_PCM_20BIT (0x1 << 1)
#define CON_PCM_24BIT (0x2 << 1)
#define CON_PCM_DATA (0x1 << 0)
#define CSTAS_MASK 0x3fffffff
#define CSTAS_SAMP_FREQ_MASK (0xF << 24)
#define CSTAS_SAMP_FREQ_44 (0x0 << 24)
#define CSTAS_SAMP_FREQ_48 (0x2 << 24)
#define CSTAS_SAMP_FREQ_32 (0x3 << 24)
#define CSTAS_SAMP_FREQ_96 (0xA << 24)
#define CSTAS_CATEGORY_MASK (0xFF << 8)
#define CSTAS_CATEGORY_CODE_CDP (0x01 << 8)
#define CSTAS_NO_COPYRIGHT (0x1 << 2)
/**
* struct samsung_spdif_info - Samsung S/PDIF Controller information
* @lock: Spin lock for S/PDIF.
* @dev: The parent device passed to use from the probe.
* @regs: The pointer to the device register block.
* @clk_rate: Current clock rate for calcurate ratio.
* @pclk: The peri-clock pointer for spdif master operation.
* @sclk: The source clock pointer for making sync signals.
* @save_clkcon: Backup clkcon reg. in suspend.
* @save_con: Backup con reg. in suspend.
* @save_cstas: Backup cstas reg. in suspend.
* @dma_playback: DMA information for playback channel.
*/
struct samsung_spdif_info {
spinlock_t lock;
struct device *dev;
void __iomem *regs;
unsigned long clk_rate;
struct clk *pclk;
struct clk *sclk;
u32 saved_clkcon;
u32 saved_con;
u32 saved_cstas;
struct s3c_dma_params *dma_playback;
};
static struct s3c2410_dma_client spdif_dma_client_out = {
.name = "S/PDIF Stereo out",
};
static struct s3c_dma_params spdif_stereo_out;
static struct samsung_spdif_info spdif_info;
static inline struct samsung_spdif_info *to_info(struct snd_soc_dai *cpu_dai)
{
return snd_soc_dai_get_drvdata(cpu_dai);
}
static void spdif_snd_txctrl(struct samsung_spdif_info *spdif, int on)
{
void __iomem *regs = spdif->regs;
u32 clkcon;
dev_dbg(spdif->dev, "Entered %s\n", __func__);
clkcon = readl(regs + CLKCON) & CLKCTL_MASK;
if (on)
writel(clkcon | CLKCTL_PWR_ON, regs + CLKCON);
else
writel(clkcon & ~CLKCTL_PWR_ON, regs + CLKCON);
}
static int spdif_set_sysclk(struct snd_soc_dai *cpu_dai,
int clk_id, unsigned int freq, int dir)
{
struct samsung_spdif_info *spdif = to_info(cpu_dai);
u32 clkcon;
dev_dbg(spdif->dev, "Entered %s\n", __func__);
clkcon = readl(spdif->regs + CLKCON);
if (clk_id == SND_SOC_SPDIF_INT_MCLK)
clkcon &= ~CLKCTL_MCLK_EXT;
else
clkcon |= CLKCTL_MCLK_EXT;
writel(clkcon, spdif->regs + CLKCON);
spdif->clk_rate = freq;
return 0;
}
static int spdif_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct samsung_spdif_info *spdif = to_info(rtd->cpu_dai);
unsigned long flags;
dev_dbg(spdif->dev, "Entered %s\n", __func__);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
spin_lock_irqsave(&spdif->lock, flags);
spdif_snd_txctrl(spdif, 1);
spin_unlock_irqrestore(&spdif->lock, flags);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
spin_lock_irqsave(&spdif->lock, flags);
spdif_snd_txctrl(spdif, 0);
spin_unlock_irqrestore(&spdif->lock, flags);
break;
default:
return -EINVAL;
}
return 0;
}
static int spdif_sysclk_ratios[] = {
512, 384, 256,
};
static int spdif_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *socdai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct samsung_spdif_info *spdif = to_info(rtd->cpu_dai);
void __iomem *regs = spdif->regs;
struct s3c_dma_params *dma_data;
u32 con, clkcon, cstas;
unsigned long flags;
int i, ratio;
dev_dbg(spdif->dev, "Entered %s\n", __func__);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
dma_data = spdif->dma_playback;
else {
dev_err(spdif->dev, "Capture is not supported\n");
return -EINVAL;
}
snd_soc_dai_set_dma_data(rtd->cpu_dai, substream, dma_data);
spin_lock_irqsave(&spdif->lock, flags);
con = readl(regs + CON) & CON_MASK;
cstas = readl(regs + CSTAS) & CSTAS_MASK;
clkcon = readl(regs + CLKCON) & CLKCTL_MASK;
con &= ~CON_FIFO_TH_MASK;
con |= (0x7 << CON_FIFO_TH_SHIFT);
con |= CON_USERDATA_23RDBIT;
con |= CON_PCM_DATA;
con &= ~CON_PCM_MASK;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
con |= CON_PCM_16BIT;
break;
default:
dev_err(spdif->dev, "Unsupported data size.\n");
goto err;
}
ratio = spdif->clk_rate / params_rate(params);
for (i = 0; i < ARRAY_SIZE(spdif_sysclk_ratios); i++)
if (ratio == spdif_sysclk_ratios[i])
break;
if (i == ARRAY_SIZE(spdif_sysclk_ratios)) {
dev_err(spdif->dev, "Invalid clock ratio %ld/%d\n",
spdif->clk_rate, params_rate(params));
goto err;
}
con &= ~CON_MCLKDIV_MASK;
switch (ratio) {
case 256:
con |= CON_MCLKDIV_256FS;
break;
case 384:
con |= CON_MCLKDIV_384FS;
break;
case 512:
con |= CON_MCLKDIV_512FS;
break;
}
cstas &= ~CSTAS_SAMP_FREQ_MASK;
switch (params_rate(params)) {
case 44100:
cstas |= CSTAS_SAMP_FREQ_44;
break;
case 48000:
cstas |= CSTAS_SAMP_FREQ_48;
break;
case 32000:
cstas |= CSTAS_SAMP_FREQ_32;
break;
case 96000:
cstas |= CSTAS_SAMP_FREQ_96;
break;
default:
dev_err(spdif->dev, "Invalid sampling rate %d\n",
params_rate(params));
goto err;
}
cstas &= ~CSTAS_CATEGORY_MASK;
cstas |= CSTAS_CATEGORY_CODE_CDP;
cstas |= CSTAS_NO_COPYRIGHT;
writel(con, regs + CON);
writel(cstas, regs + CSTAS);
writel(clkcon, regs + CLKCON);
spin_unlock_irqrestore(&spdif->lock, flags);
return 0;
err:
spin_unlock_irqrestore(&spdif->lock, flags);
return -EINVAL;
}
static void spdif_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct samsung_spdif_info *spdif = to_info(rtd->cpu_dai);
void __iomem *regs = spdif->regs;
u32 con, clkcon;
dev_dbg(spdif->dev, "Entered %s\n", __func__);
con = readl(regs + CON) & CON_MASK;
clkcon = readl(regs + CLKCON) & CLKCTL_MASK;
writel(con | CON_SW_RESET, regs + CON);
cpu_relax();
writel(clkcon & ~CLKCTL_PWR_ON, regs + CLKCON);
}
#ifdef CONFIG_PM
static int spdif_suspend(struct snd_soc_dai *cpu_dai)
{
struct samsung_spdif_info *spdif = to_info(cpu_dai);
u32 con = spdif->saved_con;
dev_dbg(spdif->dev, "Entered %s\n", __func__);
spdif->saved_clkcon = readl(spdif->regs + CLKCON) & CLKCTL_MASK;
spdif->saved_con = readl(spdif->regs + CON) & CON_MASK;
spdif->saved_cstas = readl(spdif->regs + CSTAS) & CSTAS_MASK;
writel(con | CON_SW_RESET, spdif->regs + CON);
cpu_relax();
return 0;
}
static int spdif_resume(struct snd_soc_dai *cpu_dai)
{
struct samsung_spdif_info *spdif = to_info(cpu_dai);
dev_dbg(spdif->dev, "Entered %s\n", __func__);
writel(spdif->saved_clkcon, spdif->regs + CLKCON);
writel(spdif->saved_con, spdif->regs + CON);
writel(spdif->saved_cstas, spdif->regs + CSTAS);
return 0;
}
#else
#define spdif_suspend NULL
#define spdif_resume NULL
#endif
static const struct snd_soc_dai_ops spdif_dai_ops = {
.set_sysclk = spdif_set_sysclk,
.trigger = spdif_trigger,
.hw_params = spdif_hw_params,
.shutdown = spdif_shutdown,
};
static struct snd_soc_dai_driver samsung_spdif_dai = {
.name = "samsung-spdif",
.playback = {
.stream_name = "S/PDIF Playback",
.channels_min = 2,
.channels_max = 2,
.rates = (SNDRV_PCM_RATE_32000 |
SNDRV_PCM_RATE_44100 |
SNDRV_PCM_RATE_48000 |
SNDRV_PCM_RATE_96000),
.formats = SNDRV_PCM_FMTBIT_S16_LE, },
.ops = &spdif_dai_ops,
.suspend = spdif_suspend,
.resume = spdif_resume,
};
static __devinit int spdif_probe(struct platform_device *pdev)
{
struct s3c_audio_pdata *spdif_pdata;
struct resource *mem_res, *dma_res;
struct samsung_spdif_info *spdif;
int ret;
spdif_pdata = pdev->dev.platform_data;
dev_dbg(&pdev->dev, "Entered %s\n", __func__);
dma_res = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!dma_res) {
dev_err(&pdev->dev, "Unable to get dma resource.\n");
return -ENXIO;
}
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem_res) {
dev_err(&pdev->dev, "Unable to get register resource.\n");
return -ENXIO;
}
if (spdif_pdata && spdif_pdata->cfg_gpio
&& spdif_pdata->cfg_gpio(pdev)) {
dev_err(&pdev->dev, "Unable to configure GPIO pins\n");
return -EINVAL;
}
spdif = &spdif_info;
spdif->dev = &pdev->dev;
spin_lock_init(&spdif->lock);
spdif->pclk = clk_get(&pdev->dev, "spdif");
if (IS_ERR(spdif->pclk)) {
dev_err(&pdev->dev, "failed to get peri-clock\n");
ret = -ENOENT;
goto err0;
}
clk_enable(spdif->pclk);
spdif->sclk = clk_get(&pdev->dev, "sclk_spdif");
if (IS_ERR(spdif->sclk)) {
dev_err(&pdev->dev, "failed to get internal source clock\n");
ret = -ENOENT;
goto err1;
}
clk_enable(spdif->sclk);
/* Request S/PDIF Register's memory region */
if (!request_mem_region(mem_res->start,
resource_size(mem_res), "samsung-spdif")) {
dev_err(&pdev->dev, "Unable to request register region\n");
ret = -EBUSY;
goto err2;
}
spdif->regs = ioremap(mem_res->start, 0x100);
if (spdif->regs == NULL) {
dev_err(&pdev->dev, "Cannot ioremap registers\n");
ret = -ENXIO;
goto err3;
}
dev_set_drvdata(&pdev->dev, spdif);
ret = snd_soc_register_dai(&pdev->dev, &samsung_spdif_dai);
if (ret != 0) {
dev_err(&pdev->dev, "fail to register dai\n");
goto err4;
}
spdif_stereo_out.dma_size = 2;
spdif_stereo_out.client = &spdif_dma_client_out;
spdif_stereo_out.dma_addr = mem_res->start + DATA_OUTBUF;
spdif_stereo_out.channel = dma_res->start;
spdif->dma_playback = &spdif_stereo_out;
return 0;
err4:
iounmap(spdif->regs);
err3:
release_mem_region(mem_res->start, resource_size(mem_res));
err2:
clk_disable(spdif->sclk);
clk_put(spdif->sclk);
err1:
clk_disable(spdif->pclk);
clk_put(spdif->pclk);
err0:
return ret;
}
static __devexit int spdif_remove(struct platform_device *pdev)
{
struct samsung_spdif_info *spdif = &spdif_info;
struct resource *mem_res;
snd_soc_unregister_dai(&pdev->dev);
iounmap(spdif->regs);
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (mem_res)
release_mem_region(mem_res->start, resource_size(mem_res));
clk_disable(spdif->sclk);
clk_put(spdif->sclk);
clk_disable(spdif->pclk);
clk_put(spdif->pclk);
return 0;
}
static struct platform_driver samsung_spdif_driver = {
.probe = spdif_probe,
.remove = __devexit_p(spdif_remove),
.driver = {
.name = "samsung-spdif",
.owner = THIS_MODULE,
},
};
module_platform_driver(samsung_spdif_driver);
MODULE_AUTHOR("Seungwhan Youn, <sw.youn@samsung.com>");
MODULE_DESCRIPTION("Samsung S/PDIF Controller Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:samsung-spdif");
| gpl-2.0 |
wulsic/android_kernel_samsung_nevispcm11 | fs/yaffs2/yaffs_checkptrw.c | 7941 | 10663 | /*
* YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
*
* Copyright (C) 2002-2010 Aleph One Ltd.
* for Toby Churchill Ltd and Brightstar Engineering
*
* Created by Charles Manning <charles@aleph1.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include "yaffs_checkptrw.h"
#include "yaffs_getblockinfo.h"
static int yaffs2_checkpt_space_ok(struct yaffs_dev *dev)
{
int blocks_avail = dev->n_erased_blocks - dev->param.n_reserved_blocks;
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"checkpt blocks_avail = %d", blocks_avail);
return (blocks_avail <= 0) ? 0 : 1;
}
static int yaffs_checkpt_erase(struct yaffs_dev *dev)
{
int i;
if (!dev->param.erase_fn)
return 0;
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"checking blocks %d to %d",
dev->internal_start_block, dev->internal_end_block);
for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
struct yaffs_block_info *bi = yaffs_get_block_info(dev, i);
if (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT) {
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"erasing checkpt block %d", i);
dev->n_erasures++;
if (dev->param.
erase_fn(dev,
i - dev->block_offset /* realign */ )) {
bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
dev->n_erased_blocks++;
dev->n_free_chunks +=
dev->param.chunks_per_block;
} else {
dev->param.bad_block_fn(dev, i);
bi->block_state = YAFFS_BLOCK_STATE_DEAD;
}
}
}
dev->blocks_in_checkpt = 0;
return 1;
}
static void yaffs2_checkpt_find_erased_block(struct yaffs_dev *dev)
{
int i;
int blocks_avail = dev->n_erased_blocks - dev->param.n_reserved_blocks;
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"allocating checkpt block: erased %d reserved %d avail %d next %d ",
dev->n_erased_blocks, dev->param.n_reserved_blocks,
blocks_avail, dev->checkpt_next_block);
if (dev->checkpt_next_block >= 0 &&
dev->checkpt_next_block <= dev->internal_end_block &&
blocks_avail > 0) {
for (i = dev->checkpt_next_block; i <= dev->internal_end_block;
i++) {
struct yaffs_block_info *bi =
yaffs_get_block_info(dev, i);
if (bi->block_state == YAFFS_BLOCK_STATE_EMPTY) {
dev->checkpt_next_block = i + 1;
dev->checkpt_cur_block = i;
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"allocating checkpt block %d", i);
return;
}
}
}
yaffs_trace(YAFFS_TRACE_CHECKPOINT, "out of checkpt blocks");
dev->checkpt_next_block = -1;
dev->checkpt_cur_block = -1;
}
static void yaffs2_checkpt_find_block(struct yaffs_dev *dev)
{
int i;
struct yaffs_ext_tags tags;
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"find next checkpt block: start: blocks %d next %d",
dev->blocks_in_checkpt, dev->checkpt_next_block);
if (dev->blocks_in_checkpt < dev->checkpt_max_blocks)
for (i = dev->checkpt_next_block; i <= dev->internal_end_block;
i++) {
int chunk = i * dev->param.chunks_per_block;
int realigned_chunk = chunk - dev->chunk_offset;
dev->param.read_chunk_tags_fn(dev, realigned_chunk,
NULL, &tags);
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"find next checkpt block: search: block %d oid %d seq %d eccr %d",
i, tags.obj_id, tags.seq_number,
tags.ecc_result);
if (tags.seq_number == YAFFS_SEQUENCE_CHECKPOINT_DATA) {
/* Right kind of block */
dev->checkpt_next_block = tags.obj_id;
dev->checkpt_cur_block = i;
dev->checkpt_block_list[dev->
blocks_in_checkpt] = i;
dev->blocks_in_checkpt++;
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"found checkpt block %d", i);
return;
}
}
yaffs_trace(YAFFS_TRACE_CHECKPOINT, "found no more checkpt blocks");
dev->checkpt_next_block = -1;
dev->checkpt_cur_block = -1;
}
int yaffs2_checkpt_open(struct yaffs_dev *dev, int writing)
{
dev->checkpt_open_write = writing;
/* Got the functions we need? */
if (!dev->param.write_chunk_tags_fn ||
!dev->param.read_chunk_tags_fn ||
!dev->param.erase_fn || !dev->param.bad_block_fn)
return 0;
if (writing && !yaffs2_checkpt_space_ok(dev))
return 0;
if (!dev->checkpt_buffer)
dev->checkpt_buffer =
kmalloc(dev->param.total_bytes_per_chunk, GFP_NOFS);
if (!dev->checkpt_buffer)
return 0;
dev->checkpt_page_seq = 0;
dev->checkpt_byte_count = 0;
dev->checkpt_sum = 0;
dev->checkpt_xor = 0;
dev->checkpt_cur_block = -1;
dev->checkpt_cur_chunk = -1;
dev->checkpt_next_block = dev->internal_start_block;
/* Erase all the blocks in the checkpoint area */
if (writing) {
memset(dev->checkpt_buffer, 0, dev->data_bytes_per_chunk);
dev->checkpt_byte_offs = 0;
return yaffs_checkpt_erase(dev);
} else {
int i;
/* Set to a value that will kick off a read */
dev->checkpt_byte_offs = dev->data_bytes_per_chunk;
/* A checkpoint block list of 1 checkpoint block per 16 block is (hopefully)
* going to be way more than we need */
dev->blocks_in_checkpt = 0;
dev->checkpt_max_blocks =
(dev->internal_end_block - dev->internal_start_block) / 16 +
2;
dev->checkpt_block_list =
kmalloc(sizeof(int) * dev->checkpt_max_blocks, GFP_NOFS);
if (!dev->checkpt_block_list)
return 0;
for (i = 0; i < dev->checkpt_max_blocks; i++)
dev->checkpt_block_list[i] = -1;
}
return 1;
}
int yaffs2_get_checkpt_sum(struct yaffs_dev *dev, u32 * sum)
{
u32 composite_sum;
composite_sum = (dev->checkpt_sum << 8) | (dev->checkpt_xor & 0xFF);
*sum = composite_sum;
return 1;
}
static int yaffs2_checkpt_flush_buffer(struct yaffs_dev *dev)
{
int chunk;
int realigned_chunk;
struct yaffs_ext_tags tags;
if (dev->checkpt_cur_block < 0) {
yaffs2_checkpt_find_erased_block(dev);
dev->checkpt_cur_chunk = 0;
}
if (dev->checkpt_cur_block < 0)
return 0;
tags.is_deleted = 0;
tags.obj_id = dev->checkpt_next_block; /* Hint to next place to look */
tags.chunk_id = dev->checkpt_page_seq + 1;
tags.seq_number = YAFFS_SEQUENCE_CHECKPOINT_DATA;
tags.n_bytes = dev->data_bytes_per_chunk;
if (dev->checkpt_cur_chunk == 0) {
/* First chunk we write for the block? Set block state to
checkpoint */
struct yaffs_block_info *bi =
yaffs_get_block_info(dev, dev->checkpt_cur_block);
bi->block_state = YAFFS_BLOCK_STATE_CHECKPOINT;
dev->blocks_in_checkpt++;
}
chunk =
dev->checkpt_cur_block * dev->param.chunks_per_block +
dev->checkpt_cur_chunk;
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"checkpoint wite buffer nand %d(%d:%d) objid %d chId %d",
chunk, dev->checkpt_cur_block, dev->checkpt_cur_chunk,
tags.obj_id, tags.chunk_id);
realigned_chunk = chunk - dev->chunk_offset;
dev->n_page_writes++;
dev->param.write_chunk_tags_fn(dev, realigned_chunk,
dev->checkpt_buffer, &tags);
dev->checkpt_byte_offs = 0;
dev->checkpt_page_seq++;
dev->checkpt_cur_chunk++;
if (dev->checkpt_cur_chunk >= dev->param.chunks_per_block) {
dev->checkpt_cur_chunk = 0;
dev->checkpt_cur_block = -1;
}
memset(dev->checkpt_buffer, 0, dev->data_bytes_per_chunk);
return 1;
}
int yaffs2_checkpt_wr(struct yaffs_dev *dev, const void *data, int n_bytes)
{
int i = 0;
int ok = 1;
u8 *data_bytes = (u8 *) data;
if (!dev->checkpt_buffer)
return 0;
if (!dev->checkpt_open_write)
return -1;
while (i < n_bytes && ok) {
dev->checkpt_buffer[dev->checkpt_byte_offs] = *data_bytes;
dev->checkpt_sum += *data_bytes;
dev->checkpt_xor ^= *data_bytes;
dev->checkpt_byte_offs++;
i++;
data_bytes++;
dev->checkpt_byte_count++;
if (dev->checkpt_byte_offs < 0 ||
dev->checkpt_byte_offs >= dev->data_bytes_per_chunk)
ok = yaffs2_checkpt_flush_buffer(dev);
}
return i;
}
int yaffs2_checkpt_rd(struct yaffs_dev *dev, void *data, int n_bytes)
{
int i = 0;
int ok = 1;
struct yaffs_ext_tags tags;
int chunk;
int realigned_chunk;
u8 *data_bytes = (u8 *) data;
if (!dev->checkpt_buffer)
return 0;
if (dev->checkpt_open_write)
return -1;
while (i < n_bytes && ok) {
if (dev->checkpt_byte_offs < 0 ||
dev->checkpt_byte_offs >= dev->data_bytes_per_chunk) {
if (dev->checkpt_cur_block < 0) {
yaffs2_checkpt_find_block(dev);
dev->checkpt_cur_chunk = 0;
}
if (dev->checkpt_cur_block < 0)
ok = 0;
else {
chunk = dev->checkpt_cur_block *
dev->param.chunks_per_block +
dev->checkpt_cur_chunk;
realigned_chunk = chunk - dev->chunk_offset;
dev->n_page_reads++;
/* read in the next chunk */
dev->param.read_chunk_tags_fn(dev,
realigned_chunk,
dev->
checkpt_buffer,
&tags);
if (tags.chunk_id != (dev->checkpt_page_seq + 1)
|| tags.ecc_result > YAFFS_ECC_RESULT_FIXED
|| tags.seq_number !=
YAFFS_SEQUENCE_CHECKPOINT_DATA)
ok = 0;
dev->checkpt_byte_offs = 0;
dev->checkpt_page_seq++;
dev->checkpt_cur_chunk++;
if (dev->checkpt_cur_chunk >=
dev->param.chunks_per_block)
dev->checkpt_cur_block = -1;
}
}
if (ok) {
*data_bytes =
dev->checkpt_buffer[dev->checkpt_byte_offs];
dev->checkpt_sum += *data_bytes;
dev->checkpt_xor ^= *data_bytes;
dev->checkpt_byte_offs++;
i++;
data_bytes++;
dev->checkpt_byte_count++;
}
}
return i;
}
int yaffs_checkpt_close(struct yaffs_dev *dev)
{
if (dev->checkpt_open_write) {
if (dev->checkpt_byte_offs != 0)
yaffs2_checkpt_flush_buffer(dev);
} else if (dev->checkpt_block_list) {
int i;
for (i = 0;
i < dev->blocks_in_checkpt
&& dev->checkpt_block_list[i] >= 0; i++) {
int blk = dev->checkpt_block_list[i];
struct yaffs_block_info *bi = NULL;
if (dev->internal_start_block <= blk
&& blk <= dev->internal_end_block)
bi = yaffs_get_block_info(dev, blk);
if (bi && bi->block_state == YAFFS_BLOCK_STATE_EMPTY)
bi->block_state = YAFFS_BLOCK_STATE_CHECKPOINT;
else {
/* Todo this looks odd... */
}
}
kfree(dev->checkpt_block_list);
dev->checkpt_block_list = NULL;
}
dev->n_free_chunks -=
dev->blocks_in_checkpt * dev->param.chunks_per_block;
dev->n_erased_blocks -= dev->blocks_in_checkpt;
yaffs_trace(YAFFS_TRACE_CHECKPOINT,"checkpoint byte count %d",
dev->checkpt_byte_count);
if (dev->checkpt_buffer) {
/* free the buffer */
kfree(dev->checkpt_buffer);
dev->checkpt_buffer = NULL;
return 1;
} else {
return 0;
}
}
int yaffs2_checkpt_invalidate_stream(struct yaffs_dev *dev)
{
/* Erase the checkpoint data */
yaffs_trace(YAFFS_TRACE_CHECKPOINT,
"checkpoint invalidate of %d blocks",
dev->blocks_in_checkpt);
return yaffs_checkpt_erase(dev);
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.