repo_name
string
path
string
copies
string
size
string
content
string
license
string
TI-OpenLink/wl18xx
drivers/char/tpm/tpm_i2c_stm_st33.c
545
23439
/* * STMicroelectronics TPM I2C Linux driver for TPM ST33ZP24 * Copyright (C) 2009, 2010 STMicroelectronics * * This program is free software; you can redistribute it and/or modify * it under the terms of the 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. * * STMicroelectronics version 1.2.0, Copyright (C) 2010 * STMicroelectronics comes with ABSOLUTELY NO WARRANTY. * This is free software, and you are welcome to redistribute it * under certain conditions. * * @Author: Christophe RICARD tpmsupport@st.com * * @File: tpm_stm_st33_i2c.c * * @Synopsis: * 09/15/2010: First shot driver tpm_tis driver for lpc is used as model. */ #include <linux/pci.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/i2c.h> #include <linux/fs.h> #include <linux/miscdevice.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/wait.h> #include <linux/string.h> #include <linux/interrupt.h> #include <linux/spinlock.h> #include <linux/sysfs.h> #include <linux/gpio.h> #include <linux/sched.h> #include <linux/uaccess.h> #include <linux/io.h> #include <linux/slab.h> #include "tpm.h" #include "tpm_i2c_stm_st33.h" enum stm33zp24_access { TPM_ACCESS_VALID = 0x80, TPM_ACCESS_ACTIVE_LOCALITY = 0x20, TPM_ACCESS_REQUEST_PENDING = 0x04, TPM_ACCESS_REQUEST_USE = 0x02, }; enum stm33zp24_status { TPM_STS_VALID = 0x80, TPM_STS_COMMAND_READY = 0x40, TPM_STS_GO = 0x20, TPM_STS_DATA_AVAIL = 0x10, TPM_STS_DATA_EXPECT = 0x08, }; enum stm33zp24_int_flags { TPM_GLOBAL_INT_ENABLE = 0x80, TPM_INTF_CMD_READY_INT = 0x080, TPM_INTF_FIFO_AVALAIBLE_INT = 0x040, TPM_INTF_WAKE_UP_READY_INT = 0x020, TPM_INTF_LOCALITY_CHANGE_INT = 0x004, TPM_INTF_STS_VALID_INT = 0x002, TPM_INTF_DATA_AVAIL_INT = 0x001, }; enum tis_defaults { TIS_SHORT_TIMEOUT = 750, TIS_LONG_TIMEOUT = 2000, }; /* * write8_reg * Send byte to the TIS register according to the ST33ZP24 I2C protocol. * @param: tpm_register, the tpm tis register where the data should be written * @param: tpm_data, the tpm_data to write inside the tpm_register * @param: tpm_size, The length of the data * @return: Returns negative errno, or else the number of bytes written. */ static int write8_reg(struct i2c_client *client, u8 tpm_register, u8 *tpm_data, u16 tpm_size) { struct st33zp24_platform_data *pin_infos; pin_infos = client->dev.platform_data; pin_infos->tpm_i2c_buffer[0][0] = tpm_register; memcpy(&pin_infos->tpm_i2c_buffer[0][1], tpm_data, tpm_size); return i2c_master_send(client, pin_infos->tpm_i2c_buffer[0], tpm_size + 1); } /* write8_reg() */ /* * read8_reg * Recv byte from the TIS register according to the ST33ZP24 I2C protocol. * @param: tpm_register, the tpm tis register where the data should be read * @param: tpm_data, the TPM response * @param: tpm_size, tpm TPM response size to read. * @return: number of byte read successfully: should be one if success. */ static int read8_reg(struct i2c_client *client, u8 tpm_register, u8 *tpm_data, int tpm_size) { u8 status = 0; u8 data; data = TPM_DUMMY_BYTE; status = write8_reg(client, tpm_register, &data, 1); if (status == 2) status = i2c_master_recv(client, tpm_data, tpm_size); return status; } /* read8_reg() */ /* * I2C_WRITE_DATA * Send byte to the TIS register according to the ST33ZP24 I2C protocol. * @param: client, the chip description * @param: tpm_register, the tpm tis register where the data should be written * @param: tpm_data, the tpm_data to write inside the tpm_register * @param: tpm_size, The length of the data * @return: number of byte written successfully: should be one if success. */ #define I2C_WRITE_DATA(client, tpm_register, tpm_data, tpm_size) \ (write8_reg(client, tpm_register | \ TPM_WRITE_DIRECTION, tpm_data, tpm_size)) /* * I2C_READ_DATA * Recv byte from the TIS register according to the ST33ZP24 I2C protocol. * @param: tpm, the chip description * @param: tpm_register, the tpm tis register where the data should be read * @param: tpm_data, the TPM response * @param: tpm_size, tpm TPM response size to read. * @return: number of byte read successfully: should be one if success. */ #define I2C_READ_DATA(client, tpm_register, tpm_data, tpm_size) \ (read8_reg(client, tpm_register, tpm_data, tpm_size)) /* * clear_interruption * clear the TPM interrupt register. * @param: tpm, the chip description */ static void clear_interruption(struct i2c_client *client) { u8 interrupt; I2C_READ_DATA(client, TPM_INT_STATUS, &interrupt, 1); I2C_WRITE_DATA(client, TPM_INT_STATUS, &interrupt, 1); I2C_READ_DATA(client, TPM_INT_STATUS, &interrupt, 1); } /* clear_interruption() */ /* * _wait_for_interrupt_serirq_timeout * @param: tpm, the chip description * @param: timeout, the timeout of the interrupt * @return: the status of the interruption. */ static long _wait_for_interrupt_serirq_timeout(struct tpm_chip *chip, unsigned long timeout) { long status; struct i2c_client *client; struct st33zp24_platform_data *pin_infos; client = (struct i2c_client *)TPM_VPRIV(chip); pin_infos = client->dev.platform_data; status = wait_for_completion_interruptible_timeout( &pin_infos->irq_detection, timeout); if (status > 0) enable_irq(gpio_to_irq(pin_infos->io_serirq)); gpio_direction_input(pin_infos->io_serirq); return status; } /* wait_for_interrupt_serirq_timeout() */ static int wait_for_serirq_timeout(struct tpm_chip *chip, bool condition, unsigned long timeout) { int status = 2; struct i2c_client *client; client = (struct i2c_client *)TPM_VPRIV(chip); status = _wait_for_interrupt_serirq_timeout(chip, timeout); if (!status) { status = -EBUSY; } else { clear_interruption(client); if (condition) status = 1; } return status; } /* * tpm_stm_i2c_cancel, cancel is not implemented. * @param: chip, the tpm_chip description as specified in driver/char/tpm/tpm.h */ static void tpm_stm_i2c_cancel(struct tpm_chip *chip) { struct i2c_client *client; u8 data; client = (struct i2c_client *)TPM_VPRIV(chip); data = TPM_STS_COMMAND_READY; I2C_WRITE_DATA(client, TPM_STS, &data, 1); if (chip->vendor.irq) wait_for_serirq_timeout(chip, 1, chip->vendor.timeout_a); } /* tpm_stm_i2c_cancel() */ /* * tpm_stm_spi_status return the TPM_STS register * @param: chip, the tpm chip description * @return: the TPM_STS register value. */ static u8 tpm_stm_i2c_status(struct tpm_chip *chip) { struct i2c_client *client; u8 data; client = (struct i2c_client *)TPM_VPRIV(chip); I2C_READ_DATA(client, TPM_STS, &data, 1); return data; } /* tpm_stm_i2c_status() */ /* * check_locality if the locality is active * @param: chip, the tpm chip description * @return: the active locality or -EACCESS. */ static int check_locality(struct tpm_chip *chip) { struct i2c_client *client; u8 data; u8 status; client = (struct i2c_client *)TPM_VPRIV(chip); status = I2C_READ_DATA(client, TPM_ACCESS, &data, 1); if (status && (data & (TPM_ACCESS_ACTIVE_LOCALITY | TPM_ACCESS_VALID)) == (TPM_ACCESS_ACTIVE_LOCALITY | TPM_ACCESS_VALID)) return chip->vendor.locality; return -EACCES; } /* check_locality() */ /* * request_locality request the TPM locality * @param: chip, the chip description * @return: the active locality or EACCESS. */ static int request_locality(struct tpm_chip *chip) { unsigned long stop; long rc; struct i2c_client *client; u8 data; client = (struct i2c_client *)TPM_VPRIV(chip); if (check_locality(chip) == chip->vendor.locality) return chip->vendor.locality; data = TPM_ACCESS_REQUEST_USE; rc = I2C_WRITE_DATA(client, TPM_ACCESS, &data, 1); if (rc < 0) goto end; if (chip->vendor.irq) { rc = wait_for_serirq_timeout(chip, (check_locality (chip) >= 0), chip->vendor.timeout_a); if (rc > 0) return chip->vendor.locality; } else { stop = jiffies + chip->vendor.timeout_a; do { if (check_locality(chip) >= 0) return chip->vendor.locality; msleep(TPM_TIMEOUT); } while (time_before(jiffies, stop)); } rc = -EACCES; end: return rc; } /* request_locality() */ /* * release_locality release the active locality * @param: chip, the tpm chip description. */ static void release_locality(struct tpm_chip *chip) { struct i2c_client *client; u8 data; client = (struct i2c_client *)TPM_VPRIV(chip); data = TPM_ACCESS_ACTIVE_LOCALITY; I2C_WRITE_DATA(client, TPM_ACCESS, &data, 1); } /* * get_burstcount return the burstcount address 0x19 0x1A * @param: chip, the chip description * return: the burstcount. */ static int get_burstcount(struct tpm_chip *chip) { unsigned long stop; int burstcnt, status; u8 tpm_reg, temp; struct i2c_client *client = (struct i2c_client *)TPM_VPRIV(chip); stop = jiffies + chip->vendor.timeout_d; do { tpm_reg = TPM_STS + 1; status = I2C_READ_DATA(client, tpm_reg, &temp, 1); if (status < 0) goto end; tpm_reg = tpm_reg + 1; burstcnt = temp; status = I2C_READ_DATA(client, tpm_reg, &temp, 1); if (status < 0) goto end; burstcnt |= temp << 8; if (burstcnt) return burstcnt; msleep(TPM_TIMEOUT); } while (time_before(jiffies, stop)); end: return -EBUSY; } /* get_burstcount() */ /* * wait_for_stat wait for a TPM_STS value * @param: chip, the tpm chip description * @param: mask, the value mask to wait * @param: timeout, the timeout * @param: queue, the wait queue. * @return: the tpm status, 0 if success, -ETIME if timeout is reached. */ static int wait_for_stat(struct tpm_chip *chip, u8 mask, unsigned long timeout, wait_queue_head_t *queue) { unsigned long stop; long rc; u8 status; if (chip->vendor.irq) { rc = wait_for_serirq_timeout(chip, ((tpm_stm_i2c_status (chip) & mask) == mask), timeout); if (rc > 0) return 0; } else { stop = jiffies + timeout; do { msleep(TPM_TIMEOUT); status = tpm_stm_i2c_status(chip); if ((status & mask) == mask) return 0; } while (time_before(jiffies, stop)); } return -ETIME; } /* wait_for_stat() */ /* * recv_data receive data * @param: chip, the tpm chip description * @param: buf, the buffer where the data are received * @param: count, the number of data to receive * @return: the number of bytes read from TPM FIFO. */ static int recv_data(struct tpm_chip *chip, u8 *buf, size_t count) { int size = 0, burstcnt, len; struct i2c_client *client; client = (struct i2c_client *)TPM_VPRIV(chip); while (size < count && wait_for_stat(chip, TPM_STS_DATA_AVAIL | TPM_STS_VALID, chip->vendor.timeout_c, &chip->vendor.read_queue) == 0) { burstcnt = get_burstcount(chip); len = min_t(int, burstcnt, count - size); I2C_READ_DATA(client, TPM_DATA_FIFO, buf + size, len); size += len; } return size; } /* * tpm_ioserirq_handler the serirq irq handler * @param: irq, the tpm chip description * @param: dev_id, the description of the chip * @return: the status of the handler. */ static irqreturn_t tpm_ioserirq_handler(int irq, void *dev_id) { struct tpm_chip *chip = dev_id; struct i2c_client *client; struct st33zp24_platform_data *pin_infos; disable_irq_nosync(irq); client = (struct i2c_client *)TPM_VPRIV(chip); pin_infos = client->dev.platform_data; complete(&pin_infos->irq_detection); return IRQ_HANDLED; } /* tpm_ioserirq_handler() */ /* * tpm_stm_i2c_send send TPM commands through the I2C bus. * * @param: chip, the tpm_chip description as specified in driver/char/tpm/tpm.h * @param: buf, the buffer to send. * @param: count, the number of bytes to send. * @return: In case of success the number of bytes sent. * In other case, a < 0 value describing the issue. */ static int tpm_stm_i2c_send(struct tpm_chip *chip, unsigned char *buf, size_t len) { u32 status, burstcnt = 0, i, size; int ret; u8 data; struct i2c_client *client; if (chip == NULL) return -EBUSY; if (len < TPM_HEADER_SIZE) return -EBUSY; client = (struct i2c_client *)TPM_VPRIV(chip); client->flags = 0; ret = request_locality(chip); if (ret < 0) return ret; status = tpm_stm_i2c_status(chip); if ((status & TPM_STS_COMMAND_READY) == 0) { tpm_stm_i2c_cancel(chip); if (wait_for_stat (chip, TPM_STS_COMMAND_READY, chip->vendor.timeout_b, &chip->vendor.int_queue) < 0) { ret = -ETIME; goto out_err; } } for (i = 0; i < len - 1;) { burstcnt = get_burstcount(chip); size = min_t(int, len - i - 1, burstcnt); ret = I2C_WRITE_DATA(client, TPM_DATA_FIFO, buf, size); if (ret < 0) goto out_err; i += size; } status = tpm_stm_i2c_status(chip); if ((status & TPM_STS_DATA_EXPECT) == 0) { ret = -EIO; goto out_err; } ret = I2C_WRITE_DATA(client, TPM_DATA_FIFO, buf + len - 1, 1); if (ret < 0) goto out_err; status = tpm_stm_i2c_status(chip); if ((status & TPM_STS_DATA_EXPECT) != 0) { ret = -EIO; goto out_err; } data = TPM_STS_GO; I2C_WRITE_DATA(client, TPM_STS, &data, 1); return len; out_err: tpm_stm_i2c_cancel(chip); release_locality(chip); return ret; } /* * tpm_stm_i2c_recv received TPM response through the I2C bus. * @param: chip, the tpm_chip description as specified in driver/char/tpm/tpm.h. * @param: buf, the buffer to store datas. * @param: count, the number of bytes to send. * @return: In case of success the number of bytes received. * In other case, a < 0 value describing the issue. */ static int tpm_stm_i2c_recv(struct tpm_chip *chip, unsigned char *buf, size_t count) { int size = 0; int expected; if (chip == NULL) return -EBUSY; if (count < TPM_HEADER_SIZE) { size = -EIO; goto out; } size = recv_data(chip, buf, TPM_HEADER_SIZE); if (size < TPM_HEADER_SIZE) { dev_err(chip->dev, "Unable to read header\n"); goto out; } expected = be32_to_cpu(*(__be32 *)(buf + 2)); if (expected > count) { size = -EIO; goto out; } size += recv_data(chip, &buf[TPM_HEADER_SIZE], expected - TPM_HEADER_SIZE); if (size < expected) { dev_err(chip->dev, "Unable to read remainder of result\n"); size = -ETIME; goto out; } out: chip->vendor.cancel(chip); release_locality(chip); return size; } static bool tpm_st33_i2c_req_canceled(struct tpm_chip *chip, u8 status) { return (status == TPM_STS_COMMAND_READY); } static const struct file_operations tpm_st33_i2c_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .read = tpm_read, .write = tpm_write, .open = tpm_open, .release = tpm_release, }; static DEVICE_ATTR(pubek, S_IRUGO, tpm_show_pubek, NULL); static DEVICE_ATTR(pcrs, S_IRUGO, tpm_show_pcrs, NULL); static DEVICE_ATTR(enabled, S_IRUGO, tpm_show_enabled, NULL); static DEVICE_ATTR(active, S_IRUGO, tpm_show_active, NULL); static DEVICE_ATTR(owned, S_IRUGO, tpm_show_owned, NULL); static DEVICE_ATTR(temp_deactivated, S_IRUGO, tpm_show_temp_deactivated, NULL); static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps_1_2, NULL); static DEVICE_ATTR(cancel, S_IWUSR | S_IWGRP, NULL, tpm_store_cancel); static struct attribute *stm_tpm_attrs[] = { &dev_attr_pubek.attr, &dev_attr_pcrs.attr, &dev_attr_enabled.attr, &dev_attr_active.attr, &dev_attr_owned.attr, &dev_attr_temp_deactivated.attr, &dev_attr_caps.attr, &dev_attr_cancel.attr, NULL, }; static struct attribute_group stm_tpm_attr_grp = { .attrs = stm_tpm_attrs }; static struct tpm_vendor_specific st_i2c_tpm = { .send = tpm_stm_i2c_send, .recv = tpm_stm_i2c_recv, .cancel = tpm_stm_i2c_cancel, .status = tpm_stm_i2c_status, .req_complete_mask = TPM_STS_DATA_AVAIL | TPM_STS_VALID, .req_complete_val = TPM_STS_DATA_AVAIL | TPM_STS_VALID, .req_canceled = tpm_st33_i2c_req_canceled, .attr_group = &stm_tpm_attr_grp, .miscdev = {.fops = &tpm_st33_i2c_fops,}, }; static int interrupts; module_param(interrupts, int, 0444); MODULE_PARM_DESC(interrupts, "Enable interrupts"); static int power_mgt = 1; module_param(power_mgt, int, 0444); MODULE_PARM_DESC(power_mgt, "Power Management"); /* * tpm_st33_i2c_probe initialize the TPM device * @param: client, the i2c_client drescription (TPM I2C description). * @param: id, the i2c_device_id struct. * @return: 0 in case of success. * -1 in other case. */ static int tpm_st33_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { int err; u8 intmask; struct tpm_chip *chip; struct st33zp24_platform_data *platform_data; if (client == NULL) { pr_info("%s: i2c client is NULL. Device not accessible.\n", __func__); err = -ENODEV; goto end; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_info(&client->dev, "client not i2c capable\n"); err = -ENODEV; goto end; } chip = tpm_register_hardware(&client->dev, &st_i2c_tpm); if (!chip) { dev_info(&client->dev, "fail chip\n"); err = -ENODEV; goto end; } platform_data = client->dev.platform_data; if (!platform_data) { dev_info(&client->dev, "chip not available\n"); err = -ENODEV; goto _tpm_clean_answer; } platform_data->tpm_i2c_buffer[0] = kmalloc(TPM_BUFSIZE * sizeof(u8), GFP_KERNEL); if (platform_data->tpm_i2c_buffer[0] == NULL) { err = -ENOMEM; goto _tpm_clean_answer; } platform_data->tpm_i2c_buffer[1] = kmalloc(TPM_BUFSIZE * sizeof(u8), GFP_KERNEL); if (platform_data->tpm_i2c_buffer[1] == NULL) { err = -ENOMEM; goto _tpm_clean_response1; } TPM_VPRIV(chip) = client; chip->vendor.timeout_a = msecs_to_jiffies(TIS_SHORT_TIMEOUT); chip->vendor.timeout_b = msecs_to_jiffies(TIS_LONG_TIMEOUT); chip->vendor.timeout_c = msecs_to_jiffies(TIS_SHORT_TIMEOUT); chip->vendor.timeout_d = msecs_to_jiffies(TIS_SHORT_TIMEOUT); chip->vendor.locality = LOCALITY0; if (power_mgt) { err = gpio_request(platform_data->io_lpcpd, "TPM IO_LPCPD"); if (err) goto _gpio_init1; gpio_set_value(platform_data->io_lpcpd, 1); } if (interrupts) { init_completion(&platform_data->irq_detection); if (request_locality(chip) != LOCALITY0) { err = -ENODEV; goto _tpm_clean_response2; } err = gpio_request(platform_data->io_serirq, "TPM IO_SERIRQ"); if (err) goto _gpio_init2; clear_interruption(client); err = request_irq(gpio_to_irq(platform_data->io_serirq), &tpm_ioserirq_handler, IRQF_TRIGGER_HIGH, "TPM SERIRQ management", chip); if (err < 0) { dev_err(chip->dev , "TPM SERIRQ signals %d not available\n", gpio_to_irq(platform_data->io_serirq)); goto _irq_set; } err = I2C_READ_DATA(client, TPM_INT_ENABLE, &intmask, 1); if (err < 0) goto _irq_set; intmask |= TPM_INTF_CMD_READY_INT | TPM_INTF_FIFO_AVALAIBLE_INT | TPM_INTF_WAKE_UP_READY_INT | TPM_INTF_LOCALITY_CHANGE_INT | TPM_INTF_STS_VALID_INT | TPM_INTF_DATA_AVAIL_INT; err = I2C_WRITE_DATA(client, TPM_INT_ENABLE, &intmask, 1); if (err < 0) goto _irq_set; intmask = TPM_GLOBAL_INT_ENABLE; err = I2C_WRITE_DATA(client, (TPM_INT_ENABLE + 3), &intmask, 1); if (err < 0) goto _irq_set; err = I2C_READ_DATA(client, TPM_INT_STATUS, &intmask, 1); if (err < 0) goto _irq_set; chip->vendor.irq = interrupts; tpm_gen_interrupt(chip); } tpm_get_timeouts(chip); i2c_set_clientdata(client, chip); dev_info(chip->dev, "TPM I2C Initialized\n"); return 0; _irq_set: free_irq(gpio_to_irq(platform_data->io_serirq), (void *)chip); _gpio_init2: if (interrupts) gpio_free(platform_data->io_serirq); _gpio_init1: if (power_mgt) gpio_free(platform_data->io_lpcpd); _tpm_clean_response2: kzfree(platform_data->tpm_i2c_buffer[1]); platform_data->tpm_i2c_buffer[1] = NULL; _tpm_clean_response1: kzfree(platform_data->tpm_i2c_buffer[0]); platform_data->tpm_i2c_buffer[0] = NULL; _tpm_clean_answer: tpm_remove_hardware(chip->dev); end: pr_info("TPM I2C initialisation fail\n"); return err; } /* * tpm_st33_i2c_remove remove the TPM device * @param: client, the i2c_client drescription (TPM I2C description). clear_bit(0, &chip->is_open); * @return: 0 in case of success. */ static int tpm_st33_i2c_remove(struct i2c_client *client) { struct tpm_chip *chip = (struct tpm_chip *)i2c_get_clientdata(client); struct st33zp24_platform_data *pin_infos = ((struct i2c_client *)TPM_VPRIV(chip))->dev.platform_data; if (pin_infos != NULL) { free_irq(pin_infos->io_serirq, chip); gpio_free(pin_infos->io_serirq); gpio_free(pin_infos->io_lpcpd); tpm_remove_hardware(chip->dev); if (pin_infos->tpm_i2c_buffer[1] != NULL) { kzfree(pin_infos->tpm_i2c_buffer[1]); pin_infos->tpm_i2c_buffer[1] = NULL; } if (pin_infos->tpm_i2c_buffer[0] != NULL) { kzfree(pin_infos->tpm_i2c_buffer[0]); pin_infos->tpm_i2c_buffer[0] = NULL; } } return 0; } #ifdef CONFIG_PM_SLEEP /* * tpm_st33_i2c_pm_suspend suspend the TPM device * Added: Work around when suspend and no tpm application is running, suspend * may fail because chip->data_buffer is not set (only set in tpm_open in Linux * TPM core) * @param: client, the i2c_client drescription (TPM I2C description). * @param: mesg, the power management message. * @return: 0 in case of success. */ static int tpm_st33_i2c_pm_suspend(struct device *dev) { struct tpm_chip *chip = dev_get_drvdata(dev); struct st33zp24_platform_data *pin_infos = dev->platform_data; int ret = 0; if (power_mgt) { gpio_set_value(pin_infos->io_lpcpd, 0); } else { if (chip->data_buffer == NULL) chip->data_buffer = pin_infos->tpm_i2c_buffer[0]; ret = tpm_pm_suspend(dev); } return ret; } /* tpm_st33_i2c_suspend() */ /* * tpm_st33_i2c_pm_resume resume the TPM device * @param: client, the i2c_client drescription (TPM I2C description). * @return: 0 in case of success. */ static int tpm_st33_i2c_pm_resume(struct device *dev) { struct tpm_chip *chip = dev_get_drvdata(dev); struct st33zp24_platform_data *pin_infos = dev->platform_data; int ret = 0; if (power_mgt) { gpio_set_value(pin_infos->io_lpcpd, 1); ret = wait_for_serirq_timeout(chip, (chip->vendor.status(chip) & TPM_STS_VALID) == TPM_STS_VALID, chip->vendor.timeout_b); } else { if (chip->data_buffer == NULL) chip->data_buffer = pin_infos->tpm_i2c_buffer[0]; ret = tpm_pm_resume(dev); if (!ret) tpm_do_selftest(chip); } return ret; } /* tpm_st33_i2c_pm_resume() */ #endif static const struct i2c_device_id tpm_st33_i2c_id[] = { {TPM_ST33_I2C, 0}, {} }; MODULE_DEVICE_TABLE(i2c, tpm_st33_i2c_id); static SIMPLE_DEV_PM_OPS(tpm_st33_i2c_ops, tpm_st33_i2c_pm_suspend, tpm_st33_i2c_pm_resume); static struct i2c_driver tpm_st33_i2c_driver = { .driver = { .owner = THIS_MODULE, .name = TPM_ST33_I2C, .pm = &tpm_st33_i2c_ops, }, .probe = tpm_st33_i2c_probe, .remove = tpm_st33_i2c_remove, .id_table = tpm_st33_i2c_id }; module_i2c_driver(tpm_st33_i2c_driver); MODULE_AUTHOR("Christophe Ricard (tpmsupport@st.com)"); MODULE_DESCRIPTION("STM TPM I2C ST33 Driver"); MODULE_VERSION("1.2.0"); MODULE_LICENSE("GPL");
gpl-2.0
Gava97/android_kernel_samsung_GT-i9301
fs/exfat/exfat_blkdev.c
801
3966
/* * Copyright (C) 2012-2013 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. * * You 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/blkdev.h> #include "exfat_config.h" #include "exfat_global.h" #include "exfat_blkdev.h" #include "exfat_data.h" #include "exfat_api.h" #include "exfat_super.h" INT32 bdev_init(void) { return(FFS_SUCCESS); } INT32 bdev_shutdown(void) { return(FFS_SUCCESS); } INT32 bdev_open(struct super_block *sb) { BD_INFO_T *p_bd = &(EXFAT_SB(sb)->bd_info); if (p_bd->opened) return(FFS_SUCCESS); p_bd->sector_size = bdev_logical_block_size(sb->s_bdev); p_bd->sector_size_bits = my_log2(p_bd->sector_size); p_bd->sector_size_mask = p_bd->sector_size - 1; p_bd->num_sectors = i_size_read(sb->s_bdev->bd_inode) >> p_bd->sector_size_bits; p_bd->opened = TRUE; return(FFS_SUCCESS); } INT32 bdev_close(struct super_block *sb) { BD_INFO_T *p_bd = &(EXFAT_SB(sb)->bd_info); if (!p_bd->opened) return(FFS_SUCCESS); p_bd->opened = FALSE; return(FFS_SUCCESS); } INT32 bdev_read(struct super_block *sb, UINT32 secno, struct buffer_head **bh, UINT32 num_secs, INT32 read) { BD_INFO_T *p_bd = &(EXFAT_SB(sb)->bd_info); FS_INFO_T *p_fs = &(EXFAT_SB(sb)->fs_info); #if EXFAT_CONFIG_KERNEL_DEBUG struct exfat_sb_info *sbi = EXFAT_SB(sb); long flags = sbi->debug_flags; if (flags & EXFAT_DEBUGFLAGS_ERROR_RW) return (FFS_MEDIAERR); #endif if (!p_bd->opened) return(FFS_MEDIAERR); if (*bh) __brelse(*bh); if (read) *bh = __bread(sb->s_bdev, secno, num_secs << p_bd->sector_size_bits); else *bh = __getblk(sb->s_bdev, secno, num_secs << p_bd->sector_size_bits); if (*bh) return(FFS_SUCCESS); WARN(!p_fs->dev_ejected, "[EXFAT] No bh, device seems wrong or to be ejected.\n"); return(FFS_MEDIAERR); } INT32 bdev_write(struct super_block *sb, UINT32 secno, struct buffer_head *bh, UINT32 num_secs, INT32 sync) { INT32 count; struct buffer_head *bh2; BD_INFO_T *p_bd = &(EXFAT_SB(sb)->bd_info); FS_INFO_T *p_fs = &(EXFAT_SB(sb)->fs_info); #if EXFAT_CONFIG_KERNEL_DEBUG struct exfat_sb_info *sbi = EXFAT_SB(sb); long flags = sbi->debug_flags; if (flags & EXFAT_DEBUGFLAGS_ERROR_RW) return (FFS_MEDIAERR); #endif if (!p_bd->opened) return(FFS_MEDIAERR); if (secno == bh->b_blocknr) { lock_buffer(bh); set_buffer_uptodate(bh); mark_buffer_dirty(bh); unlock_buffer(bh); if (sync && (sync_dirty_buffer(bh) != 0)) return (FFS_MEDIAERR); } else { count = num_secs << p_bd->sector_size_bits; bh2 = __getblk(sb->s_bdev, secno, count); if (bh2 == NULL) goto no_bh; lock_buffer(bh2); MEMCPY(bh2->b_data, bh->b_data, count); set_buffer_uptodate(bh2); mark_buffer_dirty(bh2); unlock_buffer(bh2); if (sync && (sync_dirty_buffer(bh2) != 0)) { __brelse(bh2); goto no_bh; } __brelse(bh2); } return(FFS_SUCCESS); no_bh: WARN(!p_fs->dev_ejected, "[EXFAT] No bh, device seems wrong or to be ejected.\n"); return (FFS_MEDIAERR); } INT32 bdev_sync(struct super_block *sb) { BD_INFO_T *p_bd = &(EXFAT_SB(sb)->bd_info); #if EXFAT_CONFIG_KERNEL_DEBUG struct exfat_sb_info *sbi = EXFAT_SB(sb); long flags = sbi->debug_flags; if (flags & EXFAT_DEBUGFLAGS_ERROR_RW) return (FFS_MEDIAERR); #endif if (!p_bd->opened) return(FFS_MEDIAERR); return sync_blockdev(sb->s_bdev); }
gpl-2.0
heyoufei/mini2440_kernel
arch/mips/basler/excite/excite_device.c
801
10714
/* * Copyright (C) 2004 by Basler Vision Technologies AG * Author: Thomas Koeller <thomas.koeller@baslerweb.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/ioport.h> #include <linux/err.h> #include <linux/jiffies.h> #include <linux/sched.h> #include <asm/types.h> #include <asm/rm9k-ocd.h> #include <excite.h> #include <rm9k_eth.h> #include <rm9k_wdt.h> #include <rm9k_xicap.h> #include <excite_nandflash.h> #include "excite_iodev.h" #define RM9K_GE_UNIT 0 #define XICAP_UNIT 0 #define NAND_UNIT 0 #define DLL_TIMEOUT 3 /* seconds */ #define RINIT(__start__, __end__, __name__, __parent__) { \ .name = __name__ "_0", \ .start = (__start__), \ .end = (__end__), \ .flags = 0, \ .parent = (__parent__) \ } #define RINIT_IRQ(__irq__, __name__) { \ .name = __name__ "_0", \ .start = (__irq__), \ .end = (__irq__), \ .flags = IORESOURCE_IRQ, \ .parent = NULL \ } enum { slice_xicap, slice_eth }; static struct resource excite_ctr_resource __maybe_unused = { .name = "GPI counters", .start = 0, .end = 5, .flags = 0, .parent = NULL, .sibling = NULL, .child = NULL }, excite_gpislice_resource __maybe_unused = { .name = "GPI slices", .start = 0, .end = 1, .flags = 0, .parent = NULL, .sibling = NULL, .child = NULL }, excite_mdio_channel_resource __maybe_unused = { .name = "MDIO channels", .start = 0, .end = 1, .flags = 0, .parent = NULL, .sibling = NULL, .child = NULL }, excite_fifomem_resource __maybe_unused = { .name = "FIFO memory", .start = 0, .end = 767, .flags = 0, .parent = NULL, .sibling = NULL, .child = NULL }, excite_scram_resource __maybe_unused = { .name = "Scratch RAM", .start = EXCITE_PHYS_SCRAM, .end = EXCITE_PHYS_SCRAM + EXCITE_SIZE_SCRAM - 1, .flags = IORESOURCE_MEM, .parent = NULL, .sibling = NULL, .child = NULL }, excite_fpga_resource __maybe_unused = { .name = "System FPGA", .start = EXCITE_PHYS_FPGA, .end = EXCITE_PHYS_FPGA + EXCITE_SIZE_FPGA - 1, .flags = IORESOURCE_MEM, .parent = NULL, .sibling = NULL, .child = NULL }, excite_nand_resource __maybe_unused = { .name = "NAND flash control", .start = EXCITE_PHYS_NAND, .end = EXCITE_PHYS_NAND + EXCITE_SIZE_NAND - 1, .flags = IORESOURCE_MEM, .parent = NULL, .sibling = NULL, .child = NULL }, excite_titan_resource __maybe_unused = { .name = "TITAN registers", .start = EXCITE_PHYS_TITAN, .end = EXCITE_PHYS_TITAN + EXCITE_SIZE_TITAN - 1, .flags = IORESOURCE_MEM, .parent = NULL, .sibling = NULL, .child = NULL }; static void adjust_resources(struct resource *res, unsigned int n) { struct resource *p; const unsigned long mask = IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_IRQ | IORESOURCE_DMA; for (p = res; p < res + n; p++) { const struct resource * const parent = p->parent; if (parent) { p->start += parent->start; p->end += parent->start; p->flags = parent->flags & mask; } } } #if defined(CONFIG_EXCITE_FCAP_GPI) || defined(CONFIG_EXCITE_FCAP_GPI_MODULE) static struct resource xicap_rsrc[] = { RINIT(0x4840, 0x486f, XICAP_RESOURCE_FIFO_RX, &excite_titan_resource), RINIT(0x4940, 0x494b, XICAP_RESOURCE_FIFO_TX, &excite_titan_resource), RINIT(0x5040, 0x5127, XICAP_RESOURCE_XDMA, &excite_titan_resource), RINIT(0x1000, 0x112f, XICAP_RESOURCE_PKTPROC, &excite_titan_resource), RINIT(0x1100, 0x110f, XICAP_RESOURCE_PKT_STREAM, &excite_fpga_resource), RINIT(0x0800, 0x0bff, XICAP_RESOURCE_DMADESC, &excite_scram_resource), RINIT(slice_xicap, slice_xicap, XICAP_RESOURCE_GPI_SLICE, &excite_gpislice_resource), RINIT(0x0100, 0x02ff, XICAP_RESOURCE_FIFO_BLK, &excite_fifomem_resource), RINIT_IRQ(TITAN_IRQ, XICAP_RESOURCE_IRQ) }; static struct platform_device xicap_pdev = { .name = XICAP_NAME, .id = XICAP_UNIT, .num_resources = ARRAY_SIZE(xicap_rsrc), .resource = xicap_rsrc }; /* * Create a platform device for the GPI port that receives the * image data from the embedded camera. */ static int __init xicap_devinit(void) { unsigned long tend; u32 reg; int retval; adjust_resources(xicap_rsrc, ARRAY_SIZE(xicap_rsrc)); /* Power up the slice and configure it. */ reg = titan_readl(CPTC1R); reg &= ~(0x11100 << slice_xicap); titan_writel(reg, CPTC1R); /* Enable slice & DLL. */ reg= titan_readl(CPRR); reg &= ~(0x00030003 << (slice_xicap * 2)); titan_writel(reg, CPRR); /* Wait for DLLs to lock */ tend = jiffies + DLL_TIMEOUT * HZ; while (time_before(jiffies, tend)) { if (!(~titan_readl(CPDSR) & (0x1 << (slice_xicap * 4)))) break; yield(); } if (~titan_readl(CPDSR) & (0x1 << (slice_xicap * 4))) { printk(KERN_ERR "%s: DLL not locked after %u seconds\n", xicap_pdev.name, DLL_TIMEOUT); retval = -ETIME; } else { /* Register platform device */ retval = platform_device_register(&xicap_pdev); } return retval; } device_initcall(xicap_devinit); #endif /* defined(CONFIG_EXCITE_FCAP_GPI) || defined(CONFIG_EXCITE_FCAP_GPI_MODULE) */ #if defined(CONFIG_WDT_RM9K_GPI) || defined(CONFIG_WDT_RM9K_GPI_MODULE) static struct resource wdt_rsrc[] = { RINIT(0, 0, WDT_RESOURCE_COUNTER, &excite_ctr_resource), RINIT(0x0084, 0x008f, WDT_RESOURCE_REGS, &excite_titan_resource), RINIT_IRQ(TITAN_IRQ, WDT_RESOURCE_IRQ) }; static struct platform_device wdt_pdev = { .name = WDT_NAME, .id = -1, .num_resources = ARRAY_SIZE(wdt_rsrc), .resource = wdt_rsrc }; /* * Create a platform device for the GPI port that receives the * image data from the embedded camera. */ static int __init wdt_devinit(void) { adjust_resources(wdt_rsrc, ARRAY_SIZE(wdt_rsrc)); return platform_device_register(&wdt_pdev); } device_initcall(wdt_devinit); #endif /* defined(CONFIG_WDT_RM9K_GPI) || defined(CONFIG_WDT_RM9K_GPI_MODULE) */ static struct resource excite_nandflash_rsrc[] = { RINIT(0x2000, 0x201f, EXCITE_NANDFLASH_RESOURCE_REGS, &excite_nand_resource) }; static struct platform_device excite_nandflash_pdev = { .name = "excite_nand", .id = NAND_UNIT, .num_resources = ARRAY_SIZE(excite_nandflash_rsrc), .resource = excite_nandflash_rsrc }; /* * Create a platform device for the access to the nand-flash * port */ static int __init excite_nandflash_devinit(void) { adjust_resources(excite_nandflash_rsrc, ARRAY_SIZE(excite_nandflash_rsrc)); /* nothing to be done here */ /* Register platform device */ return platform_device_register(&excite_nandflash_pdev); } device_initcall(excite_nandflash_devinit); static struct resource iodev_rsrc[] = { RINIT_IRQ(FPGA1_IRQ, IODEV_RESOURCE_IRQ) }; static struct platform_device io_pdev = { .name = IODEV_NAME, .id = -1, .num_resources = ARRAY_SIZE(iodev_rsrc), .resource = iodev_rsrc }; /* * Create a platform device for the external I/O ports. */ static int __init io_devinit(void) { adjust_resources(iodev_rsrc, ARRAY_SIZE(iodev_rsrc)); return platform_device_register(&io_pdev); } device_initcall(io_devinit); #if defined(CONFIG_RM9K_GE) || defined(CONFIG_RM9K_GE_MODULE) static struct resource rm9k_ge_rsrc[] = { RINIT(0x2200, 0x27ff, RM9K_GE_RESOURCE_MAC, &excite_titan_resource), RINIT(0x1800, 0x1fff, RM9K_GE_RESOURCE_MSTAT, &excite_titan_resource), RINIT(0x2000, 0x212f, RM9K_GE_RESOURCE_PKTPROC, &excite_titan_resource), RINIT(0x5140, 0x5227, RM9K_GE_RESOURCE_XDMA, &excite_titan_resource), RINIT(0x4870, 0x489f, RM9K_GE_RESOURCE_FIFO_RX, &excite_titan_resource), RINIT(0x494c, 0x4957, RM9K_GE_RESOURCE_FIFO_TX, &excite_titan_resource), RINIT(0x0000, 0x007f, RM9K_GE_RESOURCE_FIFOMEM_RX, &excite_fifomem_resource), RINIT(0x0080, 0x00ff, RM9K_GE_RESOURCE_FIFOMEM_TX, &excite_fifomem_resource), RINIT(0x0180, 0x019f, RM9K_GE_RESOURCE_PHY, &excite_titan_resource), RINIT(0x0000, 0x03ff, RM9K_GE_RESOURCE_DMADESC_RX, &excite_scram_resource), RINIT(0x0400, 0x07ff, RM9K_GE_RESOURCE_DMADESC_TX, &excite_scram_resource), RINIT(slice_eth, slice_eth, RM9K_GE_RESOURCE_GPI_SLICE, &excite_gpislice_resource), RINIT(0, 0, RM9K_GE_RESOURCE_MDIO_CHANNEL, &excite_mdio_channel_resource), RINIT_IRQ(TITAN_IRQ, RM9K_GE_RESOURCE_IRQ_MAIN), RINIT_IRQ(PHY_IRQ, RM9K_GE_RESOURCE_IRQ_PHY) }; static struct platform_device rm9k_ge_pdev = { .name = RM9K_GE_NAME, .id = RM9K_GE_UNIT, .num_resources = ARRAY_SIZE(rm9k_ge_rsrc), .resource = rm9k_ge_rsrc }; /* * Create a platform device for the Ethernet port. */ static int __init rm9k_ge_devinit(void) { u32 reg; adjust_resources(rm9k_ge_rsrc, ARRAY_SIZE(rm9k_ge_rsrc)); /* Power up the slice and configure it. */ reg = titan_readl(CPTC1R); reg &= ~(0x11000 << slice_eth); reg |= 0x100 << slice_eth; titan_writel(reg, CPTC1R); /* Take the MAC out of reset, reset the DLLs. */ reg = titan_readl(CPRR); reg &= ~(0x00030000 << (slice_eth * 2)); reg |= 0x3 << (slice_eth * 2); titan_writel(reg, CPRR); return platform_device_register(&rm9k_ge_pdev); } device_initcall(rm9k_ge_devinit); #endif /* defined(CONFIG_RM9K_GE) || defined(CONFIG_RM9K_GE_MODULE) */ static int __init excite_setup_devs(void) { int res; u32 reg; /* Enable xdma and fifo interrupts */ reg = titan_readl(0x0050); titan_writel(reg | 0x18000000, 0x0050); res = request_resource(&iomem_resource, &excite_titan_resource); if (res) return res; res = request_resource(&iomem_resource, &excite_scram_resource); if (res) return res; res = request_resource(&iomem_resource, &excite_fpga_resource); if (res) return res; res = request_resource(&iomem_resource, &excite_nand_resource); if (res) return res; excite_fpga_resource.flags = excite_fpga_resource.parent->flags & ( IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_IRQ | IORESOURCE_DMA); excite_nand_resource.flags = excite_nand_resource.parent->flags & ( IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_IRQ | IORESOURCE_DMA); return 0; } arch_initcall(excite_setup_devs);
gpl-2.0
chrbayer/linux-sunxi
drivers/rtc/rtc-m48t86.c
1057
5353
/* * ST M48T86 / Dallas DS12887 RTC driver * Copyright (c) 2006 Tower Technologies * * Author: Alessandro Zummo <a.zummo@towertech.it> * * 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 drivers only supports the clock running in BCD and 24H mode. * If it will be ever adapted to binary and 12H mode, care must be taken * to not introduce bugs. */ #include <linux/module.h> #include <linux/rtc.h> #include <linux/platform_device.h> #include <linux/m48t86.h> #include <linux/bcd.h> #define M48T86_REG_SEC 0x00 #define M48T86_REG_SECALRM 0x01 #define M48T86_REG_MIN 0x02 #define M48T86_REG_MINALRM 0x03 #define M48T86_REG_HOUR 0x04 #define M48T86_REG_HOURALRM 0x05 #define M48T86_REG_DOW 0x06 /* 1 = sunday */ #define M48T86_REG_DOM 0x07 #define M48T86_REG_MONTH 0x08 /* 1 - 12 */ #define M48T86_REG_YEAR 0x09 /* 0 - 99 */ #define M48T86_REG_A 0x0A #define M48T86_REG_B 0x0B #define M48T86_REG_C 0x0C #define M48T86_REG_D 0x0D #define M48T86_REG_B_H24 (1 << 1) #define M48T86_REG_B_DM (1 << 2) #define M48T86_REG_B_SET (1 << 7) #define M48T86_REG_D_VRT (1 << 7) #define DRV_VERSION "0.1" static int m48t86_rtc_read_time(struct device *dev, struct rtc_time *tm) { unsigned char reg; struct platform_device *pdev = to_platform_device(dev); struct m48t86_ops *ops = dev_get_platdata(&pdev->dev); reg = ops->readbyte(M48T86_REG_B); if (reg & M48T86_REG_B_DM) { /* data (binary) mode */ tm->tm_sec = ops->readbyte(M48T86_REG_SEC); tm->tm_min = ops->readbyte(M48T86_REG_MIN); tm->tm_hour = ops->readbyte(M48T86_REG_HOUR) & 0x3F; tm->tm_mday = ops->readbyte(M48T86_REG_DOM); /* tm_mon is 0-11 */ tm->tm_mon = ops->readbyte(M48T86_REG_MONTH) - 1; tm->tm_year = ops->readbyte(M48T86_REG_YEAR) + 100; tm->tm_wday = ops->readbyte(M48T86_REG_DOW); } else { /* bcd mode */ tm->tm_sec = bcd2bin(ops->readbyte(M48T86_REG_SEC)); tm->tm_min = bcd2bin(ops->readbyte(M48T86_REG_MIN)); tm->tm_hour = bcd2bin(ops->readbyte(M48T86_REG_HOUR) & 0x3F); tm->tm_mday = bcd2bin(ops->readbyte(M48T86_REG_DOM)); /* tm_mon is 0-11 */ tm->tm_mon = bcd2bin(ops->readbyte(M48T86_REG_MONTH)) - 1; tm->tm_year = bcd2bin(ops->readbyte(M48T86_REG_YEAR)) + 100; tm->tm_wday = bcd2bin(ops->readbyte(M48T86_REG_DOW)); } /* correct the hour if the clock is in 12h mode */ if (!(reg & M48T86_REG_B_H24)) if (ops->readbyte(M48T86_REG_HOUR) & 0x80) tm->tm_hour += 12; return rtc_valid_tm(tm); } static int m48t86_rtc_set_time(struct device *dev, struct rtc_time *tm) { unsigned char reg; struct platform_device *pdev = to_platform_device(dev); struct m48t86_ops *ops = dev_get_platdata(&pdev->dev); reg = ops->readbyte(M48T86_REG_B); /* update flag and 24h mode */ reg |= M48T86_REG_B_SET | M48T86_REG_B_H24; ops->writebyte(reg, M48T86_REG_B); if (reg & M48T86_REG_B_DM) { /* data (binary) mode */ ops->writebyte(tm->tm_sec, M48T86_REG_SEC); ops->writebyte(tm->tm_min, M48T86_REG_MIN); ops->writebyte(tm->tm_hour, M48T86_REG_HOUR); ops->writebyte(tm->tm_mday, M48T86_REG_DOM); ops->writebyte(tm->tm_mon + 1, M48T86_REG_MONTH); ops->writebyte(tm->tm_year % 100, M48T86_REG_YEAR); ops->writebyte(tm->tm_wday, M48T86_REG_DOW); } else { /* bcd mode */ ops->writebyte(bin2bcd(tm->tm_sec), M48T86_REG_SEC); ops->writebyte(bin2bcd(tm->tm_min), M48T86_REG_MIN); ops->writebyte(bin2bcd(tm->tm_hour), M48T86_REG_HOUR); ops->writebyte(bin2bcd(tm->tm_mday), M48T86_REG_DOM); ops->writebyte(bin2bcd(tm->tm_mon + 1), M48T86_REG_MONTH); ops->writebyte(bin2bcd(tm->tm_year % 100), M48T86_REG_YEAR); ops->writebyte(bin2bcd(tm->tm_wday), M48T86_REG_DOW); } /* update ended */ reg &= ~M48T86_REG_B_SET; ops->writebyte(reg, M48T86_REG_B); return 0; } static int m48t86_rtc_proc(struct device *dev, struct seq_file *seq) { unsigned char reg; struct platform_device *pdev = to_platform_device(dev); struct m48t86_ops *ops = dev_get_platdata(&pdev->dev); reg = ops->readbyte(M48T86_REG_B); seq_printf(seq, "mode\t\t: %s\n", (reg & M48T86_REG_B_DM) ? "binary" : "bcd"); reg = ops->readbyte(M48T86_REG_D); seq_printf(seq, "battery\t\t: %s\n", (reg & M48T86_REG_D_VRT) ? "ok" : "exhausted"); return 0; } static const struct rtc_class_ops m48t86_rtc_ops = { .read_time = m48t86_rtc_read_time, .set_time = m48t86_rtc_set_time, .proc = m48t86_rtc_proc, }; static int m48t86_rtc_probe(struct platform_device *dev) { unsigned char reg; struct m48t86_ops *ops = dev_get_platdata(&dev->dev); struct rtc_device *rtc; rtc = devm_rtc_device_register(&dev->dev, "m48t86", &m48t86_rtc_ops, THIS_MODULE); if (IS_ERR(rtc)) return PTR_ERR(rtc); platform_set_drvdata(dev, rtc); /* read battery status */ reg = ops->readbyte(M48T86_REG_D); dev_info(&dev->dev, "battery %s\n", (reg & M48T86_REG_D_VRT) ? "ok" : "exhausted"); return 0; } static struct platform_driver m48t86_rtc_platform_driver = { .driver = { .name = "rtc-m48t86", }, .probe = m48t86_rtc_probe, }; module_platform_driver(m48t86_rtc_platform_driver); MODULE_AUTHOR("Alessandro Zummo <a.zummo@towertech.it>"); MODULE_DESCRIPTION("M48T86 RTC driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); MODULE_ALIAS("platform:rtc-m48t86");
gpl-2.0
GranPC/linux-asus-flo
drivers/acpi/acpica/nspredef.c
2849
35417
/****************************************************************************** * * Module Name: nspredef - Validation of ACPI predefined methods and objects * $Revision: 1.1 $ * *****************************************************************************/ /* * Copyright (C) 2000 - 2012, Intel Corp. * 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, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * 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 MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. */ #define ACPI_CREATE_PREDEFINED_TABLE #include <acpi/acpi.h> #include "accommon.h" #include "acnamesp.h" #include "acpredef.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME("nspredef") /******************************************************************************* * * This module validates predefined ACPI objects that appear in the namespace, * at the time they are evaluated (via acpi_evaluate_object). The purpose of this * validation is to detect problems with BIOS-exposed predefined ACPI objects * before the results are returned to the ACPI-related drivers. * * There are several areas that are validated: * * 1) The number of input arguments as defined by the method/object in the * ASL is validated against the ACPI specification. * 2) The type of the return object (if any) is validated against the ACPI * specification. * 3) For returned package objects, the count of package elements is * validated, as well as the type of each package element. Nested * packages are supported. * * For any problems found, a warning message is issued. * ******************************************************************************/ /* Local prototypes */ static acpi_status acpi_ns_check_package(struct acpi_predefined_data *data, union acpi_operand_object **return_object_ptr); static acpi_status acpi_ns_check_package_list(struct acpi_predefined_data *data, const union acpi_predefined_info *package, union acpi_operand_object **elements, u32 count); static acpi_status acpi_ns_check_package_elements(struct acpi_predefined_data *data, union acpi_operand_object **elements, u8 type1, u32 count1, u8 type2, u32 count2, u32 start_index); static acpi_status acpi_ns_check_object_type(struct acpi_predefined_data *data, union acpi_operand_object **return_object_ptr, u32 expected_btypes, u32 package_index); static acpi_status acpi_ns_check_reference(struct acpi_predefined_data *data, union acpi_operand_object *return_object); static void acpi_ns_get_expected_types(char *buffer, u32 expected_btypes); /* * Names for the types that can be returned by the predefined objects. * Used for warning messages. Must be in the same order as the ACPI_RTYPEs */ static const char *acpi_rtype_names[] = { "/Integer", "/String", "/Buffer", "/Package", "/Reference", }; /******************************************************************************* * * FUNCTION: acpi_ns_check_predefined_names * * PARAMETERS: Node - Namespace node for the method/object * user_param_count - Number of parameters actually passed * return_status - Status from the object evaluation * return_object_ptr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status * * DESCRIPTION: Check an ACPI name for a match in the predefined name list. * ******************************************************************************/ acpi_status acpi_ns_check_predefined_names(struct acpi_namespace_node *node, u32 user_param_count, acpi_status return_status, union acpi_operand_object **return_object_ptr) { union acpi_operand_object *return_object = *return_object_ptr; acpi_status status = AE_OK; const union acpi_predefined_info *predefined; char *pathname; struct acpi_predefined_data *data; /* Match the name for this method/object against the predefined list */ predefined = acpi_ns_check_for_predefined_name(node); /* Get the full pathname to the object, for use in warning messages */ pathname = acpi_ns_get_external_pathname(node); if (!pathname) { return AE_OK; /* Could not get pathname, ignore */ } /* * Check that the parameter count for this method matches the ASL * definition. For predefined names, ensure that both the caller and * the method itself are in accordance with the ACPI specification. */ acpi_ns_check_parameter_count(pathname, node, user_param_count, predefined); /* If not a predefined name, we cannot validate the return object */ if (!predefined) { goto cleanup; } /* * If the method failed or did not actually return an object, we cannot * validate the return object */ if ((return_status != AE_OK) && (return_status != AE_CTRL_RETURN_VALUE)) { goto cleanup; } /* * If there is no return value, check if we require a return value for * this predefined name. Either one return value is expected, or none, * for both methods and other objects. * * Exit now if there is no return object. Warning if one was expected. */ if (!return_object) { if ((predefined->info.expected_btypes) && (!(predefined->info.expected_btypes & ACPI_RTYPE_NONE))) { ACPI_WARN_PREDEFINED((AE_INFO, pathname, ACPI_WARN_ALWAYS, "Missing expected return value")); status = AE_AML_NO_RETURN_VALUE; } goto cleanup; } /* * Return value validation and possible repair. * * 1) Don't perform return value validation/repair if this feature * has been disabled via a global option. * * 2) We have a return value, but if one wasn't expected, just exit, * this is not a problem. For example, if the "Implicit Return" * feature is enabled, methods will always return a value. * * 3) If the return value can be of any type, then we cannot perform * any validation, just exit. */ if (acpi_gbl_disable_auto_repair || (!predefined->info.expected_btypes) || (predefined->info.expected_btypes == ACPI_RTYPE_ALL)) { goto cleanup; } /* Create the parameter data block for object validation */ data = ACPI_ALLOCATE_ZEROED(sizeof(struct acpi_predefined_data)); if (!data) { goto cleanup; } data->predefined = predefined; data->node = node; data->node_flags = node->flags; data->pathname = pathname; /* * Check that the type of the main return object is what is expected * for this predefined name */ status = acpi_ns_check_object_type(data, return_object_ptr, predefined->info.expected_btypes, ACPI_NOT_PACKAGE_ELEMENT); if (ACPI_FAILURE(status)) { goto exit; } /* * For returned Package objects, check the type of all sub-objects. * Note: Package may have been newly created by call above. */ if ((*return_object_ptr)->common.type == ACPI_TYPE_PACKAGE) { data->parent_package = *return_object_ptr; status = acpi_ns_check_package(data, return_object_ptr); if (ACPI_FAILURE(status)) { goto exit; } } /* * The return object was OK, or it was successfully repaired above. * Now make some additional checks such as verifying that package * objects are sorted correctly (if required) or buffer objects have * the correct data width (bytes vs. dwords). These repairs are * performed on a per-name basis, i.e., the code is specific to * particular predefined names. */ status = acpi_ns_complex_repairs(data, node, status, return_object_ptr); exit: /* * If the object validation failed or if we successfully repaired one * or more objects, mark the parent node to suppress further warning * messages during the next evaluation of the same method/object. */ if (ACPI_FAILURE(status) || (data->flags & ACPI_OBJECT_REPAIRED)) { node->flags |= ANOBJ_EVALUATED; } ACPI_FREE(data); cleanup: ACPI_FREE(pathname); return (status); } /******************************************************************************* * * FUNCTION: acpi_ns_check_parameter_count * * PARAMETERS: Pathname - Full pathname to the node (for error msgs) * Node - Namespace node for the method/object * user_param_count - Number of args passed in by the caller * Predefined - Pointer to entry in predefined name table * * RETURN: None * * DESCRIPTION: Check that the declared (in ASL/AML) parameter count for a * predefined name is what is expected (i.e., what is defined in * the ACPI specification for this predefined name.) * ******************************************************************************/ void acpi_ns_check_parameter_count(char *pathname, struct acpi_namespace_node *node, u32 user_param_count, const union acpi_predefined_info *predefined) { u32 param_count; u32 required_params_current; u32 required_params_old; /* Methods have 0-7 parameters. All other types have zero. */ param_count = 0; if (node->type == ACPI_TYPE_METHOD) { param_count = node->object->method.param_count; } if (!predefined) { /* * Check the parameter count for non-predefined methods/objects. * * Warning if too few or too many arguments have been passed by the * caller. An incorrect number of arguments may not cause the method * to fail. However, the method will fail if there are too few * arguments and the method attempts to use one of the missing ones. */ if (user_param_count < param_count) { ACPI_WARN_PREDEFINED((AE_INFO, pathname, ACPI_WARN_ALWAYS, "Insufficient arguments - needs %u, found %u", param_count, user_param_count)); } else if (user_param_count > param_count) { ACPI_WARN_PREDEFINED((AE_INFO, pathname, ACPI_WARN_ALWAYS, "Excess arguments - needs %u, found %u", param_count, user_param_count)); } return; } /* * Validate the user-supplied parameter count. * Allow two different legal argument counts (_SCP, etc.) */ required_params_current = predefined->info.param_count & 0x0F; required_params_old = predefined->info.param_count >> 4; if (user_param_count != ACPI_UINT32_MAX) { if ((user_param_count != required_params_current) && (user_param_count != required_params_old)) { ACPI_WARN_PREDEFINED((AE_INFO, pathname, ACPI_WARN_ALWAYS, "Parameter count mismatch - " "caller passed %u, ACPI requires %u", user_param_count, required_params_current)); } } /* * Check that the ASL-defined parameter count is what is expected for * this predefined name (parameter count as defined by the ACPI * specification) */ if ((param_count != required_params_current) && (param_count != required_params_old)) { ACPI_WARN_PREDEFINED((AE_INFO, pathname, node->flags, "Parameter count mismatch - ASL declared %u, ACPI requires %u", param_count, required_params_current)); } } /******************************************************************************* * * FUNCTION: acpi_ns_check_for_predefined_name * * PARAMETERS: Node - Namespace node for the method/object * * RETURN: Pointer to entry in predefined table. NULL indicates not found. * * DESCRIPTION: Check an object name against the predefined object list. * ******************************************************************************/ const union acpi_predefined_info *acpi_ns_check_for_predefined_name(struct acpi_namespace_node *node) { const union acpi_predefined_info *this_name; /* Quick check for a predefined name, first character must be underscore */ if (node->name.ascii[0] != '_') { return (NULL); } /* Search info table for a predefined method/object name */ this_name = predefined_names; while (this_name->info.name[0]) { if (ACPI_COMPARE_NAME(node->name.ascii, this_name->info.name)) { return (this_name); } /* * Skip next entry in the table if this name returns a Package * (next entry contains the package info) */ if (this_name->info.expected_btypes & ACPI_RTYPE_PACKAGE) { this_name++; } this_name++; } return (NULL); /* Not found */ } /******************************************************************************* * * FUNCTION: acpi_ns_check_package * * PARAMETERS: Data - Pointer to validation data structure * return_object_ptr - Pointer to the object returned from the * evaluation of a method or object * * RETURN: Status * * DESCRIPTION: Check a returned package object for the correct count and * correct type of all sub-objects. * ******************************************************************************/ static acpi_status acpi_ns_check_package(struct acpi_predefined_data *data, union acpi_operand_object **return_object_ptr) { union acpi_operand_object *return_object = *return_object_ptr; const union acpi_predefined_info *package; union acpi_operand_object **elements; acpi_status status = AE_OK; u32 expected_count; u32 count; u32 i; ACPI_FUNCTION_NAME(ns_check_package); /* The package info for this name is in the next table entry */ package = data->predefined + 1; ACPI_DEBUG_PRINT((ACPI_DB_NAMES, "%s Validating return Package of Type %X, Count %X\n", data->pathname, package->ret_info.type, return_object->package.count)); /* * For variable-length Packages, we can safely remove all embedded * and trailing NULL package elements */ acpi_ns_remove_null_elements(data, package->ret_info.type, return_object); /* Extract package count and elements array */ elements = return_object->package.elements; count = return_object->package.count; /* The package must have at least one element, else invalid */ if (!count) { ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags, "Return Package has no elements (empty)")); return (AE_AML_OPERAND_VALUE); } /* * Decode the type of the expected package contents * * PTYPE1 packages contain no subpackages * PTYPE2 packages contain sub-packages */ switch (package->ret_info.type) { case ACPI_PTYPE1_FIXED: /* * The package count is fixed and there are no sub-packages * * If package is too small, exit. * If package is larger than expected, issue warning but continue */ expected_count = package->ret_info.count1 + package->ret_info.count2; if (count < expected_count) { goto package_too_small; } else if (count > expected_count) { ACPI_DEBUG_PRINT((ACPI_DB_REPAIR, "%s: Return Package is larger than needed - " "found %u, expected %u\n", data->pathname, count, expected_count)); } /* Validate all elements of the returned package */ status = acpi_ns_check_package_elements(data, elements, package->ret_info. object_type1, package->ret_info. count1, package->ret_info. object_type2, package->ret_info. count2, 0); break; case ACPI_PTYPE1_VAR: /* * The package count is variable, there are no sub-packages, and all * elements must be of the same type */ for (i = 0; i < count; i++) { status = acpi_ns_check_object_type(data, elements, package->ret_info. object_type1, i); if (ACPI_FAILURE(status)) { return (status); } elements++; } break; case ACPI_PTYPE1_OPTION: /* * The package count is variable, there are no sub-packages. There are * a fixed number of required elements, and a variable number of * optional elements. * * Check if package is at least as large as the minimum required */ expected_count = package->ret_info3.count; if (count < expected_count) { goto package_too_small; } /* Variable number of sub-objects */ for (i = 0; i < count; i++) { if (i < package->ret_info3.count) { /* These are the required package elements (0, 1, or 2) */ status = acpi_ns_check_object_type(data, elements, package-> ret_info3. object_type[i], i); if (ACPI_FAILURE(status)) { return (status); } } else { /* These are the optional package elements */ status = acpi_ns_check_object_type(data, elements, package-> ret_info3. tail_object_type, i); if (ACPI_FAILURE(status)) { return (status); } } elements++; } break; case ACPI_PTYPE2_REV_FIXED: /* First element is the (Integer) revision */ status = acpi_ns_check_object_type(data, elements, ACPI_RTYPE_INTEGER, 0); if (ACPI_FAILURE(status)) { return (status); } elements++; count--; /* Examine the sub-packages */ status = acpi_ns_check_package_list(data, package, elements, count); break; case ACPI_PTYPE2_PKG_COUNT: /* First element is the (Integer) count of sub-packages to follow */ status = acpi_ns_check_object_type(data, elements, ACPI_RTYPE_INTEGER, 0); if (ACPI_FAILURE(status)) { return (status); } /* * Count cannot be larger than the parent package length, but allow it * to be smaller. The >= accounts for the Integer above. */ expected_count = (u32) (*elements)->integer.value; if (expected_count >= count) { goto package_too_small; } count = expected_count; elements++; /* Examine the sub-packages */ status = acpi_ns_check_package_list(data, package, elements, count); break; case ACPI_PTYPE2: case ACPI_PTYPE2_FIXED: case ACPI_PTYPE2_MIN: case ACPI_PTYPE2_COUNT: case ACPI_PTYPE2_FIX_VAR: /* * These types all return a single Package that consists of a * variable number of sub-Packages. * * First, ensure that the first element is a sub-Package. If not, * the BIOS may have incorrectly returned the object as a single * package instead of a Package of Packages (a common error if * there is only one entry). We may be able to repair this by * wrapping the returned Package with a new outer Package. */ if (*elements && ((*elements)->common.type != ACPI_TYPE_PACKAGE)) { /* Create the new outer package and populate it */ status = acpi_ns_wrap_with_package(data, *elements, return_object_ptr); if (ACPI_FAILURE(status)) { return (status); } /* Update locals to point to the new package (of 1 element) */ return_object = *return_object_ptr; elements = return_object->package.elements; count = 1; } /* Examine the sub-packages */ status = acpi_ns_check_package_list(data, package, elements, count); break; default: /* Should not get here if predefined info table is correct */ ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags, "Invalid internal return type in table entry: %X", package->ret_info.type)); return (AE_AML_INTERNAL); } return (status); package_too_small: /* Error exit for the case with an incorrect package count */ ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags, "Return Package is too small - found %u elements, expected %u", count, expected_count)); return (AE_AML_OPERAND_VALUE); } /******************************************************************************* * * FUNCTION: acpi_ns_check_package_list * * PARAMETERS: Data - Pointer to validation data structure * Package - Pointer to package-specific info for method * Elements - Element list of parent package. All elements * of this list should be of type Package. * Count - Count of subpackages * * RETURN: Status * * DESCRIPTION: Examine a list of subpackages * ******************************************************************************/ static acpi_status acpi_ns_check_package_list(struct acpi_predefined_data *data, const union acpi_predefined_info *package, union acpi_operand_object **elements, u32 count) { union acpi_operand_object *sub_package; union acpi_operand_object **sub_elements; acpi_status status; u32 expected_count; u32 i; u32 j; /* * Validate each sub-Package in the parent Package * * NOTE: assumes list of sub-packages contains no NULL elements. * Any NULL elements should have been removed by earlier call * to acpi_ns_remove_null_elements. */ for (i = 0; i < count; i++) { sub_package = *elements; sub_elements = sub_package->package.elements; data->parent_package = sub_package; /* Each sub-object must be of type Package */ status = acpi_ns_check_object_type(data, &sub_package, ACPI_RTYPE_PACKAGE, i); if (ACPI_FAILURE(status)) { return (status); } /* Examine the different types of expected sub-packages */ data->parent_package = sub_package; switch (package->ret_info.type) { case ACPI_PTYPE2: case ACPI_PTYPE2_PKG_COUNT: case ACPI_PTYPE2_REV_FIXED: /* Each subpackage has a fixed number of elements */ expected_count = package->ret_info.count1 + package->ret_info.count2; if (sub_package->package.count < expected_count) { goto package_too_small; } status = acpi_ns_check_package_elements(data, sub_elements, package->ret_info. object_type1, package->ret_info. count1, package->ret_info. object_type2, package->ret_info. count2, 0); if (ACPI_FAILURE(status)) { return (status); } break; case ACPI_PTYPE2_FIX_VAR: /* * Each subpackage has a fixed number of elements and an * optional element */ expected_count = package->ret_info.count1 + package->ret_info.count2; if (sub_package->package.count < expected_count) { goto package_too_small; } status = acpi_ns_check_package_elements(data, sub_elements, package->ret_info. object_type1, package->ret_info. count1, package->ret_info. object_type2, sub_package->package. count - package->ret_info. count1, 0); if (ACPI_FAILURE(status)) { return (status); } break; case ACPI_PTYPE2_FIXED: /* Each sub-package has a fixed length */ expected_count = package->ret_info2.count; if (sub_package->package.count < expected_count) { goto package_too_small; } /* Check the type of each sub-package element */ for (j = 0; j < expected_count; j++) { status = acpi_ns_check_object_type(data, &sub_elements[j], package-> ret_info2. object_type[j], j); if (ACPI_FAILURE(status)) { return (status); } } break; case ACPI_PTYPE2_MIN: /* Each sub-package has a variable but minimum length */ expected_count = package->ret_info.count1; if (sub_package->package.count < expected_count) { goto package_too_small; } /* Check the type of each sub-package element */ status = acpi_ns_check_package_elements(data, sub_elements, package->ret_info. object_type1, sub_package->package. count, 0, 0, 0); if (ACPI_FAILURE(status)) { return (status); } break; case ACPI_PTYPE2_COUNT: /* * First element is the (Integer) count of elements, including * the count field (the ACPI name is num_elements) */ status = acpi_ns_check_object_type(data, sub_elements, ACPI_RTYPE_INTEGER, 0); if (ACPI_FAILURE(status)) { return (status); } /* * Make sure package is large enough for the Count and is * is as large as the minimum size */ expected_count = (u32)(*sub_elements)->integer.value; if (sub_package->package.count < expected_count) { goto package_too_small; } if (sub_package->package.count < package->ret_info.count1) { expected_count = package->ret_info.count1; goto package_too_small; } if (expected_count == 0) { /* * Either the num_entries element was originally zero or it was * a NULL element and repaired to an Integer of value zero. * In either case, repair it by setting num_entries to be the * actual size of the subpackage. */ expected_count = sub_package->package.count; (*sub_elements)->integer.value = expected_count; } /* Check the type of each sub-package element */ status = acpi_ns_check_package_elements(data, (sub_elements + 1), package->ret_info. object_type1, (expected_count - 1), 0, 0, 1); if (ACPI_FAILURE(status)) { return (status); } break; default: /* Should not get here, type was validated by caller */ return (AE_AML_INTERNAL); } elements++; } return (AE_OK); package_too_small: /* The sub-package count was smaller than required */ ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags, "Return Sub-Package[%u] is too small - found %u elements, expected %u", i, sub_package->package.count, expected_count)); return (AE_AML_OPERAND_VALUE); } /******************************************************************************* * * FUNCTION: acpi_ns_check_package_elements * * PARAMETERS: Data - Pointer to validation data structure * Elements - Pointer to the package elements array * Type1 - Object type for first group * Count1 - Count for first group * Type2 - Object type for second group * Count2 - Count for second group * start_index - Start of the first group of elements * * RETURN: Status * * DESCRIPTION: Check that all elements of a package are of the correct object * type. Supports up to two groups of different object types. * ******************************************************************************/ static acpi_status acpi_ns_check_package_elements(struct acpi_predefined_data *data, union acpi_operand_object **elements, u8 type1, u32 count1, u8 type2, u32 count2, u32 start_index) { union acpi_operand_object **this_element = elements; acpi_status status; u32 i; /* * Up to two groups of package elements are supported by the data * structure. All elements in each group must be of the same type. * The second group can have a count of zero. */ for (i = 0; i < count1; i++) { status = acpi_ns_check_object_type(data, this_element, type1, i + start_index); if (ACPI_FAILURE(status)) { return (status); } this_element++; } for (i = 0; i < count2; i++) { status = acpi_ns_check_object_type(data, this_element, type2, (i + count1 + start_index)); if (ACPI_FAILURE(status)) { return (status); } this_element++; } return (AE_OK); } /******************************************************************************* * * FUNCTION: acpi_ns_check_object_type * * PARAMETERS: Data - Pointer to validation data structure * return_object_ptr - Pointer to the object returned from the * evaluation of a method or object * expected_btypes - Bitmap of expected return type(s) * package_index - Index of object within parent package (if * applicable - ACPI_NOT_PACKAGE_ELEMENT * otherwise) * * RETURN: Status * * DESCRIPTION: Check the type of the return object against the expected object * type(s). Use of Btype allows multiple expected object types. * ******************************************************************************/ static acpi_status acpi_ns_check_object_type(struct acpi_predefined_data *data, union acpi_operand_object **return_object_ptr, u32 expected_btypes, u32 package_index) { union acpi_operand_object *return_object = *return_object_ptr; acpi_status status = AE_OK; u32 return_btype; char type_buffer[48]; /* Room for 5 types */ /* * If we get a NULL return_object here, it is a NULL package element. * Since all extraneous NULL package elements were removed earlier by a * call to acpi_ns_remove_null_elements, this is an unexpected NULL element. * We will attempt to repair it. */ if (!return_object) { status = acpi_ns_repair_null_element(data, expected_btypes, package_index, return_object_ptr); if (ACPI_SUCCESS(status)) { return (AE_OK); /* Repair was successful */ } goto type_error_exit; } /* A Namespace node should not get here, but make sure */ if (ACPI_GET_DESCRIPTOR_TYPE(return_object) == ACPI_DESC_TYPE_NAMED) { ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags, "Invalid return type - Found a Namespace node [%4.4s] type %s", return_object->node.name.ascii, acpi_ut_get_type_name(return_object->node. type))); return (AE_AML_OPERAND_TYPE); } /* * Convert the object type (ACPI_TYPE_xxx) to a bitmapped object type. * The bitmapped type allows multiple possible return types. * * Note, the cases below must handle all of the possible types returned * from all of the predefined names (including elements of returned * packages) */ switch (return_object->common.type) { case ACPI_TYPE_INTEGER: return_btype = ACPI_RTYPE_INTEGER; break; case ACPI_TYPE_BUFFER: return_btype = ACPI_RTYPE_BUFFER; break; case ACPI_TYPE_STRING: return_btype = ACPI_RTYPE_STRING; break; case ACPI_TYPE_PACKAGE: return_btype = ACPI_RTYPE_PACKAGE; break; case ACPI_TYPE_LOCAL_REFERENCE: return_btype = ACPI_RTYPE_REFERENCE; break; default: /* Not one of the supported objects, must be incorrect */ goto type_error_exit; } /* Is the object one of the expected types? */ if (return_btype & expected_btypes) { /* For reference objects, check that the reference type is correct */ if (return_object->common.type == ACPI_TYPE_LOCAL_REFERENCE) { status = acpi_ns_check_reference(data, return_object); } return (status); } /* Type mismatch -- attempt repair of the returned object */ status = acpi_ns_repair_object(data, expected_btypes, package_index, return_object_ptr); if (ACPI_SUCCESS(status)) { return (AE_OK); /* Repair was successful */ } type_error_exit: /* Create a string with all expected types for this predefined object */ acpi_ns_get_expected_types(type_buffer, expected_btypes); if (package_index == ACPI_NOT_PACKAGE_ELEMENT) { ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags, "Return type mismatch - found %s, expected %s", acpi_ut_get_object_type_name (return_object), type_buffer)); } else { ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags, "Return Package type mismatch at index %u - " "found %s, expected %s", package_index, acpi_ut_get_object_type_name (return_object), type_buffer)); } return (AE_AML_OPERAND_TYPE); } /******************************************************************************* * * FUNCTION: acpi_ns_check_reference * * PARAMETERS: Data - Pointer to validation data structure * return_object - Object returned from the evaluation of a * method or object * * RETURN: Status * * DESCRIPTION: Check a returned reference object for the correct reference * type. The only reference type that can be returned from a * predefined method is a named reference. All others are invalid. * ******************************************************************************/ static acpi_status acpi_ns_check_reference(struct acpi_predefined_data *data, union acpi_operand_object *return_object) { /* * Check the reference object for the correct reference type (opcode). * The only type of reference that can be converted to an union acpi_object is * a reference to a named object (reference class: NAME) */ if (return_object->reference.class == ACPI_REFCLASS_NAME) { return (AE_OK); } ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags, "Return type mismatch - unexpected reference object type [%s] %2.2X", acpi_ut_get_reference_name(return_object), return_object->reference.class)); return (AE_AML_OPERAND_TYPE); } /******************************************************************************* * * FUNCTION: acpi_ns_get_expected_types * * PARAMETERS: Buffer - Pointer to where the string is returned * expected_btypes - Bitmap of expected return type(s) * * RETURN: Buffer is populated with type names. * * DESCRIPTION: Translate the expected types bitmap into a string of ascii * names of expected types, for use in warning messages. * ******************************************************************************/ static void acpi_ns_get_expected_types(char *buffer, u32 expected_btypes) { u32 this_rtype; u32 i; u32 j; j = 1; buffer[0] = 0; this_rtype = ACPI_RTYPE_INTEGER; for (i = 0; i < ACPI_NUM_RTYPES; i++) { /* If one of the expected types, concatenate the name of this type */ if (expected_btypes & this_rtype) { ACPI_STRCAT(buffer, &acpi_rtype_names[i][j]); j = 0; /* Use name separator from now on */ } this_rtype <<= 1; /* Next Rtype */ } }
gpl-2.0
broodplank/samsung-kernel-msm7x30-jb3.4
drivers/video/omap2/displays/panel-n8x0.c
4897
16249
/* #define DEBUG */ #include <linux/module.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/gpio.h> #include <linux/spi/spi.h> #include <linux/backlight.h> #include <linux/fb.h> #include <video/omapdss.h> #include <video/omap-panel-n8x0.h> #define BLIZZARD_REV_CODE 0x00 #define BLIZZARD_CONFIG 0x02 #define BLIZZARD_PLL_DIV 0x04 #define BLIZZARD_PLL_LOCK_RANGE 0x06 #define BLIZZARD_PLL_CLOCK_SYNTH_0 0x08 #define BLIZZARD_PLL_CLOCK_SYNTH_1 0x0a #define BLIZZARD_PLL_MODE 0x0c #define BLIZZARD_CLK_SRC 0x0e #define BLIZZARD_MEM_BANK0_ACTIVATE 0x10 #define BLIZZARD_MEM_BANK0_STATUS 0x14 #define BLIZZARD_PANEL_CONFIGURATION 0x28 #define BLIZZARD_HDISP 0x2a #define BLIZZARD_HNDP 0x2c #define BLIZZARD_VDISP0 0x2e #define BLIZZARD_VDISP1 0x30 #define BLIZZARD_VNDP 0x32 #define BLIZZARD_HSW 0x34 #define BLIZZARD_VSW 0x38 #define BLIZZARD_DISPLAY_MODE 0x68 #define BLIZZARD_INPUT_WIN_X_START_0 0x6c #define BLIZZARD_DATA_SOURCE_SELECT 0x8e #define BLIZZARD_DISP_MEM_DATA_PORT 0x90 #define BLIZZARD_DISP_MEM_READ_ADDR0 0x92 #define BLIZZARD_POWER_SAVE 0xE6 #define BLIZZARD_NDISP_CTRL_STATUS 0xE8 /* Data source select */ /* For S1D13745 */ #define BLIZZARD_SRC_WRITE_LCD_BACKGROUND 0x00 #define BLIZZARD_SRC_WRITE_LCD_DESTRUCTIVE 0x01 #define BLIZZARD_SRC_WRITE_OVERLAY_ENABLE 0x04 #define BLIZZARD_SRC_DISABLE_OVERLAY 0x05 /* For S1D13744 */ #define BLIZZARD_SRC_WRITE_LCD 0x00 #define BLIZZARD_SRC_BLT_LCD 0x06 #define BLIZZARD_COLOR_RGB565 0x01 #define BLIZZARD_COLOR_YUV420 0x09 #define BLIZZARD_VERSION_S1D13745 0x01 /* Hailstorm */ #define BLIZZARD_VERSION_S1D13744 0x02 /* Blizzard */ #define MIPID_CMD_READ_DISP_ID 0x04 #define MIPID_CMD_READ_RED 0x06 #define MIPID_CMD_READ_GREEN 0x07 #define MIPID_CMD_READ_BLUE 0x08 #define MIPID_CMD_READ_DISP_STATUS 0x09 #define MIPID_CMD_RDDSDR 0x0F #define MIPID_CMD_SLEEP_IN 0x10 #define MIPID_CMD_SLEEP_OUT 0x11 #define MIPID_CMD_DISP_OFF 0x28 #define MIPID_CMD_DISP_ON 0x29 static struct panel_drv_data { struct mutex lock; struct omap_dss_device *dssdev; struct spi_device *spidev; struct backlight_device *bldev; int blizzard_ver; } s_drv_data; static inline struct panel_n8x0_data *get_board_data(const struct omap_dss_device *dssdev) { return dssdev->data; } static inline struct panel_drv_data *get_drv_data(const struct omap_dss_device *dssdev) { return &s_drv_data; } static inline void blizzard_cmd(u8 cmd) { omap_rfbi_write_command(&cmd, 1); } static inline void blizzard_write(u8 cmd, const u8 *buf, int len) { omap_rfbi_write_command(&cmd, 1); omap_rfbi_write_data(buf, len); } static inline void blizzard_read(u8 cmd, u8 *buf, int len) { omap_rfbi_write_command(&cmd, 1); omap_rfbi_read_data(buf, len); } static u8 blizzard_read_reg(u8 cmd) { u8 data; blizzard_read(cmd, &data, 1); return data; } static void blizzard_ctrl_setup_update(struct omap_dss_device *dssdev, int x, int y, int w, int h) { struct panel_drv_data *ddata = get_drv_data(dssdev); u8 tmp[18]; int x_end, y_end; x_end = x + w - 1; y_end = y + h - 1; tmp[0] = x; tmp[1] = x >> 8; tmp[2] = y; tmp[3] = y >> 8; tmp[4] = x_end; tmp[5] = x_end >> 8; tmp[6] = y_end; tmp[7] = y_end >> 8; /* scaling? */ tmp[8] = x; tmp[9] = x >> 8; tmp[10] = y; tmp[11] = y >> 8; tmp[12] = x_end; tmp[13] = x_end >> 8; tmp[14] = y_end; tmp[15] = y_end >> 8; tmp[16] = BLIZZARD_COLOR_RGB565; if (ddata->blizzard_ver == BLIZZARD_VERSION_S1D13745) tmp[17] = BLIZZARD_SRC_WRITE_LCD_BACKGROUND; else tmp[17] = ddata->blizzard_ver == BLIZZARD_VERSION_S1D13744 ? BLIZZARD_SRC_WRITE_LCD : BLIZZARD_SRC_WRITE_LCD_DESTRUCTIVE; omap_rfbi_configure(dssdev, 16, 8); blizzard_write(BLIZZARD_INPUT_WIN_X_START_0, tmp, 18); omap_rfbi_configure(dssdev, 16, 16); } static void mipid_transfer(struct spi_device *spi, int cmd, const u8 *wbuf, int wlen, u8 *rbuf, int rlen) { struct spi_message m; struct spi_transfer *x, xfer[4]; u16 w; int r; spi_message_init(&m); memset(xfer, 0, sizeof(xfer)); x = &xfer[0]; cmd &= 0xff; x->tx_buf = &cmd; x->bits_per_word = 9; x->len = 2; spi_message_add_tail(x, &m); if (wlen) { x++; x->tx_buf = wbuf; x->len = wlen; x->bits_per_word = 9; spi_message_add_tail(x, &m); } if (rlen) { x++; x->rx_buf = &w; x->len = 1; spi_message_add_tail(x, &m); if (rlen > 1) { /* Arrange for the extra clock before the first * data bit. */ x->bits_per_word = 9; x->len = 2; x++; x->rx_buf = &rbuf[1]; x->len = rlen - 1; spi_message_add_tail(x, &m); } } r = spi_sync(spi, &m); if (r < 0) dev_dbg(&spi->dev, "spi_sync %d\n", r); if (rlen) rbuf[0] = w & 0xff; } static inline void mipid_cmd(struct spi_device *spi, int cmd) { mipid_transfer(spi, cmd, NULL, 0, NULL, 0); } static inline void mipid_write(struct spi_device *spi, int reg, const u8 *buf, int len) { mipid_transfer(spi, reg, buf, len, NULL, 0); } static inline void mipid_read(struct spi_device *spi, int reg, u8 *buf, int len) { mipid_transfer(spi, reg, NULL, 0, buf, len); } static void set_data_lines(struct spi_device *spi, int data_lines) { u16 par; switch (data_lines) { case 16: par = 0x150; break; case 18: par = 0x160; break; case 24: par = 0x170; break; } mipid_write(spi, 0x3a, (u8 *)&par, 2); } static void send_init_string(struct spi_device *spi) { u16 initpar[] = { 0x0102, 0x0100, 0x0100 }; mipid_write(spi, 0xc2, (u8 *)initpar, sizeof(initpar)); } static void send_display_on(struct spi_device *spi) { mipid_cmd(spi, MIPID_CMD_DISP_ON); } static void send_display_off(struct spi_device *spi) { mipid_cmd(spi, MIPID_CMD_DISP_OFF); } static void send_sleep_out(struct spi_device *spi) { mipid_cmd(spi, MIPID_CMD_SLEEP_OUT); msleep(120); } static void send_sleep_in(struct spi_device *spi) { mipid_cmd(spi, MIPID_CMD_SLEEP_IN); msleep(50); } static int n8x0_panel_power_on(struct omap_dss_device *dssdev) { int r; struct panel_n8x0_data *bdata = get_board_data(dssdev); struct panel_drv_data *ddata = get_drv_data(dssdev); struct spi_device *spi = ddata->spidev; u8 rev, conf; u8 display_id[3]; const char *panel_name; if (dssdev->state == OMAP_DSS_DISPLAY_ACTIVE) return 0; gpio_direction_output(bdata->ctrl_pwrdown, 1); if (bdata->platform_enable) { r = bdata->platform_enable(dssdev); if (r) goto err_plat_en; } r = omapdss_rfbi_display_enable(dssdev); if (r) goto err_rfbi_en; rev = blizzard_read_reg(BLIZZARD_REV_CODE); conf = blizzard_read_reg(BLIZZARD_CONFIG); switch (rev & 0xfc) { case 0x9c: ddata->blizzard_ver = BLIZZARD_VERSION_S1D13744; dev_info(&dssdev->dev, "s1d13744 LCD controller rev %d " "initialized (CNF pins %x)\n", rev & 0x03, conf & 0x07); break; case 0xa4: ddata->blizzard_ver = BLIZZARD_VERSION_S1D13745; dev_info(&dssdev->dev, "s1d13745 LCD controller rev %d " "initialized (CNF pins %x)\n", rev & 0x03, conf & 0x07); break; default: dev_err(&dssdev->dev, "invalid s1d1374x revision %02x\n", rev); r = -ENODEV; goto err_inv_chip; } /* panel */ gpio_direction_output(bdata->panel_reset, 1); mipid_read(spi, MIPID_CMD_READ_DISP_ID, display_id, 3); dev_dbg(&spi->dev, "MIPI display ID: %02x%02x%02x\n", display_id[0], display_id[1], display_id[2]); switch (display_id[0]) { case 0x45: panel_name = "lph8923"; break; case 0x83: panel_name = "ls041y3"; break; default: dev_err(&dssdev->dev, "invalid display ID 0x%x\n", display_id[0]); r = -ENODEV; goto err_inv_panel; } dev_info(&dssdev->dev, "%s rev %02x LCD detected\n", panel_name, display_id[1]); send_sleep_out(spi); send_init_string(spi); set_data_lines(spi, 24); send_display_on(spi); return 0; err_inv_panel: /* * HACK: we should turn off the panel here, but there is some problem * with the initialization sequence, and we fail to init the panel if we * have turned it off */ /* gpio_direction_output(bdata->panel_reset, 0); */ err_inv_chip: omapdss_rfbi_display_disable(dssdev); err_rfbi_en: if (bdata->platform_disable) bdata->platform_disable(dssdev); err_plat_en: gpio_direction_output(bdata->ctrl_pwrdown, 0); return r; } static void n8x0_panel_power_off(struct omap_dss_device *dssdev) { struct panel_n8x0_data *bdata = get_board_data(dssdev); struct panel_drv_data *ddata = get_drv_data(dssdev); struct spi_device *spi = ddata->spidev; if (dssdev->state != OMAP_DSS_DISPLAY_ACTIVE) return; send_display_off(spi); send_sleep_in(spi); if (bdata->platform_disable) bdata->platform_disable(dssdev); /* * HACK: we should turn off the panel here, but there is some problem * with the initialization sequence, and we fail to init the panel if we * have turned it off */ /* gpio_direction_output(bdata->panel_reset, 0); */ gpio_direction_output(bdata->ctrl_pwrdown, 0); omapdss_rfbi_display_disable(dssdev); } static const struct rfbi_timings n8x0_panel_timings = { .cs_on_time = 0, .we_on_time = 9000, .we_off_time = 18000, .we_cycle_time = 36000, .re_on_time = 9000, .re_off_time = 27000, .re_cycle_time = 36000, .access_time = 27000, .cs_off_time = 36000, .cs_pulse_width = 0, }; static int n8x0_bl_update_status(struct backlight_device *dev) { struct omap_dss_device *dssdev = dev_get_drvdata(&dev->dev); struct panel_n8x0_data *bdata = get_board_data(dssdev); struct panel_drv_data *ddata = get_drv_data(dssdev); int r; int level; mutex_lock(&ddata->lock); if (dev->props.fb_blank == FB_BLANK_UNBLANK && dev->props.power == FB_BLANK_UNBLANK) level = dev->props.brightness; else level = 0; dev_dbg(&dssdev->dev, "update brightness to %d\n", level); if (!bdata->set_backlight) r = -EINVAL; else r = bdata->set_backlight(dssdev, level); mutex_unlock(&ddata->lock); return r; } static int n8x0_bl_get_intensity(struct backlight_device *dev) { if (dev->props.fb_blank == FB_BLANK_UNBLANK && dev->props.power == FB_BLANK_UNBLANK) return dev->props.brightness; return 0; } static const struct backlight_ops n8x0_bl_ops = { .get_brightness = n8x0_bl_get_intensity, .update_status = n8x0_bl_update_status, }; static int n8x0_panel_probe(struct omap_dss_device *dssdev) { struct panel_n8x0_data *bdata = get_board_data(dssdev); struct panel_drv_data *ddata; struct backlight_device *bldev; struct backlight_properties props; int r; dev_dbg(&dssdev->dev, "probe\n"); if (!bdata) return -EINVAL; s_drv_data.dssdev = dssdev; ddata = &s_drv_data; mutex_init(&ddata->lock); dssdev->panel.config = OMAP_DSS_LCD_TFT; dssdev->panel.timings.x_res = 800; dssdev->panel.timings.y_res = 480; dssdev->ctrl.pixel_size = 16; dssdev->ctrl.rfbi_timings = n8x0_panel_timings; memset(&props, 0, sizeof(props)); props.max_brightness = 127; props.type = BACKLIGHT_PLATFORM; bldev = backlight_device_register(dev_name(&dssdev->dev), &dssdev->dev, dssdev, &n8x0_bl_ops, &props); if (IS_ERR(bldev)) { r = PTR_ERR(bldev); dev_err(&dssdev->dev, "register backlight failed\n"); return r; } ddata->bldev = bldev; bldev->props.fb_blank = FB_BLANK_UNBLANK; bldev->props.power = FB_BLANK_UNBLANK; bldev->props.brightness = 127; n8x0_bl_update_status(bldev); return 0; } static void n8x0_panel_remove(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = get_drv_data(dssdev); struct backlight_device *bldev; dev_dbg(&dssdev->dev, "remove\n"); bldev = ddata->bldev; bldev->props.power = FB_BLANK_POWERDOWN; n8x0_bl_update_status(bldev); backlight_device_unregister(bldev); dev_set_drvdata(&dssdev->dev, NULL); } static int n8x0_panel_enable(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = get_drv_data(dssdev); int r; dev_dbg(&dssdev->dev, "enable\n"); mutex_lock(&ddata->lock); rfbi_bus_lock(); r = n8x0_panel_power_on(dssdev); rfbi_bus_unlock(); if (r) { mutex_unlock(&ddata->lock); return r; } dssdev->state = OMAP_DSS_DISPLAY_ACTIVE; mutex_unlock(&ddata->lock); return 0; } static void n8x0_panel_disable(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = get_drv_data(dssdev); dev_dbg(&dssdev->dev, "disable\n"); mutex_lock(&ddata->lock); rfbi_bus_lock(); n8x0_panel_power_off(dssdev); rfbi_bus_unlock(); dssdev->state = OMAP_DSS_DISPLAY_DISABLED; mutex_unlock(&ddata->lock); } static int n8x0_panel_suspend(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = get_drv_data(dssdev); dev_dbg(&dssdev->dev, "suspend\n"); mutex_lock(&ddata->lock); rfbi_bus_lock(); n8x0_panel_power_off(dssdev); rfbi_bus_unlock(); dssdev->state = OMAP_DSS_DISPLAY_SUSPENDED; mutex_unlock(&ddata->lock); return 0; } static int n8x0_panel_resume(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = get_drv_data(dssdev); int r; dev_dbg(&dssdev->dev, "resume\n"); mutex_lock(&ddata->lock); rfbi_bus_lock(); r = n8x0_panel_power_on(dssdev); rfbi_bus_unlock(); if (r) { mutex_unlock(&ddata->lock); return r; } dssdev->state = OMAP_DSS_DISPLAY_ACTIVE; mutex_unlock(&ddata->lock); return 0; } static void n8x0_panel_get_timings(struct omap_dss_device *dssdev, struct omap_video_timings *timings) { *timings = dssdev->panel.timings; } static void n8x0_panel_get_resolution(struct omap_dss_device *dssdev, u16 *xres, u16 *yres) { *xres = dssdev->panel.timings.x_res; *yres = dssdev->panel.timings.y_res; } static void update_done(void *data) { rfbi_bus_unlock(); } static int n8x0_panel_update(struct omap_dss_device *dssdev, u16 x, u16 y, u16 w, u16 h) { struct panel_drv_data *ddata = get_drv_data(dssdev); dev_dbg(&dssdev->dev, "update\n"); mutex_lock(&ddata->lock); rfbi_bus_lock(); omap_rfbi_prepare_update(dssdev, &x, &y, &w, &h); blizzard_ctrl_setup_update(dssdev, x, y, w, h); omap_rfbi_update(dssdev, x, y, w, h, update_done, NULL); mutex_unlock(&ddata->lock); return 0; } static int n8x0_panel_sync(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = get_drv_data(dssdev); dev_dbg(&dssdev->dev, "sync\n"); mutex_lock(&ddata->lock); rfbi_bus_lock(); rfbi_bus_unlock(); mutex_unlock(&ddata->lock); return 0; } static struct omap_dss_driver n8x0_panel_driver = { .probe = n8x0_panel_probe, .remove = n8x0_panel_remove, .enable = n8x0_panel_enable, .disable = n8x0_panel_disable, .suspend = n8x0_panel_suspend, .resume = n8x0_panel_resume, .update = n8x0_panel_update, .sync = n8x0_panel_sync, .get_resolution = n8x0_panel_get_resolution, .get_recommended_bpp = omapdss_default_get_recommended_bpp, .get_timings = n8x0_panel_get_timings, .driver = { .name = "n8x0_panel", .owner = THIS_MODULE, }, }; /* PANEL */ static int mipid_spi_probe(struct spi_device *spi) { dev_dbg(&spi->dev, "mipid_spi_probe\n"); spi->mode = SPI_MODE_0; s_drv_data.spidev = spi; return 0; } static int mipid_spi_remove(struct spi_device *spi) { dev_dbg(&spi->dev, "mipid_spi_remove\n"); return 0; } static struct spi_driver mipid_spi_driver = { .driver = { .name = "lcd_mipid", .owner = THIS_MODULE, }, .probe = mipid_spi_probe, .remove = __devexit_p(mipid_spi_remove), }; static int __init n8x0_panel_drv_init(void) { int r; r = spi_register_driver(&mipid_spi_driver); if (r) { pr_err("n8x0_panel: spi driver registration failed\n"); return r; } r = omap_dss_register_driver(&n8x0_panel_driver); if (r) { pr_err("n8x0_panel: dss driver registration failed\n"); spi_unregister_driver(&mipid_spi_driver); return r; } return 0; } static void __exit n8x0_panel_drv_exit(void) { spi_unregister_driver(&mipid_spi_driver); omap_dss_unregister_driver(&n8x0_panel_driver); } module_init(n8x0_panel_drv_init); module_exit(n8x0_panel_drv_exit); MODULE_LICENSE("GPL");
gpl-2.0
TeamHackDroid/samsung-kernel-msm7x30
drivers/net/irda/sh_irda.c
4897
20294
/* * SuperH IrDA Driver * * Copyright (C) 2010 Renesas Solutions Corp. * Kuninori Morimoto <kuninori.morimoto.gx@renesas.com> * * Based on sh_sir.c * Copyright (C) 2009 Renesas Solutions Corp. * Copyright 2006-2009 Analog Devices 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. */ /* * CAUTION * * This driver is very simple. * So, it doesn't have below support now * - MIR/FIR support * - DMA transfer support * - FIFO mode support */ #include <linux/io.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/clk.h> #include <net/irda/wrapper.h> #include <net/irda/irda_device.h> #define DRIVER_NAME "sh_irda" #if defined(CONFIG_ARCH_SH7367) || defined(CONFIG_ARCH_SH7377) #define __IRDARAM_LEN 0x13FF #else #define __IRDARAM_LEN 0x1039 #endif #define IRTMR 0x1F00 /* Transfer mode */ #define IRCFR 0x1F02 /* Configuration */ #define IRCTR 0x1F04 /* IR control */ #define IRTFLR 0x1F20 /* Transmit frame length */ #define IRTCTR 0x1F22 /* Transmit control */ #define IRRFLR 0x1F40 /* Receive frame length */ #define IRRCTR 0x1F42 /* Receive control */ #define SIRISR 0x1F60 /* SIR-UART mode interrupt source */ #define SIRIMR 0x1F62 /* SIR-UART mode interrupt mask */ #define SIRICR 0x1F64 /* SIR-UART mode interrupt clear */ #define SIRBCR 0x1F68 /* SIR-UART mode baud rate count */ #define MFIRISR 0x1F70 /* MIR/FIR mode interrupt source */ #define MFIRIMR 0x1F72 /* MIR/FIR mode interrupt mask */ #define MFIRICR 0x1F74 /* MIR/FIR mode interrupt clear */ #define CRCCTR 0x1F80 /* CRC engine control */ #define CRCIR 0x1F86 /* CRC engine input data */ #define CRCCR 0x1F8A /* CRC engine calculation */ #define CRCOR 0x1F8E /* CRC engine output data */ #define FIFOCP 0x1FC0 /* FIFO current pointer */ #define FIFOFP 0x1FC2 /* FIFO follow pointer */ #define FIFORSMSK 0x1FC4 /* FIFO receive status mask */ #define FIFORSOR 0x1FC6 /* FIFO receive status OR */ #define FIFOSEL 0x1FC8 /* FIFO select */ #define FIFORS 0x1FCA /* FIFO receive status */ #define FIFORFL 0x1FCC /* FIFO receive frame length */ #define FIFORAMCP 0x1FCE /* FIFO RAM current pointer */ #define FIFORAMFP 0x1FD0 /* FIFO RAM follow pointer */ #define BIFCTL 0x1FD2 /* BUS interface control */ #define IRDARAM 0x0000 /* IrDA buffer RAM */ #define IRDARAM_LEN __IRDARAM_LEN /* - 8/16/32 (read-only for 32) */ /* IRTMR */ #define TMD_MASK (0x3 << 14) /* Transfer Mode */ #define TMD_SIR (0x0 << 14) #define TMD_MIR (0x3 << 14) #define TMD_FIR (0x2 << 14) #define FIFORIM (1 << 8) /* FIFO receive interrupt mask */ #define MIM (1 << 4) /* MIR/FIR Interrupt Mask */ #define SIM (1 << 0) /* SIR Interrupt Mask */ #define xIM_MASK (FIFORIM | MIM | SIM) /* IRCFR */ #define RTO_SHIFT 8 /* shift for Receive Timeout */ #define RTO (0x3 << RTO_SHIFT) /* IRTCTR */ #define ARMOD (1 << 15) /* Auto-Receive Mode */ #define TE (1 << 0) /* Transmit Enable */ /* IRRFLR */ #define RFL_MASK (0x1FFF) /* mask for Receive Frame Length */ /* IRRCTR */ #define RE (1 << 0) /* Receive Enable */ /* * SIRISR, SIRIMR, SIRICR, * MFIRISR, MFIRIMR, MFIRICR */ #define FRE (1 << 15) /* Frame Receive End */ #define TROV (1 << 11) /* Transfer Area Overflow */ #define xIR_9 (1 << 9) #define TOT xIR_9 /* for SIR Timeout */ #define ABTD xIR_9 /* for MIR/FIR Abort Detection */ #define xIR_8 (1 << 8) #define FER xIR_8 /* for SIR Framing Error */ #define CRCER xIR_8 /* for MIR/FIR CRC error */ #define FTE (1 << 7) /* Frame Transmit End */ #define xIR_MASK (FRE | TROV | xIR_9 | xIR_8 | FTE) /* SIRBCR */ #define BRC_MASK (0x3F) /* mask for Baud Rate Count */ /* CRCCTR */ #define CRC_RST (1 << 15) /* CRC Engine Reset */ #define CRC_CT_MASK 0x0FFF /* mask for CRC Engine Input Data Count */ /* CRCIR */ #define CRC_IN_MASK 0x0FFF /* mask for CRC Engine Input Data */ /************************************************************************ enum / structure ************************************************************************/ enum sh_irda_mode { SH_IRDA_NONE = 0, SH_IRDA_SIR, SH_IRDA_MIR, SH_IRDA_FIR, }; struct sh_irda_self; struct sh_irda_xir_func { int (*xir_fre) (struct sh_irda_self *self); int (*xir_trov) (struct sh_irda_self *self); int (*xir_9) (struct sh_irda_self *self); int (*xir_8) (struct sh_irda_self *self); int (*xir_fte) (struct sh_irda_self *self); }; struct sh_irda_self { void __iomem *membase; unsigned int irq; struct platform_device *pdev; struct net_device *ndev; struct irlap_cb *irlap; struct qos_info qos; iobuff_t tx_buff; iobuff_t rx_buff; enum sh_irda_mode mode; spinlock_t lock; struct sh_irda_xir_func *xir_func; }; /************************************************************************ common function ************************************************************************/ static void sh_irda_write(struct sh_irda_self *self, u32 offset, u16 data) { unsigned long flags; spin_lock_irqsave(&self->lock, flags); iowrite16(data, self->membase + offset); spin_unlock_irqrestore(&self->lock, flags); } static u16 sh_irda_read(struct sh_irda_self *self, u32 offset) { unsigned long flags; u16 ret; spin_lock_irqsave(&self->lock, flags); ret = ioread16(self->membase + offset); spin_unlock_irqrestore(&self->lock, flags); return ret; } static void sh_irda_update_bits(struct sh_irda_self *self, u32 offset, u16 mask, u16 data) { unsigned long flags; u16 old, new; spin_lock_irqsave(&self->lock, flags); old = ioread16(self->membase + offset); new = (old & ~mask) | data; if (old != new) iowrite16(data, self->membase + offset); spin_unlock_irqrestore(&self->lock, flags); } /************************************************************************ mode function ************************************************************************/ /*===================================== * * common * *=====================================*/ static void sh_irda_rcv_ctrl(struct sh_irda_self *self, int enable) { struct device *dev = &self->ndev->dev; sh_irda_update_bits(self, IRRCTR, RE, enable ? RE : 0); dev_dbg(dev, "recv %s\n", enable ? "enable" : "disable"); } static int sh_irda_set_timeout(struct sh_irda_self *self, int interval) { struct device *dev = &self->ndev->dev; if (SH_IRDA_SIR != self->mode) interval = 0; if (interval < 0 || interval > 2) { dev_err(dev, "unsupported timeout interval\n"); return -EINVAL; } sh_irda_update_bits(self, IRCFR, RTO, interval << RTO_SHIFT); return 0; } static int sh_irda_set_baudrate(struct sh_irda_self *self, int baudrate) { struct device *dev = &self->ndev->dev; u16 val; if (baudrate < 0) return 0; if (SH_IRDA_SIR != self->mode) { dev_err(dev, "it is not SIR mode\n"); return -EINVAL; } /* * Baud rate (bits/s) = * (48 MHz / 26) / (baud rate counter value + 1) x 16 */ val = (48000000 / 26 / 16 / baudrate) - 1; dev_dbg(dev, "baudrate = %d, val = 0x%02x\n", baudrate, val); sh_irda_update_bits(self, SIRBCR, BRC_MASK, val); return 0; } static int sh_irda_get_rcv_length(struct sh_irda_self *self) { return RFL_MASK & sh_irda_read(self, IRRFLR); } /*===================================== * * NONE MODE * *=====================================*/ static int sh_irda_xir_fre(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_err(dev, "none mode: frame recv\n"); return 0; } static int sh_irda_xir_trov(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_err(dev, "none mode: buffer ram over\n"); return 0; } static int sh_irda_xir_9(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_err(dev, "none mode: time over\n"); return 0; } static int sh_irda_xir_8(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_err(dev, "none mode: framing error\n"); return 0; } static int sh_irda_xir_fte(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_err(dev, "none mode: frame transmit end\n"); return 0; } static struct sh_irda_xir_func sh_irda_xir_func = { .xir_fre = sh_irda_xir_fre, .xir_trov = sh_irda_xir_trov, .xir_9 = sh_irda_xir_9, .xir_8 = sh_irda_xir_8, .xir_fte = sh_irda_xir_fte, }; /*===================================== * * MIR/FIR MODE * * MIR/FIR are not supported now *=====================================*/ static struct sh_irda_xir_func sh_irda_mfir_func = { .xir_fre = sh_irda_xir_fre, .xir_trov = sh_irda_xir_trov, .xir_9 = sh_irda_xir_9, .xir_8 = sh_irda_xir_8, .xir_fte = sh_irda_xir_fte, }; /*===================================== * * SIR MODE * *=====================================*/ static int sh_irda_sir_fre(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; u16 data16; u8 *data = (u8 *)&data16; int len = sh_irda_get_rcv_length(self); int i, j; if (len > IRDARAM_LEN) len = IRDARAM_LEN; dev_dbg(dev, "frame recv length = %d\n", len); for (i = 0; i < len; i++) { j = i % 2; if (!j) data16 = sh_irda_read(self, IRDARAM + i); async_unwrap_char(self->ndev, &self->ndev->stats, &self->rx_buff, data[j]); } self->ndev->last_rx = jiffies; sh_irda_rcv_ctrl(self, 1); return 0; } static int sh_irda_sir_trov(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_err(dev, "buffer ram over\n"); sh_irda_rcv_ctrl(self, 1); return 0; } static int sh_irda_sir_tot(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_err(dev, "time over\n"); sh_irda_set_baudrate(self, 9600); sh_irda_rcv_ctrl(self, 1); return 0; } static int sh_irda_sir_fer(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_err(dev, "framing error\n"); sh_irda_rcv_ctrl(self, 1); return 0; } static int sh_irda_sir_fte(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; dev_dbg(dev, "frame transmit end\n"); netif_wake_queue(self->ndev); return 0; } static struct sh_irda_xir_func sh_irda_sir_func = { .xir_fre = sh_irda_sir_fre, .xir_trov = sh_irda_sir_trov, .xir_9 = sh_irda_sir_tot, .xir_8 = sh_irda_sir_fer, .xir_fte = sh_irda_sir_fte, }; static void sh_irda_set_mode(struct sh_irda_self *self, enum sh_irda_mode mode) { struct device *dev = &self->ndev->dev; struct sh_irda_xir_func *func; const char *name; u16 data; switch (mode) { case SH_IRDA_SIR: name = "SIR"; data = TMD_SIR; func = &sh_irda_sir_func; break; case SH_IRDA_MIR: name = "MIR"; data = TMD_MIR; func = &sh_irda_mfir_func; break; case SH_IRDA_FIR: name = "FIR"; data = TMD_FIR; func = &sh_irda_mfir_func; break; default: name = "NONE"; data = 0; func = &sh_irda_xir_func; break; } self->mode = mode; self->xir_func = func; sh_irda_update_bits(self, IRTMR, TMD_MASK, data); dev_dbg(dev, "switch to %s mode", name); } /************************************************************************ irq function ************************************************************************/ static void sh_irda_set_irq_mask(struct sh_irda_self *self) { u16 tmr_hole; u16 xir_reg; /* set all mask */ sh_irda_update_bits(self, IRTMR, xIM_MASK, xIM_MASK); sh_irda_update_bits(self, SIRIMR, xIR_MASK, xIR_MASK); sh_irda_update_bits(self, MFIRIMR, xIR_MASK, xIR_MASK); /* clear irq */ sh_irda_update_bits(self, SIRICR, xIR_MASK, xIR_MASK); sh_irda_update_bits(self, MFIRICR, xIR_MASK, xIR_MASK); switch (self->mode) { case SH_IRDA_SIR: tmr_hole = SIM; xir_reg = SIRIMR; break; case SH_IRDA_MIR: case SH_IRDA_FIR: tmr_hole = MIM; xir_reg = MFIRIMR; break; default: tmr_hole = 0; xir_reg = 0; break; } /* open mask */ if (xir_reg) { sh_irda_update_bits(self, IRTMR, tmr_hole, 0); sh_irda_update_bits(self, xir_reg, xIR_MASK, 0); } } static irqreturn_t sh_irda_irq(int irq, void *dev_id) { struct sh_irda_self *self = dev_id; struct sh_irda_xir_func *func = self->xir_func; u16 isr = sh_irda_read(self, SIRISR); /* clear irq */ sh_irda_write(self, SIRICR, isr); if (isr & FRE) func->xir_fre(self); if (isr & TROV) func->xir_trov(self); if (isr & xIR_9) func->xir_9(self); if (isr & xIR_8) func->xir_8(self); if (isr & FTE) func->xir_fte(self); return IRQ_HANDLED; } /************************************************************************ CRC function ************************************************************************/ static void sh_irda_crc_reset(struct sh_irda_self *self) { sh_irda_write(self, CRCCTR, CRC_RST); } static void sh_irda_crc_add(struct sh_irda_self *self, u16 data) { sh_irda_write(self, CRCIR, data & CRC_IN_MASK); } static u16 sh_irda_crc_cnt(struct sh_irda_self *self) { return CRC_CT_MASK & sh_irda_read(self, CRCCTR); } static u16 sh_irda_crc_out(struct sh_irda_self *self) { return sh_irda_read(self, CRCOR); } static int sh_irda_crc_init(struct sh_irda_self *self) { struct device *dev = &self->ndev->dev; int ret = -EIO; u16 val; sh_irda_crc_reset(self); sh_irda_crc_add(self, 0xCC); sh_irda_crc_add(self, 0xF5); sh_irda_crc_add(self, 0xF1); sh_irda_crc_add(self, 0xA7); val = sh_irda_crc_cnt(self); if (4 != val) { dev_err(dev, "CRC count error %x\n", val); goto crc_init_out; } val = sh_irda_crc_out(self); if (0x51DF != val) { dev_err(dev, "CRC result error%x\n", val); goto crc_init_out; } ret = 0; crc_init_out: sh_irda_crc_reset(self); return ret; } /************************************************************************ iobuf function ************************************************************************/ static void sh_irda_remove_iobuf(struct sh_irda_self *self) { kfree(self->rx_buff.head); self->tx_buff.head = NULL; self->tx_buff.data = NULL; self->rx_buff.head = NULL; self->rx_buff.data = NULL; } static int sh_irda_init_iobuf(struct sh_irda_self *self, int rxsize, int txsize) { if (self->rx_buff.head || self->tx_buff.head) { dev_err(&self->ndev->dev, "iobuff has already existed."); return -EINVAL; } /* rx_buff */ self->rx_buff.head = kmalloc(rxsize, GFP_KERNEL); if (!self->rx_buff.head) return -ENOMEM; self->rx_buff.truesize = rxsize; self->rx_buff.in_frame = FALSE; self->rx_buff.state = OUTSIDE_FRAME; self->rx_buff.data = self->rx_buff.head; /* tx_buff */ self->tx_buff.head = self->membase + IRDARAM; self->tx_buff.truesize = IRDARAM_LEN; return 0; } /************************************************************************ net_device_ops function ************************************************************************/ static int sh_irda_hard_xmit(struct sk_buff *skb, struct net_device *ndev) { struct sh_irda_self *self = netdev_priv(ndev); struct device *dev = &self->ndev->dev; int speed = irda_get_next_speed(skb); int ret; dev_dbg(dev, "hard xmit\n"); netif_stop_queue(ndev); sh_irda_rcv_ctrl(self, 0); ret = sh_irda_set_baudrate(self, speed); if (ret < 0) goto sh_irda_hard_xmit_end; self->tx_buff.len = 0; if (skb->len) { unsigned long flags; spin_lock_irqsave(&self->lock, flags); self->tx_buff.len = async_wrap_skb(skb, self->tx_buff.head, self->tx_buff.truesize); spin_unlock_irqrestore(&self->lock, flags); if (self->tx_buff.len > self->tx_buff.truesize) self->tx_buff.len = self->tx_buff.truesize; sh_irda_write(self, IRTFLR, self->tx_buff.len); sh_irda_write(self, IRTCTR, ARMOD | TE); } else goto sh_irda_hard_xmit_end; dev_kfree_skb(skb); return 0; sh_irda_hard_xmit_end: sh_irda_set_baudrate(self, 9600); netif_wake_queue(self->ndev); sh_irda_rcv_ctrl(self, 1); dev_kfree_skb(skb); return ret; } static int sh_irda_ioctl(struct net_device *ndev, struct ifreq *ifreq, int cmd) { /* * FIXME * * This function is needed for irda framework. * But nothing to do now */ return 0; } static struct net_device_stats *sh_irda_stats(struct net_device *ndev) { struct sh_irda_self *self = netdev_priv(ndev); return &self->ndev->stats; } static int sh_irda_open(struct net_device *ndev) { struct sh_irda_self *self = netdev_priv(ndev); int err; pm_runtime_get_sync(&self->pdev->dev); err = sh_irda_crc_init(self); if (err) goto open_err; sh_irda_set_mode(self, SH_IRDA_SIR); sh_irda_set_timeout(self, 2); sh_irda_set_baudrate(self, 9600); self->irlap = irlap_open(ndev, &self->qos, DRIVER_NAME); if (!self->irlap) { err = -ENODEV; goto open_err; } netif_start_queue(ndev); sh_irda_rcv_ctrl(self, 1); sh_irda_set_irq_mask(self); dev_info(&ndev->dev, "opened\n"); return 0; open_err: pm_runtime_put_sync(&self->pdev->dev); return err; } static int sh_irda_stop(struct net_device *ndev) { struct sh_irda_self *self = netdev_priv(ndev); /* Stop IrLAP */ if (self->irlap) { irlap_close(self->irlap); self->irlap = NULL; } netif_stop_queue(ndev); pm_runtime_put_sync(&self->pdev->dev); dev_info(&ndev->dev, "stoped\n"); return 0; } static const struct net_device_ops sh_irda_ndo = { .ndo_open = sh_irda_open, .ndo_stop = sh_irda_stop, .ndo_start_xmit = sh_irda_hard_xmit, .ndo_do_ioctl = sh_irda_ioctl, .ndo_get_stats = sh_irda_stats, }; /************************************************************************ platform_driver function ************************************************************************/ static int __devinit sh_irda_probe(struct platform_device *pdev) { struct net_device *ndev; struct sh_irda_self *self; struct resource *res; int irq; int err = -ENOMEM; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); irq = platform_get_irq(pdev, 0); if (!res || irq < 0) { dev_err(&pdev->dev, "Not enough platform resources.\n"); goto exit; } ndev = alloc_irdadev(sizeof(*self)); if (!ndev) goto exit; self = netdev_priv(ndev); self->membase = ioremap_nocache(res->start, resource_size(res)); if (!self->membase) { err = -ENXIO; dev_err(&pdev->dev, "Unable to ioremap.\n"); goto err_mem_1; } err = sh_irda_init_iobuf(self, IRDA_SKB_MAX_MTU, IRDA_SIR_MAX_FRAME); if (err) goto err_mem_2; self->pdev = pdev; pm_runtime_enable(&pdev->dev); irda_init_max_qos_capabilies(&self->qos); ndev->netdev_ops = &sh_irda_ndo; ndev->irq = irq; self->ndev = ndev; self->qos.baud_rate.bits &= IR_9600; /* FIXME */ self->qos.min_turn_time.bits = 1; /* 10 ms or more */ spin_lock_init(&self->lock); irda_qos_bits_to_value(&self->qos); err = register_netdev(ndev); if (err) goto err_mem_4; platform_set_drvdata(pdev, ndev); if (request_irq(irq, sh_irda_irq, IRQF_DISABLED, "sh_irda", self)) { dev_warn(&pdev->dev, "Unable to attach sh_irda interrupt\n"); goto err_mem_4; } dev_info(&pdev->dev, "SuperH IrDA probed\n"); goto exit; err_mem_4: pm_runtime_disable(&pdev->dev); sh_irda_remove_iobuf(self); err_mem_2: iounmap(self->membase); err_mem_1: free_netdev(ndev); exit: return err; } static int __devexit sh_irda_remove(struct platform_device *pdev) { struct net_device *ndev = platform_get_drvdata(pdev); struct sh_irda_self *self = netdev_priv(ndev); if (!self) return 0; unregister_netdev(ndev); pm_runtime_disable(&pdev->dev); sh_irda_remove_iobuf(self); iounmap(self->membase); free_netdev(ndev); platform_set_drvdata(pdev, NULL); return 0; } static int sh_irda_runtime_nop(struct device *dev) { /* Runtime PM callback shared between ->runtime_suspend() * and ->runtime_resume(). Simply returns success. * * This driver re-initializes all registers after * pm_runtime_get_sync() anyway so there is no need * to save and restore registers here. */ return 0; } static const struct dev_pm_ops sh_irda_pm_ops = { .runtime_suspend = sh_irda_runtime_nop, .runtime_resume = sh_irda_runtime_nop, }; static struct platform_driver sh_irda_driver = { .probe = sh_irda_probe, .remove = __devexit_p(sh_irda_remove), .driver = { .name = DRIVER_NAME, .pm = &sh_irda_pm_ops, }, }; module_platform_driver(sh_irda_driver); MODULE_AUTHOR("Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>"); MODULE_DESCRIPTION("SuperH IrDA driver"); MODULE_LICENSE("GPL");
gpl-2.0
aidfarh/lightning-kernel
drivers/mfd/menelaus.c
5153
31779
/* * Copyright (C) 2004 Texas Instruments, Inc. * * Some parts based tps65010.c: * Copyright (C) 2004 Texas Instruments and * Copyright (C) 2004-2005 David Brownell * * Some parts based on tlv320aic24.c: * Copyright (C) by Kai Svahn <kai.svahn@nokia.com> * * Changes for interrupt handling and clean-up by * Tony Lindgren <tony@atomide.com> and Imre Deak <imre.deak@nokia.com> * Cleanup and generalized support for voltage setting by * Juha Yrjola * Added support for controlling VCORE and regulator sleep states, * Amit Kucheria <amit.kucheria@nokia.com> * Copyright (C) 2005, 2006 Nokia 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/module.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/sched.h> #include <linux/mutex.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/rtc.h> #include <linux/bcd.h> #include <linux/slab.h> #include <asm/mach/irq.h> #include <asm/gpio.h> #include <plat/menelaus.h> #define DRIVER_NAME "menelaus" #define MENELAUS_I2C_ADDRESS 0x72 #define MENELAUS_REV 0x01 #define MENELAUS_VCORE_CTRL1 0x02 #define MENELAUS_VCORE_CTRL2 0x03 #define MENELAUS_VCORE_CTRL3 0x04 #define MENELAUS_VCORE_CTRL4 0x05 #define MENELAUS_VCORE_CTRL5 0x06 #define MENELAUS_DCDC_CTRL1 0x07 #define MENELAUS_DCDC_CTRL2 0x08 #define MENELAUS_DCDC_CTRL3 0x09 #define MENELAUS_LDO_CTRL1 0x0A #define MENELAUS_LDO_CTRL2 0x0B #define MENELAUS_LDO_CTRL3 0x0C #define MENELAUS_LDO_CTRL4 0x0D #define MENELAUS_LDO_CTRL5 0x0E #define MENELAUS_LDO_CTRL6 0x0F #define MENELAUS_LDO_CTRL7 0x10 #define MENELAUS_LDO_CTRL8 0x11 #define MENELAUS_SLEEP_CTRL1 0x12 #define MENELAUS_SLEEP_CTRL2 0x13 #define MENELAUS_DEVICE_OFF 0x14 #define MENELAUS_OSC_CTRL 0x15 #define MENELAUS_DETECT_CTRL 0x16 #define MENELAUS_INT_MASK1 0x17 #define MENELAUS_INT_MASK2 0x18 #define MENELAUS_INT_STATUS1 0x19 #define MENELAUS_INT_STATUS2 0x1A #define MENELAUS_INT_ACK1 0x1B #define MENELAUS_INT_ACK2 0x1C #define MENELAUS_GPIO_CTRL 0x1D #define MENELAUS_GPIO_IN 0x1E #define MENELAUS_GPIO_OUT 0x1F #define MENELAUS_BBSMS 0x20 #define MENELAUS_RTC_CTRL 0x21 #define MENELAUS_RTC_UPDATE 0x22 #define MENELAUS_RTC_SEC 0x23 #define MENELAUS_RTC_MIN 0x24 #define MENELAUS_RTC_HR 0x25 #define MENELAUS_RTC_DAY 0x26 #define MENELAUS_RTC_MON 0x27 #define MENELAUS_RTC_YR 0x28 #define MENELAUS_RTC_WKDAY 0x29 #define MENELAUS_RTC_AL_SEC 0x2A #define MENELAUS_RTC_AL_MIN 0x2B #define MENELAUS_RTC_AL_HR 0x2C #define MENELAUS_RTC_AL_DAY 0x2D #define MENELAUS_RTC_AL_MON 0x2E #define MENELAUS_RTC_AL_YR 0x2F #define MENELAUS_RTC_COMP_MSB 0x30 #define MENELAUS_RTC_COMP_LSB 0x31 #define MENELAUS_S1_PULL_EN 0x32 #define MENELAUS_S1_PULL_DIR 0x33 #define MENELAUS_S2_PULL_EN 0x34 #define MENELAUS_S2_PULL_DIR 0x35 #define MENELAUS_MCT_CTRL1 0x36 #define MENELAUS_MCT_CTRL2 0x37 #define MENELAUS_MCT_CTRL3 0x38 #define MENELAUS_MCT_PIN_ST 0x39 #define MENELAUS_DEBOUNCE1 0x3A #define IH_MENELAUS_IRQS 12 #define MENELAUS_MMC_S1CD_IRQ 0 /* MMC slot 1 card change */ #define MENELAUS_MMC_S2CD_IRQ 1 /* MMC slot 2 card change */ #define MENELAUS_MMC_S1D1_IRQ 2 /* MMC DAT1 low in slot 1 */ #define MENELAUS_MMC_S2D1_IRQ 3 /* MMC DAT1 low in slot 2 */ #define MENELAUS_LOWBAT_IRQ 4 /* Low battery */ #define MENELAUS_HOTDIE_IRQ 5 /* Hot die detect */ #define MENELAUS_UVLO_IRQ 6 /* UVLO detect */ #define MENELAUS_TSHUT_IRQ 7 /* Thermal shutdown */ #define MENELAUS_RTCTMR_IRQ 8 /* RTC timer */ #define MENELAUS_RTCALM_IRQ 9 /* RTC alarm */ #define MENELAUS_RTCERR_IRQ 10 /* RTC error */ #define MENELAUS_PSHBTN_IRQ 11 /* Push button */ #define MENELAUS_RESERVED12_IRQ 12 /* Reserved */ #define MENELAUS_RESERVED13_IRQ 13 /* Reserved */ #define MENELAUS_RESERVED14_IRQ 14 /* Reserved */ #define MENELAUS_RESERVED15_IRQ 15 /* Reserved */ /* VCORE_CTRL1 register */ #define VCORE_CTRL1_BYP_COMP (1 << 5) #define VCORE_CTRL1_HW_NSW (1 << 7) /* GPIO_CTRL register */ #define GPIO_CTRL_SLOTSELEN (1 << 5) #define GPIO_CTRL_SLPCTLEN (1 << 6) #define GPIO1_DIR_INPUT (1 << 0) #define GPIO2_DIR_INPUT (1 << 1) #define GPIO3_DIR_INPUT (1 << 2) /* MCT_CTRL1 register */ #define MCT_CTRL1_S1_CMD_OD (1 << 2) #define MCT_CTRL1_S2_CMD_OD (1 << 3) /* MCT_CTRL2 register */ #define MCT_CTRL2_VS2_SEL_D0 (1 << 0) #define MCT_CTRL2_VS2_SEL_D1 (1 << 1) #define MCT_CTRL2_S1CD_BUFEN (1 << 4) #define MCT_CTRL2_S2CD_BUFEN (1 << 5) #define MCT_CTRL2_S1CD_DBEN (1 << 6) #define MCT_CTRL2_S2CD_BEN (1 << 7) /* MCT_CTRL3 register */ #define MCT_CTRL3_SLOT1_EN (1 << 0) #define MCT_CTRL3_SLOT2_EN (1 << 1) #define MCT_CTRL3_S1_AUTO_EN (1 << 2) #define MCT_CTRL3_S2_AUTO_EN (1 << 3) /* MCT_PIN_ST register */ #define MCT_PIN_ST_S1_CD_ST (1 << 0) #define MCT_PIN_ST_S2_CD_ST (1 << 1) static void menelaus_work(struct work_struct *_menelaus); struct menelaus_chip { struct mutex lock; struct i2c_client *client; struct work_struct work; #ifdef CONFIG_RTC_DRV_TWL92330 struct rtc_device *rtc; u8 rtc_control; unsigned uie:1; #endif unsigned vcore_hw_mode:1; u8 mask1, mask2; void (*handlers[16])(struct menelaus_chip *); void (*mmc_callback)(void *data, u8 mask); void *mmc_callback_data; }; static struct menelaus_chip *the_menelaus; static int menelaus_write_reg(int reg, u8 value) { int val = i2c_smbus_write_byte_data(the_menelaus->client, reg, value); if (val < 0) { pr_err(DRIVER_NAME ": write error"); return val; } return 0; } static int menelaus_read_reg(int reg) { int val = i2c_smbus_read_byte_data(the_menelaus->client, reg); if (val < 0) pr_err(DRIVER_NAME ": read error"); return val; } static int menelaus_enable_irq(int irq) { if (irq > 7) { irq -= 8; the_menelaus->mask2 &= ~(1 << irq); return menelaus_write_reg(MENELAUS_INT_MASK2, the_menelaus->mask2); } else { the_menelaus->mask1 &= ~(1 << irq); return menelaus_write_reg(MENELAUS_INT_MASK1, the_menelaus->mask1); } } static int menelaus_disable_irq(int irq) { if (irq > 7) { irq -= 8; the_menelaus->mask2 |= (1 << irq); return menelaus_write_reg(MENELAUS_INT_MASK2, the_menelaus->mask2); } else { the_menelaus->mask1 |= (1 << irq); return menelaus_write_reg(MENELAUS_INT_MASK1, the_menelaus->mask1); } } static int menelaus_ack_irq(int irq) { if (irq > 7) return menelaus_write_reg(MENELAUS_INT_ACK2, 1 << (irq - 8)); else return menelaus_write_reg(MENELAUS_INT_ACK1, 1 << irq); } /* Adds a handler for an interrupt. Does not run in interrupt context */ static int menelaus_add_irq_work(int irq, void (*handler)(struct menelaus_chip *)) { int ret = 0; mutex_lock(&the_menelaus->lock); the_menelaus->handlers[irq] = handler; ret = menelaus_enable_irq(irq); mutex_unlock(&the_menelaus->lock); return ret; } /* Removes handler for an interrupt */ static int menelaus_remove_irq_work(int irq) { int ret = 0; mutex_lock(&the_menelaus->lock); ret = menelaus_disable_irq(irq); the_menelaus->handlers[irq] = NULL; mutex_unlock(&the_menelaus->lock); return ret; } /* * Gets scheduled when a card detect interrupt happens. Note that in some cases * this line is wired to card cover switch rather than the card detect switch * in each slot. In this case the cards are not seen by menelaus. * FIXME: Add handling for D1 too */ static void menelaus_mmc_cd_work(struct menelaus_chip *menelaus_hw) { int reg; unsigned char card_mask = 0; reg = menelaus_read_reg(MENELAUS_MCT_PIN_ST); if (reg < 0) return; if (!(reg & 0x1)) card_mask |= MCT_PIN_ST_S1_CD_ST; if (!(reg & 0x2)) card_mask |= MCT_PIN_ST_S2_CD_ST; if (menelaus_hw->mmc_callback) menelaus_hw->mmc_callback(menelaus_hw->mmc_callback_data, card_mask); } /* * Toggles the MMC slots between open-drain and push-pull mode. */ int menelaus_set_mmc_opendrain(int slot, int enable) { int ret, val; if (slot != 1 && slot != 2) return -EINVAL; mutex_lock(&the_menelaus->lock); ret = menelaus_read_reg(MENELAUS_MCT_CTRL1); if (ret < 0) { mutex_unlock(&the_menelaus->lock); return ret; } val = ret; if (slot == 1) { if (enable) val |= MCT_CTRL1_S1_CMD_OD; else val &= ~MCT_CTRL1_S1_CMD_OD; } else { if (enable) val |= MCT_CTRL1_S2_CMD_OD; else val &= ~MCT_CTRL1_S2_CMD_OD; } ret = menelaus_write_reg(MENELAUS_MCT_CTRL1, val); mutex_unlock(&the_menelaus->lock); return ret; } EXPORT_SYMBOL(menelaus_set_mmc_opendrain); int menelaus_set_slot_sel(int enable) { int ret; mutex_lock(&the_menelaus->lock); ret = menelaus_read_reg(MENELAUS_GPIO_CTRL); if (ret < 0) goto out; ret |= GPIO2_DIR_INPUT; if (enable) ret |= GPIO_CTRL_SLOTSELEN; else ret &= ~GPIO_CTRL_SLOTSELEN; ret = menelaus_write_reg(MENELAUS_GPIO_CTRL, ret); out: mutex_unlock(&the_menelaus->lock); return ret; } EXPORT_SYMBOL(menelaus_set_slot_sel); int menelaus_set_mmc_slot(int slot, int enable, int power, int cd_en) { int ret, val; if (slot != 1 && slot != 2) return -EINVAL; if (power >= 3) return -EINVAL; mutex_lock(&the_menelaus->lock); ret = menelaus_read_reg(MENELAUS_MCT_CTRL2); if (ret < 0) goto out; val = ret; if (slot == 1) { if (cd_en) val |= MCT_CTRL2_S1CD_BUFEN | MCT_CTRL2_S1CD_DBEN; else val &= ~(MCT_CTRL2_S1CD_BUFEN | MCT_CTRL2_S1CD_DBEN); } else { if (cd_en) val |= MCT_CTRL2_S2CD_BUFEN | MCT_CTRL2_S2CD_BEN; else val &= ~(MCT_CTRL2_S2CD_BUFEN | MCT_CTRL2_S2CD_BEN); } ret = menelaus_write_reg(MENELAUS_MCT_CTRL2, val); if (ret < 0) goto out; ret = menelaus_read_reg(MENELAUS_MCT_CTRL3); if (ret < 0) goto out; val = ret; if (slot == 1) { if (enable) val |= MCT_CTRL3_SLOT1_EN; else val &= ~MCT_CTRL3_SLOT1_EN; } else { int b; if (enable) val |= MCT_CTRL3_SLOT2_EN; else val &= ~MCT_CTRL3_SLOT2_EN; b = menelaus_read_reg(MENELAUS_MCT_CTRL2); b &= ~(MCT_CTRL2_VS2_SEL_D0 | MCT_CTRL2_VS2_SEL_D1); b |= power; ret = menelaus_write_reg(MENELAUS_MCT_CTRL2, b); if (ret < 0) goto out; } /* Disable autonomous shutdown */ val &= ~(MCT_CTRL3_S1_AUTO_EN | MCT_CTRL3_S2_AUTO_EN); ret = menelaus_write_reg(MENELAUS_MCT_CTRL3, val); out: mutex_unlock(&the_menelaus->lock); return ret; } EXPORT_SYMBOL(menelaus_set_mmc_slot); int menelaus_register_mmc_callback(void (*callback)(void *data, u8 card_mask), void *data) { int ret = 0; the_menelaus->mmc_callback_data = data; the_menelaus->mmc_callback = callback; ret = menelaus_add_irq_work(MENELAUS_MMC_S1CD_IRQ, menelaus_mmc_cd_work); if (ret < 0) return ret; ret = menelaus_add_irq_work(MENELAUS_MMC_S2CD_IRQ, menelaus_mmc_cd_work); if (ret < 0) return ret; ret = menelaus_add_irq_work(MENELAUS_MMC_S1D1_IRQ, menelaus_mmc_cd_work); if (ret < 0) return ret; ret = menelaus_add_irq_work(MENELAUS_MMC_S2D1_IRQ, menelaus_mmc_cd_work); return ret; } EXPORT_SYMBOL(menelaus_register_mmc_callback); void menelaus_unregister_mmc_callback(void) { menelaus_remove_irq_work(MENELAUS_MMC_S1CD_IRQ); menelaus_remove_irq_work(MENELAUS_MMC_S2CD_IRQ); menelaus_remove_irq_work(MENELAUS_MMC_S1D1_IRQ); menelaus_remove_irq_work(MENELAUS_MMC_S2D1_IRQ); the_menelaus->mmc_callback = NULL; the_menelaus->mmc_callback_data = 0; } EXPORT_SYMBOL(menelaus_unregister_mmc_callback); struct menelaus_vtg { const char *name; u8 vtg_reg; u8 vtg_shift; u8 vtg_bits; u8 mode_reg; }; struct menelaus_vtg_value { u16 vtg; u16 val; }; static int menelaus_set_voltage(const struct menelaus_vtg *vtg, int mV, int vtg_val, int mode) { int val, ret; struct i2c_client *c = the_menelaus->client; mutex_lock(&the_menelaus->lock); if (vtg == 0) goto set_voltage; ret = menelaus_read_reg(vtg->vtg_reg); if (ret < 0) goto out; val = ret & ~(((1 << vtg->vtg_bits) - 1) << vtg->vtg_shift); val |= vtg_val << vtg->vtg_shift; dev_dbg(&c->dev, "Setting voltage '%s'" "to %d mV (reg 0x%02x, val 0x%02x)\n", vtg->name, mV, vtg->vtg_reg, val); ret = menelaus_write_reg(vtg->vtg_reg, val); if (ret < 0) goto out; set_voltage: ret = menelaus_write_reg(vtg->mode_reg, mode); out: mutex_unlock(&the_menelaus->lock); if (ret == 0) { /* Wait for voltage to stabilize */ msleep(1); } return ret; } static int menelaus_get_vtg_value(int vtg, const struct menelaus_vtg_value *tbl, int n) { int i; for (i = 0; i < n; i++, tbl++) if (tbl->vtg == vtg) return tbl->val; return -EINVAL; } /* * Vcore can be programmed in two ways: * SW-controlled: Required voltage is programmed into VCORE_CTRL1 * HW-controlled: Required range (roof-floor) is programmed into VCORE_CTRL3 * and VCORE_CTRL4 * * Call correct 'set' function accordingly */ static const struct menelaus_vtg_value vcore_values[] = { { 1000, 0 }, { 1025, 1 }, { 1050, 2 }, { 1075, 3 }, { 1100, 4 }, { 1125, 5 }, { 1150, 6 }, { 1175, 7 }, { 1200, 8 }, { 1225, 9 }, { 1250, 10 }, { 1275, 11 }, { 1300, 12 }, { 1325, 13 }, { 1350, 14 }, { 1375, 15 }, { 1400, 16 }, { 1425, 17 }, { 1450, 18 }, }; int menelaus_set_vcore_sw(unsigned int mV) { int val, ret; struct i2c_client *c = the_menelaus->client; val = menelaus_get_vtg_value(mV, vcore_values, ARRAY_SIZE(vcore_values)); if (val < 0) return -EINVAL; dev_dbg(&c->dev, "Setting VCORE to %d mV (val 0x%02x)\n", mV, val); /* Set SW mode and the voltage in one go. */ mutex_lock(&the_menelaus->lock); ret = menelaus_write_reg(MENELAUS_VCORE_CTRL1, val); if (ret == 0) the_menelaus->vcore_hw_mode = 0; mutex_unlock(&the_menelaus->lock); msleep(1); return ret; } int menelaus_set_vcore_hw(unsigned int roof_mV, unsigned int floor_mV) { int fval, rval, val, ret; struct i2c_client *c = the_menelaus->client; rval = menelaus_get_vtg_value(roof_mV, vcore_values, ARRAY_SIZE(vcore_values)); if (rval < 0) return -EINVAL; fval = menelaus_get_vtg_value(floor_mV, vcore_values, ARRAY_SIZE(vcore_values)); if (fval < 0) return -EINVAL; dev_dbg(&c->dev, "Setting VCORE FLOOR to %d mV and ROOF to %d mV\n", floor_mV, roof_mV); mutex_lock(&the_menelaus->lock); ret = menelaus_write_reg(MENELAUS_VCORE_CTRL3, fval); if (ret < 0) goto out; ret = menelaus_write_reg(MENELAUS_VCORE_CTRL4, rval); if (ret < 0) goto out; if (!the_menelaus->vcore_hw_mode) { val = menelaus_read_reg(MENELAUS_VCORE_CTRL1); /* HW mode, turn OFF byte comparator */ val |= (VCORE_CTRL1_HW_NSW | VCORE_CTRL1_BYP_COMP); ret = menelaus_write_reg(MENELAUS_VCORE_CTRL1, val); the_menelaus->vcore_hw_mode = 1; } msleep(1); out: mutex_unlock(&the_menelaus->lock); return ret; } static const struct menelaus_vtg vmem_vtg = { .name = "VMEM", .vtg_reg = MENELAUS_LDO_CTRL1, .vtg_shift = 0, .vtg_bits = 2, .mode_reg = MENELAUS_LDO_CTRL3, }; static const struct menelaus_vtg_value vmem_values[] = { { 1500, 0 }, { 1800, 1 }, { 1900, 2 }, { 2500, 3 }, }; int menelaus_set_vmem(unsigned int mV) { int val; if (mV == 0) return menelaus_set_voltage(&vmem_vtg, 0, 0, 0); val = menelaus_get_vtg_value(mV, vmem_values, ARRAY_SIZE(vmem_values)); if (val < 0) return -EINVAL; return menelaus_set_voltage(&vmem_vtg, mV, val, 0x02); } EXPORT_SYMBOL(menelaus_set_vmem); static const struct menelaus_vtg vio_vtg = { .name = "VIO", .vtg_reg = MENELAUS_LDO_CTRL1, .vtg_shift = 2, .vtg_bits = 2, .mode_reg = MENELAUS_LDO_CTRL4, }; static const struct menelaus_vtg_value vio_values[] = { { 1500, 0 }, { 1800, 1 }, { 2500, 2 }, { 2800, 3 }, }; int menelaus_set_vio(unsigned int mV) { int val; if (mV == 0) return menelaus_set_voltage(&vio_vtg, 0, 0, 0); val = menelaus_get_vtg_value(mV, vio_values, ARRAY_SIZE(vio_values)); if (val < 0) return -EINVAL; return menelaus_set_voltage(&vio_vtg, mV, val, 0x02); } EXPORT_SYMBOL(menelaus_set_vio); static const struct menelaus_vtg_value vdcdc_values[] = { { 1500, 0 }, { 1800, 1 }, { 2000, 2 }, { 2200, 3 }, { 2400, 4 }, { 2800, 5 }, { 3000, 6 }, { 3300, 7 }, }; static const struct menelaus_vtg vdcdc2_vtg = { .name = "VDCDC2", .vtg_reg = MENELAUS_DCDC_CTRL1, .vtg_shift = 0, .vtg_bits = 3, .mode_reg = MENELAUS_DCDC_CTRL2, }; static const struct menelaus_vtg vdcdc3_vtg = { .name = "VDCDC3", .vtg_reg = MENELAUS_DCDC_CTRL1, .vtg_shift = 3, .vtg_bits = 3, .mode_reg = MENELAUS_DCDC_CTRL3, }; int menelaus_set_vdcdc(int dcdc, unsigned int mV) { const struct menelaus_vtg *vtg; int val; if (dcdc != 2 && dcdc != 3) return -EINVAL; if (dcdc == 2) vtg = &vdcdc2_vtg; else vtg = &vdcdc3_vtg; if (mV == 0) return menelaus_set_voltage(vtg, 0, 0, 0); val = menelaus_get_vtg_value(mV, vdcdc_values, ARRAY_SIZE(vdcdc_values)); if (val < 0) return -EINVAL; return menelaus_set_voltage(vtg, mV, val, 0x03); } static const struct menelaus_vtg_value vmmc_values[] = { { 1850, 0 }, { 2800, 1 }, { 3000, 2 }, { 3100, 3 }, }; static const struct menelaus_vtg vmmc_vtg = { .name = "VMMC", .vtg_reg = MENELAUS_LDO_CTRL1, .vtg_shift = 6, .vtg_bits = 2, .mode_reg = MENELAUS_LDO_CTRL7, }; int menelaus_set_vmmc(unsigned int mV) { int val; if (mV == 0) return menelaus_set_voltage(&vmmc_vtg, 0, 0, 0); val = menelaus_get_vtg_value(mV, vmmc_values, ARRAY_SIZE(vmmc_values)); if (val < 0) return -EINVAL; return menelaus_set_voltage(&vmmc_vtg, mV, val, 0x02); } EXPORT_SYMBOL(menelaus_set_vmmc); static const struct menelaus_vtg_value vaux_values[] = { { 1500, 0 }, { 1800, 1 }, { 2500, 2 }, { 2800, 3 }, }; static const struct menelaus_vtg vaux_vtg = { .name = "VAUX", .vtg_reg = MENELAUS_LDO_CTRL1, .vtg_shift = 4, .vtg_bits = 2, .mode_reg = MENELAUS_LDO_CTRL6, }; int menelaus_set_vaux(unsigned int mV) { int val; if (mV == 0) return menelaus_set_voltage(&vaux_vtg, 0, 0, 0); val = menelaus_get_vtg_value(mV, vaux_values, ARRAY_SIZE(vaux_values)); if (val < 0) return -EINVAL; return menelaus_set_voltage(&vaux_vtg, mV, val, 0x02); } EXPORT_SYMBOL(menelaus_set_vaux); int menelaus_get_slot_pin_states(void) { return menelaus_read_reg(MENELAUS_MCT_PIN_ST); } EXPORT_SYMBOL(menelaus_get_slot_pin_states); int menelaus_set_regulator_sleep(int enable, u32 val) { int t, ret; struct i2c_client *c = the_menelaus->client; mutex_lock(&the_menelaus->lock); ret = menelaus_write_reg(MENELAUS_SLEEP_CTRL2, val); if (ret < 0) goto out; dev_dbg(&c->dev, "regulator sleep configuration: %02x\n", val); ret = menelaus_read_reg(MENELAUS_GPIO_CTRL); if (ret < 0) goto out; t = (GPIO_CTRL_SLPCTLEN | GPIO3_DIR_INPUT); if (enable) ret |= t; else ret &= ~t; ret = menelaus_write_reg(MENELAUS_GPIO_CTRL, ret); out: mutex_unlock(&the_menelaus->lock); return ret; } /*-----------------------------------------------------------------------*/ /* Handles Menelaus interrupts. Does not run in interrupt context */ static void menelaus_work(struct work_struct *_menelaus) { struct menelaus_chip *menelaus = container_of(_menelaus, struct menelaus_chip, work); void (*handler)(struct menelaus_chip *menelaus); while (1) { unsigned isr; isr = (menelaus_read_reg(MENELAUS_INT_STATUS2) & ~menelaus->mask2) << 8; isr |= menelaus_read_reg(MENELAUS_INT_STATUS1) & ~menelaus->mask1; if (!isr) break; while (isr) { int irq = fls(isr) - 1; isr &= ~(1 << irq); mutex_lock(&menelaus->lock); menelaus_disable_irq(irq); menelaus_ack_irq(irq); handler = menelaus->handlers[irq]; if (handler) handler(menelaus); menelaus_enable_irq(irq); mutex_unlock(&menelaus->lock); } } enable_irq(menelaus->client->irq); } /* * We cannot use I2C in interrupt context, so we just schedule work. */ static irqreturn_t menelaus_irq(int irq, void *_menelaus) { struct menelaus_chip *menelaus = _menelaus; disable_irq_nosync(irq); (void)schedule_work(&menelaus->work); return IRQ_HANDLED; } /*-----------------------------------------------------------------------*/ /* * The RTC needs to be set once, then it runs on backup battery power. * It supports alarms, including system wake alarms (from some modes); * and 1/second IRQs if requested. */ #ifdef CONFIG_RTC_DRV_TWL92330 #define RTC_CTRL_RTC_EN (1 << 0) #define RTC_CTRL_AL_EN (1 << 1) #define RTC_CTRL_MODE12 (1 << 2) #define RTC_CTRL_EVERY_MASK (3 << 3) #define RTC_CTRL_EVERY_SEC (0 << 3) #define RTC_CTRL_EVERY_MIN (1 << 3) #define RTC_CTRL_EVERY_HR (2 << 3) #define RTC_CTRL_EVERY_DAY (3 << 3) #define RTC_UPDATE_EVERY 0x08 #define RTC_HR_PM (1 << 7) static void menelaus_to_time(char *regs, struct rtc_time *t) { t->tm_sec = bcd2bin(regs[0]); t->tm_min = bcd2bin(regs[1]); if (the_menelaus->rtc_control & RTC_CTRL_MODE12) { t->tm_hour = bcd2bin(regs[2] & 0x1f) - 1; if (regs[2] & RTC_HR_PM) t->tm_hour += 12; } else t->tm_hour = bcd2bin(regs[2] & 0x3f); t->tm_mday = bcd2bin(regs[3]); t->tm_mon = bcd2bin(regs[4]) - 1; t->tm_year = bcd2bin(regs[5]) + 100; } static int time_to_menelaus(struct rtc_time *t, int regnum) { int hour, status; status = menelaus_write_reg(regnum++, bin2bcd(t->tm_sec)); if (status < 0) goto fail; status = menelaus_write_reg(regnum++, bin2bcd(t->tm_min)); if (status < 0) goto fail; if (the_menelaus->rtc_control & RTC_CTRL_MODE12) { hour = t->tm_hour + 1; if (hour > 12) hour = RTC_HR_PM | bin2bcd(hour - 12); else hour = bin2bcd(hour); } else hour = bin2bcd(t->tm_hour); status = menelaus_write_reg(regnum++, hour); if (status < 0) goto fail; status = menelaus_write_reg(regnum++, bin2bcd(t->tm_mday)); if (status < 0) goto fail; status = menelaus_write_reg(regnum++, bin2bcd(t->tm_mon + 1)); if (status < 0) goto fail; status = menelaus_write_reg(regnum++, bin2bcd(t->tm_year - 100)); if (status < 0) goto fail; return 0; fail: dev_err(&the_menelaus->client->dev, "rtc write reg %02x, err %d\n", --regnum, status); return status; } static int menelaus_read_time(struct device *dev, struct rtc_time *t) { struct i2c_msg msg[2]; char regs[7]; int status; /* block read date and time registers */ regs[0] = MENELAUS_RTC_SEC; msg[0].addr = MENELAUS_I2C_ADDRESS; msg[0].flags = 0; msg[0].len = 1; msg[0].buf = regs; msg[1].addr = MENELAUS_I2C_ADDRESS; msg[1].flags = I2C_M_RD; msg[1].len = sizeof(regs); msg[1].buf = regs; status = i2c_transfer(the_menelaus->client->adapter, msg, 2); if (status != 2) { dev_err(dev, "%s error %d\n", "read", status); return -EIO; } menelaus_to_time(regs, t); t->tm_wday = bcd2bin(regs[6]); return 0; } static int menelaus_set_time(struct device *dev, struct rtc_time *t) { int status; /* write date and time registers */ status = time_to_menelaus(t, MENELAUS_RTC_SEC); if (status < 0) return status; status = menelaus_write_reg(MENELAUS_RTC_WKDAY, bin2bcd(t->tm_wday)); if (status < 0) { dev_err(&the_menelaus->client->dev, "rtc write reg %02x " "err %d\n", MENELAUS_RTC_WKDAY, status); return status; } /* now commit the write */ status = menelaus_write_reg(MENELAUS_RTC_UPDATE, RTC_UPDATE_EVERY); if (status < 0) dev_err(&the_menelaus->client->dev, "rtc commit time, err %d\n", status); return 0; } static int menelaus_read_alarm(struct device *dev, struct rtc_wkalrm *w) { struct i2c_msg msg[2]; char regs[6]; int status; /* block read alarm registers */ regs[0] = MENELAUS_RTC_AL_SEC; msg[0].addr = MENELAUS_I2C_ADDRESS; msg[0].flags = 0; msg[0].len = 1; msg[0].buf = regs; msg[1].addr = MENELAUS_I2C_ADDRESS; msg[1].flags = I2C_M_RD; msg[1].len = sizeof(regs); msg[1].buf = regs; status = i2c_transfer(the_menelaus->client->adapter, msg, 2); if (status != 2) { dev_err(dev, "%s error %d\n", "alarm read", status); return -EIO; } menelaus_to_time(regs, &w->time); w->enabled = !!(the_menelaus->rtc_control & RTC_CTRL_AL_EN); /* NOTE we *could* check if actually pending... */ w->pending = 0; return 0; } static int menelaus_set_alarm(struct device *dev, struct rtc_wkalrm *w) { int status; if (the_menelaus->client->irq <= 0 && w->enabled) return -ENODEV; /* clear previous alarm enable */ if (the_menelaus->rtc_control & RTC_CTRL_AL_EN) { the_menelaus->rtc_control &= ~RTC_CTRL_AL_EN; status = menelaus_write_reg(MENELAUS_RTC_CTRL, the_menelaus->rtc_control); if (status < 0) return status; } /* write alarm registers */ status = time_to_menelaus(&w->time, MENELAUS_RTC_AL_SEC); if (status < 0) return status; /* enable alarm if requested */ if (w->enabled) { the_menelaus->rtc_control |= RTC_CTRL_AL_EN; status = menelaus_write_reg(MENELAUS_RTC_CTRL, the_menelaus->rtc_control); } return status; } #ifdef CONFIG_RTC_INTF_DEV static void menelaus_rtc_update_work(struct menelaus_chip *m) { /* report 1/sec update */ local_irq_disable(); rtc_update_irq(m->rtc, 1, RTC_IRQF | RTC_UF); local_irq_enable(); } static int menelaus_ioctl(struct device *dev, unsigned cmd, unsigned long arg) { int status; if (the_menelaus->client->irq <= 0) return -ENOIOCTLCMD; switch (cmd) { /* alarm IRQ */ case RTC_AIE_ON: if (the_menelaus->rtc_control & RTC_CTRL_AL_EN) return 0; the_menelaus->rtc_control |= RTC_CTRL_AL_EN; break; case RTC_AIE_OFF: if (!(the_menelaus->rtc_control & RTC_CTRL_AL_EN)) return 0; the_menelaus->rtc_control &= ~RTC_CTRL_AL_EN; break; /* 1/second "update" IRQ */ case RTC_UIE_ON: if (the_menelaus->uie) return 0; status = menelaus_remove_irq_work(MENELAUS_RTCTMR_IRQ); status = menelaus_add_irq_work(MENELAUS_RTCTMR_IRQ, menelaus_rtc_update_work); if (status == 0) the_menelaus->uie = 1; return status; case RTC_UIE_OFF: if (!the_menelaus->uie) return 0; status = menelaus_remove_irq_work(MENELAUS_RTCTMR_IRQ); if (status == 0) the_menelaus->uie = 0; return status; default: return -ENOIOCTLCMD; } return menelaus_write_reg(MENELAUS_RTC_CTRL, the_menelaus->rtc_control); } #else #define menelaus_ioctl NULL #endif /* REVISIT no compensation register support ... */ static const struct rtc_class_ops menelaus_rtc_ops = { .ioctl = menelaus_ioctl, .read_time = menelaus_read_time, .set_time = menelaus_set_time, .read_alarm = menelaus_read_alarm, .set_alarm = menelaus_set_alarm, }; static void menelaus_rtc_alarm_work(struct menelaus_chip *m) { /* report alarm */ local_irq_disable(); rtc_update_irq(m->rtc, 1, RTC_IRQF | RTC_AF); local_irq_enable(); /* then disable it; alarms are oneshot */ the_menelaus->rtc_control &= ~RTC_CTRL_AL_EN; menelaus_write_reg(MENELAUS_RTC_CTRL, the_menelaus->rtc_control); } static inline void menelaus_rtc_init(struct menelaus_chip *m) { int alarm = (m->client->irq > 0); /* assume 32KDETEN pin is pulled high */ if (!(menelaus_read_reg(MENELAUS_OSC_CTRL) & 0x80)) { dev_dbg(&m->client->dev, "no 32k oscillator\n"); return; } /* support RTC alarm; it can issue wakeups */ if (alarm) { if (menelaus_add_irq_work(MENELAUS_RTCALM_IRQ, menelaus_rtc_alarm_work) < 0) { dev_err(&m->client->dev, "can't handle RTC alarm\n"); return; } device_init_wakeup(&m->client->dev, 1); } /* be sure RTC is enabled; allow 1/sec irqs; leave 12hr mode alone */ m->rtc_control = menelaus_read_reg(MENELAUS_RTC_CTRL); if (!(m->rtc_control & RTC_CTRL_RTC_EN) || (m->rtc_control & RTC_CTRL_AL_EN) || (m->rtc_control & RTC_CTRL_EVERY_MASK)) { if (!(m->rtc_control & RTC_CTRL_RTC_EN)) { dev_warn(&m->client->dev, "rtc clock needs setting\n"); m->rtc_control |= RTC_CTRL_RTC_EN; } m->rtc_control &= ~RTC_CTRL_EVERY_MASK; m->rtc_control &= ~RTC_CTRL_AL_EN; menelaus_write_reg(MENELAUS_RTC_CTRL, m->rtc_control); } m->rtc = rtc_device_register(DRIVER_NAME, &m->client->dev, &menelaus_rtc_ops, THIS_MODULE); if (IS_ERR(m->rtc)) { if (alarm) { menelaus_remove_irq_work(MENELAUS_RTCALM_IRQ); device_init_wakeup(&m->client->dev, 0); } dev_err(&m->client->dev, "can't register RTC: %d\n", (int) PTR_ERR(m->rtc)); the_menelaus->rtc = NULL; } } #else static inline void menelaus_rtc_init(struct menelaus_chip *m) { /* nothing */ } #endif /*-----------------------------------------------------------------------*/ static struct i2c_driver menelaus_i2c_driver; static int menelaus_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct menelaus_chip *menelaus; int rev = 0, val; int err = 0; struct menelaus_platform_data *menelaus_pdata = client->dev.platform_data; if (the_menelaus) { dev_dbg(&client->dev, "only one %s for now\n", DRIVER_NAME); return -ENODEV; } menelaus = kzalloc(sizeof *menelaus, GFP_KERNEL); if (!menelaus) return -ENOMEM; i2c_set_clientdata(client, menelaus); the_menelaus = menelaus; menelaus->client = client; /* If a true probe check the device */ rev = menelaus_read_reg(MENELAUS_REV); if (rev < 0) { pr_err(DRIVER_NAME ": device not found"); err = -ENODEV; goto fail1; } /* Ack and disable all Menelaus interrupts */ menelaus_write_reg(MENELAUS_INT_ACK1, 0xff); menelaus_write_reg(MENELAUS_INT_ACK2, 0xff); menelaus_write_reg(MENELAUS_INT_MASK1, 0xff); menelaus_write_reg(MENELAUS_INT_MASK2, 0xff); menelaus->mask1 = 0xff; menelaus->mask2 = 0xff; /* Set output buffer strengths */ menelaus_write_reg(MENELAUS_MCT_CTRL1, 0x73); if (client->irq > 0) { err = request_irq(client->irq, menelaus_irq, 0, DRIVER_NAME, menelaus); if (err) { dev_dbg(&client->dev, "can't get IRQ %d, err %d\n", client->irq, err); goto fail1; } } mutex_init(&menelaus->lock); INIT_WORK(&menelaus->work, menelaus_work); pr_info("Menelaus rev %d.%d\n", rev >> 4, rev & 0x0f); val = menelaus_read_reg(MENELAUS_VCORE_CTRL1); if (val < 0) goto fail2; if (val & (1 << 7)) menelaus->vcore_hw_mode = 1; else menelaus->vcore_hw_mode = 0; if (menelaus_pdata != NULL && menelaus_pdata->late_init != NULL) { err = menelaus_pdata->late_init(&client->dev); if (err < 0) goto fail2; } menelaus_rtc_init(menelaus); return 0; fail2: free_irq(client->irq, menelaus); flush_work_sync(&menelaus->work); fail1: kfree(menelaus); return err; } static int __exit menelaus_remove(struct i2c_client *client) { struct menelaus_chip *menelaus = i2c_get_clientdata(client); free_irq(client->irq, menelaus); flush_work_sync(&menelaus->work); kfree(menelaus); the_menelaus = NULL; return 0; } static const struct i2c_device_id menelaus_id[] = { { "menelaus", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, menelaus_id); static struct i2c_driver menelaus_i2c_driver = { .driver = { .name = DRIVER_NAME, }, .probe = menelaus_probe, .remove = __exit_p(menelaus_remove), .id_table = menelaus_id, }; static int __init menelaus_init(void) { int res; res = i2c_add_driver(&menelaus_i2c_driver); if (res < 0) { pr_err(DRIVER_NAME ": driver registration failed\n"); return res; } return 0; } static void __exit menelaus_exit(void) { i2c_del_driver(&menelaus_i2c_driver); /* FIXME: Shutdown menelaus parts that can be shut down */ } MODULE_AUTHOR("Texas Instruments, Inc. (and others)"); MODULE_DESCRIPTION("I2C interface for Menelaus."); MODULE_LICENSE("GPL"); module_init(menelaus_init); module_exit(menelaus_exit);
gpl-2.0
SlimRoms/kernel_motorola_shamu
arch/sparc/kernel/viohs.c
7457
18129
/* viohs.c: LDOM Virtual I/O handshake helper layer. * * Copyright (C) 2007 David S. Miller <davem@davemloft.net> */ #include <linux/kernel.h> #include <linux/export.h> #include <linux/string.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/slab.h> #include <asm/ldc.h> #include <asm/vio.h> int vio_ldc_send(struct vio_driver_state *vio, void *data, int len) { int err, limit = 1000; err = -EINVAL; while (limit-- > 0) { err = ldc_write(vio->lp, data, len); if (!err || (err != -EAGAIN)) break; udelay(1); } return err; } EXPORT_SYMBOL(vio_ldc_send); static int send_ctrl(struct vio_driver_state *vio, struct vio_msg_tag *tag, int len) { tag->sid = vio_send_sid(vio); return vio_ldc_send(vio, tag, len); } static void init_tag(struct vio_msg_tag *tag, u8 type, u8 stype, u16 stype_env) { tag->type = type; tag->stype = stype; tag->stype_env = stype_env; } static int send_version(struct vio_driver_state *vio, u16 major, u16 minor) { struct vio_ver_info pkt; vio->_local_sid = (u32) sched_clock(); memset(&pkt, 0, sizeof(pkt)); init_tag(&pkt.tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO, VIO_VER_INFO); pkt.major = major; pkt.minor = minor; pkt.dev_class = vio->dev_class; viodbg(HS, "SEND VERSION INFO maj[%u] min[%u] devclass[%u]\n", major, minor, vio->dev_class); return send_ctrl(vio, &pkt.tag, sizeof(pkt)); } static int start_handshake(struct vio_driver_state *vio) { int err; viodbg(HS, "START HANDSHAKE\n"); vio->hs_state = VIO_HS_INVALID; err = send_version(vio, vio->ver_table[0].major, vio->ver_table[0].minor); if (err < 0) return err; return 0; } static void flush_rx_dring(struct vio_driver_state *vio) { struct vio_dring_state *dr; u64 ident; BUG_ON(!(vio->dr_state & VIO_DR_STATE_RXREG)); dr = &vio->drings[VIO_DRIVER_RX_RING]; ident = dr->ident; BUG_ON(!vio->desc_buf); kfree(vio->desc_buf); vio->desc_buf = NULL; memset(dr, 0, sizeof(*dr)); dr->ident = ident; } void vio_link_state_change(struct vio_driver_state *vio, int event) { if (event == LDC_EVENT_UP) { vio->hs_state = VIO_HS_INVALID; switch (vio->dev_class) { case VDEV_NETWORK: case VDEV_NETWORK_SWITCH: vio->dr_state = (VIO_DR_STATE_TXREQ | VIO_DR_STATE_RXREQ); break; case VDEV_DISK: vio->dr_state = VIO_DR_STATE_TXREQ; break; case VDEV_DISK_SERVER: vio->dr_state = VIO_DR_STATE_RXREQ; break; } start_handshake(vio); } else if (event == LDC_EVENT_RESET) { vio->hs_state = VIO_HS_INVALID; if (vio->dr_state & VIO_DR_STATE_RXREG) flush_rx_dring(vio); vio->dr_state = 0x00; memset(&vio->ver, 0, sizeof(vio->ver)); ldc_disconnect(vio->lp); } } EXPORT_SYMBOL(vio_link_state_change); static int handshake_failure(struct vio_driver_state *vio) { struct vio_dring_state *dr; /* XXX Put policy here... Perhaps start a timer to fire * XXX in 100 ms, which will bring the link up and retry * XXX the handshake. */ viodbg(HS, "HANDSHAKE FAILURE\n"); vio->dr_state &= ~(VIO_DR_STATE_TXREG | VIO_DR_STATE_RXREG); dr = &vio->drings[VIO_DRIVER_RX_RING]; memset(dr, 0, sizeof(*dr)); kfree(vio->desc_buf); vio->desc_buf = NULL; vio->desc_buf_len = 0; vio->hs_state = VIO_HS_INVALID; return -ECONNRESET; } static int process_unknown(struct vio_driver_state *vio, void *arg) { struct vio_msg_tag *pkt = arg; viodbg(HS, "UNKNOWN CONTROL [%02x:%02x:%04x:%08x]\n", pkt->type, pkt->stype, pkt->stype_env, pkt->sid); printk(KERN_ERR "vio: ID[%lu] Resetting connection.\n", vio->vdev->channel_id); ldc_disconnect(vio->lp); return -ECONNRESET; } static int send_dreg(struct vio_driver_state *vio) { struct vio_dring_state *dr = &vio->drings[VIO_DRIVER_TX_RING]; union { struct vio_dring_register pkt; char all[sizeof(struct vio_dring_register) + (sizeof(struct ldc_trans_cookie) * dr->ncookies)]; } u; int i; memset(&u, 0, sizeof(u)); init_tag(&u.pkt.tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO, VIO_DRING_REG); u.pkt.dring_ident = 0; u.pkt.num_descr = dr->num_entries; u.pkt.descr_size = dr->entry_size; u.pkt.options = VIO_TX_DRING; u.pkt.num_cookies = dr->ncookies; viodbg(HS, "SEND DRING_REG INFO ndesc[%u] dsz[%u] opt[0x%x] " "ncookies[%u]\n", u.pkt.num_descr, u.pkt.descr_size, u.pkt.options, u.pkt.num_cookies); for (i = 0; i < dr->ncookies; i++) { u.pkt.cookies[i] = dr->cookies[i]; viodbg(HS, "DRING COOKIE(%d) [%016llx:%016llx]\n", i, (unsigned long long) u.pkt.cookies[i].cookie_addr, (unsigned long long) u.pkt.cookies[i].cookie_size); } return send_ctrl(vio, &u.pkt.tag, sizeof(u)); } static int send_rdx(struct vio_driver_state *vio) { struct vio_rdx pkt; memset(&pkt, 0, sizeof(pkt)); init_tag(&pkt.tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO, VIO_RDX); viodbg(HS, "SEND RDX INFO\n"); return send_ctrl(vio, &pkt.tag, sizeof(pkt)); } static int send_attr(struct vio_driver_state *vio) { return vio->ops->send_attr(vio); } static struct vio_version *find_by_major(struct vio_driver_state *vio, u16 major) { struct vio_version *ret = NULL; int i; for (i = 0; i < vio->ver_table_entries; i++) { struct vio_version *v = &vio->ver_table[i]; if (v->major <= major) { ret = v; break; } } return ret; } static int process_ver_info(struct vio_driver_state *vio, struct vio_ver_info *pkt) { struct vio_version *vap; int err; viodbg(HS, "GOT VERSION INFO maj[%u] min[%u] devclass[%u]\n", pkt->major, pkt->minor, pkt->dev_class); if (vio->hs_state != VIO_HS_INVALID) { /* XXX Perhaps invoke start_handshake? XXX */ memset(&vio->ver, 0, sizeof(vio->ver)); vio->hs_state = VIO_HS_INVALID; } vap = find_by_major(vio, pkt->major); vio->_peer_sid = pkt->tag.sid; if (!vap) { pkt->tag.stype = VIO_SUBTYPE_NACK; pkt->major = 0; pkt->minor = 0; viodbg(HS, "SEND VERSION NACK maj[0] min[0]\n"); err = send_ctrl(vio, &pkt->tag, sizeof(*pkt)); } else if (vap->major != pkt->major) { pkt->tag.stype = VIO_SUBTYPE_NACK; pkt->major = vap->major; pkt->minor = vap->minor; viodbg(HS, "SEND VERSION NACK maj[%u] min[%u]\n", pkt->major, pkt->minor); err = send_ctrl(vio, &pkt->tag, sizeof(*pkt)); } else { struct vio_version ver = { .major = pkt->major, .minor = pkt->minor, }; if (ver.minor > vap->minor) ver.minor = vap->minor; pkt->minor = ver.minor; pkt->tag.stype = VIO_SUBTYPE_ACK; viodbg(HS, "SEND VERSION ACK maj[%u] min[%u]\n", pkt->major, pkt->minor); err = send_ctrl(vio, &pkt->tag, sizeof(*pkt)); if (err > 0) { vio->ver = ver; vio->hs_state = VIO_HS_GOTVERS; } } if (err < 0) return handshake_failure(vio); return 0; } static int process_ver_ack(struct vio_driver_state *vio, struct vio_ver_info *pkt) { viodbg(HS, "GOT VERSION ACK maj[%u] min[%u] devclass[%u]\n", pkt->major, pkt->minor, pkt->dev_class); if (vio->hs_state & VIO_HS_GOTVERS) { if (vio->ver.major != pkt->major || vio->ver.minor != pkt->minor) { pkt->tag.stype = VIO_SUBTYPE_NACK; (void) send_ctrl(vio, &pkt->tag, sizeof(*pkt)); return handshake_failure(vio); } } else { vio->ver.major = pkt->major; vio->ver.minor = pkt->minor; vio->hs_state = VIO_HS_GOTVERS; } switch (vio->dev_class) { case VDEV_NETWORK: case VDEV_DISK: if (send_attr(vio) < 0) return handshake_failure(vio); break; default: break; } return 0; } static int process_ver_nack(struct vio_driver_state *vio, struct vio_ver_info *pkt) { struct vio_version *nver; viodbg(HS, "GOT VERSION NACK maj[%u] min[%u] devclass[%u]\n", pkt->major, pkt->minor, pkt->dev_class); if (pkt->major == 0 && pkt->minor == 0) return handshake_failure(vio); nver = find_by_major(vio, pkt->major); if (!nver) return handshake_failure(vio); if (send_version(vio, nver->major, nver->minor) < 0) return handshake_failure(vio); return 0; } static int process_ver(struct vio_driver_state *vio, struct vio_ver_info *pkt) { switch (pkt->tag.stype) { case VIO_SUBTYPE_INFO: return process_ver_info(vio, pkt); case VIO_SUBTYPE_ACK: return process_ver_ack(vio, pkt); case VIO_SUBTYPE_NACK: return process_ver_nack(vio, pkt); default: return handshake_failure(vio); } } static int process_attr(struct vio_driver_state *vio, void *pkt) { int err; if (!(vio->hs_state & VIO_HS_GOTVERS)) return handshake_failure(vio); err = vio->ops->handle_attr(vio, pkt); if (err < 0) { return handshake_failure(vio); } else { vio->hs_state |= VIO_HS_GOT_ATTR; if ((vio->dr_state & VIO_DR_STATE_TXREQ) && !(vio->hs_state & VIO_HS_SENT_DREG)) { if (send_dreg(vio) < 0) return handshake_failure(vio); vio->hs_state |= VIO_HS_SENT_DREG; } } return 0; } static int all_drings_registered(struct vio_driver_state *vio) { int need_rx, need_tx; need_rx = (vio->dr_state & VIO_DR_STATE_RXREQ); need_tx = (vio->dr_state & VIO_DR_STATE_TXREQ); if (need_rx && !(vio->dr_state & VIO_DR_STATE_RXREG)) return 0; if (need_tx && !(vio->dr_state & VIO_DR_STATE_TXREG)) return 0; return 1; } static int process_dreg_info(struct vio_driver_state *vio, struct vio_dring_register *pkt) { struct vio_dring_state *dr; int i, len; viodbg(HS, "GOT DRING_REG INFO ident[%llx] " "ndesc[%u] dsz[%u] opt[0x%x] ncookies[%u]\n", (unsigned long long) pkt->dring_ident, pkt->num_descr, pkt->descr_size, pkt->options, pkt->num_cookies); if (!(vio->dr_state & VIO_DR_STATE_RXREQ)) goto send_nack; if (vio->dr_state & VIO_DR_STATE_RXREG) goto send_nack; BUG_ON(vio->desc_buf); vio->desc_buf = kzalloc(pkt->descr_size, GFP_ATOMIC); if (!vio->desc_buf) goto send_nack; vio->desc_buf_len = pkt->descr_size; dr = &vio->drings[VIO_DRIVER_RX_RING]; dr->num_entries = pkt->num_descr; dr->entry_size = pkt->descr_size; dr->ncookies = pkt->num_cookies; for (i = 0; i < dr->ncookies; i++) { dr->cookies[i] = pkt->cookies[i]; viodbg(HS, "DRING COOKIE(%d) [%016llx:%016llx]\n", i, (unsigned long long) pkt->cookies[i].cookie_addr, (unsigned long long) pkt->cookies[i].cookie_size); } pkt->tag.stype = VIO_SUBTYPE_ACK; pkt->dring_ident = ++dr->ident; viodbg(HS, "SEND DRING_REG ACK ident[%llx]\n", (unsigned long long) pkt->dring_ident); len = (sizeof(*pkt) + (dr->ncookies * sizeof(struct ldc_trans_cookie))); if (send_ctrl(vio, &pkt->tag, len) < 0) goto send_nack; vio->dr_state |= VIO_DR_STATE_RXREG; return 0; send_nack: pkt->tag.stype = VIO_SUBTYPE_NACK; viodbg(HS, "SEND DRING_REG NACK\n"); (void) send_ctrl(vio, &pkt->tag, sizeof(*pkt)); return handshake_failure(vio); } static int process_dreg_ack(struct vio_driver_state *vio, struct vio_dring_register *pkt) { struct vio_dring_state *dr; viodbg(HS, "GOT DRING_REG ACK ident[%llx] " "ndesc[%u] dsz[%u] opt[0x%x] ncookies[%u]\n", (unsigned long long) pkt->dring_ident, pkt->num_descr, pkt->descr_size, pkt->options, pkt->num_cookies); dr = &vio->drings[VIO_DRIVER_TX_RING]; if (!(vio->dr_state & VIO_DR_STATE_TXREQ)) return handshake_failure(vio); dr->ident = pkt->dring_ident; vio->dr_state |= VIO_DR_STATE_TXREG; if (all_drings_registered(vio)) { if (send_rdx(vio) < 0) return handshake_failure(vio); vio->hs_state = VIO_HS_SENT_RDX; } return 0; } static int process_dreg_nack(struct vio_driver_state *vio, struct vio_dring_register *pkt) { viodbg(HS, "GOT DRING_REG NACK ident[%llx] " "ndesc[%u] dsz[%u] opt[0x%x] ncookies[%u]\n", (unsigned long long) pkt->dring_ident, pkt->num_descr, pkt->descr_size, pkt->options, pkt->num_cookies); return handshake_failure(vio); } static int process_dreg(struct vio_driver_state *vio, struct vio_dring_register *pkt) { if (!(vio->hs_state & VIO_HS_GOTVERS)) return handshake_failure(vio); switch (pkt->tag.stype) { case VIO_SUBTYPE_INFO: return process_dreg_info(vio, pkt); case VIO_SUBTYPE_ACK: return process_dreg_ack(vio, pkt); case VIO_SUBTYPE_NACK: return process_dreg_nack(vio, pkt); default: return handshake_failure(vio); } } static int process_dunreg(struct vio_driver_state *vio, struct vio_dring_unregister *pkt) { struct vio_dring_state *dr = &vio->drings[VIO_DRIVER_RX_RING]; viodbg(HS, "GOT DRING_UNREG\n"); if (pkt->dring_ident != dr->ident) return 0; vio->dr_state &= ~VIO_DR_STATE_RXREG; memset(dr, 0, sizeof(*dr)); kfree(vio->desc_buf); vio->desc_buf = NULL; vio->desc_buf_len = 0; return 0; } static int process_rdx_info(struct vio_driver_state *vio, struct vio_rdx *pkt) { viodbg(HS, "GOT RDX INFO\n"); pkt->tag.stype = VIO_SUBTYPE_ACK; viodbg(HS, "SEND RDX ACK\n"); if (send_ctrl(vio, &pkt->tag, sizeof(*pkt)) < 0) return handshake_failure(vio); vio->hs_state |= VIO_HS_SENT_RDX_ACK; return 0; } static int process_rdx_ack(struct vio_driver_state *vio, struct vio_rdx *pkt) { viodbg(HS, "GOT RDX ACK\n"); if (!(vio->hs_state & VIO_HS_SENT_RDX)) return handshake_failure(vio); vio->hs_state |= VIO_HS_GOT_RDX_ACK; return 0; } static int process_rdx_nack(struct vio_driver_state *vio, struct vio_rdx *pkt) { viodbg(HS, "GOT RDX NACK\n"); return handshake_failure(vio); } static int process_rdx(struct vio_driver_state *vio, struct vio_rdx *pkt) { if (!all_drings_registered(vio)) handshake_failure(vio); switch (pkt->tag.stype) { case VIO_SUBTYPE_INFO: return process_rdx_info(vio, pkt); case VIO_SUBTYPE_ACK: return process_rdx_ack(vio, pkt); case VIO_SUBTYPE_NACK: return process_rdx_nack(vio, pkt); default: return handshake_failure(vio); } } int vio_control_pkt_engine(struct vio_driver_state *vio, void *pkt) { struct vio_msg_tag *tag = pkt; u8 prev_state = vio->hs_state; int err; switch (tag->stype_env) { case VIO_VER_INFO: err = process_ver(vio, pkt); break; case VIO_ATTR_INFO: err = process_attr(vio, pkt); break; case VIO_DRING_REG: err = process_dreg(vio, pkt); break; case VIO_DRING_UNREG: err = process_dunreg(vio, pkt); break; case VIO_RDX: err = process_rdx(vio, pkt); break; default: err = process_unknown(vio, pkt); break; } if (!err && vio->hs_state != prev_state && (vio->hs_state & VIO_HS_COMPLETE)) vio->ops->handshake_complete(vio); return err; } EXPORT_SYMBOL(vio_control_pkt_engine); void vio_conn_reset(struct vio_driver_state *vio) { } EXPORT_SYMBOL(vio_conn_reset); /* The issue is that the Solaris virtual disk server just mirrors the * SID values it gets from the client peer. So we work around that * here in vio_{validate,send}_sid() so that the drivers don't need * to be aware of this crap. */ int vio_validate_sid(struct vio_driver_state *vio, struct vio_msg_tag *tp) { u32 sid; /* Always let VERSION+INFO packets through unchecked, they * define the new SID. */ if (tp->type == VIO_TYPE_CTRL && tp->stype == VIO_SUBTYPE_INFO && tp->stype_env == VIO_VER_INFO) return 0; /* Ok, now figure out which SID to use. */ switch (vio->dev_class) { case VDEV_NETWORK: case VDEV_NETWORK_SWITCH: case VDEV_DISK_SERVER: default: sid = vio->_peer_sid; break; case VDEV_DISK: sid = vio->_local_sid; break; } if (sid == tp->sid) return 0; viodbg(DATA, "BAD SID tag->sid[%08x] peer_sid[%08x] local_sid[%08x]\n", tp->sid, vio->_peer_sid, vio->_local_sid); return -EINVAL; } EXPORT_SYMBOL(vio_validate_sid); u32 vio_send_sid(struct vio_driver_state *vio) { switch (vio->dev_class) { case VDEV_NETWORK: case VDEV_NETWORK_SWITCH: case VDEV_DISK: default: return vio->_local_sid; case VDEV_DISK_SERVER: return vio->_peer_sid; } } EXPORT_SYMBOL(vio_send_sid); int vio_ldc_alloc(struct vio_driver_state *vio, struct ldc_channel_config *base_cfg, void *event_arg) { struct ldc_channel_config cfg = *base_cfg; struct ldc_channel *lp; cfg.tx_irq = vio->vdev->tx_irq; cfg.rx_irq = vio->vdev->rx_irq; lp = ldc_alloc(vio->vdev->channel_id, &cfg, event_arg); if (IS_ERR(lp)) return PTR_ERR(lp); vio->lp = lp; return 0; } EXPORT_SYMBOL(vio_ldc_alloc); void vio_ldc_free(struct vio_driver_state *vio) { ldc_free(vio->lp); vio->lp = NULL; kfree(vio->desc_buf); vio->desc_buf = NULL; vio->desc_buf_len = 0; } EXPORT_SYMBOL(vio_ldc_free); void vio_port_up(struct vio_driver_state *vio) { unsigned long flags; int err, state; spin_lock_irqsave(&vio->lock, flags); state = ldc_state(vio->lp); err = 0; if (state == LDC_STATE_INIT) { err = ldc_bind(vio->lp, vio->name); if (err) printk(KERN_WARNING "%s: Port %lu bind failed, " "err=%d\n", vio->name, vio->vdev->channel_id, err); } if (!err) { err = ldc_connect(vio->lp); if (err) printk(KERN_WARNING "%s: Port %lu connect failed, " "err=%d\n", vio->name, vio->vdev->channel_id, err); } if (err) { unsigned long expires = jiffies + HZ; expires = round_jiffies(expires); mod_timer(&vio->timer, expires); } spin_unlock_irqrestore(&vio->lock, flags); } EXPORT_SYMBOL(vio_port_up); static void vio_port_timer(unsigned long _arg) { struct vio_driver_state *vio = (struct vio_driver_state *) _arg; vio_port_up(vio); } int vio_driver_init(struct vio_driver_state *vio, struct vio_dev *vdev, u8 dev_class, struct vio_version *ver_table, int ver_table_size, struct vio_driver_ops *ops, char *name) { switch (dev_class) { case VDEV_NETWORK: case VDEV_NETWORK_SWITCH: case VDEV_DISK: case VDEV_DISK_SERVER: break; default: return -EINVAL; } if (!ops->send_attr || !ops->handle_attr || !ops->handshake_complete) return -EINVAL; if (!ver_table || ver_table_size < 0) return -EINVAL; if (!name) return -EINVAL; spin_lock_init(&vio->lock); vio->name = name; vio->dev_class = dev_class; vio->vdev = vdev; vio->ver_table = ver_table; vio->ver_table_entries = ver_table_size; vio->ops = ops; setup_timer(&vio->timer, vio_port_timer, (unsigned long) vio); return 0; } EXPORT_SYMBOL(vio_driver_init);
gpl-2.0
wzhy90/Huawei_Watch_Kernel
arch/sparc/kernel/viohs.c
7457
18129
/* viohs.c: LDOM Virtual I/O handshake helper layer. * * Copyright (C) 2007 David S. Miller <davem@davemloft.net> */ #include <linux/kernel.h> #include <linux/export.h> #include <linux/string.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/slab.h> #include <asm/ldc.h> #include <asm/vio.h> int vio_ldc_send(struct vio_driver_state *vio, void *data, int len) { int err, limit = 1000; err = -EINVAL; while (limit-- > 0) { err = ldc_write(vio->lp, data, len); if (!err || (err != -EAGAIN)) break; udelay(1); } return err; } EXPORT_SYMBOL(vio_ldc_send); static int send_ctrl(struct vio_driver_state *vio, struct vio_msg_tag *tag, int len) { tag->sid = vio_send_sid(vio); return vio_ldc_send(vio, tag, len); } static void init_tag(struct vio_msg_tag *tag, u8 type, u8 stype, u16 stype_env) { tag->type = type; tag->stype = stype; tag->stype_env = stype_env; } static int send_version(struct vio_driver_state *vio, u16 major, u16 minor) { struct vio_ver_info pkt; vio->_local_sid = (u32) sched_clock(); memset(&pkt, 0, sizeof(pkt)); init_tag(&pkt.tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO, VIO_VER_INFO); pkt.major = major; pkt.minor = minor; pkt.dev_class = vio->dev_class; viodbg(HS, "SEND VERSION INFO maj[%u] min[%u] devclass[%u]\n", major, minor, vio->dev_class); return send_ctrl(vio, &pkt.tag, sizeof(pkt)); } static int start_handshake(struct vio_driver_state *vio) { int err; viodbg(HS, "START HANDSHAKE\n"); vio->hs_state = VIO_HS_INVALID; err = send_version(vio, vio->ver_table[0].major, vio->ver_table[0].minor); if (err < 0) return err; return 0; } static void flush_rx_dring(struct vio_driver_state *vio) { struct vio_dring_state *dr; u64 ident; BUG_ON(!(vio->dr_state & VIO_DR_STATE_RXREG)); dr = &vio->drings[VIO_DRIVER_RX_RING]; ident = dr->ident; BUG_ON(!vio->desc_buf); kfree(vio->desc_buf); vio->desc_buf = NULL; memset(dr, 0, sizeof(*dr)); dr->ident = ident; } void vio_link_state_change(struct vio_driver_state *vio, int event) { if (event == LDC_EVENT_UP) { vio->hs_state = VIO_HS_INVALID; switch (vio->dev_class) { case VDEV_NETWORK: case VDEV_NETWORK_SWITCH: vio->dr_state = (VIO_DR_STATE_TXREQ | VIO_DR_STATE_RXREQ); break; case VDEV_DISK: vio->dr_state = VIO_DR_STATE_TXREQ; break; case VDEV_DISK_SERVER: vio->dr_state = VIO_DR_STATE_RXREQ; break; } start_handshake(vio); } else if (event == LDC_EVENT_RESET) { vio->hs_state = VIO_HS_INVALID; if (vio->dr_state & VIO_DR_STATE_RXREG) flush_rx_dring(vio); vio->dr_state = 0x00; memset(&vio->ver, 0, sizeof(vio->ver)); ldc_disconnect(vio->lp); } } EXPORT_SYMBOL(vio_link_state_change); static int handshake_failure(struct vio_driver_state *vio) { struct vio_dring_state *dr; /* XXX Put policy here... Perhaps start a timer to fire * XXX in 100 ms, which will bring the link up and retry * XXX the handshake. */ viodbg(HS, "HANDSHAKE FAILURE\n"); vio->dr_state &= ~(VIO_DR_STATE_TXREG | VIO_DR_STATE_RXREG); dr = &vio->drings[VIO_DRIVER_RX_RING]; memset(dr, 0, sizeof(*dr)); kfree(vio->desc_buf); vio->desc_buf = NULL; vio->desc_buf_len = 0; vio->hs_state = VIO_HS_INVALID; return -ECONNRESET; } static int process_unknown(struct vio_driver_state *vio, void *arg) { struct vio_msg_tag *pkt = arg; viodbg(HS, "UNKNOWN CONTROL [%02x:%02x:%04x:%08x]\n", pkt->type, pkt->stype, pkt->stype_env, pkt->sid); printk(KERN_ERR "vio: ID[%lu] Resetting connection.\n", vio->vdev->channel_id); ldc_disconnect(vio->lp); return -ECONNRESET; } static int send_dreg(struct vio_driver_state *vio) { struct vio_dring_state *dr = &vio->drings[VIO_DRIVER_TX_RING]; union { struct vio_dring_register pkt; char all[sizeof(struct vio_dring_register) + (sizeof(struct ldc_trans_cookie) * dr->ncookies)]; } u; int i; memset(&u, 0, sizeof(u)); init_tag(&u.pkt.tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO, VIO_DRING_REG); u.pkt.dring_ident = 0; u.pkt.num_descr = dr->num_entries; u.pkt.descr_size = dr->entry_size; u.pkt.options = VIO_TX_DRING; u.pkt.num_cookies = dr->ncookies; viodbg(HS, "SEND DRING_REG INFO ndesc[%u] dsz[%u] opt[0x%x] " "ncookies[%u]\n", u.pkt.num_descr, u.pkt.descr_size, u.pkt.options, u.pkt.num_cookies); for (i = 0; i < dr->ncookies; i++) { u.pkt.cookies[i] = dr->cookies[i]; viodbg(HS, "DRING COOKIE(%d) [%016llx:%016llx]\n", i, (unsigned long long) u.pkt.cookies[i].cookie_addr, (unsigned long long) u.pkt.cookies[i].cookie_size); } return send_ctrl(vio, &u.pkt.tag, sizeof(u)); } static int send_rdx(struct vio_driver_state *vio) { struct vio_rdx pkt; memset(&pkt, 0, sizeof(pkt)); init_tag(&pkt.tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO, VIO_RDX); viodbg(HS, "SEND RDX INFO\n"); return send_ctrl(vio, &pkt.tag, sizeof(pkt)); } static int send_attr(struct vio_driver_state *vio) { return vio->ops->send_attr(vio); } static struct vio_version *find_by_major(struct vio_driver_state *vio, u16 major) { struct vio_version *ret = NULL; int i; for (i = 0; i < vio->ver_table_entries; i++) { struct vio_version *v = &vio->ver_table[i]; if (v->major <= major) { ret = v; break; } } return ret; } static int process_ver_info(struct vio_driver_state *vio, struct vio_ver_info *pkt) { struct vio_version *vap; int err; viodbg(HS, "GOT VERSION INFO maj[%u] min[%u] devclass[%u]\n", pkt->major, pkt->minor, pkt->dev_class); if (vio->hs_state != VIO_HS_INVALID) { /* XXX Perhaps invoke start_handshake? XXX */ memset(&vio->ver, 0, sizeof(vio->ver)); vio->hs_state = VIO_HS_INVALID; } vap = find_by_major(vio, pkt->major); vio->_peer_sid = pkt->tag.sid; if (!vap) { pkt->tag.stype = VIO_SUBTYPE_NACK; pkt->major = 0; pkt->minor = 0; viodbg(HS, "SEND VERSION NACK maj[0] min[0]\n"); err = send_ctrl(vio, &pkt->tag, sizeof(*pkt)); } else if (vap->major != pkt->major) { pkt->tag.stype = VIO_SUBTYPE_NACK; pkt->major = vap->major; pkt->minor = vap->minor; viodbg(HS, "SEND VERSION NACK maj[%u] min[%u]\n", pkt->major, pkt->minor); err = send_ctrl(vio, &pkt->tag, sizeof(*pkt)); } else { struct vio_version ver = { .major = pkt->major, .minor = pkt->minor, }; if (ver.minor > vap->minor) ver.minor = vap->minor; pkt->minor = ver.minor; pkt->tag.stype = VIO_SUBTYPE_ACK; viodbg(HS, "SEND VERSION ACK maj[%u] min[%u]\n", pkt->major, pkt->minor); err = send_ctrl(vio, &pkt->tag, sizeof(*pkt)); if (err > 0) { vio->ver = ver; vio->hs_state = VIO_HS_GOTVERS; } } if (err < 0) return handshake_failure(vio); return 0; } static int process_ver_ack(struct vio_driver_state *vio, struct vio_ver_info *pkt) { viodbg(HS, "GOT VERSION ACK maj[%u] min[%u] devclass[%u]\n", pkt->major, pkt->minor, pkt->dev_class); if (vio->hs_state & VIO_HS_GOTVERS) { if (vio->ver.major != pkt->major || vio->ver.minor != pkt->minor) { pkt->tag.stype = VIO_SUBTYPE_NACK; (void) send_ctrl(vio, &pkt->tag, sizeof(*pkt)); return handshake_failure(vio); } } else { vio->ver.major = pkt->major; vio->ver.minor = pkt->minor; vio->hs_state = VIO_HS_GOTVERS; } switch (vio->dev_class) { case VDEV_NETWORK: case VDEV_DISK: if (send_attr(vio) < 0) return handshake_failure(vio); break; default: break; } return 0; } static int process_ver_nack(struct vio_driver_state *vio, struct vio_ver_info *pkt) { struct vio_version *nver; viodbg(HS, "GOT VERSION NACK maj[%u] min[%u] devclass[%u]\n", pkt->major, pkt->minor, pkt->dev_class); if (pkt->major == 0 && pkt->minor == 0) return handshake_failure(vio); nver = find_by_major(vio, pkt->major); if (!nver) return handshake_failure(vio); if (send_version(vio, nver->major, nver->minor) < 0) return handshake_failure(vio); return 0; } static int process_ver(struct vio_driver_state *vio, struct vio_ver_info *pkt) { switch (pkt->tag.stype) { case VIO_SUBTYPE_INFO: return process_ver_info(vio, pkt); case VIO_SUBTYPE_ACK: return process_ver_ack(vio, pkt); case VIO_SUBTYPE_NACK: return process_ver_nack(vio, pkt); default: return handshake_failure(vio); } } static int process_attr(struct vio_driver_state *vio, void *pkt) { int err; if (!(vio->hs_state & VIO_HS_GOTVERS)) return handshake_failure(vio); err = vio->ops->handle_attr(vio, pkt); if (err < 0) { return handshake_failure(vio); } else { vio->hs_state |= VIO_HS_GOT_ATTR; if ((vio->dr_state & VIO_DR_STATE_TXREQ) && !(vio->hs_state & VIO_HS_SENT_DREG)) { if (send_dreg(vio) < 0) return handshake_failure(vio); vio->hs_state |= VIO_HS_SENT_DREG; } } return 0; } static int all_drings_registered(struct vio_driver_state *vio) { int need_rx, need_tx; need_rx = (vio->dr_state & VIO_DR_STATE_RXREQ); need_tx = (vio->dr_state & VIO_DR_STATE_TXREQ); if (need_rx && !(vio->dr_state & VIO_DR_STATE_RXREG)) return 0; if (need_tx && !(vio->dr_state & VIO_DR_STATE_TXREG)) return 0; return 1; } static int process_dreg_info(struct vio_driver_state *vio, struct vio_dring_register *pkt) { struct vio_dring_state *dr; int i, len; viodbg(HS, "GOT DRING_REG INFO ident[%llx] " "ndesc[%u] dsz[%u] opt[0x%x] ncookies[%u]\n", (unsigned long long) pkt->dring_ident, pkt->num_descr, pkt->descr_size, pkt->options, pkt->num_cookies); if (!(vio->dr_state & VIO_DR_STATE_RXREQ)) goto send_nack; if (vio->dr_state & VIO_DR_STATE_RXREG) goto send_nack; BUG_ON(vio->desc_buf); vio->desc_buf = kzalloc(pkt->descr_size, GFP_ATOMIC); if (!vio->desc_buf) goto send_nack; vio->desc_buf_len = pkt->descr_size; dr = &vio->drings[VIO_DRIVER_RX_RING]; dr->num_entries = pkt->num_descr; dr->entry_size = pkt->descr_size; dr->ncookies = pkt->num_cookies; for (i = 0; i < dr->ncookies; i++) { dr->cookies[i] = pkt->cookies[i]; viodbg(HS, "DRING COOKIE(%d) [%016llx:%016llx]\n", i, (unsigned long long) pkt->cookies[i].cookie_addr, (unsigned long long) pkt->cookies[i].cookie_size); } pkt->tag.stype = VIO_SUBTYPE_ACK; pkt->dring_ident = ++dr->ident; viodbg(HS, "SEND DRING_REG ACK ident[%llx]\n", (unsigned long long) pkt->dring_ident); len = (sizeof(*pkt) + (dr->ncookies * sizeof(struct ldc_trans_cookie))); if (send_ctrl(vio, &pkt->tag, len) < 0) goto send_nack; vio->dr_state |= VIO_DR_STATE_RXREG; return 0; send_nack: pkt->tag.stype = VIO_SUBTYPE_NACK; viodbg(HS, "SEND DRING_REG NACK\n"); (void) send_ctrl(vio, &pkt->tag, sizeof(*pkt)); return handshake_failure(vio); } static int process_dreg_ack(struct vio_driver_state *vio, struct vio_dring_register *pkt) { struct vio_dring_state *dr; viodbg(HS, "GOT DRING_REG ACK ident[%llx] " "ndesc[%u] dsz[%u] opt[0x%x] ncookies[%u]\n", (unsigned long long) pkt->dring_ident, pkt->num_descr, pkt->descr_size, pkt->options, pkt->num_cookies); dr = &vio->drings[VIO_DRIVER_TX_RING]; if (!(vio->dr_state & VIO_DR_STATE_TXREQ)) return handshake_failure(vio); dr->ident = pkt->dring_ident; vio->dr_state |= VIO_DR_STATE_TXREG; if (all_drings_registered(vio)) { if (send_rdx(vio) < 0) return handshake_failure(vio); vio->hs_state = VIO_HS_SENT_RDX; } return 0; } static int process_dreg_nack(struct vio_driver_state *vio, struct vio_dring_register *pkt) { viodbg(HS, "GOT DRING_REG NACK ident[%llx] " "ndesc[%u] dsz[%u] opt[0x%x] ncookies[%u]\n", (unsigned long long) pkt->dring_ident, pkt->num_descr, pkt->descr_size, pkt->options, pkt->num_cookies); return handshake_failure(vio); } static int process_dreg(struct vio_driver_state *vio, struct vio_dring_register *pkt) { if (!(vio->hs_state & VIO_HS_GOTVERS)) return handshake_failure(vio); switch (pkt->tag.stype) { case VIO_SUBTYPE_INFO: return process_dreg_info(vio, pkt); case VIO_SUBTYPE_ACK: return process_dreg_ack(vio, pkt); case VIO_SUBTYPE_NACK: return process_dreg_nack(vio, pkt); default: return handshake_failure(vio); } } static int process_dunreg(struct vio_driver_state *vio, struct vio_dring_unregister *pkt) { struct vio_dring_state *dr = &vio->drings[VIO_DRIVER_RX_RING]; viodbg(HS, "GOT DRING_UNREG\n"); if (pkt->dring_ident != dr->ident) return 0; vio->dr_state &= ~VIO_DR_STATE_RXREG; memset(dr, 0, sizeof(*dr)); kfree(vio->desc_buf); vio->desc_buf = NULL; vio->desc_buf_len = 0; return 0; } static int process_rdx_info(struct vio_driver_state *vio, struct vio_rdx *pkt) { viodbg(HS, "GOT RDX INFO\n"); pkt->tag.stype = VIO_SUBTYPE_ACK; viodbg(HS, "SEND RDX ACK\n"); if (send_ctrl(vio, &pkt->tag, sizeof(*pkt)) < 0) return handshake_failure(vio); vio->hs_state |= VIO_HS_SENT_RDX_ACK; return 0; } static int process_rdx_ack(struct vio_driver_state *vio, struct vio_rdx *pkt) { viodbg(HS, "GOT RDX ACK\n"); if (!(vio->hs_state & VIO_HS_SENT_RDX)) return handshake_failure(vio); vio->hs_state |= VIO_HS_GOT_RDX_ACK; return 0; } static int process_rdx_nack(struct vio_driver_state *vio, struct vio_rdx *pkt) { viodbg(HS, "GOT RDX NACK\n"); return handshake_failure(vio); } static int process_rdx(struct vio_driver_state *vio, struct vio_rdx *pkt) { if (!all_drings_registered(vio)) handshake_failure(vio); switch (pkt->tag.stype) { case VIO_SUBTYPE_INFO: return process_rdx_info(vio, pkt); case VIO_SUBTYPE_ACK: return process_rdx_ack(vio, pkt); case VIO_SUBTYPE_NACK: return process_rdx_nack(vio, pkt); default: return handshake_failure(vio); } } int vio_control_pkt_engine(struct vio_driver_state *vio, void *pkt) { struct vio_msg_tag *tag = pkt; u8 prev_state = vio->hs_state; int err; switch (tag->stype_env) { case VIO_VER_INFO: err = process_ver(vio, pkt); break; case VIO_ATTR_INFO: err = process_attr(vio, pkt); break; case VIO_DRING_REG: err = process_dreg(vio, pkt); break; case VIO_DRING_UNREG: err = process_dunreg(vio, pkt); break; case VIO_RDX: err = process_rdx(vio, pkt); break; default: err = process_unknown(vio, pkt); break; } if (!err && vio->hs_state != prev_state && (vio->hs_state & VIO_HS_COMPLETE)) vio->ops->handshake_complete(vio); return err; } EXPORT_SYMBOL(vio_control_pkt_engine); void vio_conn_reset(struct vio_driver_state *vio) { } EXPORT_SYMBOL(vio_conn_reset); /* The issue is that the Solaris virtual disk server just mirrors the * SID values it gets from the client peer. So we work around that * here in vio_{validate,send}_sid() so that the drivers don't need * to be aware of this crap. */ int vio_validate_sid(struct vio_driver_state *vio, struct vio_msg_tag *tp) { u32 sid; /* Always let VERSION+INFO packets through unchecked, they * define the new SID. */ if (tp->type == VIO_TYPE_CTRL && tp->stype == VIO_SUBTYPE_INFO && tp->stype_env == VIO_VER_INFO) return 0; /* Ok, now figure out which SID to use. */ switch (vio->dev_class) { case VDEV_NETWORK: case VDEV_NETWORK_SWITCH: case VDEV_DISK_SERVER: default: sid = vio->_peer_sid; break; case VDEV_DISK: sid = vio->_local_sid; break; } if (sid == tp->sid) return 0; viodbg(DATA, "BAD SID tag->sid[%08x] peer_sid[%08x] local_sid[%08x]\n", tp->sid, vio->_peer_sid, vio->_local_sid); return -EINVAL; } EXPORT_SYMBOL(vio_validate_sid); u32 vio_send_sid(struct vio_driver_state *vio) { switch (vio->dev_class) { case VDEV_NETWORK: case VDEV_NETWORK_SWITCH: case VDEV_DISK: default: return vio->_local_sid; case VDEV_DISK_SERVER: return vio->_peer_sid; } } EXPORT_SYMBOL(vio_send_sid); int vio_ldc_alloc(struct vio_driver_state *vio, struct ldc_channel_config *base_cfg, void *event_arg) { struct ldc_channel_config cfg = *base_cfg; struct ldc_channel *lp; cfg.tx_irq = vio->vdev->tx_irq; cfg.rx_irq = vio->vdev->rx_irq; lp = ldc_alloc(vio->vdev->channel_id, &cfg, event_arg); if (IS_ERR(lp)) return PTR_ERR(lp); vio->lp = lp; return 0; } EXPORT_SYMBOL(vio_ldc_alloc); void vio_ldc_free(struct vio_driver_state *vio) { ldc_free(vio->lp); vio->lp = NULL; kfree(vio->desc_buf); vio->desc_buf = NULL; vio->desc_buf_len = 0; } EXPORT_SYMBOL(vio_ldc_free); void vio_port_up(struct vio_driver_state *vio) { unsigned long flags; int err, state; spin_lock_irqsave(&vio->lock, flags); state = ldc_state(vio->lp); err = 0; if (state == LDC_STATE_INIT) { err = ldc_bind(vio->lp, vio->name); if (err) printk(KERN_WARNING "%s: Port %lu bind failed, " "err=%d\n", vio->name, vio->vdev->channel_id, err); } if (!err) { err = ldc_connect(vio->lp); if (err) printk(KERN_WARNING "%s: Port %lu connect failed, " "err=%d\n", vio->name, vio->vdev->channel_id, err); } if (err) { unsigned long expires = jiffies + HZ; expires = round_jiffies(expires); mod_timer(&vio->timer, expires); } spin_unlock_irqrestore(&vio->lock, flags); } EXPORT_SYMBOL(vio_port_up); static void vio_port_timer(unsigned long _arg) { struct vio_driver_state *vio = (struct vio_driver_state *) _arg; vio_port_up(vio); } int vio_driver_init(struct vio_driver_state *vio, struct vio_dev *vdev, u8 dev_class, struct vio_version *ver_table, int ver_table_size, struct vio_driver_ops *ops, char *name) { switch (dev_class) { case VDEV_NETWORK: case VDEV_NETWORK_SWITCH: case VDEV_DISK: case VDEV_DISK_SERVER: break; default: return -EINVAL; } if (!ops->send_attr || !ops->handle_attr || !ops->handshake_complete) return -EINVAL; if (!ver_table || ver_table_size < 0) return -EINVAL; if (!name) return -EINVAL; spin_lock_init(&vio->lock); vio->name = name; vio->dev_class = dev_class; vio->vdev = vdev; vio->ver_table = ver_table; vio->ver_table_entries = ver_table_size; vio->ops = ops; setup_timer(&vio->timer, vio_port_timer, (unsigned long) vio); return 0; } EXPORT_SYMBOL(vio_driver_init);
gpl-2.0
Red680812/android_443_KitKat_kernel_htc_dlxub1
drivers/watchdog/octeon-wdt-main.c
7713
19456
/* * Octeon Watchdog driver * * Copyright (C) 2007, 2008, 2009, 2010 Cavium Networks * * Some parts derived from wdt.c * * (c) Copyright 1996-1997 Alan Cox <alan@lxorguk.ukuu.org.uk>, * 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. * * Neither Alan Cox nor CymruNet Ltd. admit liability nor provide * warranty for any of this software. This material is provided * "AS-IS" and at no charge. * * (c) Copyright 1995 Alan Cox <alan@lxorguk.ukuu.org.uk> * * 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. * * * The OCTEON watchdog has a maximum timeout of 2^32 * io_clock. * For most systems this is less than 10 seconds, so to allow for * software to request longer watchdog heartbeats, we maintain software * counters to count multiples of the base rate. If the system locks * up in such a manner that we can not run the software counters, the * only result is a watchdog reset sooner than was requested. But * that is OK, because in this case userspace would likely not be able * to do anything anyhow. * * The hardware watchdog interval we call the period. The OCTEON * watchdog goes through several stages, after the first period an * irq is asserted, then if it is not reset, after the next period NMI * is asserted, then after an additional period a chip wide soft reset. * So for the software counters, we reset watchdog after each period * and decrement the counter. But for the last two periods we need to * let the watchdog progress to the NMI stage so we disable the irq * and let it proceed. Once in the NMI, we print the register state * to the serial port and then wait for the reset. * * A watchdog is maintained for each CPU in the system, that way if * one CPU suffers a lockup, we also get a register dump and reset. * The userspace ping resets the watchdog on all CPUs. * * Before userspace opens the watchdog device, we still run the * watchdogs to catch any lockups that may be kernel related. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/miscdevice.h> #include <linux/interrupt.h> #include <linux/watchdog.h> #include <linux/cpumask.h> #include <linux/bitops.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/string.h> #include <linux/delay.h> #include <linux/cpu.h> #include <linux/smp.h> #include <linux/fs.h> #include <linux/irq.h> #include <asm/mipsregs.h> #include <asm/uasm.h> #include <asm/octeon/octeon.h> /* The count needed to achieve timeout_sec. */ static unsigned int timeout_cnt; /* The maximum period supported. */ static unsigned int max_timeout_sec; /* The current period. */ static unsigned int timeout_sec; /* Set to non-zero when userspace countdown mode active */ static int do_coundown; static unsigned int countdown_reset; static unsigned int per_cpu_countdown[NR_CPUS]; static cpumask_t irq_enabled_cpus; #define WD_TIMO 60 /* Default heartbeat = 60 seconds */ static int heartbeat = WD_TIMO; module_param(heartbeat, int, S_IRUGO); MODULE_PARM_DESC(heartbeat, "Watchdog heartbeat in seconds. (0 < heartbeat, default=" __MODULE_STRING(WD_TIMO) ")"); static bool nowayout = WATCHDOG_NOWAYOUT; module_param(nowayout, bool, S_IRUGO); MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); static unsigned long octeon_wdt_is_open; static char expect_close; static u32 __initdata nmi_stage1_insns[64]; /* We need one branch and therefore one relocation per target label. */ static struct uasm_label __initdata labels[5]; static struct uasm_reloc __initdata relocs[5]; enum lable_id { label_enter_bootloader = 1 }; /* Some CP0 registers */ #define K0 26 #define C0_CVMMEMCTL 11, 7 #define C0_STATUS 12, 0 #define C0_EBASE 15, 1 #define C0_DESAVE 31, 0 void octeon_wdt_nmi_stage2(void); static void __init octeon_wdt_build_stage1(void) { int i; int len; u32 *p = nmi_stage1_insns; #ifdef CONFIG_HOTPLUG_CPU struct uasm_label *l = labels; struct uasm_reloc *r = relocs; #endif /* * For the next few instructions running the debugger may * cause corruption of k0 in the saved registers. Since we're * about to crash, nobody probably cares. * * Save K0 into the debug scratch register */ uasm_i_dmtc0(&p, K0, C0_DESAVE); uasm_i_mfc0(&p, K0, C0_STATUS); #ifdef CONFIG_HOTPLUG_CPU uasm_il_bbit0(&p, &r, K0, ilog2(ST0_NMI), label_enter_bootloader); #endif /* Force 64-bit addressing enabled */ uasm_i_ori(&p, K0, K0, ST0_UX | ST0_SX | ST0_KX); uasm_i_mtc0(&p, K0, C0_STATUS); #ifdef CONFIG_HOTPLUG_CPU uasm_i_mfc0(&p, K0, C0_EBASE); /* Coreid number in K0 */ uasm_i_andi(&p, K0, K0, 0xf); /* 8 * coreid in bits 16-31 */ uasm_i_dsll_safe(&p, K0, K0, 3 + 16); uasm_i_ori(&p, K0, K0, 0x8001); uasm_i_dsll_safe(&p, K0, K0, 16); uasm_i_ori(&p, K0, K0, 0x0700); uasm_i_drotr_safe(&p, K0, K0, 32); /* * Should result in: 0x8001,0700,0000,8*coreid which is * CVMX_CIU_WDOGX(coreid) - 0x0500 * * Now ld K0, CVMX_CIU_WDOGX(coreid) */ uasm_i_ld(&p, K0, 0x500, K0); /* * If bit one set handle the NMI as a watchdog event. * otherwise transfer control to bootloader. */ uasm_il_bbit0(&p, &r, K0, 1, label_enter_bootloader); uasm_i_nop(&p); #endif /* Clear Dcache so cvmseg works right. */ uasm_i_cache(&p, 1, 0, 0); /* Use K0 to do a read/modify/write of CVMMEMCTL */ uasm_i_dmfc0(&p, K0, C0_CVMMEMCTL); /* Clear out the size of CVMSEG */ uasm_i_dins(&p, K0, 0, 0, 6); /* Set CVMSEG to its largest value */ uasm_i_ori(&p, K0, K0, 0x1c0 | 54); /* Store the CVMMEMCTL value */ uasm_i_dmtc0(&p, K0, C0_CVMMEMCTL); /* Load the address of the second stage handler */ UASM_i_LA(&p, K0, (long)octeon_wdt_nmi_stage2); uasm_i_jr(&p, K0); uasm_i_dmfc0(&p, K0, C0_DESAVE); #ifdef CONFIG_HOTPLUG_CPU uasm_build_label(&l, p, label_enter_bootloader); /* Jump to the bootloader and restore K0 */ UASM_i_LA(&p, K0, (long)octeon_bootloader_entry_addr); uasm_i_jr(&p, K0); uasm_i_dmfc0(&p, K0, C0_DESAVE); #endif uasm_resolve_relocs(relocs, labels); len = (int)(p - nmi_stage1_insns); pr_debug("Synthesized NMI stage 1 handler (%d instructions)\n", len); pr_debug("\t.set push\n"); pr_debug("\t.set noreorder\n"); for (i = 0; i < len; i++) pr_debug("\t.word 0x%08x\n", nmi_stage1_insns[i]); pr_debug("\t.set pop\n"); if (len > 32) panic("NMI stage 1 handler exceeds 32 instructions, was %d\n", len); } static int cpu2core(int cpu) { #ifdef CONFIG_SMP return cpu_logical_map(cpu); #else return cvmx_get_core_num(); #endif } static int core2cpu(int coreid) { #ifdef CONFIG_SMP return cpu_number_map(coreid); #else return 0; #endif } /** * Poke the watchdog when an interrupt is received * * @cpl: * @dev_id: * * Returns */ static irqreturn_t octeon_wdt_poke_irq(int cpl, void *dev_id) { unsigned int core = cvmx_get_core_num(); int cpu = core2cpu(core); if (do_coundown) { if (per_cpu_countdown[cpu] > 0) { /* We're alive, poke the watchdog */ cvmx_write_csr(CVMX_CIU_PP_POKEX(core), 1); per_cpu_countdown[cpu]--; } else { /* Bad news, you are about to reboot. */ disable_irq_nosync(cpl); cpumask_clear_cpu(cpu, &irq_enabled_cpus); } } else { /* Not open, just ping away... */ cvmx_write_csr(CVMX_CIU_PP_POKEX(core), 1); } return IRQ_HANDLED; } /* From setup.c */ extern int prom_putchar(char c); /** * Write a string to the uart * * @str: String to write */ static void octeon_wdt_write_string(const char *str) { /* Just loop writing one byte at a time */ while (*str) prom_putchar(*str++); } /** * Write a hex number out of the uart * * @value: Number to display * @digits: Number of digits to print (1 to 16) */ static void octeon_wdt_write_hex(u64 value, int digits) { int d; int v; for (d = 0; d < digits; d++) { v = (value >> ((digits - d - 1) * 4)) & 0xf; if (v >= 10) prom_putchar('a' + v - 10); else prom_putchar('0' + v); } } const char *reg_name[] = { "$0", "at", "v0", "v1", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "t0", "t1", "t2", "t3", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8", "t9", "k0", "k1", "gp", "sp", "s8", "ra" }; /** * NMI stage 3 handler. NMIs are handled in the following manner: * 1) The first NMI handler enables CVMSEG and transfers from * the bootbus region into normal memory. It is careful to not * destroy any registers. * 2) The second stage handler uses CVMSEG to save the registers * and create a stack for C code. It then calls the third level * handler with one argument, a pointer to the register values. * 3) The third, and final, level handler is the following C * function that prints out some useful infomration. * * @reg: Pointer to register state before the NMI */ void octeon_wdt_nmi_stage3(u64 reg[32]) { u64 i; unsigned int coreid = cvmx_get_core_num(); /* * Save status and cause early to get them before any changes * might happen. */ u64 cp0_cause = read_c0_cause(); u64 cp0_status = read_c0_status(); u64 cp0_error_epc = read_c0_errorepc(); u64 cp0_epc = read_c0_epc(); /* Delay so output from all cores output is not jumbled together. */ __delay(100000000ull * coreid); octeon_wdt_write_string("\r\n*** NMI Watchdog interrupt on Core 0x"); octeon_wdt_write_hex(coreid, 1); octeon_wdt_write_string(" ***\r\n"); for (i = 0; i < 32; i++) { octeon_wdt_write_string("\t"); octeon_wdt_write_string(reg_name[i]); octeon_wdt_write_string("\t0x"); octeon_wdt_write_hex(reg[i], 16); if (i & 1) octeon_wdt_write_string("\r\n"); } octeon_wdt_write_string("\terr_epc\t0x"); octeon_wdt_write_hex(cp0_error_epc, 16); octeon_wdt_write_string("\tepc\t0x"); octeon_wdt_write_hex(cp0_epc, 16); octeon_wdt_write_string("\r\n"); octeon_wdt_write_string("\tstatus\t0x"); octeon_wdt_write_hex(cp0_status, 16); octeon_wdt_write_string("\tcause\t0x"); octeon_wdt_write_hex(cp0_cause, 16); octeon_wdt_write_string("\r\n"); octeon_wdt_write_string("\tsum0\t0x"); octeon_wdt_write_hex(cvmx_read_csr(CVMX_CIU_INTX_SUM0(coreid * 2)), 16); octeon_wdt_write_string("\ten0\t0x"); octeon_wdt_write_hex(cvmx_read_csr(CVMX_CIU_INTX_EN0(coreid * 2)), 16); octeon_wdt_write_string("\r\n"); octeon_wdt_write_string("*** Chip soft reset soon ***\r\n"); } static void octeon_wdt_disable_interrupt(int cpu) { unsigned int core; unsigned int irq; union cvmx_ciu_wdogx ciu_wdog; core = cpu2core(cpu); irq = OCTEON_IRQ_WDOG0 + core; /* Poke the watchdog to clear out its state */ cvmx_write_csr(CVMX_CIU_PP_POKEX(core), 1); /* Disable the hardware. */ ciu_wdog.u64 = 0; cvmx_write_csr(CVMX_CIU_WDOGX(core), ciu_wdog.u64); free_irq(irq, octeon_wdt_poke_irq); } static void octeon_wdt_setup_interrupt(int cpu) { unsigned int core; unsigned int irq; union cvmx_ciu_wdogx ciu_wdog; core = cpu2core(cpu); /* Disable it before doing anything with the interrupts. */ ciu_wdog.u64 = 0; cvmx_write_csr(CVMX_CIU_WDOGX(core), ciu_wdog.u64); per_cpu_countdown[cpu] = countdown_reset; irq = OCTEON_IRQ_WDOG0 + core; if (request_irq(irq, octeon_wdt_poke_irq, IRQF_NO_THREAD, "octeon_wdt", octeon_wdt_poke_irq)) panic("octeon_wdt: Couldn't obtain irq %d", irq); cpumask_set_cpu(cpu, &irq_enabled_cpus); /* Poke the watchdog to clear out its state */ cvmx_write_csr(CVMX_CIU_PP_POKEX(core), 1); /* Finally enable the watchdog now that all handlers are installed */ ciu_wdog.u64 = 0; ciu_wdog.s.len = timeout_cnt; ciu_wdog.s.mode = 3; /* 3 = Interrupt + NMI + Soft-Reset */ cvmx_write_csr(CVMX_CIU_WDOGX(core), ciu_wdog.u64); } static int octeon_wdt_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { unsigned int cpu = (unsigned long)hcpu; switch (action) { case CPU_DOWN_PREPARE: octeon_wdt_disable_interrupt(cpu); break; case CPU_ONLINE: case CPU_DOWN_FAILED: octeon_wdt_setup_interrupt(cpu); break; default: break; } return NOTIFY_OK; } static void octeon_wdt_ping(void) { int cpu; int coreid; for_each_online_cpu(cpu) { coreid = cpu2core(cpu); cvmx_write_csr(CVMX_CIU_PP_POKEX(coreid), 1); per_cpu_countdown[cpu] = countdown_reset; if ((countdown_reset || !do_coundown) && !cpumask_test_cpu(cpu, &irq_enabled_cpus)) { /* We have to enable the irq */ int irq = OCTEON_IRQ_WDOG0 + coreid; enable_irq(irq); cpumask_set_cpu(cpu, &irq_enabled_cpus); } } } static void octeon_wdt_calc_parameters(int t) { unsigned int periods; timeout_sec = max_timeout_sec; /* * Find the largest interrupt period, that can evenly divide * the requested heartbeat time. */ while ((t % timeout_sec) != 0) timeout_sec--; periods = t / timeout_sec; /* * The last two periods are after the irq is disabled, and * then to the nmi, so we subtract them off. */ countdown_reset = periods > 2 ? periods - 2 : 0; heartbeat = t; timeout_cnt = ((octeon_get_io_clock_rate() >> 8) * timeout_sec) >> 8; } static int octeon_wdt_set_heartbeat(int t) { int cpu; int coreid; union cvmx_ciu_wdogx ciu_wdog; if (t <= 0) return -1; octeon_wdt_calc_parameters(t); for_each_online_cpu(cpu) { coreid = cpu2core(cpu); cvmx_write_csr(CVMX_CIU_PP_POKEX(coreid), 1); ciu_wdog.u64 = 0; ciu_wdog.s.len = timeout_cnt; ciu_wdog.s.mode = 3; /* 3 = Interrupt + NMI + Soft-Reset */ cvmx_write_csr(CVMX_CIU_WDOGX(coreid), ciu_wdog.u64); cvmx_write_csr(CVMX_CIU_PP_POKEX(coreid), 1); } octeon_wdt_ping(); /* Get the irqs back on. */ return 0; } /** * octeon_wdt_write: * @file: file handle to the watchdog * @buf: buffer to write (unused as data does not matter here * @count: count of bytes * @ppos: pointer to the position to write. No seeks allowed * * A write to a watchdog device is defined as a keepalive signal. Any * write of data will do, as we we don't define content meaning. */ static ssize_t octeon_wdt_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { if (count) { if (!nowayout) { size_t i; /* In case it was set long ago */ expect_close = 0; for (i = 0; i != count; i++) { char c; if (get_user(c, buf + i)) return -EFAULT; if (c == 'V') expect_close = 1; } } octeon_wdt_ping(); } return count; } /** * octeon_wdt_ioctl: * @file: file handle to the device * @cmd: watchdog command * @arg: argument pointer * * The watchdog API defines a common set of functions for all * watchdogs according to their available features. We only * actually usefully support querying capabilities and setting * the timeout. */ static long octeon_wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int __user *p = argp; int new_heartbeat; static struct watchdog_info ident = { .options = WDIOF_SETTIMEOUT| WDIOF_MAGICCLOSE| WDIOF_KEEPALIVEPING, .firmware_version = 1, .identity = "OCTEON", }; switch (cmd) { case WDIOC_GETSUPPORT: return copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0; case WDIOC_GETSTATUS: case WDIOC_GETBOOTSTATUS: return put_user(0, p); case WDIOC_KEEPALIVE: octeon_wdt_ping(); return 0; case WDIOC_SETTIMEOUT: if (get_user(new_heartbeat, p)) return -EFAULT; if (octeon_wdt_set_heartbeat(new_heartbeat)) return -EINVAL; /* Fall through. */ case WDIOC_GETTIMEOUT: return put_user(heartbeat, p); default: return -ENOTTY; } } /** * octeon_wdt_open: * @inode: inode of device * @file: file handle to device * * The watchdog device has been opened. The watchdog device is single * open and on opening we do a ping to reset the counters. */ static int octeon_wdt_open(struct inode *inode, struct file *file) { if (test_and_set_bit(0, &octeon_wdt_is_open)) return -EBUSY; /* * Activate */ octeon_wdt_ping(); do_coundown = 1; return nonseekable_open(inode, file); } /** * octeon_wdt_release: * @inode: inode to board * @file: file handle to board * * The watchdog has a configurable API. There is a religious dispute * between people who want their watchdog to be able to shut down and * those who want to be sure if the watchdog manager dies the machine * reboots. In the former case we disable the counters, in the latter * case you have to open it again very soon. */ static int octeon_wdt_release(struct inode *inode, struct file *file) { if (expect_close) { do_coundown = 0; octeon_wdt_ping(); } else { pr_crit("WDT device closed unexpectedly. WDT will not stop!\n"); } clear_bit(0, &octeon_wdt_is_open); expect_close = 0; return 0; } static const struct file_operations octeon_wdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .write = octeon_wdt_write, .unlocked_ioctl = octeon_wdt_ioctl, .open = octeon_wdt_open, .release = octeon_wdt_release, }; static struct miscdevice octeon_wdt_miscdev = { .minor = WATCHDOG_MINOR, .name = "watchdog", .fops = &octeon_wdt_fops, }; static struct notifier_block octeon_wdt_cpu_notifier = { .notifier_call = octeon_wdt_cpu_callback, }; /** * Module/ driver initialization. * * Returns Zero on success */ static int __init octeon_wdt_init(void) { int i; int ret; int cpu; u64 *ptr; /* * Watchdog time expiration length = The 16 bits of LEN * represent the most significant bits of a 24 bit decrementer * that decrements every 256 cycles. * * Try for a timeout of 5 sec, if that fails a smaller number * of even seconds, */ max_timeout_sec = 6; do { max_timeout_sec--; timeout_cnt = ((octeon_get_io_clock_rate() >> 8) * max_timeout_sec) >> 8; } while (timeout_cnt > 65535); BUG_ON(timeout_cnt == 0); octeon_wdt_calc_parameters(heartbeat); pr_info("Initial granularity %d Sec\n", timeout_sec); ret = misc_register(&octeon_wdt_miscdev); if (ret) { pr_err("cannot register miscdev on minor=%d (err=%d)\n", WATCHDOG_MINOR, ret); goto out; } /* Build the NMI handler ... */ octeon_wdt_build_stage1(); /* ... and install it. */ ptr = (u64 *) nmi_stage1_insns; for (i = 0; i < 16; i++) { cvmx_write_csr(CVMX_MIO_BOOT_LOC_ADR, i * 8); cvmx_write_csr(CVMX_MIO_BOOT_LOC_DAT, ptr[i]); } cvmx_write_csr(CVMX_MIO_BOOT_LOC_CFGX(0), 0x81fc0000); cpumask_clear(&irq_enabled_cpus); for_each_online_cpu(cpu) octeon_wdt_setup_interrupt(cpu); register_hotcpu_notifier(&octeon_wdt_cpu_notifier); out: return ret; } /** * Module / driver shutdown */ static void __exit octeon_wdt_cleanup(void) { int cpu; misc_deregister(&octeon_wdt_miscdev); unregister_hotcpu_notifier(&octeon_wdt_cpu_notifier); for_each_online_cpu(cpu) { int core = cpu2core(cpu); /* Disable the watchdog */ cvmx_write_csr(CVMX_CIU_WDOGX(core), 0); /* Free the interrupt handler */ free_irq(OCTEON_IRQ_WDOG0 + core, octeon_wdt_poke_irq); } /* * Disable the boot-bus memory, the code it points to is soon * to go missing. */ cvmx_write_csr(CVMX_MIO_BOOT_LOC_CFGX(0), 0); } MODULE_LICENSE("GPL"); MODULE_AUTHOR("Cavium Networks <support@caviumnetworks.com>"); MODULE_DESCRIPTION("Cavium Networks Octeon Watchdog driver."); module_init(octeon_wdt_init); module_exit(octeon_wdt_cleanup);
gpl-2.0
Split-Screen/android_kernel_htc_msm8974
drivers/pci/pcie/aer/aerdrv.c
8225
12263
/* * drivers/pci/pcie/aer/aerdrv.c * * 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. * * This file implements the AER root port service driver. The driver will * register an irq handler. When root port triggers an AER interrupt, the irq * handler will collect root port status and schedule a work. * * Copyright (C) 2006 Intel Corp. * Tom Long Nguyen (tom.l.nguyen@intel.com) * Zhang Yanmin (yanmin.zhang@intel.com) * */ #include <linux/module.h> #include <linux/pci.h> #include <linux/pci-acpi.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/pm.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/pcieport_if.h> #include <linux/slab.h> #include "aerdrv.h" #include "../../pci.h" /* * Version Information */ #define DRIVER_VERSION "v1.0" #define DRIVER_AUTHOR "tom.l.nguyen@intel.com" #define DRIVER_DESC "Root Port Advanced Error Reporting Driver" MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); static int __devinit aer_probe(struct pcie_device *dev); static void aer_remove(struct pcie_device *dev); static pci_ers_result_t aer_error_detected(struct pci_dev *dev, enum pci_channel_state error); static void aer_error_resume(struct pci_dev *dev); static pci_ers_result_t aer_root_reset(struct pci_dev *dev); static struct pci_error_handlers aer_error_handlers = { .error_detected = aer_error_detected, .resume = aer_error_resume, }; static struct pcie_port_service_driver aerdriver = { .name = "aer", .port_type = PCI_EXP_TYPE_ROOT_PORT, .service = PCIE_PORT_SERVICE_AER, .probe = aer_probe, .remove = aer_remove, .err_handler = &aer_error_handlers, .reset_link = aer_root_reset, }; static int pcie_aer_disable; void pci_no_aer(void) { pcie_aer_disable = 1; /* has priority over 'forceload' */ } bool pci_aer_available(void) { return !pcie_aer_disable && pci_msi_enabled(); } static int set_device_error_reporting(struct pci_dev *dev, void *data) { bool enable = *((bool *)data); if ((dev->pcie_type == PCI_EXP_TYPE_ROOT_PORT) || (dev->pcie_type == PCI_EXP_TYPE_UPSTREAM) || (dev->pcie_type == PCI_EXP_TYPE_DOWNSTREAM)) { if (enable) pci_enable_pcie_error_reporting(dev); else pci_disable_pcie_error_reporting(dev); } if (enable) pcie_set_ecrc_checking(dev); return 0; } /** * set_downstream_devices_error_reporting - enable/disable the error reporting bits on the root port and its downstream ports. * @dev: pointer to root port's pci_dev data structure * @enable: true = enable error reporting, false = disable error reporting. */ static void set_downstream_devices_error_reporting(struct pci_dev *dev, bool enable) { set_device_error_reporting(dev, &enable); if (!dev->subordinate) return; pci_walk_bus(dev->subordinate, set_device_error_reporting, &enable); } /** * aer_enable_rootport - enable Root Port's interrupts when receiving messages * @rpc: pointer to a Root Port data structure * * Invoked when PCIe bus loads AER service driver. */ static void aer_enable_rootport(struct aer_rpc *rpc) { struct pci_dev *pdev = rpc->rpd->port; int pos, aer_pos; u16 reg16; u32 reg32; pos = pci_pcie_cap(pdev); /* Clear PCIe Capability's Device Status */ pci_read_config_word(pdev, pos+PCI_EXP_DEVSTA, &reg16); pci_write_config_word(pdev, pos+PCI_EXP_DEVSTA, reg16); /* Disable system error generation in response to error messages */ pci_read_config_word(pdev, pos + PCI_EXP_RTCTL, &reg16); reg16 &= ~(SYSTEM_ERROR_INTR_ON_MESG_MASK); pci_write_config_word(pdev, pos + PCI_EXP_RTCTL, reg16); aer_pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ERR); /* Clear error status */ pci_read_config_dword(pdev, aer_pos + PCI_ERR_ROOT_STATUS, &reg32); pci_write_config_dword(pdev, aer_pos + PCI_ERR_ROOT_STATUS, reg32); pci_read_config_dword(pdev, aer_pos + PCI_ERR_COR_STATUS, &reg32); pci_write_config_dword(pdev, aer_pos + PCI_ERR_COR_STATUS, reg32); pci_read_config_dword(pdev, aer_pos + PCI_ERR_UNCOR_STATUS, &reg32); pci_write_config_dword(pdev, aer_pos + PCI_ERR_UNCOR_STATUS, reg32); /* * Enable error reporting for the root port device and downstream port * devices. */ set_downstream_devices_error_reporting(pdev, true); /* Enable Root Port's interrupt in response to error messages */ pci_read_config_dword(pdev, aer_pos + PCI_ERR_ROOT_COMMAND, &reg32); reg32 |= ROOT_PORT_INTR_ON_MESG_MASK; pci_write_config_dword(pdev, aer_pos + PCI_ERR_ROOT_COMMAND, reg32); } /** * aer_disable_rootport - disable Root Port's interrupts when receiving messages * @rpc: pointer to a Root Port data structure * * Invoked when PCIe bus unloads AER service driver. */ static void aer_disable_rootport(struct aer_rpc *rpc) { struct pci_dev *pdev = rpc->rpd->port; u32 reg32; int pos; /* * Disable error reporting for the root port device and downstream port * devices. */ set_downstream_devices_error_reporting(pdev, false); pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ERR); /* Disable Root's interrupt in response to error messages */ pci_read_config_dword(pdev, pos + PCI_ERR_ROOT_COMMAND, &reg32); reg32 &= ~ROOT_PORT_INTR_ON_MESG_MASK; pci_write_config_dword(pdev, pos + PCI_ERR_ROOT_COMMAND, reg32); /* Clear Root's error status reg */ pci_read_config_dword(pdev, pos + PCI_ERR_ROOT_STATUS, &reg32); pci_write_config_dword(pdev, pos + PCI_ERR_ROOT_STATUS, reg32); } /** * aer_irq - Root Port's ISR * @irq: IRQ assigned to Root Port * @context: pointer to Root Port data structure * * Invoked when Root Port detects AER messages. */ irqreturn_t aer_irq(int irq, void *context) { unsigned int status, id; struct pcie_device *pdev = (struct pcie_device *)context; struct aer_rpc *rpc = get_service_data(pdev); int next_prod_idx; unsigned long flags; int pos; pos = pci_find_ext_capability(pdev->port, PCI_EXT_CAP_ID_ERR); /* * Must lock access to Root Error Status Reg, Root Error ID Reg, * and Root error producer/consumer index */ spin_lock_irqsave(&rpc->e_lock, flags); /* Read error status */ pci_read_config_dword(pdev->port, pos + PCI_ERR_ROOT_STATUS, &status); if (!(status & (PCI_ERR_ROOT_UNCOR_RCV|PCI_ERR_ROOT_COR_RCV))) { spin_unlock_irqrestore(&rpc->e_lock, flags); return IRQ_NONE; } /* Read error source and clear error status */ pci_read_config_dword(pdev->port, pos + PCI_ERR_ROOT_ERR_SRC, &id); pci_write_config_dword(pdev->port, pos + PCI_ERR_ROOT_STATUS, status); /* Store error source for later DPC handler */ next_prod_idx = rpc->prod_idx + 1; if (next_prod_idx == AER_ERROR_SOURCES_MAX) next_prod_idx = 0; if (next_prod_idx == rpc->cons_idx) { /* * Error Storm Condition - possibly the same error occurred. * Drop the error. */ spin_unlock_irqrestore(&rpc->e_lock, flags); return IRQ_HANDLED; } rpc->e_sources[rpc->prod_idx].status = status; rpc->e_sources[rpc->prod_idx].id = id; rpc->prod_idx = next_prod_idx; spin_unlock_irqrestore(&rpc->e_lock, flags); /* Invoke DPC handler */ schedule_work(&rpc->dpc_handler); return IRQ_HANDLED; } EXPORT_SYMBOL_GPL(aer_irq); /** * aer_alloc_rpc - allocate Root Port data structure * @dev: pointer to the pcie_dev data structure * * Invoked when Root Port's AER service is loaded. */ static struct aer_rpc *aer_alloc_rpc(struct pcie_device *dev) { struct aer_rpc *rpc; rpc = kzalloc(sizeof(struct aer_rpc), GFP_KERNEL); if (!rpc) return NULL; /* Initialize Root lock access, e_lock, to Root Error Status Reg */ spin_lock_init(&rpc->e_lock); rpc->rpd = dev; INIT_WORK(&rpc->dpc_handler, aer_isr); mutex_init(&rpc->rpc_mutex); init_waitqueue_head(&rpc->wait_release); /* Use PCIe bus function to store rpc into PCIe device */ set_service_data(dev, rpc); return rpc; } /** * aer_remove - clean up resources * @dev: pointer to the pcie_dev data structure * * Invoked when PCI Express bus unloads or AER probe fails. */ static void aer_remove(struct pcie_device *dev) { struct aer_rpc *rpc = get_service_data(dev); if (rpc) { /* If register interrupt service, it must be free. */ if (rpc->isr) free_irq(dev->irq, dev); wait_event(rpc->wait_release, rpc->prod_idx == rpc->cons_idx); aer_disable_rootport(rpc); kfree(rpc); set_service_data(dev, NULL); } } /** * aer_probe - initialize resources * @dev: pointer to the pcie_dev data structure * @id: pointer to the service id data structure * * Invoked when PCI Express bus loads AER service driver. */ static int __devinit aer_probe(struct pcie_device *dev) { int status; struct aer_rpc *rpc; struct device *device = &dev->device; /* Init */ status = aer_init(dev); if (status) return status; /* Alloc rpc data structure */ rpc = aer_alloc_rpc(dev); if (!rpc) { dev_printk(KERN_DEBUG, device, "alloc rpc failed\n"); aer_remove(dev); return -ENOMEM; } /* Request IRQ ISR */ status = request_irq(dev->irq, aer_irq, IRQF_SHARED, "aerdrv", dev); if (status) { dev_printk(KERN_DEBUG, device, "request IRQ failed\n"); aer_remove(dev); return status; } rpc->isr = 1; aer_enable_rootport(rpc); return status; } /** * aer_root_reset - reset link on Root Port * @dev: pointer to Root Port's pci_dev data structure * * Invoked by Port Bus driver when performing link reset at Root Port. */ static pci_ers_result_t aer_root_reset(struct pci_dev *dev) { u32 reg32; int pos; pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR); /* Disable Root's interrupt in response to error messages */ pci_read_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND, &reg32); reg32 &= ~ROOT_PORT_INTR_ON_MESG_MASK; pci_write_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND, reg32); aer_do_secondary_bus_reset(dev); dev_printk(KERN_DEBUG, &dev->dev, "Root Port link has been reset\n"); /* Clear Root Error Status */ pci_read_config_dword(dev, pos + PCI_ERR_ROOT_STATUS, &reg32); pci_write_config_dword(dev, pos + PCI_ERR_ROOT_STATUS, reg32); /* Enable Root Port's interrupt in response to error messages */ pci_read_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND, &reg32); reg32 |= ROOT_PORT_INTR_ON_MESG_MASK; pci_write_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND, reg32); return PCI_ERS_RESULT_RECOVERED; } /** * aer_error_detected - update severity status * @dev: pointer to Root Port's pci_dev data structure * @error: error severity being notified by port bus * * Invoked by Port Bus driver during error recovery. */ static pci_ers_result_t aer_error_detected(struct pci_dev *dev, enum pci_channel_state error) { /* Root Port has no impact. Always recovers. */ return PCI_ERS_RESULT_CAN_RECOVER; } /** * aer_error_resume - clean up corresponding error status bits * @dev: pointer to Root Port's pci_dev data structure * * Invoked by Port Bus driver during nonfatal recovery. */ static void aer_error_resume(struct pci_dev *dev) { int pos; u32 status, mask; u16 reg16; /* Clean up Root device status */ pos = pci_pcie_cap(dev); pci_read_config_word(dev, pos + PCI_EXP_DEVSTA, &reg16); pci_write_config_word(dev, pos + PCI_EXP_DEVSTA, reg16); /* Clean AER Root Error Status */ pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR); pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status); pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_SEVER, &mask); if (dev->error_state == pci_channel_io_normal) status &= ~mask; /* Clear corresponding nonfatal bits */ else status &= mask; /* Clear corresponding fatal bits */ pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, status); } /** * aer_service_init - register AER root service driver * * Invoked when AER root service driver is loaded. */ static int __init aer_service_init(void) { if (!pci_aer_available() || aer_acpi_firmware_first()) return -ENXIO; return pcie_port_service_register(&aerdriver); } /** * aer_service_exit - unregister AER root service driver * * Invoked when AER root service driver is unloaded. */ static void __exit aer_service_exit(void) { pcie_port_service_unregister(&aerdriver); } module_init(aer_service_init); module_exit(aer_service_exit);
gpl-2.0
goutamniwas/android_kernel_motorola_msm8610
drivers/parport/parport_amiga.c
8993
7636
/* Low-level parallel port routines for the Amiga built-in port * * Author: Joerg Dorchain <joerg@dorchain.net> * * This is a complete rewrite of the code, but based heaviy upon the old * lp_intern. code. * * The built-in Amiga parallel port provides one port at a fixed address * with 8 bidirectional data lines (D0 - D7) and 3 bidirectional status * lines (BUSY, POUT, SEL), 1 output control line /STROBE (raised automatically * in hardware when the data register is accessed), and 1 input control line * /ACK, able to cause an interrupt, but both not directly settable by * software. */ #include <linux/module.h> #include <linux/init.h> #include <linux/parport.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <asm/setup.h> #include <asm/amigahw.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/amigaints.h> #undef DEBUG #ifdef DEBUG #define DPRINTK printk #else #define DPRINTK(x...) do { } while (0) #endif static void amiga_write_data(struct parport *p, unsigned char data) { DPRINTK(KERN_DEBUG "write_data %c\n",data); /* Triggers also /STROBE. This behavior cannot be changed */ ciaa.prb = data; mb(); } static unsigned char amiga_read_data(struct parport *p) { /* Triggers also /STROBE. This behavior cannot be changed */ return ciaa.prb; } #if 0 static unsigned char control_pc_to_amiga(unsigned char control) { unsigned char ret = 0; if (control & PARPORT_CONTROL_SELECT) /* XXX: What is SELECP? */ ; if (control & PARPORT_CONTROL_INIT) /* INITP */ /* reset connected to cpu reset pin */; if (control & PARPORT_CONTROL_AUTOFD) /* AUTOLF */ /* Not connected */; if (control & PARPORT_CONTROL_STROBE) /* Strobe */ /* Handled only directly by hardware */; return ret; } #endif static unsigned char control_amiga_to_pc(unsigned char control) { return PARPORT_CONTROL_SELECT | PARPORT_CONTROL_AUTOFD | PARPORT_CONTROL_STROBE; /* fake value: interrupt enable, select in, no reset, no autolf, no strobe - seems to be closest the wiring diagram */ } static void amiga_write_control(struct parport *p, unsigned char control) { DPRINTK(KERN_DEBUG "write_control %02x\n",control); /* No implementation possible */ } static unsigned char amiga_read_control( struct parport *p) { DPRINTK(KERN_DEBUG "read_control \n"); return control_amiga_to_pc(0); } static unsigned char amiga_frob_control( struct parport *p, unsigned char mask, unsigned char val) { unsigned char old; DPRINTK(KERN_DEBUG "frob_control mask %02x, value %02x\n",mask,val); old = amiga_read_control(p); amiga_write_control(p, (old & ~mask) ^ val); return old; } #if 0 /* currently unused */ static unsigned char status_pc_to_amiga(unsigned char status) { unsigned char ret = 1; if (status & PARPORT_STATUS_BUSY) /* Busy */ ret &= ~1; if (status & PARPORT_STATUS_ACK) /* Ack */ /* handled in hardware */; if (status & PARPORT_STATUS_PAPEROUT) /* PaperOut */ ret |= 2; if (status & PARPORT_STATUS_SELECT) /* select */ ret |= 4; if (status & PARPORT_STATUS_ERROR) /* error */ /* not connected */; return ret; } #endif static unsigned char status_amiga_to_pc(unsigned char status) { unsigned char ret = PARPORT_STATUS_BUSY | PARPORT_STATUS_ACK | PARPORT_STATUS_ERROR; if (status & 1) /* Busy */ ret &= ~PARPORT_STATUS_BUSY; if (status & 2) /* PaperOut */ ret |= PARPORT_STATUS_PAPEROUT; if (status & 4) /* Selected */ ret |= PARPORT_STATUS_SELECT; /* the rest is not connected or handled autonomously in hardware */ return ret; } static unsigned char amiga_read_status(struct parport *p) { unsigned char status; status = status_amiga_to_pc(ciab.pra & 7); DPRINTK(KERN_DEBUG "read_status %02x\n", status); return status; } static void amiga_enable_irq(struct parport *p) { enable_irq(IRQ_AMIGA_CIAA_FLG); } static void amiga_disable_irq(struct parport *p) { disable_irq(IRQ_AMIGA_CIAA_FLG); } static void amiga_data_forward(struct parport *p) { DPRINTK(KERN_DEBUG "forward\n"); ciaa.ddrb = 0xff; /* all pins output */ mb(); } static void amiga_data_reverse(struct parport *p) { DPRINTK(KERN_DEBUG "reverse\n"); ciaa.ddrb = 0; /* all pins input */ mb(); } static void amiga_init_state(struct pardevice *dev, struct parport_state *s) { s->u.amiga.data = 0; s->u.amiga.datadir = 255; s->u.amiga.status = 0; s->u.amiga.statusdir = 0; } static void amiga_save_state(struct parport *p, struct parport_state *s) { mb(); s->u.amiga.data = ciaa.prb; s->u.amiga.datadir = ciaa.ddrb; s->u.amiga.status = ciab.pra & 7; s->u.amiga.statusdir = ciab.ddra & 7; mb(); } static void amiga_restore_state(struct parport *p, struct parport_state *s) { mb(); ciaa.prb = s->u.amiga.data; ciaa.ddrb = s->u.amiga.datadir; ciab.pra |= (ciab.pra & 0xf8) | s->u.amiga.status; ciab.ddra |= (ciab.ddra & 0xf8) | s->u.amiga.statusdir; mb(); } static struct parport_operations pp_amiga_ops = { .write_data = amiga_write_data, .read_data = amiga_read_data, .write_control = amiga_write_control, .read_control = amiga_read_control, .frob_control = amiga_frob_control, .read_status = amiga_read_status, .enable_irq = amiga_enable_irq, .disable_irq = amiga_disable_irq, .data_forward = amiga_data_forward, .data_reverse = amiga_data_reverse, .init_state = amiga_init_state, .save_state = amiga_save_state, .restore_state = amiga_restore_state, .epp_write_data = parport_ieee1284_epp_write_data, .epp_read_data = parport_ieee1284_epp_read_data, .epp_write_addr = parport_ieee1284_epp_write_addr, .epp_read_addr = parport_ieee1284_epp_read_addr, .ecp_write_data = parport_ieee1284_ecp_write_data, .ecp_read_data = parport_ieee1284_ecp_read_data, .ecp_write_addr = parport_ieee1284_ecp_write_addr, .compat_write_data = parport_ieee1284_write_compat, .nibble_read_data = parport_ieee1284_read_nibble, .byte_read_data = parport_ieee1284_read_byte, .owner = THIS_MODULE, }; /* ----------- Initialisation code --------------------------------- */ static int __init amiga_parallel_probe(struct platform_device *pdev) { struct parport *p; int err; ciaa.ddrb = 0xff; ciab.ddra &= 0xf8; mb(); p = parport_register_port((unsigned long)&ciaa.prb, IRQ_AMIGA_CIAA_FLG, PARPORT_DMA_NONE, &pp_amiga_ops); if (!p) return -EBUSY; err = request_irq(IRQ_AMIGA_CIAA_FLG, parport_irq_handler, 0, p->name, p); if (err) goto out_irq; printk(KERN_INFO "%s: Amiga built-in port using irq\n", p->name); /* XXX: set operating mode */ parport_announce_port(p); platform_set_drvdata(pdev, p); return 0; out_irq: parport_put_port(p); return err; } static int __exit amiga_parallel_remove(struct platform_device *pdev) { struct parport *port = platform_get_drvdata(pdev); parport_remove_port(port); if (port->irq != PARPORT_IRQ_NONE) free_irq(IRQ_AMIGA_CIAA_FLG, port); parport_put_port(port); platform_set_drvdata(pdev, NULL); return 0; } static struct platform_driver amiga_parallel_driver = { .remove = __exit_p(amiga_parallel_remove), .driver = { .name = "amiga-parallel", .owner = THIS_MODULE, }, }; static int __init amiga_parallel_init(void) { return platform_driver_probe(&amiga_parallel_driver, amiga_parallel_probe); } module_init(amiga_parallel_init); static void __exit amiga_parallel_exit(void) { platform_driver_unregister(&amiga_parallel_driver); } module_exit(amiga_parallel_exit); MODULE_AUTHOR("Joerg Dorchain <joerg@dorchain.net>"); MODULE_DESCRIPTION("Parport Driver for Amiga builtin Port"); MODULE_SUPPORTED_DEVICE("Amiga builtin Parallel Port"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:amiga-parallel");
gpl-2.0
vie-camera-team/linux-socfpga
arch/mips/pci/fixup-rbtx4938.c
13857
1221
/* * Toshiba rbtx4938 pci routines * Copyright (C) 2000-2001 Toshiba Corporation * * 2003-2005 (c) MontaVista Software, Inc. 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. * * Support for TX4938 in 2.6 - Manish Lachwani (mlachwani@mvista.com) */ #include <linux/types.h> #include <asm/txx9/pci.h> #include <asm/txx9/rbtx4938.h> int __init rbtx4938_pci_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { int irq = tx4938_pcic1_map_irq(dev, slot); if (irq >= 0) return irq; irq = pin; /* IRQ rotation */ irq--; /* 0-3 */ if (slot == TX4927_PCIC_IDSEL_AD_TO_SLOT(23)) { /* PCI CardSlot (IDSEL=A23) */ /* PCIA => PCIA (IDSEL=A23) */ irq = (irq + 0 + slot) % 4; } else { /* PCI Backplane */ if (txx9_pci_option & TXX9_PCI_OPT_PICMG) irq = (irq + 33 - slot) % 4; else irq = (irq + 3 + slot) % 4; } irq++; /* 1-4 */ switch (irq) { case 1: irq = RBTX4938_IRQ_IOC_PCIA; break; case 2: irq = RBTX4938_IRQ_IOC_PCIB; break; case 3: irq = RBTX4938_IRQ_IOC_PCIC; break; case 4: irq = RBTX4938_IRQ_IOC_PCID; break; } return irq; }
gpl-2.0
ebildude123/Geass-Kernel-TF300T
arch/mips/pci/fixup-rbtx4927.c
13857
2373
/* * * BRIEF MODULE DESCRIPTION * Board specific pci fixups for the Toshiba rbtx4927 * * Copyright 2001 MontaVista Software Inc. * Author: MontaVista Software, Inc. * ppopov@mvista.com or source@mvista.com * * Copyright (C) 2000-2001 Toshiba Corporation * * Copyright (C) 2004 MontaVista Software Inc. * Author: Manish Lachwani (mlachwani@mvista.com) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * 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/types.h> #include <asm/txx9/pci.h> #include <asm/txx9/rbtx4927.h> int __init rbtx4927_pci_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { unsigned char irq = pin; /* IRQ rotation */ irq--; /* 0-3 */ if (slot == TX4927_PCIC_IDSEL_AD_TO_SLOT(23)) { /* PCI CardSlot (IDSEL=A23) */ /* PCIA => PCIA */ irq = (irq + 0 + slot) % 4; } else { /* PCI Backplane */ if (txx9_pci_option & TXX9_PCI_OPT_PICMG) irq = (irq + 33 - slot) % 4; else irq = (irq + 3 + slot) % 4; } irq++; /* 1-4 */ switch (irq) { case 1: irq = RBTX4927_IRQ_IOC_PCIA; break; case 2: irq = RBTX4927_IRQ_IOC_PCIB; break; case 3: irq = RBTX4927_IRQ_IOC_PCIC; break; case 4: irq = RBTX4927_IRQ_IOC_PCID; break; } return irq; }
gpl-2.0
noneabove1182/HTC_M8_Kernel
drivers/idle/i7300_idle.c
34
12975
/* * (C) Copyright 2008 Intel Corporation * Authors: * Andy Henroid <andrew.d.henroid@intel.com> * Venkatesh Pallipadi <venkatesh.pallipadi@intel.com> */ #include <linux/module.h> #include <linux/pci.h> #include <linux/gfp.h> #include <linux/sched.h> #include <linux/notifier.h> #include <linux/cpumask.h> #include <linux/ktime.h> #include <linux/delay.h> #include <linux/debugfs.h> #include <linux/stop_machine.h> #include <linux/i7300_idle.h> #include <asm/idle.h> #include "../dma/ioat/hw.h" #include "../dma/ioat/registers.h" #define I7300_IDLE_DRIVER_VERSION "1.55" #define I7300_PRINT "i7300_idle:" #define MAX_STOP_RETRIES 10 static int debug; module_param_named(debug, debug, uint, 0644); MODULE_PARM_DESC(debug, "Enable debug printks in this driver"); static int forceload; module_param_named(forceload, forceload, uint, 0644); MODULE_PARM_DESC(debug, "Enable driver testing on unvalidated i5000"); #define dprintk(fmt, arg...) \ do { if (debug) printk(KERN_INFO I7300_PRINT fmt, ##arg); } while (0) #define MAX_THROTTLE_LOW_LIMIT 168 static uint throttle_low_limit = 1; module_param_named(throttle_low_limit, throttle_low_limit, uint, 0644); MODULE_PARM_DESC(throttle_low_limit, "Value for THRTLOWLM activation field " "(0 = disable throttle, 1 = Max throttle, 168 = Min throttle)"); static unsigned long total_starts; static unsigned long total_us; #ifdef DEBUG static unsigned long past_skip; #endif static struct pci_dev *fbd_dev; static spinlock_t i7300_idle_lock; static int i7300_idle_active; static u8 i7300_idle_thrtctl_saved; static u8 i7300_idle_thrtlow_saved; static u32 i7300_idle_mc_saved; static cpumask_var_t idle_cpumask; static ktime_t start_ktime; static unsigned long avg_idle_us; static struct dentry *debugfs_dir; #define IOAT_CHANBASE(ioat_ctl, chan) (ioat_ctl + 0x80 + 0x80 * chan) #define IOAT_DESC_SADDR_SNP_CTL (1UL << 1) #define IOAT_DESC_DADDR_SNP_CTL (1UL << 2) static struct pci_dev *ioat_dev; static struct ioat_dma_descriptor *ioat_desc; static unsigned long ioat_desc_phys; static u8 *ioat_iomap; static u8 *ioat_chanbase; static int i7300_idle_ioat_start(void) { u32 err; err = readl(ioat_chanbase + IOAT_CHANERR_OFFSET); if (err) writel(err, ioat_chanbase + IOAT_CHANERR_OFFSET); writeb(IOAT_CHANCMD_START, ioat_chanbase + IOAT1_CHANCMD_OFFSET); return 0; } static void i7300_idle_ioat_stop(void) { int i; u64 sts; for (i = 0; i < MAX_STOP_RETRIES; i++) { writeb(IOAT_CHANCMD_RESET, ioat_chanbase + IOAT1_CHANCMD_OFFSET); udelay(10); sts = readq(ioat_chanbase + IOAT1_CHANSTS_OFFSET) & IOAT_CHANSTS_STATUS; if (sts != IOAT_CHANSTS_ACTIVE) break; } if (i == MAX_STOP_RETRIES) { dprintk("failed to stop I/O AT after %d retries\n", MAX_STOP_RETRIES); } } static int __init i7300_idle_ioat_selftest(u8 *ctl, struct ioat_dma_descriptor *desc, unsigned long desc_phys) { u64 chan_sts; memset(desc, 0, 2048); memset((u8 *) desc + 2048, 0xab, 1024); desc[0].size = 1024; desc[0].ctl = 0; desc[0].src_addr = desc_phys + 2048; desc[0].dst_addr = desc_phys + 1024; desc[0].next = 0; writeb(IOAT_CHANCMD_RESET, ioat_chanbase + IOAT1_CHANCMD_OFFSET); writeb(IOAT_CHANCMD_START, ioat_chanbase + IOAT1_CHANCMD_OFFSET); udelay(1000); chan_sts = readq(ioat_chanbase + IOAT1_CHANSTS_OFFSET) & IOAT_CHANSTS_STATUS; if (chan_sts != IOAT_CHANSTS_DONE) { writeb(IOAT_CHANCMD_RESET, ioat_chanbase + IOAT1_CHANCMD_OFFSET); return -1; } if (*(u32 *) ((u8 *) desc + 3068) != 0xabababab || *(u32 *) ((u8 *) desc + 2044) != 0xabababab) { dprintk("Data values src 0x%x, dest 0x%x, memset 0x%x\n", *(u32 *) ((u8 *) desc + 2048), *(u32 *) ((u8 *) desc + 1024), *(u32 *) ((u8 *) desc + 3072)); return -1; } return 0; } static struct device dummy_dma_dev = { .init_name = "fallback device", .coherent_dma_mask = DMA_BIT_MASK(64), .dma_mask = &dummy_dma_dev.coherent_dma_mask, }; static int __init i7300_idle_ioat_init(void) { u8 ver, chan_count, ioat_chan; u16 chan_ctl; ioat_iomap = (u8 *) ioremap_nocache(pci_resource_start(ioat_dev, 0), pci_resource_len(ioat_dev, 0)); if (!ioat_iomap) { printk(KERN_ERR I7300_PRINT "failed to map I/O AT registers\n"); goto err_ret; } ver = readb(ioat_iomap + IOAT_VER_OFFSET); if (ver != IOAT_VER_1_2) { printk(KERN_ERR I7300_PRINT "unknown I/O AT version (%u.%u)\n", ver >> 4, ver & 0xf); goto err_unmap; } chan_count = readb(ioat_iomap + IOAT_CHANCNT_OFFSET); if (!chan_count) { printk(KERN_ERR I7300_PRINT "unexpected # of I/O AT channels " "(%u)\n", chan_count); goto err_unmap; } ioat_chan = chan_count - 1; ioat_chanbase = IOAT_CHANBASE(ioat_iomap, ioat_chan); chan_ctl = readw(ioat_chanbase + IOAT_CHANCTRL_OFFSET); if (chan_ctl & IOAT_CHANCTRL_CHANNEL_IN_USE) { printk(KERN_ERR I7300_PRINT "channel %d in use\n", ioat_chan); goto err_unmap; } writew(IOAT_CHANCTRL_CHANNEL_IN_USE, ioat_chanbase + IOAT_CHANCTRL_OFFSET); ioat_desc = (struct ioat_dma_descriptor *)dma_alloc_coherent( &dummy_dma_dev, 4096, (dma_addr_t *)&ioat_desc_phys, GFP_KERNEL); if (!ioat_desc) { printk(KERN_ERR I7300_PRINT "failed to allocate I/O AT desc\n"); goto err_mark_unused; } writel(ioat_desc_phys & 0xffffffffUL, ioat_chanbase + IOAT1_CHAINADDR_OFFSET_LOW); writel(ioat_desc_phys >> 32, ioat_chanbase + IOAT1_CHAINADDR_OFFSET_HIGH); if (i7300_idle_ioat_selftest(ioat_iomap, ioat_desc, ioat_desc_phys)) { printk(KERN_ERR I7300_PRINT "I/O AT self-test failed\n"); goto err_free; } ioat_desc[0].ctl = IOAT_DESC_SADDR_SNP_CTL | IOAT_DESC_DADDR_SNP_CTL; ioat_desc[0].src_addr = ioat_desc_phys + 2048; ioat_desc[0].dst_addr = ioat_desc_phys + 3072; ioat_desc[0].size = 128; ioat_desc[0].next = ioat_desc_phys + sizeof(struct ioat_dma_descriptor); ioat_desc[1].ctl = ioat_desc[0].ctl; ioat_desc[1].src_addr = ioat_desc[0].src_addr; ioat_desc[1].dst_addr = ioat_desc[0].dst_addr; ioat_desc[1].size = ioat_desc[0].size; ioat_desc[1].next = ioat_desc_phys; return 0; err_free: dma_free_coherent(&dummy_dma_dev, 4096, (void *)ioat_desc, 0); err_mark_unused: writew(0, ioat_chanbase + IOAT_CHANCTRL_OFFSET); err_unmap: iounmap(ioat_iomap); err_ret: return -ENODEV; } static void __exit i7300_idle_ioat_exit(void) { int i; u64 chan_sts; i7300_idle_ioat_stop(); for (i = 0; i < MAX_STOP_RETRIES; i++) { writeb(IOAT_CHANCMD_RESET, ioat_chanbase + IOAT1_CHANCMD_OFFSET); chan_sts = readq(ioat_chanbase + IOAT1_CHANSTS_OFFSET) & IOAT_CHANSTS_STATUS; if (chan_sts != IOAT_CHANSTS_ACTIVE) { writew(0, ioat_chanbase + IOAT_CHANCTRL_OFFSET); break; } udelay(1000); } chan_sts = readq(ioat_chanbase + IOAT1_CHANSTS_OFFSET) & IOAT_CHANSTS_STATUS; if (chan_sts == IOAT_CHANSTS_ACTIVE) { printk(KERN_ERR I7300_PRINT "Unable to stop IO A/T channels." " Not freeing resources\n"); return; } dma_free_coherent(&dummy_dma_dev, 4096, (void *)ioat_desc, 0); iounmap(ioat_iomap); } #define DIMM_THRTLOW 0x64 #define DIMM_THRTCTL 0x67 #define DIMM_THRTCTL_THRMHUNT (1UL << 0) #define DIMM_MC 0x40 #define DIMM_GTW_MODE (1UL << 17) #define DIMM_GBLACT 0x60 #define DURATION_WEIGHT_PCT 55 #define DURATION_THRESHOLD_US 100 static int i7300_idle_thrt_save(void) { u32 new_mc_val; u8 gblactlm; pci_read_config_byte(fbd_dev, DIMM_THRTCTL, &i7300_idle_thrtctl_saved); pci_read_config_byte(fbd_dev, DIMM_THRTLOW, &i7300_idle_thrtlow_saved); pci_read_config_dword(fbd_dev, DIMM_MC, &i7300_idle_mc_saved); pci_read_config_byte(fbd_dev, DIMM_GBLACT, &gblactlm); dprintk("thrtctl_saved = 0x%02x, thrtlow_saved = 0x%02x\n", i7300_idle_thrtctl_saved, i7300_idle_thrtlow_saved); dprintk("mc_saved = 0x%08x, gblactlm = 0x%02x\n", i7300_idle_mc_saved, gblactlm); if (gblactlm == 0) { new_mc_val = i7300_idle_mc_saved | DIMM_GTW_MODE; pci_write_config_dword(fbd_dev, DIMM_MC, new_mc_val); return 0; } else { dprintk("could not set GTW_MODE = 1 (OLTT enabled)\n"); return -ENODEV; } } static void i7300_idle_thrt_restore(void) { pci_write_config_dword(fbd_dev, DIMM_MC, i7300_idle_mc_saved); pci_write_config_byte(fbd_dev, DIMM_THRTLOW, i7300_idle_thrtlow_saved); pci_write_config_byte(fbd_dev, DIMM_THRTCTL, i7300_idle_thrtctl_saved); } static void i7300_idle_start(void) { u8 new_ctl; u8 limit; new_ctl = i7300_idle_thrtctl_saved & ~DIMM_THRTCTL_THRMHUNT; pci_write_config_byte(fbd_dev, DIMM_THRTCTL, new_ctl); limit = throttle_low_limit; if (unlikely(limit > MAX_THROTTLE_LOW_LIMIT)) limit = MAX_THROTTLE_LOW_LIMIT; pci_write_config_byte(fbd_dev, DIMM_THRTLOW, limit); new_ctl = i7300_idle_thrtctl_saved | DIMM_THRTCTL_THRMHUNT; pci_write_config_byte(fbd_dev, DIMM_THRTCTL, new_ctl); } static void i7300_idle_stop(void) { u8 new_ctl; u8 got_ctl; new_ctl = i7300_idle_thrtctl_saved & ~DIMM_THRTCTL_THRMHUNT; pci_write_config_byte(fbd_dev, DIMM_THRTCTL, new_ctl); pci_write_config_byte(fbd_dev, DIMM_THRTLOW, i7300_idle_thrtlow_saved); pci_write_config_byte(fbd_dev, DIMM_THRTCTL, i7300_idle_thrtctl_saved); pci_read_config_byte(fbd_dev, DIMM_THRTCTL, &got_ctl); WARN_ON_ONCE(got_ctl != i7300_idle_thrtctl_saved); } static int i7300_avg_duration_check(void) { if (avg_idle_us >= DURATION_THRESHOLD_US) return 0; #ifdef DEBUG past_skip++; #endif return 1; } static int i7300_idle_notifier(struct notifier_block *nb, unsigned long val, void *data) { unsigned long flags; ktime_t now_ktime; static ktime_t idle_begin_time; static int time_init = 1; if (!throttle_low_limit) return 0; if (unlikely(time_init)) { time_init = 0; idle_begin_time = ktime_get(); } spin_lock_irqsave(&i7300_idle_lock, flags); if (val == IDLE_START) { cpumask_set_cpu(smp_processor_id(), idle_cpumask); if (cpumask_weight(idle_cpumask) != num_online_cpus()) goto end; now_ktime = ktime_get(); idle_begin_time = now_ktime; if (i7300_avg_duration_check()) goto end; i7300_idle_active = 1; total_starts++; start_ktime = now_ktime; i7300_idle_start(); i7300_idle_ioat_start(); } else if (val == IDLE_END) { cpumask_clear_cpu(smp_processor_id(), idle_cpumask); if (cpumask_weight(idle_cpumask) == (num_online_cpus() - 1)) { u64 idle_duration_us; now_ktime = ktime_get(); idle_duration_us = ktime_to_us(ktime_sub (now_ktime, idle_begin_time)); avg_idle_us = ((100 - DURATION_WEIGHT_PCT) * avg_idle_us + DURATION_WEIGHT_PCT * idle_duration_us) / 100; if (i7300_idle_active) { ktime_t idle_ktime; idle_ktime = ktime_sub(now_ktime, start_ktime); total_us += ktime_to_us(idle_ktime); i7300_idle_ioat_stop(); i7300_idle_stop(); i7300_idle_active = 0; } } } end: spin_unlock_irqrestore(&i7300_idle_lock, flags); return 0; } static struct notifier_block i7300_idle_nb = { .notifier_call = i7300_idle_notifier, }; MODULE_DEVICE_TABLE(pci, pci_tbl); static ssize_t stats_read_ul(struct file *fp, char __user *ubuf, size_t count, loff_t *off) { unsigned long *p = fp->private_data; char buf[32]; int len; len = snprintf(buf, 32, "%lu\n", *p); return simple_read_from_buffer(ubuf, count, off, buf, len); } static const struct file_operations idle_fops = { .open = simple_open, .read = stats_read_ul, .llseek = default_llseek, }; struct debugfs_file_info { void *ptr; char name[32]; struct dentry *file; } debugfs_file_list[] = { {&total_starts, "total_starts", NULL}, {&total_us, "total_us", NULL}, #ifdef DEBUG {&past_skip, "past_skip", NULL}, #endif {NULL, "", NULL} }; static int __init i7300_idle_init(void) { spin_lock_init(&i7300_idle_lock); total_us = 0; if (i7300_idle_platform_probe(&fbd_dev, &ioat_dev, forceload)) return -ENODEV; if (i7300_idle_thrt_save()) return -ENODEV; if (i7300_idle_ioat_init()) return -ENODEV; if (!zalloc_cpumask_var(&idle_cpumask, GFP_KERNEL)) return -ENOMEM; debugfs_dir = debugfs_create_dir("i7300_idle", NULL); if (debugfs_dir) { int i = 0; while (debugfs_file_list[i].ptr != NULL) { debugfs_file_list[i].file = debugfs_create_file( debugfs_file_list[i].name, S_IRUSR, debugfs_dir, debugfs_file_list[i].ptr, &idle_fops); i++; } } idle_notifier_register(&i7300_idle_nb); printk(KERN_INFO "i7300_idle: loaded v%s\n", I7300_IDLE_DRIVER_VERSION); return 0; } static void __exit i7300_idle_exit(void) { idle_notifier_unregister(&i7300_idle_nb); free_cpumask_var(idle_cpumask); if (debugfs_dir) { int i = 0; while (debugfs_file_list[i].file != NULL) { debugfs_remove(debugfs_file_list[i].file); i++; } debugfs_remove(debugfs_dir); } i7300_idle_thrt_restore(); i7300_idle_ioat_exit(); } module_init(i7300_idle_init); module_exit(i7300_idle_exit); MODULE_AUTHOR("Andy Henroid <andrew.d.henroid@intel.com>"); MODULE_DESCRIPTION("Intel Chipset DIMM Idle Power Saving Driver v" I7300_IDLE_DRIVER_VERSION); MODULE_LICENSE("GPL");
gpl-2.0
zhangzr1026/MySQL_Chinese_Comments
storage/mroonga/vendor/groonga/benchmark/bench-ctx-create.c
34
4638
/* -*- c-basic-offset: 2; coding: utf-8 -*- */ /* Copyright (C) 2013-2014 Kouhei Sutou <kou@clear-code.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* Groonga: 6b128f318d682e50648f3b82c5f7956f3bcb3fe8 CFLAGS: -O0 -g3 % (cd benchmark/ && make --quiet run-bench-ctx-create) run-bench-ctx-create: (time) with mruby1: 288KB (0.0091s) without mruby1: 28KB (0.0240ms) with mruby2: 0KB (0.0097s) without mruby2: 0KB (0.0220ms) Groonga: c4379140c02699e3c74b94cd9e7b88d372202aa5 CFLAGS: -O2 -g % make --quiet -C benchmark run-bench-ctx-create run-bench-ctx-create: (time) with mruby1: 524KB (0.0041s) without mruby1: 32KB (0.0220ms) with mruby2: 0KB (0.0040s) without mruby2: 0KB (0.0200ms) */ #include <stdlib.h> #include <glib.h> #include <groonga.h> #include "lib/benchmark.h" typedef struct _BenchmarkData { grn_ctx context; grn_obj *database; guint memory_usage_before; } BenchmarkData; static guint get_memory_usage(void) { GRegex *vm_rss_pattern; gchar *status; GMatchInfo *match_info; gchar *vm_rss_string; guint vm_rss; g_file_get_contents("/proc/self/status", &status, NULL, NULL); vm_rss_pattern = g_regex_new("VmRSS:\\s*(\\d*)\\s+kB", 0, 0, NULL); if (!g_regex_match(vm_rss_pattern, status, 0, &match_info)) { g_print("not match...: %s\n", status); return 0; } vm_rss_string = g_match_info_fetch(match_info, 1); vm_rss = atoi(vm_rss_string); g_free(vm_rss_string); g_match_info_free(match_info); g_regex_unref(vm_rss_pattern); g_free(status); return vm_rss; } static void bench_with_mruby(gpointer user_data) { BenchmarkData *data = user_data; g_setenv("GRN_MRUBY_ENABLED", "yes", TRUE); grn_ctx_init(&(data->context), 0); grn_ctx_use(&(data->context), data->database); } static void bench_without_mruby(gpointer user_data) { BenchmarkData *data = user_data; g_setenv("GRN_MRUBY_ENABLED", "no", TRUE); grn_ctx_init(&(data->context), 0); grn_ctx_use(&(data->context), data->database); } static void bench_setup(gpointer user_data) { BenchmarkData *data = user_data; data->memory_usage_before = get_memory_usage(); } static void bench_teardown(gpointer user_data) { BenchmarkData *data = user_data; grn_ctx_fin(&(data->context)); g_print("%3dKB ", get_memory_usage() - data->memory_usage_before); } static gchar * get_tmp_dir(void) { gchar *current_dir; gchar *tmp_dir; current_dir = g_get_current_dir(); tmp_dir = g_build_filename(current_dir, "tmp", NULL); g_free(current_dir); return tmp_dir; } static grn_obj * setup_database(grn_ctx *context) { gchar *tmp_dir; gchar *database_path; grn_obj *database; tmp_dir = get_tmp_dir(); database_path = g_build_filename(tmp_dir, "ctx-create", "db", NULL); database = grn_db_open(context, database_path); g_free(database_path); return database; } static void teardown_database(grn_ctx *context, grn_obj *database) { grn_obj_close(context, database); } int main(int argc, gchar **argv) { grn_ctx context; BenchmarkData data; BenchReporter *reporter; gint n = 1; grn_init(); bench_init(&argc, &argv); grn_ctx_init(&context, 0); data.database = setup_database(&context); reporter = bench_reporter_new(); #define REGISTER(label, bench_function) \ bench_reporter_register(reporter, label, n, \ bench_setup, \ bench_function, \ bench_teardown, \ &data) REGISTER("with mruby1", bench_with_mruby); REGISTER("without mruby1", bench_without_mruby); REGISTER("with mruby2", bench_with_mruby); REGISTER("without mruby2", bench_without_mruby); #undef REGISTER bench_reporter_run(reporter); g_object_unref(reporter); teardown_database(&context, data.database); grn_ctx_fin(&context); grn_fin(); return 0; }
gpl-2.0
k5t4j5/kernel_htc_hybrid
arch/arm/mach-omap2/dpll44xx.c
34
2579
/* * OMAP4-specific DPLL control functions * * Copyright (C) 2011 Texas Instruments, Inc. * Rajendra Nayak * * 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/errno.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/bitops.h> #include <plat/cpu.h> #include <plat/clock.h> #include "clock.h" #include "clock44xx.h" #include "cm-regbits-44xx.h" int omap4_dpllmx_gatectrl_read(struct clk *clk) { u32 v; u32 mask; if (!clk || !clk->clksel_reg || !cpu_is_omap44xx()) return -EINVAL; mask = clk->flags & CLOCK_CLKOUTX2 ? OMAP4430_DPLL_CLKOUTX2_GATE_CTRL_MASK : OMAP4430_DPLL_CLKOUT_GATE_CTRL_MASK; v = __raw_readl(clk->clksel_reg); v &= mask; v >>= __ffs(mask); return v; } void omap4_dpllmx_allow_gatectrl(struct clk *clk) { u32 v; u32 mask; if (!clk || !clk->clksel_reg || !cpu_is_omap44xx()) return; mask = clk->flags & CLOCK_CLKOUTX2 ? OMAP4430_DPLL_CLKOUTX2_GATE_CTRL_MASK : OMAP4430_DPLL_CLKOUT_GATE_CTRL_MASK; v = __raw_readl(clk->clksel_reg); v &= ~mask; __raw_writel(v, clk->clksel_reg); } void omap4_dpllmx_deny_gatectrl(struct clk *clk) { u32 v; u32 mask; if (!clk || !clk->clksel_reg || !cpu_is_omap44xx()) return; mask = clk->flags & CLOCK_CLKOUTX2 ? OMAP4430_DPLL_CLKOUTX2_GATE_CTRL_MASK : OMAP4430_DPLL_CLKOUT_GATE_CTRL_MASK; v = __raw_readl(clk->clksel_reg); v |= mask; __raw_writel(v, clk->clksel_reg); } const struct clkops clkops_omap4_dpllmx_ops = { .allow_idle = omap4_dpllmx_allow_gatectrl, .deny_idle = omap4_dpllmx_deny_gatectrl, }; unsigned long omap4_dpll_regm4xen_recalc(struct clk *clk) { u32 v; unsigned long rate; struct dpll_data *dd; if (!clk || !clk->dpll_data) return 0; dd = clk->dpll_data; rate = omap2_get_dpll_rate(clk); v = __raw_readl(dd->control_reg); if (v & OMAP4430_DPLL_REGM4XEN_MASK) rate *= OMAP4430_REGM4XEN_MULT; return rate; } long omap4_dpll_regm4xen_round_rate(struct clk *clk, unsigned long target_rate) { u32 v; struct dpll_data *dd; long r; if (!clk || !clk->dpll_data) return -EINVAL; dd = clk->dpll_data; v = __raw_readl(dd->control_reg) & OMAP4430_DPLL_REGM4XEN_MASK; if (v) target_rate = target_rate / OMAP4430_REGM4XEN_MULT; r = omap2_dpll_round_rate(clk, target_rate); if (r == ~0) return r; if (v) clk->dpll_data->last_rounded_rate *= OMAP4430_REGM4XEN_MULT; return clk->dpll_data->last_rounded_rate; }
gpl-2.0
mlachwani/Android-4.4.3-HTC-M8-Kernel-ATT
sound/soc/mxs/mxs-saif.c
34
15768
/* * Copyright 2011 Freescale Semiconductor, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License 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 <linux/module.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/dma-mapping.h> #include <linux/clk.h> #include <linux/delay.h> #include <linux/time.h> #include <linux/fsl/mxs-dma.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/saif.h> #include <asm/mach-types.h> #include <mach/hardware.h> #include <mach/mxs.h> #include "mxs-saif.h" static struct mxs_saif *mxs_saif[2]; static int mxs_saif_set_dai_sysclk(struct snd_soc_dai *cpu_dai, int clk_id, unsigned int freq, int dir) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); switch (clk_id) { case MXS_SAIF_MCLK: saif->mclk = freq; break; default: return -EINVAL; } return 0; } static inline struct mxs_saif *mxs_saif_get_master(struct mxs_saif * saif) { return mxs_saif[saif->master_id]; } static int mxs_saif_set_clk(struct mxs_saif *saif, unsigned int mclk, unsigned int rate) { u32 scr; int ret; struct mxs_saif *master_saif; dev_dbg(saif->dev, "mclk %d rate %d\n", mclk, rate); master_saif = mxs_saif_get_master(saif); if (!master_saif) return -EINVAL; dev_dbg(saif->dev, "master saif%d\n", master_saif->id); if (master_saif->ongoing && rate != master_saif->cur_rate) { dev_err(saif->dev, "can not change clock, master saif%d(rate %d) is ongoing\n", master_saif->id, master_saif->cur_rate); return -EINVAL; } scr = __raw_readl(master_saif->base + SAIF_CTRL); scr &= ~BM_SAIF_CTRL_BITCLK_MULT_RATE; scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; clk_prepare_enable(master_saif->clk); if (master_saif->mclk_in_use) { if (mclk % 32 == 0) { scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; ret = clk_set_rate(master_saif->clk, 512 * rate); } else if (mclk % 48 == 0) { scr |= BM_SAIF_CTRL_BITCLK_BASE_RATE; ret = clk_set_rate(master_saif->clk, 384 * rate); } else { clk_disable_unprepare(master_saif->clk); return -EINVAL; } } else { ret = clk_set_rate(master_saif->clk, 512 * rate); scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; } clk_disable_unprepare(master_saif->clk); if (ret) return ret; master_saif->cur_rate = rate; if (!master_saif->mclk_in_use) { __raw_writel(scr, master_saif->base + SAIF_CTRL); return 0; } switch (mclk / rate) { case 32: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(4); break; case 64: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(3); break; case 128: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(2); break; case 256: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(1); break; case 512: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(0); break; case 48: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(3); break; case 96: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(2); break; case 192: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(1); break; case 384: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(0); break; default: return -EINVAL; } __raw_writel(scr, master_saif->base + SAIF_CTRL); return 0; } int mxs_saif_put_mclk(unsigned int saif_id) { struct mxs_saif *saif = mxs_saif[saif_id]; u32 stat; if (!saif) return -EINVAL; stat = __raw_readl(saif->base + SAIF_STAT); if (stat & BM_SAIF_STAT_BUSY) { dev_err(saif->dev, "error: busy\n"); return -EBUSY; } clk_disable_unprepare(saif->clk); __raw_writel(BM_SAIF_CTRL_CLKGATE, saif->base + SAIF_CTRL + MXS_SET_ADDR); __raw_writel(BM_SAIF_CTRL_RUN, saif->base + SAIF_CTRL + MXS_CLR_ADDR); saif->mclk_in_use = 0; return 0; } int mxs_saif_get_mclk(unsigned int saif_id, unsigned int mclk, unsigned int rate) { struct mxs_saif *saif = mxs_saif[saif_id]; u32 stat; int ret; struct mxs_saif *master_saif; if (!saif) return -EINVAL; __raw_writel(BM_SAIF_CTRL_SFTRST, saif->base + SAIF_CTRL + MXS_CLR_ADDR); __raw_writel(BM_SAIF_CTRL_CLKGATE, saif->base + SAIF_CTRL + MXS_CLR_ADDR); master_saif = mxs_saif_get_master(saif); if (saif != master_saif) { dev_err(saif->dev, "can not get mclk from a non-master saif\n"); return -EINVAL; } stat = __raw_readl(saif->base + SAIF_STAT); if (stat & BM_SAIF_STAT_BUSY) { dev_err(saif->dev, "error: busy\n"); return -EBUSY; } saif->mclk_in_use = 1; ret = mxs_saif_set_clk(saif, mclk, rate); if (ret) return ret; ret = clk_prepare_enable(saif->clk); if (ret) return ret; __raw_writel(BM_SAIF_CTRL_RUN, saif->base + SAIF_CTRL + MXS_SET_ADDR); return 0; } static int mxs_saif_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt) { u32 scr, stat; u32 scr0; struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); stat = __raw_readl(saif->base + SAIF_STAT); if (stat & BM_SAIF_STAT_BUSY) { dev_err(cpu_dai->dev, "error: busy\n"); return -EBUSY; } scr0 = __raw_readl(saif->base + SAIF_CTRL); scr0 = scr0 & ~BM_SAIF_CTRL_BITCLK_EDGE & ~BM_SAIF_CTRL_LRCLK_POLARITY \ & ~BM_SAIF_CTRL_JUSTIFY & ~BM_SAIF_CTRL_DELAY; scr = 0; switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: scr |= BM_SAIF_CTRL_DELAY; scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; break; case SND_SOC_DAIFMT_LEFT_J: scr &= ~BM_SAIF_CTRL_DELAY; scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; scr &= ~BM_SAIF_CTRL_JUSTIFY; break; default: return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_IB_IF: scr |= BM_SAIF_CTRL_BITCLK_EDGE; scr |= BM_SAIF_CTRL_LRCLK_POLARITY; break; case SND_SOC_DAIFMT_IB_NF: scr |= BM_SAIF_CTRL_BITCLK_EDGE; scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; break; case SND_SOC_DAIFMT_NB_IF: scr &= ~BM_SAIF_CTRL_BITCLK_EDGE; scr |= BM_SAIF_CTRL_LRCLK_POLARITY; break; case SND_SOC_DAIFMT_NB_NF: scr &= ~BM_SAIF_CTRL_BITCLK_EDGE; scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; break; } switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: if (saif->id == saif->master_id) scr &= ~BM_SAIF_CTRL_SLAVE_MODE; else scr |= BM_SAIF_CTRL_SLAVE_MODE; __raw_writel(scr | scr0, saif->base + SAIF_CTRL); break; default: return -EINVAL; } return 0; } static int mxs_saif_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); snd_soc_dai_set_dma_data(cpu_dai, substream, &saif->dma_param); saif->fifo_underrun = 0; saif->fifo_overrun = 0; __raw_writel(BM_SAIF_CTRL_SFTRST, saif->base + SAIF_CTRL + MXS_CLR_ADDR); __raw_writel(BM_SAIF_CTRL_CLKGATE, saif->base + SAIF_CTRL + MXS_CLR_ADDR); return 0; } static int mxs_saif_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); u32 scr, stat; int ret; if (!saif->mclk && saif->mclk_in_use) { dev_err(cpu_dai->dev, "set mclk first\n"); return -EINVAL; } stat = __raw_readl(saif->base + SAIF_STAT); if (stat & BM_SAIF_STAT_BUSY) { dev_err(cpu_dai->dev, "error: busy\n"); return -EBUSY; } ret = mxs_saif_set_clk(saif, saif->mclk, params_rate(params)); if (ret) { dev_err(cpu_dai->dev, "unable to get proper clk\n"); return ret; } scr = __raw_readl(saif->base + SAIF_CTRL); scr &= ~BM_SAIF_CTRL_WORD_LENGTH; scr &= ~BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: scr |= BF_SAIF_CTRL_WORD_LENGTH(0); break; case SNDRV_PCM_FORMAT_S20_3LE: scr |= BF_SAIF_CTRL_WORD_LENGTH(4); scr |= BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; break; case SNDRV_PCM_FORMAT_S24_LE: scr |= BF_SAIF_CTRL_WORD_LENGTH(8); scr |= BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; break; default: return -EINVAL; } if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { scr &= ~BM_SAIF_CTRL_READ_MODE; } else { scr |= BM_SAIF_CTRL_READ_MODE; } __raw_writel(scr, saif->base + SAIF_CTRL); return 0; } static int mxs_saif_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); __raw_writel(BM_SAIF_CTRL_FIFO_ERROR_IRQ_EN, saif->base + SAIF_CTRL + MXS_SET_ADDR); return 0; } static int mxs_saif_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); struct mxs_saif *master_saif; u32 delay; master_saif = mxs_saif_get_master(saif); if (!master_saif) return -EINVAL; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: dev_dbg(cpu_dai->dev, "start\n"); clk_enable(master_saif->clk); if (!master_saif->mclk_in_use) __raw_writel(BM_SAIF_CTRL_RUN, master_saif->base + SAIF_CTRL + MXS_SET_ADDR); if (saif != master_saif) { clk_enable(saif->clk); __raw_writel(BM_SAIF_CTRL_RUN, saif->base + SAIF_CTRL + MXS_SET_ADDR); } if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { __raw_writel(0, saif->base + SAIF_DATA); } else { __raw_readl(saif->base + SAIF_DATA); } master_saif->ongoing = 1; dev_dbg(saif->dev, "CTRL 0x%x STAT 0x%x\n", __raw_readl(saif->base + SAIF_CTRL), __raw_readl(saif->base + SAIF_STAT)); dev_dbg(master_saif->dev, "CTRL 0x%x STAT 0x%x\n", __raw_readl(master_saif->base + SAIF_CTRL), __raw_readl(master_saif->base + SAIF_STAT)); break; case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: dev_dbg(cpu_dai->dev, "stop\n"); delay = USEC_PER_SEC / master_saif->cur_rate; if (!master_saif->mclk_in_use) { __raw_writel(BM_SAIF_CTRL_RUN, master_saif->base + SAIF_CTRL + MXS_CLR_ADDR); udelay(delay); } clk_disable(master_saif->clk); if (saif != master_saif) { __raw_writel(BM_SAIF_CTRL_RUN, saif->base + SAIF_CTRL + MXS_CLR_ADDR); udelay(delay); clk_disable(saif->clk); } master_saif->ongoing = 0; break; default: return -EINVAL; } return 0; } #define MXS_SAIF_RATES SNDRV_PCM_RATE_8000_192000 #define MXS_SAIF_FORMATS \ (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ SNDRV_PCM_FMTBIT_S24_LE) static const struct snd_soc_dai_ops mxs_saif_dai_ops = { .startup = mxs_saif_startup, .trigger = mxs_saif_trigger, .prepare = mxs_saif_prepare, .hw_params = mxs_saif_hw_params, .set_sysclk = mxs_saif_set_dai_sysclk, .set_fmt = mxs_saif_set_dai_fmt, }; static int mxs_saif_dai_probe(struct snd_soc_dai *dai) { struct mxs_saif *saif = dev_get_drvdata(dai->dev); snd_soc_dai_set_drvdata(dai, saif); return 0; } static struct snd_soc_dai_driver mxs_saif_dai = { .name = "mxs-saif", .probe = mxs_saif_dai_probe, .playback = { .channels_min = 2, .channels_max = 2, .rates = MXS_SAIF_RATES, .formats = MXS_SAIF_FORMATS, }, .capture = { .channels_min = 2, .channels_max = 2, .rates = MXS_SAIF_RATES, .formats = MXS_SAIF_FORMATS, }, .ops = &mxs_saif_dai_ops, }; static irqreturn_t mxs_saif_irq(int irq, void *dev_id) { struct mxs_saif *saif = dev_id; unsigned int stat; stat = __raw_readl(saif->base + SAIF_STAT); if (!(stat & (BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ | BM_SAIF_STAT_FIFO_OVERFLOW_IRQ))) return IRQ_NONE; if (stat & BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ) { dev_dbg(saif->dev, "underrun!!! %d\n", ++saif->fifo_underrun); __raw_writel(BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ, saif->base + SAIF_STAT + MXS_CLR_ADDR); } if (stat & BM_SAIF_STAT_FIFO_OVERFLOW_IRQ) { dev_dbg(saif->dev, "overrun!!! %d\n", ++saif->fifo_overrun); __raw_writel(BM_SAIF_STAT_FIFO_OVERFLOW_IRQ, saif->base + SAIF_STAT + MXS_CLR_ADDR); } dev_dbg(saif->dev, "SAIF_CTRL %x SAIF_STAT %x\n", __raw_readl(saif->base + SAIF_CTRL), __raw_readl(saif->base + SAIF_STAT)); return IRQ_HANDLED; } static int mxs_saif_probe(struct platform_device *pdev) { struct resource *iores, *dmares; struct mxs_saif *saif; struct mxs_saif_platform_data *pdata; int ret = 0; if (pdev->id >= ARRAY_SIZE(mxs_saif)) return -EINVAL; saif = devm_kzalloc(&pdev->dev, sizeof(*saif), GFP_KERNEL); if (!saif) return -ENOMEM; mxs_saif[pdev->id] = saif; saif->id = pdev->id; pdata = pdev->dev.platform_data; if (pdata && !pdata->master_mode) { saif->master_id = pdata->master_id; if (saif->master_id < 0 || saif->master_id >= ARRAY_SIZE(mxs_saif) || saif->master_id == saif->id) { dev_err(&pdev->dev, "get wrong master id\n"); return -EINVAL; } } else { saif->master_id = saif->id; } saif->clk = clk_get(&pdev->dev, NULL); if (IS_ERR(saif->clk)) { ret = PTR_ERR(saif->clk); dev_err(&pdev->dev, "Cannot get the clock: %d\n", ret); return ret; } iores = platform_get_resource(pdev, IORESOURCE_MEM, 0); saif->base = devm_request_and_ioremap(&pdev->dev, iores); if (!saif->base) { dev_err(&pdev->dev, "ioremap failed\n"); ret = -ENODEV; goto failed_get_resource; } dmares = platform_get_resource(pdev, IORESOURCE_DMA, 0); if (!dmares) { ret = -ENODEV; dev_err(&pdev->dev, "failed to get dma resource: %d\n", ret); goto failed_get_resource; } saif->dma_param.chan_num = dmares->start; saif->irq = platform_get_irq(pdev, 0); if (saif->irq < 0) { ret = saif->irq; dev_err(&pdev->dev, "failed to get irq resource: %d\n", ret); goto failed_get_resource; } saif->dev = &pdev->dev; ret = devm_request_irq(&pdev->dev, saif->irq, mxs_saif_irq, 0, "mxs-saif", saif); if (ret) { dev_err(&pdev->dev, "failed to request irq\n"); goto failed_get_resource; } saif->dma_param.chan_irq = platform_get_irq(pdev, 1); if (saif->dma_param.chan_irq < 0) { ret = saif->dma_param.chan_irq; dev_err(&pdev->dev, "failed to get dma irq resource: %d\n", ret); goto failed_get_resource; } platform_set_drvdata(pdev, saif); ret = snd_soc_register_dai(&pdev->dev, &mxs_saif_dai); if (ret) { dev_err(&pdev->dev, "register DAI failed\n"); goto failed_get_resource; } saif->soc_platform_pdev = platform_device_alloc( "mxs-pcm-audio", pdev->id); if (!saif->soc_platform_pdev) { ret = -ENOMEM; goto failed_pdev_alloc; } platform_set_drvdata(saif->soc_platform_pdev, saif); ret = platform_device_add(saif->soc_platform_pdev); if (ret) { dev_err(&pdev->dev, "failed to add soc platform device\n"); goto failed_pdev_add; } return 0; failed_pdev_add: platform_device_put(saif->soc_platform_pdev); failed_pdev_alloc: snd_soc_unregister_dai(&pdev->dev); failed_get_resource: clk_put(saif->clk); return ret; } static int __devexit mxs_saif_remove(struct platform_device *pdev) { struct mxs_saif *saif = platform_get_drvdata(pdev); platform_device_unregister(saif->soc_platform_pdev); snd_soc_unregister_dai(&pdev->dev); clk_put(saif->clk); return 0; } static struct platform_driver mxs_saif_driver = { .probe = mxs_saif_probe, .remove = __devexit_p(mxs_saif_remove), .driver = { .name = "mxs-saif", .owner = THIS_MODULE, }, }; module_platform_driver(mxs_saif_driver); MODULE_AUTHOR("Freescale Semiconductor, Inc."); MODULE_DESCRIPTION("MXS ASoC SAIF driver"); MODULE_LICENSE("GPL");
gpl-2.0
aduggan/rpi-linux
drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c
34
12238
/* * Copyright 2008 Advanced Micro Devices, Inc. * Copyright 2008 Red Hat Inc. * Copyright 2009 Jerome Glisse. * * 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. * * 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. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Dave Airlie * Alex Deucher * Jerome Glisse * Christian König */ #include <linux/seq_file.h> #include <linux/slab.h> #include <drm/drmP.h> #include <drm/amdgpu_drm.h> #include "amdgpu.h" #include "atom.h" /* * Rings * Most engines on the GPU are fed via ring buffers. Ring * buffers are areas of GPU accessible memory that the host * writes commands into and the GPU reads commands out of. * There is a rptr (read pointer) that determines where the * GPU is currently reading, and a wptr (write pointer) * which determines where the host has written. When the * pointers are equal, the ring is idle. When the host * writes commands to the ring buffer, it increments the * wptr. The GPU then starts fetching commands and executes * them until the pointers are equal again. */ static int amdgpu_debugfs_ring_init(struct amdgpu_device *adev, struct amdgpu_ring *ring); /** * amdgpu_ring_alloc - allocate space on the ring buffer * * @adev: amdgpu_device pointer * @ring: amdgpu_ring structure holding ring information * @ndw: number of dwords to allocate in the ring buffer * * Allocate @ndw dwords in the ring buffer (all asics). * Returns 0 on success, error on failure. */ int amdgpu_ring_alloc(struct amdgpu_ring *ring, unsigned ndw) { /* Align requested size with padding so unlock_commit can * pad safely */ ndw = (ndw + ring->align_mask) & ~ring->align_mask; /* Make sure we aren't trying to allocate more space * than the maximum for one submission */ if (WARN_ON_ONCE(ndw > ring->max_dw)) return -ENOMEM; ring->count_dw = ndw; ring->wptr_old = ring->wptr; return 0; } /** amdgpu_ring_insert_nop - insert NOP packets * * @ring: amdgpu_ring structure holding ring information * @count: the number of NOP packets to insert * * This is the generic insert_nop function for rings except SDMA */ void amdgpu_ring_insert_nop(struct amdgpu_ring *ring, uint32_t count) { int i; for (i = 0; i < count; i++) amdgpu_ring_write(ring, ring->nop); } /** amdgpu_ring_generic_pad_ib - pad IB with NOP packets * * @ring: amdgpu_ring structure holding ring information * @ib: IB to add NOP packets to * * This is the generic pad_ib function for rings except SDMA */ void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib) { while (ib->length_dw & ring->align_mask) ib->ptr[ib->length_dw++] = ring->nop; } /** * amdgpu_ring_commit - tell the GPU to execute the new * commands on the ring buffer * * @adev: amdgpu_device pointer * @ring: amdgpu_ring structure holding ring information * * Update the wptr (write pointer) to tell the GPU to * execute new commands on the ring buffer (all asics). */ void amdgpu_ring_commit(struct amdgpu_ring *ring) { uint32_t count; /* We pad to match fetch size */ count = ring->align_mask + 1 - (ring->wptr & ring->align_mask); count %= ring->align_mask + 1; ring->funcs->insert_nop(ring, count); mb(); amdgpu_ring_set_wptr(ring); } /** * amdgpu_ring_undo - reset the wptr * * @ring: amdgpu_ring structure holding ring information * * Reset the driver's copy of the wptr (all asics). */ void amdgpu_ring_undo(struct amdgpu_ring *ring) { ring->wptr = ring->wptr_old; } /** * amdgpu_ring_backup - Back up the content of a ring * * @ring: the ring we want to back up * * Saves all unprocessed commits from a ring, returns the number of dwords saved. */ unsigned amdgpu_ring_backup(struct amdgpu_ring *ring, uint32_t **data) { unsigned size, ptr, i; *data = NULL; if (ring->ring_obj == NULL) return 0; /* it doesn't make sense to save anything if all fences are signaled */ if (!amdgpu_fence_count_emitted(ring)) return 0; ptr = le32_to_cpu(*ring->next_rptr_cpu_addr); size = ring->wptr + (ring->ring_size / 4); size -= ptr; size &= ring->ptr_mask; if (size == 0) return 0; /* and then save the content of the ring */ *data = kmalloc_array(size, sizeof(uint32_t), GFP_KERNEL); if (!*data) return 0; for (i = 0; i < size; ++i) { (*data)[i] = ring->ring[ptr++]; ptr &= ring->ptr_mask; } return size; } /** * amdgpu_ring_restore - append saved commands to the ring again * * @ring: ring to append commands to * @size: number of dwords we want to write * @data: saved commands * * Allocates space on the ring and restore the previously saved commands. */ int amdgpu_ring_restore(struct amdgpu_ring *ring, unsigned size, uint32_t *data) { int i, r; if (!size || !data) return 0; /* restore the saved ring content */ r = amdgpu_ring_alloc(ring, size); if (r) return r; for (i = 0; i < size; ++i) { amdgpu_ring_write(ring, data[i]); } amdgpu_ring_commit(ring); kfree(data); return 0; } /** * amdgpu_ring_init - init driver ring struct. * * @adev: amdgpu_device pointer * @ring: amdgpu_ring structure holding ring information * @max_ndw: maximum number of dw for ring alloc * @nop: nop packet for this ring * * Initialize the driver information for the selected ring (all asics). * Returns 0 on success, error on failure. */ int amdgpu_ring_init(struct amdgpu_device *adev, struct amdgpu_ring *ring, unsigned max_dw, u32 nop, u32 align_mask, struct amdgpu_irq_src *irq_src, unsigned irq_type, enum amdgpu_ring_type ring_type) { int r; if (ring->adev == NULL) { if (adev->num_rings >= AMDGPU_MAX_RINGS) return -EINVAL; ring->adev = adev; ring->idx = adev->num_rings++; adev->rings[ring->idx] = ring; r = amdgpu_fence_driver_init_ring(ring, amdgpu_sched_hw_submission); if (r) return r; } r = amdgpu_wb_get(adev, &ring->rptr_offs); if (r) { dev_err(adev->dev, "(%d) ring rptr_offs wb alloc failed\n", r); return r; } r = amdgpu_wb_get(adev, &ring->wptr_offs); if (r) { dev_err(adev->dev, "(%d) ring wptr_offs wb alloc failed\n", r); return r; } r = amdgpu_wb_get(adev, &ring->fence_offs); if (r) { dev_err(adev->dev, "(%d) ring fence_offs wb alloc failed\n", r); return r; } r = amdgpu_wb_get(adev, &ring->next_rptr_offs); if (r) { dev_err(adev->dev, "(%d) ring next_rptr wb alloc failed\n", r); return r; } ring->next_rptr_gpu_addr = adev->wb.gpu_addr + ring->next_rptr_offs * 4; ring->next_rptr_cpu_addr = &adev->wb.wb[ring->next_rptr_offs]; r = amdgpu_wb_get(adev, &ring->cond_exe_offs); if (r) { dev_err(adev->dev, "(%d) ring cond_exec_polling wb alloc failed\n", r); return r; } ring->cond_exe_gpu_addr = adev->wb.gpu_addr + (ring->cond_exe_offs * 4); ring->cond_exe_cpu_addr = &adev->wb.wb[ring->cond_exe_offs]; spin_lock_init(&ring->fence_lock); r = amdgpu_fence_driver_start_ring(ring, irq_src, irq_type); if (r) { dev_err(adev->dev, "failed initializing fences (%d).\n", r); return r; } ring->ring_size = roundup_pow_of_two(max_dw * 4 * amdgpu_sched_hw_submission); ring->align_mask = align_mask; ring->nop = nop; ring->type = ring_type; /* Allocate ring buffer */ if (ring->ring_obj == NULL) { r = amdgpu_bo_create(adev, ring->ring_size, PAGE_SIZE, true, AMDGPU_GEM_DOMAIN_GTT, 0, NULL, NULL, &ring->ring_obj); if (r) { dev_err(adev->dev, "(%d) ring create failed\n", r); return r; } r = amdgpu_bo_reserve(ring->ring_obj, false); if (unlikely(r != 0)) return r; r = amdgpu_bo_pin(ring->ring_obj, AMDGPU_GEM_DOMAIN_GTT, &ring->gpu_addr); if (r) { amdgpu_bo_unreserve(ring->ring_obj); dev_err(adev->dev, "(%d) ring pin failed\n", r); return r; } r = amdgpu_bo_kmap(ring->ring_obj, (void **)&ring->ring); amdgpu_bo_unreserve(ring->ring_obj); if (r) { dev_err(adev->dev, "(%d) ring map failed\n", r); return r; } } ring->ptr_mask = (ring->ring_size / 4) - 1; ring->max_dw = max_dw; if (amdgpu_debugfs_ring_init(adev, ring)) { DRM_ERROR("Failed to register debugfs file for rings !\n"); } return 0; } /** * amdgpu_ring_fini - tear down the driver ring struct. * * @adev: amdgpu_device pointer * @ring: amdgpu_ring structure holding ring information * * Tear down the driver information for the selected ring (all asics). */ void amdgpu_ring_fini(struct amdgpu_ring *ring) { int r; struct amdgpu_bo *ring_obj; ring_obj = ring->ring_obj; ring->ready = false; ring->ring = NULL; ring->ring_obj = NULL; amdgpu_wb_free(ring->adev, ring->cond_exe_offs); amdgpu_wb_free(ring->adev, ring->fence_offs); amdgpu_wb_free(ring->adev, ring->rptr_offs); amdgpu_wb_free(ring->adev, ring->wptr_offs); amdgpu_wb_free(ring->adev, ring->next_rptr_offs); if (ring_obj) { r = amdgpu_bo_reserve(ring_obj, false); if (likely(r == 0)) { amdgpu_bo_kunmap(ring_obj); amdgpu_bo_unpin(ring_obj); amdgpu_bo_unreserve(ring_obj); } amdgpu_bo_unref(&ring_obj); } } /* * Debugfs info */ #if defined(CONFIG_DEBUG_FS) static int amdgpu_debugfs_ring_info(struct seq_file *m, void *data) { struct drm_info_node *node = (struct drm_info_node *) m->private; struct drm_device *dev = node->minor->dev; struct amdgpu_device *adev = dev->dev_private; int roffset = (unsigned long)node->info_ent->data; struct amdgpu_ring *ring = (void *)(((uint8_t*)adev) + roffset); uint32_t rptr, wptr, rptr_next; unsigned i; wptr = amdgpu_ring_get_wptr(ring); seq_printf(m, "wptr: 0x%08x [%5d]\n", wptr, wptr); rptr = amdgpu_ring_get_rptr(ring); rptr_next = le32_to_cpu(*ring->next_rptr_cpu_addr); seq_printf(m, "rptr: 0x%08x [%5d]\n", rptr, rptr); seq_printf(m, "driver's copy of the wptr: 0x%08x [%5d]\n", ring->wptr, ring->wptr); if (!ring->ready) return 0; /* print 8 dw before current rptr as often it's the last executed * packet that is the root issue */ i = (rptr + ring->ptr_mask + 1 - 32) & ring->ptr_mask; while (i != rptr) { seq_printf(m, "r[%5d]=0x%08x", i, ring->ring[i]); if (i == rptr) seq_puts(m, " *"); if (i == rptr_next) seq_puts(m, " #"); seq_puts(m, "\n"); i = (i + 1) & ring->ptr_mask; } while (i != wptr) { seq_printf(m, "r[%5d]=0x%08x", i, ring->ring[i]); if (i == rptr) seq_puts(m, " *"); if (i == rptr_next) seq_puts(m, " #"); seq_puts(m, "\n"); i = (i + 1) & ring->ptr_mask; } return 0; } static struct drm_info_list amdgpu_debugfs_ring_info_list[AMDGPU_MAX_RINGS]; static char amdgpu_debugfs_ring_names[AMDGPU_MAX_RINGS][32]; #endif static int amdgpu_debugfs_ring_init(struct amdgpu_device *adev, struct amdgpu_ring *ring) { #if defined(CONFIG_DEBUG_FS) unsigned offset = (uint8_t*)ring - (uint8_t*)adev; unsigned i; struct drm_info_list *info; char *name; for (i = 0; i < ARRAY_SIZE(amdgpu_debugfs_ring_info_list); ++i) { info = &amdgpu_debugfs_ring_info_list[i]; if (!info->data) break; } if (i == ARRAY_SIZE(amdgpu_debugfs_ring_info_list)) return -ENOSPC; name = &amdgpu_debugfs_ring_names[i][0]; sprintf(name, "amdgpu_ring_%s", ring->name); info->name = name; info->show = amdgpu_debugfs_ring_info; info->driver_features = 0; info->data = (void*)(uintptr_t)offset; return amdgpu_debugfs_add_files(adev, info, 1); #endif return 0; }
gpl-2.0
zerovm/gdb
gdb/testsuite/gdb.threads/non-ldr-exc-4.c
34
2151
/* This testcase is part of GDB, the GNU debugger. Copyright 2009-2013 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 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 <pthread.h> #include <unistd.h> #include <stdlib.h> #include <assert.h> static const char *image; static pthread_barrier_t barrier; static char *argv1 = "go away"; static void * thread_execler (void *arg) { int i; pthread_barrier_wait (&barrier); /* Exec ourselves again. */ if (execl (image, image, argv1, NULL) == -1) /* break-here */ { perror ("execl"); abort (); } return NULL; } static void * just_loop (void *arg) { unsigned int i; pthread_barrier_wait (&barrier); for (i = 1; i > 0; i++) usleep (1); return NULL; } #define THREADS 5 pthread_t loop_thread[THREADS]; int main (int argc, char **argv) { pthread_t thread; int i, t; image = argv[0]; /* Pass "inf" as argument to keep re-execing ad infinitum, which can be useful for manual testing. Passing any other argument exits immediately (and that's what the execl above does by default). */ if (argc == 2 && strcmp (argv[1], "inf") == 0) argv1 = argv[1]; else if (argc > 1) exit (0); pthread_barrier_init (&barrier, NULL, 2 + THREADS); i = pthread_create (&thread, NULL, thread_execler, NULL); assert (i == 0); for (t = 0; t < THREADS; t++) { i = pthread_create (&loop_thread[t], NULL, just_loop, NULL); assert (i == 0); } pthread_barrier_wait (&barrier); pthread_join (thread, NULL); return 0; }
gpl-2.0
bradfa/linux
drivers/net/ethernet/mellanox/mlx5/core/en_rep.c
34
16220
/* * Copyright (c) 2016, Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * 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. 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 <generated/utsrelease.h> #include <linux/mlx5/fs.h> #include <net/switchdev.h> #include <net/pkt_cls.h> #include "eswitch.h" #include "en.h" #include "en_tc.h" static const char mlx5e_rep_driver_name[] = "mlx5e_rep"; static void mlx5e_rep_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *drvinfo) { strlcpy(drvinfo->driver, mlx5e_rep_driver_name, sizeof(drvinfo->driver)); strlcpy(drvinfo->version, UTS_RELEASE, sizeof(drvinfo->version)); } static const struct counter_desc sw_rep_stats_desc[] = { { MLX5E_DECLARE_STAT(struct mlx5e_sw_stats, rx_packets) }, { MLX5E_DECLARE_STAT(struct mlx5e_sw_stats, rx_bytes) }, { MLX5E_DECLARE_STAT(struct mlx5e_sw_stats, tx_packets) }, { MLX5E_DECLARE_STAT(struct mlx5e_sw_stats, tx_bytes) }, }; #define NUM_VPORT_REP_COUNTERS ARRAY_SIZE(sw_rep_stats_desc) static void mlx5e_rep_get_strings(struct net_device *dev, u32 stringset, uint8_t *data) { int i; switch (stringset) { case ETH_SS_STATS: for (i = 0; i < NUM_VPORT_REP_COUNTERS; i++) strcpy(data + (i * ETH_GSTRING_LEN), sw_rep_stats_desc[i].format); break; } } static void mlx5e_rep_update_hw_counters(struct mlx5e_priv *priv) { struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; struct mlx5_eswitch_rep *rep = priv->ppriv; struct rtnl_link_stats64 *vport_stats; struct ifla_vf_stats vf_stats; int err; err = mlx5_eswitch_get_vport_stats(esw, rep->vport, &vf_stats); if (err) { pr_warn("vport %d error %d reading stats\n", rep->vport, err); return; } vport_stats = &priv->stats.vf_vport; /* flip tx/rx as we are reporting the counters for the switch vport */ vport_stats->rx_packets = vf_stats.tx_packets; vport_stats->rx_bytes = vf_stats.tx_bytes; vport_stats->tx_packets = vf_stats.rx_packets; vport_stats->tx_bytes = vf_stats.rx_bytes; } static void mlx5e_rep_update_sw_counters(struct mlx5e_priv *priv) { struct mlx5e_sw_stats *s = &priv->stats.sw; struct mlx5e_rq_stats *rq_stats; struct mlx5e_sq_stats *sq_stats; int i, j; memset(s, 0, sizeof(*s)); for (i = 0; i < priv->params.num_channels; i++) { rq_stats = &priv->channel[i]->rq.stats; s->rx_packets += rq_stats->packets; s->rx_bytes += rq_stats->bytes; for (j = 0; j < priv->params.num_tc; j++) { sq_stats = &priv->channel[i]->sq[j].stats; s->tx_packets += sq_stats->packets; s->tx_bytes += sq_stats->bytes; } } } static void mlx5e_rep_update_stats(struct mlx5e_priv *priv) { mlx5e_rep_update_sw_counters(priv); mlx5e_rep_update_hw_counters(priv); } static void mlx5e_rep_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *stats, u64 *data) { struct mlx5e_priv *priv = netdev_priv(dev); int i; if (!data) return; mutex_lock(&priv->state_lock); if (test_bit(MLX5E_STATE_OPENED, &priv->state)) mlx5e_rep_update_sw_counters(priv); mutex_unlock(&priv->state_lock); for (i = 0; i < NUM_VPORT_REP_COUNTERS; i++) data[i] = MLX5E_READ_CTR64_CPU(&priv->stats.sw, sw_rep_stats_desc, i); } static int mlx5e_rep_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_STATS: return NUM_VPORT_REP_COUNTERS; default: return -EOPNOTSUPP; } } static const struct ethtool_ops mlx5e_rep_ethtool_ops = { .get_drvinfo = mlx5e_rep_get_drvinfo, .get_link = ethtool_op_get_link, .get_strings = mlx5e_rep_get_strings, .get_sset_count = mlx5e_rep_get_sset_count, .get_ethtool_stats = mlx5e_rep_get_ethtool_stats, }; int mlx5e_attr_get(struct net_device *dev, struct switchdev_attr *attr) { struct mlx5e_priv *priv = netdev_priv(dev); struct mlx5_eswitch_rep *rep = priv->ppriv; struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; if (esw->mode == SRIOV_NONE) return -EOPNOTSUPP; switch (attr->id) { case SWITCHDEV_ATTR_ID_PORT_PARENT_ID: attr->u.ppid.id_len = ETH_ALEN; ether_addr_copy(attr->u.ppid.id, rep->hw_id); break; default: return -EOPNOTSUPP; } return 0; } int mlx5e_add_sqs_fwd_rules(struct mlx5e_priv *priv) { struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; struct mlx5_eswitch_rep *rep = priv->ppriv; struct mlx5e_channel *c; int n, tc, err, num_sqs = 0; u16 *sqs; sqs = kcalloc(priv->params.num_channels * priv->params.num_tc, sizeof(u16), GFP_KERNEL); if (!sqs) return -ENOMEM; for (n = 0; n < priv->params.num_channels; n++) { c = priv->channel[n]; for (tc = 0; tc < c->num_tc; tc++) sqs[num_sqs++] = c->sq[tc].sqn; } err = mlx5_eswitch_sqs2vport_start(esw, rep, sqs, num_sqs); kfree(sqs); return err; } int mlx5e_nic_rep_load(struct mlx5_eswitch *esw, struct mlx5_eswitch_rep *rep) { struct net_device *netdev = rep->netdev; struct mlx5e_priv *priv = netdev_priv(netdev); if (test_bit(MLX5E_STATE_OPENED, &priv->state)) return mlx5e_add_sqs_fwd_rules(priv); return 0; } void mlx5e_remove_sqs_fwd_rules(struct mlx5e_priv *priv) { struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; struct mlx5_eswitch_rep *rep = priv->ppriv; mlx5_eswitch_sqs2vport_stop(esw, rep); } void mlx5e_nic_rep_unload(struct mlx5_eswitch *esw, struct mlx5_eswitch_rep *rep) { struct net_device *netdev = rep->netdev; struct mlx5e_priv *priv = netdev_priv(netdev); if (test_bit(MLX5E_STATE_OPENED, &priv->state)) mlx5e_remove_sqs_fwd_rules(priv); /* clean (and re-init) existing uplink offloaded TC rules */ mlx5e_tc_cleanup(priv); mlx5e_tc_init(priv); } static int mlx5e_rep_open(struct net_device *dev) { struct mlx5e_priv *priv = netdev_priv(dev); struct mlx5_eswitch_rep *rep = priv->ppriv; struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; int err; err = mlx5e_open(dev); if (err) return err; err = mlx5_eswitch_set_vport_state(esw, rep->vport, MLX5_ESW_VPORT_ADMIN_STATE_UP); if (!err) netif_carrier_on(dev); return 0; } static int mlx5e_rep_close(struct net_device *dev) { struct mlx5e_priv *priv = netdev_priv(dev); struct mlx5_eswitch_rep *rep = priv->ppriv; struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; (void)mlx5_eswitch_set_vport_state(esw, rep->vport, MLX5_ESW_VPORT_ADMIN_STATE_DOWN); return mlx5e_close(dev); } static int mlx5e_rep_get_phys_port_name(struct net_device *dev, char *buf, size_t len) { struct mlx5e_priv *priv = netdev_priv(dev); struct mlx5_eswitch_rep *rep = priv->ppriv; int ret; ret = snprintf(buf, len, "%d", rep->vport - 1); if (ret >= len) return -EOPNOTSUPP; return 0; } static int mlx5e_rep_ndo_setup_tc(struct net_device *dev, u32 handle, __be16 proto, struct tc_to_netdev *tc) { struct mlx5e_priv *priv = netdev_priv(dev); if (TC_H_MAJ(handle) != TC_H_MAJ(TC_H_INGRESS)) return -EOPNOTSUPP; if (tc->egress_dev) { struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; struct net_device *uplink_dev = mlx5_eswitch_get_uplink_netdev(esw); return uplink_dev->netdev_ops->ndo_setup_tc(uplink_dev, handle, proto, tc); } switch (tc->type) { case TC_SETUP_CLSFLOWER: switch (tc->cls_flower->command) { case TC_CLSFLOWER_REPLACE: return mlx5e_configure_flower(priv, proto, tc->cls_flower); case TC_CLSFLOWER_DESTROY: return mlx5e_delete_flower(priv, tc->cls_flower); case TC_CLSFLOWER_STATS: return mlx5e_stats_flower(priv, tc->cls_flower); } default: return -EOPNOTSUPP; } } bool mlx5e_is_uplink_rep(struct mlx5e_priv *priv) { struct mlx5_eswitch_rep *rep = (struct mlx5_eswitch_rep *)priv->ppriv; struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; if (rep && rep->vport == FDB_UPLINK_VPORT && esw->mode == SRIOV_OFFLOADS) return true; return false; } bool mlx5e_is_vf_vport_rep(struct mlx5e_priv *priv) { struct mlx5_eswitch_rep *rep = (struct mlx5_eswitch_rep *)priv->ppriv; if (rep && rep->vport != FDB_UPLINK_VPORT) return true; return false; } bool mlx5e_has_offload_stats(const struct net_device *dev, int attr_id) { struct mlx5e_priv *priv = netdev_priv(dev); switch (attr_id) { case IFLA_OFFLOAD_XSTATS_CPU_HIT: if (mlx5e_is_vf_vport_rep(priv) || mlx5e_is_uplink_rep(priv)) return true; } return false; } static int mlx5e_get_sw_stats64(const struct net_device *dev, struct rtnl_link_stats64 *stats) { struct mlx5e_priv *priv = netdev_priv(dev); struct mlx5e_sw_stats *sstats = &priv->stats.sw; stats->rx_packets = sstats->rx_packets; stats->rx_bytes = sstats->rx_bytes; stats->tx_packets = sstats->tx_packets; stats->tx_bytes = sstats->tx_bytes; stats->tx_dropped = sstats->tx_queue_dropped; return 0; } int mlx5e_get_offload_stats(int attr_id, const struct net_device *dev, void *sp) { switch (attr_id) { case IFLA_OFFLOAD_XSTATS_CPU_HIT: return mlx5e_get_sw_stats64(dev, sp); } return -EINVAL; } static struct rtnl_link_stats64 * mlx5e_rep_get_stats(struct net_device *dev, struct rtnl_link_stats64 *stats) { struct mlx5e_priv *priv = netdev_priv(dev); memcpy(stats, &priv->stats.vf_vport, sizeof(*stats)); return stats; } static const struct switchdev_ops mlx5e_rep_switchdev_ops = { .switchdev_port_attr_get = mlx5e_attr_get, }; static const struct net_device_ops mlx5e_netdev_ops_rep = { .ndo_open = mlx5e_rep_open, .ndo_stop = mlx5e_rep_close, .ndo_start_xmit = mlx5e_xmit, .ndo_get_phys_port_name = mlx5e_rep_get_phys_port_name, .ndo_setup_tc = mlx5e_rep_ndo_setup_tc, .ndo_get_stats64 = mlx5e_rep_get_stats, .ndo_udp_tunnel_add = mlx5e_add_vxlan_port, .ndo_udp_tunnel_del = mlx5e_del_vxlan_port, .ndo_has_offload_stats = mlx5e_has_offload_stats, .ndo_get_offload_stats = mlx5e_get_offload_stats, }; static void mlx5e_build_rep_netdev_priv(struct mlx5_core_dev *mdev, struct net_device *netdev, const struct mlx5e_profile *profile, void *ppriv) { struct mlx5e_priv *priv = netdev_priv(netdev); u8 cq_period_mode = MLX5_CAP_GEN(mdev, cq_period_start_from_cqe) ? MLX5_CQ_PERIOD_MODE_START_FROM_CQE : MLX5_CQ_PERIOD_MODE_START_FROM_EQE; priv->params.log_sq_size = MLX5E_PARAMS_MINIMUM_LOG_SQ_SIZE; priv->params.rq_wq_type = MLX5_WQ_TYPE_LINKED_LIST; priv->params.log_rq_size = MLX5E_PARAMS_MINIMUM_LOG_RQ_SIZE; priv->params.min_rx_wqes = mlx5_min_rx_wqes(priv->params.rq_wq_type, BIT(priv->params.log_rq_size)); priv->params.rx_am_enabled = MLX5_CAP_GEN(mdev, cq_moderation); mlx5e_set_rx_cq_mode_params(&priv->params, cq_period_mode); priv->params.tx_max_inline = mlx5e_get_max_inline_cap(mdev); priv->params.num_tc = 1; priv->params.lro_wqe_sz = MLX5E_PARAMS_DEFAULT_LRO_WQE_SZ; priv->mdev = mdev; priv->netdev = netdev; priv->params.num_channels = profile->max_nch(mdev); priv->profile = profile; priv->ppriv = ppriv; mutex_init(&priv->state_lock); INIT_DELAYED_WORK(&priv->update_stats_work, mlx5e_update_stats_work); } static void mlx5e_build_rep_netdev(struct net_device *netdev) { netdev->netdev_ops = &mlx5e_netdev_ops_rep; netdev->watchdog_timeo = 15 * HZ; netdev->ethtool_ops = &mlx5e_rep_ethtool_ops; #ifdef CONFIG_NET_SWITCHDEV netdev->switchdev_ops = &mlx5e_rep_switchdev_ops; #endif netdev->features |= NETIF_F_VLAN_CHALLENGED | NETIF_F_HW_TC | NETIF_F_NETNS_LOCAL; netdev->hw_features |= NETIF_F_HW_TC; eth_hw_addr_random(netdev); } static void mlx5e_init_rep(struct mlx5_core_dev *mdev, struct net_device *netdev, const struct mlx5e_profile *profile, void *ppriv) { mlx5e_build_rep_netdev_priv(mdev, netdev, profile, ppriv); mlx5e_build_rep_netdev(netdev); } static int mlx5e_init_rep_rx(struct mlx5e_priv *priv) { struct mlx5_eswitch *esw = priv->mdev->priv.eswitch; struct mlx5_eswitch_rep *rep = priv->ppriv; struct mlx5_core_dev *mdev = priv->mdev; struct mlx5_flow_handle *flow_rule; int err; int i; err = mlx5e_create_direct_rqts(priv); if (err) { mlx5_core_warn(mdev, "create direct rqts failed, %d\n", err); return err; } err = mlx5e_create_direct_tirs(priv); if (err) { mlx5_core_warn(mdev, "create direct tirs failed, %d\n", err); goto err_destroy_direct_rqts; } flow_rule = mlx5_eswitch_create_vport_rx_rule(esw, rep->vport, priv->direct_tir[0].tirn); if (IS_ERR(flow_rule)) { err = PTR_ERR(flow_rule); goto err_destroy_direct_tirs; } rep->vport_rx_rule = flow_rule; err = mlx5e_tc_init(priv); if (err) goto err_del_flow_rule; return 0; err_del_flow_rule: mlx5_del_flow_rules(rep->vport_rx_rule); err_destroy_direct_tirs: mlx5e_destroy_direct_tirs(priv); err_destroy_direct_rqts: for (i = 0; i < priv->params.num_channels; i++) mlx5e_destroy_rqt(priv, &priv->direct_tir[i].rqt); return err; } static void mlx5e_cleanup_rep_rx(struct mlx5e_priv *priv) { struct mlx5_eswitch_rep *rep = priv->ppriv; int i; mlx5e_tc_cleanup(priv); mlx5_del_flow_rules(rep->vport_rx_rule); mlx5e_destroy_direct_tirs(priv); for (i = 0; i < priv->params.num_channels; i++) mlx5e_destroy_rqt(priv, &priv->direct_tir[i].rqt); } static int mlx5e_init_rep_tx(struct mlx5e_priv *priv) { int err; err = mlx5e_create_tises(priv); if (err) { mlx5_core_warn(priv->mdev, "create tises failed, %d\n", err); return err; } return 0; } static int mlx5e_get_rep_max_num_channels(struct mlx5_core_dev *mdev) { #define MLX5E_PORT_REPRESENTOR_NCH 1 return MLX5E_PORT_REPRESENTOR_NCH; } static struct mlx5e_profile mlx5e_rep_profile = { .init = mlx5e_init_rep, .init_rx = mlx5e_init_rep_rx, .cleanup_rx = mlx5e_cleanup_rep_rx, .init_tx = mlx5e_init_rep_tx, .cleanup_tx = mlx5e_cleanup_nic_tx, .update_stats = mlx5e_rep_update_stats, .max_nch = mlx5e_get_rep_max_num_channels, .max_tc = 1, }; int mlx5e_vport_rep_load(struct mlx5_eswitch *esw, struct mlx5_eswitch_rep *rep) { struct net_device *netdev; int err; netdev = mlx5e_create_netdev(esw->dev, &mlx5e_rep_profile, rep); if (!netdev) { pr_warn("Failed to create representor netdev for vport %d\n", rep->vport); return -EINVAL; } rep->netdev = netdev; err = mlx5e_attach_netdev(esw->dev, netdev); if (err) { pr_warn("Failed to attach representor netdev for vport %d\n", rep->vport); goto err_destroy_netdev; } err = register_netdev(netdev); if (err) { pr_warn("Failed to register representor netdev for vport %d\n", rep->vport); goto err_detach_netdev; } return 0; err_detach_netdev: mlx5e_detach_netdev(esw->dev, netdev); err_destroy_netdev: mlx5e_destroy_netdev(esw->dev, netdev_priv(netdev)); return err; } void mlx5e_vport_rep_unload(struct mlx5_eswitch *esw, struct mlx5_eswitch_rep *rep) { struct net_device *netdev = rep->netdev; unregister_netdev(netdev); mlx5e_detach_netdev(esw->dev, netdev); mlx5e_destroy_netdev(esw->dev, netdev_priv(netdev)); }
gpl-2.0
k5t4j5/kernel_htc_hybrid
drivers/net/ethernet/intel/e1000/e1000_param.c
34
17833
/******************************************************************************* Intel PRO/1000 Linux driver Copyright(c) 1999 - 2006 Intel Corporation. This program is free software; you can redistribute it and/or modify it under the terms and conditions of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called "COPYING". Contact Information: Linux NICS <linux.nics@intel.com> e1000-devel Mailing List <e1000-devel@lists.sourceforge.net> Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 *******************************************************************************/ #include "e1000.h" #define E1000_MAX_NIC 32 #define OPTION_UNSET -1 #define OPTION_DISABLED 0 #define OPTION_ENABLED 1 #define E1000_PARAM_INIT { [0 ... E1000_MAX_NIC] = OPTION_UNSET } #define E1000_PARAM(X, desc) \ static int __devinitdata X[E1000_MAX_NIC+1] = E1000_PARAM_INIT; \ static unsigned int num_##X; \ module_param_array_named(X, X, int, &num_##X, 0); \ MODULE_PARM_DESC(X, desc); E1000_PARAM(TxDescriptors, "Number of transmit descriptors"); E1000_PARAM(RxDescriptors, "Number of receive descriptors"); E1000_PARAM(Speed, "Speed setting"); E1000_PARAM(Duplex, "Duplex setting"); E1000_PARAM(AutoNeg, "Advertised auto-negotiation setting"); #define AUTONEG_ADV_DEFAULT 0x2F #define AUTONEG_ADV_MASK 0x2F E1000_PARAM(FlowControl, "Flow Control setting"); #define FLOW_CONTROL_DEFAULT FLOW_CONTROL_FULL E1000_PARAM(XsumRX, "Disable or enable Receive Checksum offload"); E1000_PARAM(TxIntDelay, "Transmit Interrupt Delay"); #define DEFAULT_TIDV 8 #define MAX_TXDELAY 0xFFFF #define MIN_TXDELAY 0 E1000_PARAM(TxAbsIntDelay, "Transmit Absolute Interrupt Delay"); #define DEFAULT_TADV 32 #define MAX_TXABSDELAY 0xFFFF #define MIN_TXABSDELAY 0 E1000_PARAM(RxIntDelay, "Receive Interrupt Delay"); #define DEFAULT_RDTR 0 #define MAX_RXDELAY 0xFFFF #define MIN_RXDELAY 0 E1000_PARAM(RxAbsIntDelay, "Receive Absolute Interrupt Delay"); #define DEFAULT_RADV 8 #define MAX_RXABSDELAY 0xFFFF #define MIN_RXABSDELAY 0 E1000_PARAM(InterruptThrottleRate, "Interrupt Throttling Rate"); #define DEFAULT_ITR 3 #define MAX_ITR 100000 #define MIN_ITR 100 E1000_PARAM(SmartPowerDownEnable, "Enable PHY smart power down"); struct e1000_option { enum { enable_option, range_option, list_option } type; const char *name; const char *err; int def; union { struct { int min; int max; } r; struct { int nr; const struct e1000_opt_list { int i; char *str; } *p; } l; } arg; }; static int __devinit e1000_validate_option(unsigned int *value, const struct e1000_option *opt, struct e1000_adapter *adapter) { if (*value == OPTION_UNSET) { *value = opt->def; return 0; } switch (opt->type) { case enable_option: switch (*value) { case OPTION_ENABLED: e_dev_info("%s Enabled\n", opt->name); return 0; case OPTION_DISABLED: e_dev_info("%s Disabled\n", opt->name); return 0; } break; case range_option: if (*value >= opt->arg.r.min && *value <= opt->arg.r.max) { e_dev_info("%s set to %i\n", opt->name, *value); return 0; } break; case list_option: { int i; const struct e1000_opt_list *ent; for (i = 0; i < opt->arg.l.nr; i++) { ent = &opt->arg.l.p[i]; if (*value == ent->i) { if (ent->str[0] != '\0') e_dev_info("%s\n", ent->str); return 0; } } } break; default: BUG(); } e_dev_info("Invalid %s value specified (%i) %s\n", opt->name, *value, opt->err); *value = opt->def; return -1; } static void e1000_check_fiber_options(struct e1000_adapter *adapter); static void e1000_check_copper_options(struct e1000_adapter *adapter); void __devinit e1000_check_options(struct e1000_adapter *adapter) { struct e1000_option opt; int bd = adapter->bd_number; if (bd >= E1000_MAX_NIC) { e_dev_warn("Warning: no configuration for board #%i " "using defaults for all values\n", bd); } { struct e1000_tx_ring *tx_ring = adapter->tx_ring; int i; e1000_mac_type mac_type = adapter->hw.mac_type; opt = (struct e1000_option) { .type = range_option, .name = "Transmit Descriptors", .err = "using default of " __MODULE_STRING(E1000_DEFAULT_TXD), .def = E1000_DEFAULT_TXD, .arg = { .r = { .min = E1000_MIN_TXD, .max = mac_type < e1000_82544 ? E1000_MAX_TXD : E1000_MAX_82544_TXD }} }; if (num_TxDescriptors > bd) { tx_ring->count = TxDescriptors[bd]; e1000_validate_option(&tx_ring->count, &opt, adapter); tx_ring->count = ALIGN(tx_ring->count, REQ_TX_DESCRIPTOR_MULTIPLE); } else { tx_ring->count = opt.def; } for (i = 0; i < adapter->num_tx_queues; i++) tx_ring[i].count = tx_ring->count; } { struct e1000_rx_ring *rx_ring = adapter->rx_ring; int i; e1000_mac_type mac_type = adapter->hw.mac_type; opt = (struct e1000_option) { .type = range_option, .name = "Receive Descriptors", .err = "using default of " __MODULE_STRING(E1000_DEFAULT_RXD), .def = E1000_DEFAULT_RXD, .arg = { .r = { .min = E1000_MIN_RXD, .max = mac_type < e1000_82544 ? E1000_MAX_RXD : E1000_MAX_82544_RXD }} }; if (num_RxDescriptors > bd) { rx_ring->count = RxDescriptors[bd]; e1000_validate_option(&rx_ring->count, &opt, adapter); rx_ring->count = ALIGN(rx_ring->count, REQ_RX_DESCRIPTOR_MULTIPLE); } else { rx_ring->count = opt.def; } for (i = 0; i < adapter->num_rx_queues; i++) rx_ring[i].count = rx_ring->count; } { opt = (struct e1000_option) { .type = enable_option, .name = "Checksum Offload", .err = "defaulting to Enabled", .def = OPTION_ENABLED }; if (num_XsumRX > bd) { unsigned int rx_csum = XsumRX[bd]; e1000_validate_option(&rx_csum, &opt, adapter); adapter->rx_csum = rx_csum; } else { adapter->rx_csum = opt.def; } } { static const struct e1000_opt_list fc_list[] = { { E1000_FC_NONE, "Flow Control Disabled" }, { E1000_FC_RX_PAUSE, "Flow Control Receive Only" }, { E1000_FC_TX_PAUSE, "Flow Control Transmit Only" }, { E1000_FC_FULL, "Flow Control Enabled" }, { E1000_FC_DEFAULT, "Flow Control Hardware Default" } }; opt = (struct e1000_option) { .type = list_option, .name = "Flow Control", .err = "reading default settings from EEPROM", .def = E1000_FC_DEFAULT, .arg = { .l = { .nr = ARRAY_SIZE(fc_list), .p = fc_list }} }; if (num_FlowControl > bd) { unsigned int fc = FlowControl[bd]; e1000_validate_option(&fc, &opt, adapter); adapter->hw.fc = adapter->hw.original_fc = fc; } else { adapter->hw.fc = adapter->hw.original_fc = opt.def; } } { opt = (struct e1000_option) { .type = range_option, .name = "Transmit Interrupt Delay", .err = "using default of " __MODULE_STRING(DEFAULT_TIDV), .def = DEFAULT_TIDV, .arg = { .r = { .min = MIN_TXDELAY, .max = MAX_TXDELAY }} }; if (num_TxIntDelay > bd) { adapter->tx_int_delay = TxIntDelay[bd]; e1000_validate_option(&adapter->tx_int_delay, &opt, adapter); } else { adapter->tx_int_delay = opt.def; } } { opt = (struct e1000_option) { .type = range_option, .name = "Transmit Absolute Interrupt Delay", .err = "using default of " __MODULE_STRING(DEFAULT_TADV), .def = DEFAULT_TADV, .arg = { .r = { .min = MIN_TXABSDELAY, .max = MAX_TXABSDELAY }} }; if (num_TxAbsIntDelay > bd) { adapter->tx_abs_int_delay = TxAbsIntDelay[bd]; e1000_validate_option(&adapter->tx_abs_int_delay, &opt, adapter); } else { adapter->tx_abs_int_delay = opt.def; } } { opt = (struct e1000_option) { .type = range_option, .name = "Receive Interrupt Delay", .err = "using default of " __MODULE_STRING(DEFAULT_RDTR), .def = DEFAULT_RDTR, .arg = { .r = { .min = MIN_RXDELAY, .max = MAX_RXDELAY }} }; if (num_RxIntDelay > bd) { adapter->rx_int_delay = RxIntDelay[bd]; e1000_validate_option(&adapter->rx_int_delay, &opt, adapter); } else { adapter->rx_int_delay = opt.def; } } { opt = (struct e1000_option) { .type = range_option, .name = "Receive Absolute Interrupt Delay", .err = "using default of " __MODULE_STRING(DEFAULT_RADV), .def = DEFAULT_RADV, .arg = { .r = { .min = MIN_RXABSDELAY, .max = MAX_RXABSDELAY }} }; if (num_RxAbsIntDelay > bd) { adapter->rx_abs_int_delay = RxAbsIntDelay[bd]; e1000_validate_option(&adapter->rx_abs_int_delay, &opt, adapter); } else { adapter->rx_abs_int_delay = opt.def; } } { opt = (struct e1000_option) { .type = range_option, .name = "Interrupt Throttling Rate (ints/sec)", .err = "using default of " __MODULE_STRING(DEFAULT_ITR), .def = DEFAULT_ITR, .arg = { .r = { .min = MIN_ITR, .max = MAX_ITR }} }; if (num_InterruptThrottleRate > bd) { adapter->itr = InterruptThrottleRate[bd]; switch (adapter->itr) { case 0: e_dev_info("%s turned off\n", opt.name); break; case 1: e_dev_info("%s set to dynamic mode\n", opt.name); adapter->itr_setting = adapter->itr; adapter->itr = 20000; break; case 3: e_dev_info("%s set to dynamic conservative " "mode\n", opt.name); adapter->itr_setting = adapter->itr; adapter->itr = 20000; break; case 4: e_dev_info("%s set to simplified " "(2000-8000) ints mode\n", opt.name); adapter->itr_setting = adapter->itr; break; default: e1000_validate_option(&adapter->itr, &opt, adapter); adapter->itr_setting = adapter->itr & ~3; break; } } else { adapter->itr_setting = opt.def; adapter->itr = 20000; } } { opt = (struct e1000_option) { .type = enable_option, .name = "PHY Smart Power Down", .err = "defaulting to Disabled", .def = OPTION_DISABLED }; if (num_SmartPowerDownEnable > bd) { unsigned int spd = SmartPowerDownEnable[bd]; e1000_validate_option(&spd, &opt, adapter); adapter->smart_power_down = spd; } else { adapter->smart_power_down = opt.def; } } switch (adapter->hw.media_type) { case e1000_media_type_fiber: case e1000_media_type_internal_serdes: e1000_check_fiber_options(adapter); break; case e1000_media_type_copper: e1000_check_copper_options(adapter); break; default: BUG(); } } static void __devinit e1000_check_fiber_options(struct e1000_adapter *adapter) { int bd = adapter->bd_number; if (num_Speed > bd) { e_dev_info("Speed not valid for fiber adapters, parameter " "ignored\n"); } if (num_Duplex > bd) { e_dev_info("Duplex not valid for fiber adapters, parameter " "ignored\n"); } if ((num_AutoNeg > bd) && (AutoNeg[bd] != 0x20)) { e_dev_info("AutoNeg other than 1000/Full is not valid for fiber" "adapters, parameter ignored\n"); } } static void __devinit e1000_check_copper_options(struct e1000_adapter *adapter) { struct e1000_option opt; unsigned int speed, dplx, an; int bd = adapter->bd_number; { static const struct e1000_opt_list speed_list[] = { { 0, "" }, { SPEED_10, "" }, { SPEED_100, "" }, { SPEED_1000, "" }}; opt = (struct e1000_option) { .type = list_option, .name = "Speed", .err = "parameter ignored", .def = 0, .arg = { .l = { .nr = ARRAY_SIZE(speed_list), .p = speed_list }} }; if (num_Speed > bd) { speed = Speed[bd]; e1000_validate_option(&speed, &opt, adapter); } else { speed = opt.def; } } { static const struct e1000_opt_list dplx_list[] = { { 0, "" }, { HALF_DUPLEX, "" }, { FULL_DUPLEX, "" }}; opt = (struct e1000_option) { .type = list_option, .name = "Duplex", .err = "parameter ignored", .def = 0, .arg = { .l = { .nr = ARRAY_SIZE(dplx_list), .p = dplx_list }} }; if (num_Duplex > bd) { dplx = Duplex[bd]; e1000_validate_option(&dplx, &opt, adapter); } else { dplx = opt.def; } } if ((num_AutoNeg > bd) && (speed != 0 || dplx != 0)) { e_dev_info("AutoNeg specified along with Speed or Duplex, " "parameter ignored\n"); adapter->hw.autoneg_advertised = AUTONEG_ADV_DEFAULT; } else { static const struct e1000_opt_list an_list[] = #define AA "AutoNeg advertising " {{ 0x01, AA "10/HD" }, { 0x02, AA "10/FD" }, { 0x03, AA "10/FD, 10/HD" }, { 0x04, AA "100/HD" }, { 0x05, AA "100/HD, 10/HD" }, { 0x06, AA "100/HD, 10/FD" }, { 0x07, AA "100/HD, 10/FD, 10/HD" }, { 0x08, AA "100/FD" }, { 0x09, AA "100/FD, 10/HD" }, { 0x0a, AA "100/FD, 10/FD" }, { 0x0b, AA "100/FD, 10/FD, 10/HD" }, { 0x0c, AA "100/FD, 100/HD" }, { 0x0d, AA "100/FD, 100/HD, 10/HD" }, { 0x0e, AA "100/FD, 100/HD, 10/FD" }, { 0x0f, AA "100/FD, 100/HD, 10/FD, 10/HD" }, { 0x20, AA "1000/FD" }, { 0x21, AA "1000/FD, 10/HD" }, { 0x22, AA "1000/FD, 10/FD" }, { 0x23, AA "1000/FD, 10/FD, 10/HD" }, { 0x24, AA "1000/FD, 100/HD" }, { 0x25, AA "1000/FD, 100/HD, 10/HD" }, { 0x26, AA "1000/FD, 100/HD, 10/FD" }, { 0x27, AA "1000/FD, 100/HD, 10/FD, 10/HD" }, { 0x28, AA "1000/FD, 100/FD" }, { 0x29, AA "1000/FD, 100/FD, 10/HD" }, { 0x2a, AA "1000/FD, 100/FD, 10/FD" }, { 0x2b, AA "1000/FD, 100/FD, 10/FD, 10/HD" }, { 0x2c, AA "1000/FD, 100/FD, 100/HD" }, { 0x2d, AA "1000/FD, 100/FD, 100/HD, 10/HD" }, { 0x2e, AA "1000/FD, 100/FD, 100/HD, 10/FD" }, { 0x2f, AA "1000/FD, 100/FD, 100/HD, 10/FD, 10/HD" }}; opt = (struct e1000_option) { .type = list_option, .name = "AutoNeg", .err = "parameter ignored", .def = AUTONEG_ADV_DEFAULT, .arg = { .l = { .nr = ARRAY_SIZE(an_list), .p = an_list }} }; if (num_AutoNeg > bd) { an = AutoNeg[bd]; e1000_validate_option(&an, &opt, adapter); } else { an = opt.def; } adapter->hw.autoneg_advertised = an; } switch (speed + dplx) { case 0: adapter->hw.autoneg = adapter->fc_autoneg = 1; if ((num_Speed > bd) && (speed != 0 || dplx != 0)) e_dev_info("Speed and duplex autonegotiation " "enabled\n"); break; case HALF_DUPLEX: e_dev_info("Half Duplex specified without Speed\n"); e_dev_info("Using Autonegotiation at Half Duplex only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_10_HALF | ADVERTISE_100_HALF; break; case FULL_DUPLEX: e_dev_info("Full Duplex specified without Speed\n"); e_dev_info("Using Autonegotiation at Full Duplex only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_10_FULL | ADVERTISE_100_FULL | ADVERTISE_1000_FULL; break; case SPEED_10: e_dev_info("10 Mbps Speed specified without Duplex\n"); e_dev_info("Using Autonegotiation at 10 Mbps only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_10_HALF | ADVERTISE_10_FULL; break; case SPEED_10 + HALF_DUPLEX: e_dev_info("Forcing to 10 Mbps Half Duplex\n"); adapter->hw.autoneg = adapter->fc_autoneg = 0; adapter->hw.forced_speed_duplex = e1000_10_half; adapter->hw.autoneg_advertised = 0; break; case SPEED_10 + FULL_DUPLEX: e_dev_info("Forcing to 10 Mbps Full Duplex\n"); adapter->hw.autoneg = adapter->fc_autoneg = 0; adapter->hw.forced_speed_duplex = e1000_10_full; adapter->hw.autoneg_advertised = 0; break; case SPEED_100: e_dev_info("100 Mbps Speed specified without Duplex\n"); e_dev_info("Using Autonegotiation at 100 Mbps only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_100_HALF | ADVERTISE_100_FULL; break; case SPEED_100 + HALF_DUPLEX: e_dev_info("Forcing to 100 Mbps Half Duplex\n"); adapter->hw.autoneg = adapter->fc_autoneg = 0; adapter->hw.forced_speed_duplex = e1000_100_half; adapter->hw.autoneg_advertised = 0; break; case SPEED_100 + FULL_DUPLEX: e_dev_info("Forcing to 100 Mbps Full Duplex\n"); adapter->hw.autoneg = adapter->fc_autoneg = 0; adapter->hw.forced_speed_duplex = e1000_100_full; adapter->hw.autoneg_advertised = 0; break; case SPEED_1000: e_dev_info("1000 Mbps Speed specified without Duplex\n"); goto full_duplex_only; case SPEED_1000 + HALF_DUPLEX: e_dev_info("Half Duplex is not supported at 1000 Mbps\n"); case SPEED_1000 + FULL_DUPLEX: full_duplex_only: e_dev_info("Using Autonegotiation at 1000 Mbps Full Duplex " "only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_1000_FULL; break; default: BUG(); } if (e1000_validate_mdi_setting(&(adapter->hw)) < 0) { e_dev_info("Speed, AutoNeg and MDI-X specs are incompatible. " "Setting MDI-X to a compatible value.\n"); } }
gpl-2.0
invisiblek/android_kernel_htc_m8
arch/arm/mach-imx/mach-qong.c
34
6412
/* * Copyright (C) 2009 Ilya Yanok, Emcraft Systems Ltd, <yanok@emcraft.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. */ #include <linux/types.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/memory.h> #include <linux/platform_device.h> #include <linux/mtd/physmap.h> #include <linux/mtd/nand.h> #include <linux/gpio.h> #include <mach/hardware.h> #include <mach/irqs.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/time.h> #include <asm/mach/map.h> #include <mach/common.h> #include <asm/page.h> #include <asm/setup.h> #include <mach/iomux-mx3.h> #include "devices-imx31.h" #define QONG_FPGA_VERSION(major, minor, rev) \ (((major & 0xF) << 12) | ((minor & 0xF) << 8) | (rev & 0xFF)) #define QONG_FPGA_BASEADDR MX31_CS1_BASE_ADDR #define QONG_FPGA_PERIPH_SIZE (1 << 24) #define QONG_FPGA_CTRL_BASEADDR QONG_FPGA_BASEADDR #define QONG_FPGA_CTRL_SIZE 0x10 #define QONG_FPGA_CTRL_VERSION 0x00 #define QONG_DNET_ID 1 #define QONG_DNET_BASEADDR \ (QONG_FPGA_BASEADDR + QONG_DNET_ID * QONG_FPGA_PERIPH_SIZE) #define QONG_DNET_SIZE 0x00001000 #define QONG_FPGA_IRQ IOMUX_TO_IRQ(MX31_PIN_DTR_DCE1) static const struct imxuart_platform_data uart_pdata __initconst = { .flags = IMXUART_HAVE_RTSCTS, }; static int uart_pins[] = { MX31_PIN_CTS1__CTS1, MX31_PIN_RTS1__RTS1, MX31_PIN_TXD1__TXD1, MX31_PIN_RXD1__RXD1 }; static inline void __init mxc_init_imx_uart(void) { mxc_iomux_setup_multiple_pins(uart_pins, ARRAY_SIZE(uart_pins), "uart-0"); imx31_add_imx_uart0(&uart_pdata); } static struct resource dnet_resources[] = { { .name = "dnet-memory", .start = QONG_DNET_BASEADDR, .end = QONG_DNET_BASEADDR + QONG_DNET_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = QONG_FPGA_IRQ, .end = QONG_FPGA_IRQ, .flags = IORESOURCE_IRQ, }, }; static struct platform_device dnet_device = { .name = "dnet", .id = -1, .num_resources = ARRAY_SIZE(dnet_resources), .resource = dnet_resources, }; static int __init qong_init_dnet(void) { int ret; ret = platform_device_register(&dnet_device); return ret; } static struct physmap_flash_data qong_flash_data = { .width = 2, }; static struct resource qong_flash_resource = { .start = MX31_CS0_BASE_ADDR, .end = MX31_CS0_BASE_ADDR + SZ_128M - 1, .flags = IORESOURCE_MEM, }; static struct platform_device qong_nor_mtd_device = { .name = "physmap-flash", .id = 0, .dev = { .platform_data = &qong_flash_data, }, .resource = &qong_flash_resource, .num_resources = 1, }; static void qong_init_nor_mtd(void) { (void)platform_device_register(&qong_nor_mtd_device); } static void qong_nand_cmd_ctrl(struct mtd_info *mtd, int cmd, unsigned int ctrl) { struct nand_chip *nand_chip = mtd->priv; if (cmd == NAND_CMD_NONE) return; if (ctrl & NAND_CLE) writeb(cmd, nand_chip->IO_ADDR_W + (1 << 24)); else writeb(cmd, nand_chip->IO_ADDR_W + (1 << 23)); } static int qong_nand_device_ready(struct mtd_info *mtd) { return gpio_get_value(IOMUX_TO_GPIO(MX31_PIN_NFRB)); } static void qong_nand_select_chip(struct mtd_info *mtd, int chip) { if (chip >= 0) gpio_set_value(IOMUX_TO_GPIO(MX31_PIN_NFCE_B), 0); else gpio_set_value(IOMUX_TO_GPIO(MX31_PIN_NFCE_B), 1); } static struct platform_nand_data qong_nand_data = { .chip = { .nr_chips = 1, .chip_delay = 20, .options = 0, }, .ctrl = { .cmd_ctrl = qong_nand_cmd_ctrl, .dev_ready = qong_nand_device_ready, .select_chip = qong_nand_select_chip, } }; static struct resource qong_nand_resource = { .start = MX31_CS3_BASE_ADDR, .end = MX31_CS3_BASE_ADDR + SZ_32M - 1, .flags = IORESOURCE_MEM, }; static struct platform_device qong_nand_device = { .name = "gen_nand", .id = -1, .dev = { .platform_data = &qong_nand_data, }, .num_resources = 1, .resource = &qong_nand_resource, }; static void __init qong_init_nand_mtd(void) { __raw_writel(0x00004f00, MX31_IO_ADDRESS(MX31_WEIM_CSCRxU(3))); __raw_writel(0x20013b31, MX31_IO_ADDRESS(MX31_WEIM_CSCRxL(3))); __raw_writel(0x00020800, MX31_IO_ADDRESS(MX31_WEIM_CSCRxA(3))); mxc_iomux_set_gpr(MUX_SDCTL_CSD1_SEL, true); mxc_iomux_mode(IOMUX_MODE(MX31_PIN_NFCE_B, IOMUX_CONFIG_GPIO)); if (!gpio_request(IOMUX_TO_GPIO(MX31_PIN_NFCE_B), "nand_enable")) gpio_direction_output(IOMUX_TO_GPIO(MX31_PIN_NFCE_B), 0); mxc_iomux_mode(IOMUX_MODE(MX31_PIN_NFRB, IOMUX_CONFIG_GPIO)); if (!gpio_request(IOMUX_TO_GPIO(MX31_PIN_NFRB), "nand_rdy")) gpio_direction_input(IOMUX_TO_GPIO(MX31_PIN_NFRB)); mxc_iomux_mode(IOMUX_MODE(MX31_PIN_NFWP_B, IOMUX_CONFIG_GPIO)); if (!gpio_request(IOMUX_TO_GPIO(MX31_PIN_NFWP_B), "nand_wp")) gpio_direction_input(IOMUX_TO_GPIO(MX31_PIN_NFWP_B)); platform_device_register(&qong_nand_device); } static void __init qong_init_fpga(void) { void __iomem *regs; u32 fpga_ver; regs = ioremap(QONG_FPGA_CTRL_BASEADDR, QONG_FPGA_CTRL_SIZE); if (!regs) { printk(KERN_ERR "%s: failed to map registers, aborting.\n", __func__); return; } fpga_ver = readl(regs + QONG_FPGA_CTRL_VERSION); iounmap(regs); printk(KERN_INFO "Qong FPGA version %d.%d.%d\n", (fpga_ver & 0xF000) >> 12, (fpga_ver & 0x0F00) >> 8, fpga_ver & 0x00FF); if (fpga_ver < QONG_FPGA_VERSION(0, 8, 7)) { printk(KERN_ERR "qong: Unexpected FPGA version, FPGA-based " "devices won't be registered!\n"); return; } qong_init_nand_mtd(); qong_init_dnet(); } static void __init qong_init(void) { imx31_soc_init(); mxc_init_imx_uart(); qong_init_nor_mtd(); qong_init_fpga(); imx31_add_imx2_wdt(NULL); } static void __init qong_timer_init(void) { mx31_clocks_init(26000000); } static struct sys_timer qong_timer = { .init = qong_timer_init, }; MACHINE_START(QONG, "Dave/DENX QongEVB-LITE") .atag_offset = 0x100, .map_io = mx31_map_io, .init_early = imx31_init_early, .init_irq = mx31_init_irq, .handle_irq = imx31_handle_irq, .timer = &qong_timer, .init_machine = qong_init, .restart = mxc_restart, MACHINE_END
gpl-2.0
ndmsystems/linux-2.6.36
fs/xfs/xfs_dir2_node.c
290
60847
/* * Copyright (c) 2000-2005 Silicon Graphics, 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. * * 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. See the * GNU General Public License for more details. * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_types.h" #include "xfs_log.h" #include "xfs_inum.h" #include "xfs_trans.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_dir2.h" #include "xfs_mount.h" #include "xfs_da_btree.h" #include "xfs_bmap_btree.h" #include "xfs_dir2_sf.h" #include "xfs_dinode.h" #include "xfs_inode.h" #include "xfs_bmap.h" #include "xfs_dir2_data.h" #include "xfs_dir2_leaf.h" #include "xfs_dir2_block.h" #include "xfs_dir2_node.h" #include "xfs_error.h" #include "xfs_trace.h" /* * Function declarations. */ static void xfs_dir2_free_log_header(xfs_trans_t *tp, xfs_dabuf_t *bp); static int xfs_dir2_leafn_add(xfs_dabuf_t *bp, xfs_da_args_t *args, int index); #ifdef DEBUG static void xfs_dir2_leafn_check(xfs_inode_t *dp, xfs_dabuf_t *bp); #else #define xfs_dir2_leafn_check(dp, bp) #endif static void xfs_dir2_leafn_moveents(xfs_da_args_t *args, xfs_dabuf_t *bp_s, int start_s, xfs_dabuf_t *bp_d, int start_d, int count); static void xfs_dir2_leafn_rebalance(xfs_da_state_t *state, xfs_da_state_blk_t *blk1, xfs_da_state_blk_t *blk2); static int xfs_dir2_leafn_remove(xfs_da_args_t *args, xfs_dabuf_t *bp, int index, xfs_da_state_blk_t *dblk, int *rval); static int xfs_dir2_node_addname_int(xfs_da_args_t *args, xfs_da_state_blk_t *fblk); /* * Log entries from a freespace block. */ STATIC void xfs_dir2_free_log_bests( xfs_trans_t *tp, /* transaction pointer */ xfs_dabuf_t *bp, /* freespace buffer */ int first, /* first entry to log */ int last) /* last entry to log */ { xfs_dir2_free_t *free; /* freespace structure */ free = bp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); xfs_da_log_buf(tp, bp, (uint)((char *)&free->bests[first] - (char *)free), (uint)((char *)&free->bests[last] - (char *)free + sizeof(free->bests[0]) - 1)); } /* * Log header from a freespace block. */ static void xfs_dir2_free_log_header( xfs_trans_t *tp, /* transaction pointer */ xfs_dabuf_t *bp) /* freespace buffer */ { xfs_dir2_free_t *free; /* freespace structure */ free = bp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); xfs_da_log_buf(tp, bp, (uint)((char *)&free->hdr - (char *)free), (uint)(sizeof(xfs_dir2_free_hdr_t) - 1)); } /* * Convert a leaf-format directory to a node-format directory. * We need to change the magic number of the leaf block, and copy * the freespace table out of the leaf block into its own block. */ int /* error */ xfs_dir2_leaf_to_node( xfs_da_args_t *args, /* operation arguments */ xfs_dabuf_t *lbp) /* leaf buffer */ { xfs_inode_t *dp; /* incore directory inode */ int error; /* error return value */ xfs_dabuf_t *fbp; /* freespace buffer */ xfs_dir2_db_t fdb; /* freespace block number */ xfs_dir2_free_t *free; /* freespace structure */ __be16 *from; /* pointer to freespace entry */ int i; /* leaf freespace index */ xfs_dir2_leaf_t *leaf; /* leaf structure */ xfs_dir2_leaf_tail_t *ltp; /* leaf tail structure */ xfs_mount_t *mp; /* filesystem mount point */ int n; /* count of live freespc ents */ xfs_dir2_data_off_t off; /* freespace entry value */ __be16 *to; /* pointer to freespace entry */ xfs_trans_t *tp; /* transaction pointer */ trace_xfs_dir2_leaf_to_node(args); dp = args->dp; mp = dp->i_mount; tp = args->trans; /* * Add a freespace block to the directory. */ if ((error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fdb))) { return error; } ASSERT(fdb == XFS_DIR2_FREE_FIRSTDB(mp)); /* * Get the buffer for the new freespace block. */ if ((error = xfs_da_get_buf(tp, dp, xfs_dir2_db_to_da(mp, fdb), -1, &fbp, XFS_DATA_FORK))) { return error; } ASSERT(fbp != NULL); free = fbp->data; leaf = lbp->data; ltp = xfs_dir2_leaf_tail_p(mp, leaf); /* * Initialize the freespace block header. */ free->hdr.magic = cpu_to_be32(XFS_DIR2_FREE_MAGIC); free->hdr.firstdb = 0; ASSERT(be32_to_cpu(ltp->bestcount) <= (uint)dp->i_d.di_size / mp->m_dirblksize); free->hdr.nvalid = ltp->bestcount; /* * Copy freespace entries from the leaf block to the new block. * Count active entries. */ for (i = n = 0, from = xfs_dir2_leaf_bests_p(ltp), to = free->bests; i < be32_to_cpu(ltp->bestcount); i++, from++, to++) { if ((off = be16_to_cpu(*from)) != NULLDATAOFF) n++; *to = cpu_to_be16(off); } free->hdr.nused = cpu_to_be32(n); leaf->hdr.info.magic = cpu_to_be16(XFS_DIR2_LEAFN_MAGIC); /* * Log everything. */ xfs_dir2_leaf_log_header(tp, lbp); xfs_dir2_free_log_header(tp, fbp); xfs_dir2_free_log_bests(tp, fbp, 0, be32_to_cpu(free->hdr.nvalid) - 1); xfs_da_buf_done(fbp); xfs_dir2_leafn_check(dp, lbp); return 0; } /* * Add a leaf entry to a leaf block in a node-form directory. * The other work necessary is done from the caller. */ static int /* error */ xfs_dir2_leafn_add( xfs_dabuf_t *bp, /* leaf buffer */ xfs_da_args_t *args, /* operation arguments */ int index) /* insertion pt for new entry */ { int compact; /* compacting stale leaves */ xfs_inode_t *dp; /* incore directory inode */ int highstale; /* next stale entry */ xfs_dir2_leaf_t *leaf; /* leaf structure */ xfs_dir2_leaf_entry_t *lep; /* leaf entry */ int lfloghigh; /* high leaf entry logging */ int lfloglow; /* low leaf entry logging */ int lowstale; /* previous stale entry */ xfs_mount_t *mp; /* filesystem mount point */ xfs_trans_t *tp; /* transaction pointer */ trace_xfs_dir2_leafn_add(args, index); dp = args->dp; mp = dp->i_mount; tp = args->trans; leaf = bp->data; /* * Quick check just to make sure we are not going to index * into other peoples memory */ if (index < 0) return XFS_ERROR(EFSCORRUPTED); /* * If there are already the maximum number of leaf entries in * the block, if there are no stale entries it won't fit. * Caller will do a split. If there are stale entries we'll do * a compact. */ if (be16_to_cpu(leaf->hdr.count) == xfs_dir2_max_leaf_ents(mp)) { if (!leaf->hdr.stale) return XFS_ERROR(ENOSPC); compact = be16_to_cpu(leaf->hdr.stale) > 1; } else compact = 0; ASSERT(index == 0 || be32_to_cpu(leaf->ents[index - 1].hashval) <= args->hashval); ASSERT(index == be16_to_cpu(leaf->hdr.count) || be32_to_cpu(leaf->ents[index].hashval) >= args->hashval); if (args->op_flags & XFS_DA_OP_JUSTCHECK) return 0; /* * Compact out all but one stale leaf entry. Leaves behind * the entry closest to index. */ if (compact) { xfs_dir2_leaf_compact_x1(bp, &index, &lowstale, &highstale, &lfloglow, &lfloghigh); } /* * Set impossible logging indices for this case. */ else if (leaf->hdr.stale) { lfloglow = be16_to_cpu(leaf->hdr.count); lfloghigh = -1; } /* * No stale entries, just insert a space for the new entry. */ if (!leaf->hdr.stale) { lep = &leaf->ents[index]; if (index < be16_to_cpu(leaf->hdr.count)) memmove(lep + 1, lep, (be16_to_cpu(leaf->hdr.count) - index) * sizeof(*lep)); lfloglow = index; lfloghigh = be16_to_cpu(leaf->hdr.count); be16_add_cpu(&leaf->hdr.count, 1); } /* * There are stale entries. We'll use one for the new entry. */ else { /* * If we didn't do a compact then we need to figure out * which stale entry will be used. */ if (compact == 0) { /* * Find first stale entry before our insertion point. */ for (lowstale = index - 1; lowstale >= 0 && be32_to_cpu(leaf->ents[lowstale].address) != XFS_DIR2_NULL_DATAPTR; lowstale--) continue; /* * Find next stale entry after insertion point. * Stop looking if the answer would be worse than * lowstale already found. */ for (highstale = index; highstale < be16_to_cpu(leaf->hdr.count) && be32_to_cpu(leaf->ents[highstale].address) != XFS_DIR2_NULL_DATAPTR && (lowstale < 0 || index - lowstale - 1 >= highstale - index); highstale++) continue; } /* * Using the low stale entry. * Shift entries up toward the stale slot. */ if (lowstale >= 0 && (highstale == be16_to_cpu(leaf->hdr.count) || index - lowstale - 1 < highstale - index)) { ASSERT(be32_to_cpu(leaf->ents[lowstale].address) == XFS_DIR2_NULL_DATAPTR); ASSERT(index - lowstale - 1 >= 0); if (index - lowstale - 1 > 0) memmove(&leaf->ents[lowstale], &leaf->ents[lowstale + 1], (index - lowstale - 1) * sizeof(*lep)); lep = &leaf->ents[index - 1]; lfloglow = MIN(lowstale, lfloglow); lfloghigh = MAX(index - 1, lfloghigh); } /* * Using the high stale entry. * Shift entries down toward the stale slot. */ else { ASSERT(be32_to_cpu(leaf->ents[highstale].address) == XFS_DIR2_NULL_DATAPTR); ASSERT(highstale - index >= 0); if (highstale - index > 0) memmove(&leaf->ents[index + 1], &leaf->ents[index], (highstale - index) * sizeof(*lep)); lep = &leaf->ents[index]; lfloglow = MIN(index, lfloglow); lfloghigh = MAX(highstale, lfloghigh); } be16_add_cpu(&leaf->hdr.stale, -1); } /* * Insert the new entry, log everything. */ lep->hashval = cpu_to_be32(args->hashval); lep->address = cpu_to_be32(xfs_dir2_db_off_to_dataptr(mp, args->blkno, args->index)); xfs_dir2_leaf_log_header(tp, bp); xfs_dir2_leaf_log_ents(tp, bp, lfloglow, lfloghigh); xfs_dir2_leafn_check(dp, bp); return 0; } #ifdef DEBUG /* * Check internal consistency of a leafn block. */ void xfs_dir2_leafn_check( xfs_inode_t *dp, /* incore directory inode */ xfs_dabuf_t *bp) /* leaf buffer */ { int i; /* leaf index */ xfs_dir2_leaf_t *leaf; /* leaf structure */ xfs_mount_t *mp; /* filesystem mount point */ int stale; /* count of stale leaves */ leaf = bp->data; mp = dp->i_mount; ASSERT(be16_to_cpu(leaf->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); ASSERT(be16_to_cpu(leaf->hdr.count) <= xfs_dir2_max_leaf_ents(mp)); for (i = stale = 0; i < be16_to_cpu(leaf->hdr.count); i++) { if (i + 1 < be16_to_cpu(leaf->hdr.count)) { ASSERT(be32_to_cpu(leaf->ents[i].hashval) <= be32_to_cpu(leaf->ents[i + 1].hashval)); } if (be32_to_cpu(leaf->ents[i].address) == XFS_DIR2_NULL_DATAPTR) stale++; } ASSERT(be16_to_cpu(leaf->hdr.stale) == stale); } #endif /* DEBUG */ /* * Return the last hash value in the leaf. * Stale entries are ok. */ xfs_dahash_t /* hash value */ xfs_dir2_leafn_lasthash( xfs_dabuf_t *bp, /* leaf buffer */ int *count) /* count of entries in leaf */ { xfs_dir2_leaf_t *leaf; /* leaf structure */ leaf = bp->data; ASSERT(be16_to_cpu(leaf->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); if (count) *count = be16_to_cpu(leaf->hdr.count); if (!leaf->hdr.count) return 0; return be32_to_cpu(leaf->ents[be16_to_cpu(leaf->hdr.count) - 1].hashval); } /* * Look up a leaf entry for space to add a name in a node-format leaf block. * The extrablk in state is a freespace block. */ STATIC int xfs_dir2_leafn_lookup_for_addname( xfs_dabuf_t *bp, /* leaf buffer */ xfs_da_args_t *args, /* operation arguments */ int *indexp, /* out: leaf entry index */ xfs_da_state_t *state) /* state to fill in */ { xfs_dabuf_t *curbp = NULL; /* current data/free buffer */ xfs_dir2_db_t curdb = -1; /* current data block number */ xfs_dir2_db_t curfdb = -1; /* current free block number */ xfs_inode_t *dp; /* incore directory inode */ int error; /* error return value */ int fi; /* free entry index */ xfs_dir2_free_t *free = NULL; /* free block structure */ int index; /* leaf entry index */ xfs_dir2_leaf_t *leaf; /* leaf structure */ int length; /* length of new data entry */ xfs_dir2_leaf_entry_t *lep; /* leaf entry */ xfs_mount_t *mp; /* filesystem mount point */ xfs_dir2_db_t newdb; /* new data block number */ xfs_dir2_db_t newfdb; /* new free block number */ xfs_trans_t *tp; /* transaction pointer */ dp = args->dp; tp = args->trans; mp = dp->i_mount; leaf = bp->data; ASSERT(be16_to_cpu(leaf->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); #ifdef __KERNEL__ ASSERT(be16_to_cpu(leaf->hdr.count) > 0); #endif xfs_dir2_leafn_check(dp, bp); /* * Look up the hash value in the leaf entries. */ index = xfs_dir2_leaf_search_hash(args, bp); /* * Do we have a buffer coming in? */ if (state->extravalid) { /* If so, it's a free block buffer, get the block number. */ curbp = state->extrablk.bp; curfdb = state->extrablk.blkno; free = curbp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); } length = xfs_dir2_data_entsize(args->namelen); /* * Loop over leaf entries with the right hash value. */ for (lep = &leaf->ents[index]; index < be16_to_cpu(leaf->hdr.count) && be32_to_cpu(lep->hashval) == args->hashval; lep++, index++) { /* * Skip stale leaf entries. */ if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR) continue; /* * Pull the data block number from the entry. */ newdb = xfs_dir2_dataptr_to_db(mp, be32_to_cpu(lep->address)); /* * For addname, we're looking for a place to put the new entry. * We want to use a data block with an entry of equal * hash value to ours if there is one with room. * * If this block isn't the data block we already have * in hand, take a look at it. */ if (newdb != curdb) { curdb = newdb; /* * Convert the data block to the free block * holding its freespace information. */ newfdb = xfs_dir2_db_to_fdb(mp, newdb); /* * If it's not the one we have in hand, read it in. */ if (newfdb != curfdb) { /* * If we had one before, drop it. */ if (curbp) xfs_da_brelse(tp, curbp); /* * Read the free block. */ error = xfs_da_read_buf(tp, dp, xfs_dir2_db_to_da(mp, newfdb), -1, &curbp, XFS_DATA_FORK); if (error) return error; free = curbp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); ASSERT((be32_to_cpu(free->hdr.firstdb) % XFS_DIR2_MAX_FREE_BESTS(mp)) == 0); ASSERT(be32_to_cpu(free->hdr.firstdb) <= curdb); ASSERT(curdb < be32_to_cpu(free->hdr.firstdb) + be32_to_cpu(free->hdr.nvalid)); } /* * Get the index for our entry. */ fi = xfs_dir2_db_to_fdindex(mp, curdb); /* * If it has room, return it. */ if (unlikely(be16_to_cpu(free->bests[fi]) == NULLDATAOFF)) { XFS_ERROR_REPORT("xfs_dir2_leafn_lookup_int", XFS_ERRLEVEL_LOW, mp); if (curfdb != newfdb) xfs_da_brelse(tp, curbp); return XFS_ERROR(EFSCORRUPTED); } curfdb = newfdb; if (be16_to_cpu(free->bests[fi]) >= length) goto out; } } /* Didn't find any space */ fi = -1; out: ASSERT(args->op_flags & XFS_DA_OP_OKNOENT); if (curbp) { /* Giving back a free block. */ state->extravalid = 1; state->extrablk.bp = curbp; state->extrablk.index = fi; state->extrablk.blkno = curfdb; state->extrablk.magic = XFS_DIR2_FREE_MAGIC; } else { state->extravalid = 0; } /* * Return the index, that will be the insertion point. */ *indexp = index; return XFS_ERROR(ENOENT); } /* * Look up a leaf entry in a node-format leaf block. * The extrablk in state a data block. */ STATIC int xfs_dir2_leafn_lookup_for_entry( xfs_dabuf_t *bp, /* leaf buffer */ xfs_da_args_t *args, /* operation arguments */ int *indexp, /* out: leaf entry index */ xfs_da_state_t *state) /* state to fill in */ { xfs_dabuf_t *curbp = NULL; /* current data/free buffer */ xfs_dir2_db_t curdb = -1; /* current data block number */ xfs_dir2_data_entry_t *dep; /* data block entry */ xfs_inode_t *dp; /* incore directory inode */ int error; /* error return value */ int index; /* leaf entry index */ xfs_dir2_leaf_t *leaf; /* leaf structure */ xfs_dir2_leaf_entry_t *lep; /* leaf entry */ xfs_mount_t *mp; /* filesystem mount point */ xfs_dir2_db_t newdb; /* new data block number */ xfs_trans_t *tp; /* transaction pointer */ enum xfs_dacmp cmp; /* comparison result */ dp = args->dp; tp = args->trans; mp = dp->i_mount; leaf = bp->data; ASSERT(be16_to_cpu(leaf->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); #ifdef __KERNEL__ ASSERT(be16_to_cpu(leaf->hdr.count) > 0); #endif xfs_dir2_leafn_check(dp, bp); /* * Look up the hash value in the leaf entries. */ index = xfs_dir2_leaf_search_hash(args, bp); /* * Do we have a buffer coming in? */ if (state->extravalid) { curbp = state->extrablk.bp; curdb = state->extrablk.blkno; } /* * Loop over leaf entries with the right hash value. */ for (lep = &leaf->ents[index]; index < be16_to_cpu(leaf->hdr.count) && be32_to_cpu(lep->hashval) == args->hashval; lep++, index++) { /* * Skip stale leaf entries. */ if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR) continue; /* * Pull the data block number from the entry. */ newdb = xfs_dir2_dataptr_to_db(mp, be32_to_cpu(lep->address)); /* * Not adding a new entry, so we really want to find * the name given to us. * * If it's a different data block, go get it. */ if (newdb != curdb) { /* * If we had a block before that we aren't saving * for a CI name, drop it */ if (curbp && (args->cmpresult == XFS_CMP_DIFFERENT || curdb != state->extrablk.blkno)) xfs_da_brelse(tp, curbp); /* * If needing the block that is saved with a CI match, * use it otherwise read in the new data block. */ if (args->cmpresult != XFS_CMP_DIFFERENT && newdb == state->extrablk.blkno) { ASSERT(state->extravalid); curbp = state->extrablk.bp; } else { error = xfs_da_read_buf(tp, dp, xfs_dir2_db_to_da(mp, newdb), -1, &curbp, XFS_DATA_FORK); if (error) return error; } xfs_dir2_data_check(dp, curbp); curdb = newdb; } /* * Point to the data entry. */ dep = (xfs_dir2_data_entry_t *)((char *)curbp->data + xfs_dir2_dataptr_to_off(mp, be32_to_cpu(lep->address))); /* * Compare the entry and if it's an exact match, return * EEXIST immediately. If it's the first case-insensitive * match, store the block & inode number and continue looking. */ cmp = mp->m_dirnameops->compname(args, dep->name, dep->namelen); if (cmp != XFS_CMP_DIFFERENT && cmp != args->cmpresult) { /* If there is a CI match block, drop it */ if (args->cmpresult != XFS_CMP_DIFFERENT && curdb != state->extrablk.blkno) xfs_da_brelse(tp, state->extrablk.bp); args->cmpresult = cmp; args->inumber = be64_to_cpu(dep->inumber); *indexp = index; state->extravalid = 1; state->extrablk.bp = curbp; state->extrablk.blkno = curdb; state->extrablk.index = (int)((char *)dep - (char *)curbp->data); state->extrablk.magic = XFS_DIR2_DATA_MAGIC; if (cmp == XFS_CMP_EXACT) return XFS_ERROR(EEXIST); } } ASSERT(index == be16_to_cpu(leaf->hdr.count) || (args->op_flags & XFS_DA_OP_OKNOENT)); if (curbp) { if (args->cmpresult == XFS_CMP_DIFFERENT) { /* Giving back last used data block. */ state->extravalid = 1; state->extrablk.bp = curbp; state->extrablk.index = -1; state->extrablk.blkno = curdb; state->extrablk.magic = XFS_DIR2_DATA_MAGIC; } else { /* If the curbp is not the CI match block, drop it */ if (state->extrablk.bp != curbp) xfs_da_brelse(tp, curbp); } } else { state->extravalid = 0; } *indexp = index; return XFS_ERROR(ENOENT); } /* * Look up a leaf entry in a node-format leaf block. * If this is an addname then the extrablk in state is a freespace block, * otherwise it's a data block. */ int xfs_dir2_leafn_lookup_int( xfs_dabuf_t *bp, /* leaf buffer */ xfs_da_args_t *args, /* operation arguments */ int *indexp, /* out: leaf entry index */ xfs_da_state_t *state) /* state to fill in */ { if (args->op_flags & XFS_DA_OP_ADDNAME) return xfs_dir2_leafn_lookup_for_addname(bp, args, indexp, state); return xfs_dir2_leafn_lookup_for_entry(bp, args, indexp, state); } /* * Move count leaf entries from source to destination leaf. * Log entries and headers. Stale entries are preserved. */ static void xfs_dir2_leafn_moveents( xfs_da_args_t *args, /* operation arguments */ xfs_dabuf_t *bp_s, /* source leaf buffer */ int start_s, /* source leaf index */ xfs_dabuf_t *bp_d, /* destination leaf buffer */ int start_d, /* destination leaf index */ int count) /* count of leaves to copy */ { xfs_dir2_leaf_t *leaf_d; /* destination leaf structure */ xfs_dir2_leaf_t *leaf_s; /* source leaf structure */ int stale; /* count stale leaves copied */ xfs_trans_t *tp; /* transaction pointer */ trace_xfs_dir2_leafn_moveents(args, start_s, start_d, count); /* * Silently return if nothing to do. */ if (count == 0) { return; } tp = args->trans; leaf_s = bp_s->data; leaf_d = bp_d->data; /* * If the destination index is not the end of the current * destination leaf entries, open up a hole in the destination * to hold the new entries. */ if (start_d < be16_to_cpu(leaf_d->hdr.count)) { memmove(&leaf_d->ents[start_d + count], &leaf_d->ents[start_d], (be16_to_cpu(leaf_d->hdr.count) - start_d) * sizeof(xfs_dir2_leaf_entry_t)); xfs_dir2_leaf_log_ents(tp, bp_d, start_d + count, count + be16_to_cpu(leaf_d->hdr.count) - 1); } /* * If the source has stale leaves, count the ones in the copy range * so we can update the header correctly. */ if (leaf_s->hdr.stale) { int i; /* temp leaf index */ for (i = start_s, stale = 0; i < start_s + count; i++) { if (be32_to_cpu(leaf_s->ents[i].address) == XFS_DIR2_NULL_DATAPTR) stale++; } } else stale = 0; /* * Copy the leaf entries from source to destination. */ memcpy(&leaf_d->ents[start_d], &leaf_s->ents[start_s], count * sizeof(xfs_dir2_leaf_entry_t)); xfs_dir2_leaf_log_ents(tp, bp_d, start_d, start_d + count - 1); /* * If there are source entries after the ones we copied, * delete the ones we copied by sliding the next ones down. */ if (start_s + count < be16_to_cpu(leaf_s->hdr.count)) { memmove(&leaf_s->ents[start_s], &leaf_s->ents[start_s + count], count * sizeof(xfs_dir2_leaf_entry_t)); xfs_dir2_leaf_log_ents(tp, bp_s, start_s, start_s + count - 1); } /* * Update the headers and log them. */ be16_add_cpu(&leaf_s->hdr.count, -(count)); be16_add_cpu(&leaf_s->hdr.stale, -(stale)); be16_add_cpu(&leaf_d->hdr.count, count); be16_add_cpu(&leaf_d->hdr.stale, stale); xfs_dir2_leaf_log_header(tp, bp_s); xfs_dir2_leaf_log_header(tp, bp_d); xfs_dir2_leafn_check(args->dp, bp_s); xfs_dir2_leafn_check(args->dp, bp_d); } /* * Determine the sort order of two leaf blocks. * Returns 1 if both are valid and leaf2 should be before leaf1, else 0. */ int /* sort order */ xfs_dir2_leafn_order( xfs_dabuf_t *leaf1_bp, /* leaf1 buffer */ xfs_dabuf_t *leaf2_bp) /* leaf2 buffer */ { xfs_dir2_leaf_t *leaf1; /* leaf1 structure */ xfs_dir2_leaf_t *leaf2; /* leaf2 structure */ leaf1 = leaf1_bp->data; leaf2 = leaf2_bp->data; ASSERT(be16_to_cpu(leaf1->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); ASSERT(be16_to_cpu(leaf2->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); if (be16_to_cpu(leaf1->hdr.count) > 0 && be16_to_cpu(leaf2->hdr.count) > 0 && (be32_to_cpu(leaf2->ents[0].hashval) < be32_to_cpu(leaf1->ents[0].hashval) || be32_to_cpu(leaf2->ents[be16_to_cpu(leaf2->hdr.count) - 1].hashval) < be32_to_cpu(leaf1->ents[be16_to_cpu(leaf1->hdr.count) - 1].hashval))) return 1; return 0; } /* * Rebalance leaf entries between two leaf blocks. * This is actually only called when the second block is new, * though the code deals with the general case. * A new entry will be inserted in one of the blocks, and that * entry is taken into account when balancing. */ static void xfs_dir2_leafn_rebalance( xfs_da_state_t *state, /* btree cursor */ xfs_da_state_blk_t *blk1, /* first btree block */ xfs_da_state_blk_t *blk2) /* second btree block */ { xfs_da_args_t *args; /* operation arguments */ int count; /* count (& direction) leaves */ int isleft; /* new goes in left leaf */ xfs_dir2_leaf_t *leaf1; /* first leaf structure */ xfs_dir2_leaf_t *leaf2; /* second leaf structure */ int mid; /* midpoint leaf index */ #ifdef DEBUG int oldstale; /* old count of stale leaves */ #endif int oldsum; /* old total leaf count */ int swap; /* swapped leaf blocks */ args = state->args; /* * If the block order is wrong, swap the arguments. */ if ((swap = xfs_dir2_leafn_order(blk1->bp, blk2->bp))) { xfs_da_state_blk_t *tmp; /* temp for block swap */ tmp = blk1; blk1 = blk2; blk2 = tmp; } leaf1 = blk1->bp->data; leaf2 = blk2->bp->data; oldsum = be16_to_cpu(leaf1->hdr.count) + be16_to_cpu(leaf2->hdr.count); #ifdef DEBUG oldstale = be16_to_cpu(leaf1->hdr.stale) + be16_to_cpu(leaf2->hdr.stale); #endif mid = oldsum >> 1; /* * If the old leaf count was odd then the new one will be even, * so we need to divide the new count evenly. */ if (oldsum & 1) { xfs_dahash_t midhash; /* middle entry hash value */ if (mid >= be16_to_cpu(leaf1->hdr.count)) midhash = be32_to_cpu(leaf2->ents[mid - be16_to_cpu(leaf1->hdr.count)].hashval); else midhash = be32_to_cpu(leaf1->ents[mid].hashval); isleft = args->hashval <= midhash; } /* * If the old count is even then the new count is odd, so there's * no preferred side for the new entry. * Pick the left one. */ else isleft = 1; /* * Calculate moved entry count. Positive means left-to-right, * negative means right-to-left. Then move the entries. */ count = be16_to_cpu(leaf1->hdr.count) - mid + (isleft == 0); if (count > 0) xfs_dir2_leafn_moveents(args, blk1->bp, be16_to_cpu(leaf1->hdr.count) - count, blk2->bp, 0, count); else if (count < 0) xfs_dir2_leafn_moveents(args, blk2->bp, 0, blk1->bp, be16_to_cpu(leaf1->hdr.count), count); ASSERT(be16_to_cpu(leaf1->hdr.count) + be16_to_cpu(leaf2->hdr.count) == oldsum); ASSERT(be16_to_cpu(leaf1->hdr.stale) + be16_to_cpu(leaf2->hdr.stale) == oldstale); /* * Mark whether we're inserting into the old or new leaf. */ if (be16_to_cpu(leaf1->hdr.count) < be16_to_cpu(leaf2->hdr.count)) state->inleaf = swap; else if (be16_to_cpu(leaf1->hdr.count) > be16_to_cpu(leaf2->hdr.count)) state->inleaf = !swap; else state->inleaf = swap ^ (blk1->index <= be16_to_cpu(leaf1->hdr.count)); /* * Adjust the expected index for insertion. */ if (!state->inleaf) blk2->index = blk1->index - be16_to_cpu(leaf1->hdr.count); /* * Finally sanity check just to make sure we are not returning a * negative index */ if(blk2->index < 0) { state->inleaf = 1; blk2->index = 0; cmn_err(CE_ALERT, "xfs_dir2_leafn_rebalance: picked the wrong leaf? reverting original leaf: " "blk1->index %d\n", blk1->index); } } /* * Remove an entry from a node directory. * This removes the leaf entry and the data entry, * and updates the free block if necessary. */ static int /* error */ xfs_dir2_leafn_remove( xfs_da_args_t *args, /* operation arguments */ xfs_dabuf_t *bp, /* leaf buffer */ int index, /* leaf entry index */ xfs_da_state_blk_t *dblk, /* data block */ int *rval) /* resulting block needs join */ { xfs_dir2_data_t *data; /* data block structure */ xfs_dir2_db_t db; /* data block number */ xfs_dabuf_t *dbp; /* data block buffer */ xfs_dir2_data_entry_t *dep; /* data block entry */ xfs_inode_t *dp; /* incore directory inode */ xfs_dir2_leaf_t *leaf; /* leaf structure */ xfs_dir2_leaf_entry_t *lep; /* leaf entry */ int longest; /* longest data free entry */ int off; /* data block entry offset */ xfs_mount_t *mp; /* filesystem mount point */ int needlog; /* need to log data header */ int needscan; /* need to rescan data frees */ xfs_trans_t *tp; /* transaction pointer */ trace_xfs_dir2_leafn_remove(args, index); dp = args->dp; tp = args->trans; mp = dp->i_mount; leaf = bp->data; ASSERT(be16_to_cpu(leaf->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); /* * Point to the entry we're removing. */ lep = &leaf->ents[index]; /* * Extract the data block and offset from the entry. */ db = xfs_dir2_dataptr_to_db(mp, be32_to_cpu(lep->address)); ASSERT(dblk->blkno == db); off = xfs_dir2_dataptr_to_off(mp, be32_to_cpu(lep->address)); ASSERT(dblk->index == off); /* * Kill the leaf entry by marking it stale. * Log the leaf block changes. */ be16_add_cpu(&leaf->hdr.stale, 1); xfs_dir2_leaf_log_header(tp, bp); lep->address = cpu_to_be32(XFS_DIR2_NULL_DATAPTR); xfs_dir2_leaf_log_ents(tp, bp, index, index); /* * Make the data entry free. Keep track of the longest freespace * in the data block in case it changes. */ dbp = dblk->bp; data = dbp->data; dep = (xfs_dir2_data_entry_t *)((char *)data + off); longest = be16_to_cpu(data->hdr.bestfree[0].length); needlog = needscan = 0; xfs_dir2_data_make_free(tp, dbp, off, xfs_dir2_data_entsize(dep->namelen), &needlog, &needscan); /* * Rescan the data block freespaces for bestfree. * Log the data block header if needed. */ if (needscan) xfs_dir2_data_freescan(mp, data, &needlog); if (needlog) xfs_dir2_data_log_header(tp, dbp); xfs_dir2_data_check(dp, dbp); /* * If the longest data block freespace changes, need to update * the corresponding freeblock entry. */ if (longest < be16_to_cpu(data->hdr.bestfree[0].length)) { int error; /* error return value */ xfs_dabuf_t *fbp; /* freeblock buffer */ xfs_dir2_db_t fdb; /* freeblock block number */ int findex; /* index in freeblock entries */ xfs_dir2_free_t *free; /* freeblock structure */ int logfree; /* need to log free entry */ /* * Convert the data block number to a free block, * read in the free block. */ fdb = xfs_dir2_db_to_fdb(mp, db); if ((error = xfs_da_read_buf(tp, dp, xfs_dir2_db_to_da(mp, fdb), -1, &fbp, XFS_DATA_FORK))) { return error; } free = fbp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); ASSERT(be32_to_cpu(free->hdr.firstdb) == XFS_DIR2_MAX_FREE_BESTS(mp) * (fdb - XFS_DIR2_FREE_FIRSTDB(mp))); /* * Calculate which entry we need to fix. */ findex = xfs_dir2_db_to_fdindex(mp, db); longest = be16_to_cpu(data->hdr.bestfree[0].length); /* * If the data block is now empty we can get rid of it * (usually). */ if (longest == mp->m_dirblksize - (uint)sizeof(data->hdr)) { /* * Try to punch out the data block. */ error = xfs_dir2_shrink_inode(args, db, dbp); if (error == 0) { dblk->bp = NULL; data = NULL; } /* * We can get ENOSPC if there's no space reservation. * In this case just drop the buffer and some one else * will eventually get rid of the empty block. */ else if (error == ENOSPC && args->total == 0) xfs_da_buf_done(dbp); else return error; } /* * If we got rid of the data block, we can eliminate that entry * in the free block. */ if (data == NULL) { /* * One less used entry in the free table. */ be32_add_cpu(&free->hdr.nused, -1); xfs_dir2_free_log_header(tp, fbp); /* * If this was the last entry in the table, we can * trim the table size back. There might be other * entries at the end referring to non-existent * data blocks, get those too. */ if (findex == be32_to_cpu(free->hdr.nvalid) - 1) { int i; /* free entry index */ for (i = findex - 1; i >= 0 && be16_to_cpu(free->bests[i]) == NULLDATAOFF; i--) continue; free->hdr.nvalid = cpu_to_be32(i + 1); logfree = 0; } /* * Not the last entry, just punch it out. */ else { free->bests[findex] = cpu_to_be16(NULLDATAOFF); logfree = 1; } /* * If there are no useful entries left in the block, * get rid of the block if we can. */ if (!free->hdr.nused) { error = xfs_dir2_shrink_inode(args, fdb, fbp); if (error == 0) { fbp = NULL; logfree = 0; } else if (error != ENOSPC || args->total != 0) return error; /* * It's possible to get ENOSPC if there is no * space reservation. In this case some one * else will eventually get rid of this block. */ } } /* * Data block is not empty, just set the free entry to * the new value. */ else { free->bests[findex] = cpu_to_be16(longest); logfree = 1; } /* * Log the free entry that changed, unless we got rid of it. */ if (logfree) xfs_dir2_free_log_bests(tp, fbp, findex, findex); /* * Drop the buffer if we still have it. */ if (fbp) xfs_da_buf_done(fbp); } xfs_dir2_leafn_check(dp, bp); /* * Return indication of whether this leaf block is empty enough * to justify trying to join it with a neighbor. */ *rval = ((uint)sizeof(leaf->hdr) + (uint)sizeof(leaf->ents[0]) * (be16_to_cpu(leaf->hdr.count) - be16_to_cpu(leaf->hdr.stale))) < mp->m_dir_magicpct; return 0; } /* * Split the leaf entries in the old block into old and new blocks. */ int /* error */ xfs_dir2_leafn_split( xfs_da_state_t *state, /* btree cursor */ xfs_da_state_blk_t *oldblk, /* original block */ xfs_da_state_blk_t *newblk) /* newly created block */ { xfs_da_args_t *args; /* operation arguments */ xfs_dablk_t blkno; /* new leaf block number */ int error; /* error return value */ xfs_mount_t *mp; /* filesystem mount point */ /* * Allocate space for a new leaf node. */ args = state->args; mp = args->dp->i_mount; ASSERT(args != NULL); ASSERT(oldblk->magic == XFS_DIR2_LEAFN_MAGIC); error = xfs_da_grow_inode(args, &blkno); if (error) { return error; } /* * Initialize the new leaf block. */ error = xfs_dir2_leaf_init(args, xfs_dir2_da_to_db(mp, blkno), &newblk->bp, XFS_DIR2_LEAFN_MAGIC); if (error) { return error; } newblk->blkno = blkno; newblk->magic = XFS_DIR2_LEAFN_MAGIC; /* * Rebalance the entries across the two leaves, link the new * block into the leaves. */ xfs_dir2_leafn_rebalance(state, oldblk, newblk); error = xfs_da_blk_link(state, oldblk, newblk); if (error) { return error; } /* * Insert the new entry in the correct block. */ if (state->inleaf) error = xfs_dir2_leafn_add(oldblk->bp, args, oldblk->index); else error = xfs_dir2_leafn_add(newblk->bp, args, newblk->index); /* * Update last hashval in each block since we added the name. */ oldblk->hashval = xfs_dir2_leafn_lasthash(oldblk->bp, NULL); newblk->hashval = xfs_dir2_leafn_lasthash(newblk->bp, NULL); xfs_dir2_leafn_check(args->dp, oldblk->bp); xfs_dir2_leafn_check(args->dp, newblk->bp); return error; } /* * Check a leaf block and its neighbors to see if the block should be * collapsed into one or the other neighbor. Always keep the block * with the smaller block number. * If the current block is over 50% full, don't try to join it, return 0. * If the block is empty, fill in the state structure and return 2. * If it can be collapsed, fill in the state structure and return 1. * If nothing can be done, return 0. */ int /* error */ xfs_dir2_leafn_toosmall( xfs_da_state_t *state, /* btree cursor */ int *action) /* resulting action to take */ { xfs_da_state_blk_t *blk; /* leaf block */ xfs_dablk_t blkno; /* leaf block number */ xfs_dabuf_t *bp; /* leaf buffer */ int bytes; /* bytes in use */ int count; /* leaf live entry count */ int error; /* error return value */ int forward; /* sibling block direction */ int i; /* sibling counter */ xfs_da_blkinfo_t *info; /* leaf block header */ xfs_dir2_leaf_t *leaf; /* leaf structure */ int rval; /* result from path_shift */ /* * Check for the degenerate case of the block being over 50% full. * If so, it's not worth even looking to see if we might be able * to coalesce with a sibling. */ blk = &state->path.blk[state->path.active - 1]; info = blk->bp->data; ASSERT(be16_to_cpu(info->magic) == XFS_DIR2_LEAFN_MAGIC); leaf = (xfs_dir2_leaf_t *)info; count = be16_to_cpu(leaf->hdr.count) - be16_to_cpu(leaf->hdr.stale); bytes = (uint)sizeof(leaf->hdr) + count * (uint)sizeof(leaf->ents[0]); if (bytes > (state->blocksize >> 1)) { /* * Blk over 50%, don't try to join. */ *action = 0; return 0; } /* * Check for the degenerate case of the block being empty. * If the block is empty, we'll simply delete it, no need to * coalesce it with a sibling block. We choose (arbitrarily) * to merge with the forward block unless it is NULL. */ if (count == 0) { /* * Make altpath point to the block we want to keep and * path point to the block we want to drop (this one). */ forward = (info->forw != 0); memcpy(&state->altpath, &state->path, sizeof(state->path)); error = xfs_da_path_shift(state, &state->altpath, forward, 0, &rval); if (error) return error; *action = rval ? 2 : 0; return 0; } /* * Examine each sibling block to see if we can coalesce with * at least 25% free space to spare. We need to figure out * whether to merge with the forward or the backward block. * We prefer coalescing with the lower numbered sibling so as * to shrink a directory over time. */ forward = be32_to_cpu(info->forw) < be32_to_cpu(info->back); for (i = 0, bp = NULL; i < 2; forward = !forward, i++) { blkno = forward ? be32_to_cpu(info->forw) : be32_to_cpu(info->back); if (blkno == 0) continue; /* * Read the sibling leaf block. */ if ((error = xfs_da_read_buf(state->args->trans, state->args->dp, blkno, -1, &bp, XFS_DATA_FORK))) { return error; } ASSERT(bp != NULL); /* * Count bytes in the two blocks combined. */ leaf = (xfs_dir2_leaf_t *)info; count = be16_to_cpu(leaf->hdr.count) - be16_to_cpu(leaf->hdr.stale); bytes = state->blocksize - (state->blocksize >> 2); leaf = bp->data; ASSERT(be16_to_cpu(leaf->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); count += be16_to_cpu(leaf->hdr.count) - be16_to_cpu(leaf->hdr.stale); bytes -= count * (uint)sizeof(leaf->ents[0]); /* * Fits with at least 25% to spare. */ if (bytes >= 0) break; xfs_da_brelse(state->args->trans, bp); } /* * Didn't like either block, give up. */ if (i >= 2) { *action = 0; return 0; } /* * Done with the sibling leaf block here, drop the dabuf * so path_shift can get it. */ xfs_da_buf_done(bp); /* * Make altpath point to the block we want to keep (the lower * numbered block) and path point to the block we want to drop. */ memcpy(&state->altpath, &state->path, sizeof(state->path)); if (blkno < blk->blkno) error = xfs_da_path_shift(state, &state->altpath, forward, 0, &rval); else error = xfs_da_path_shift(state, &state->path, forward, 0, &rval); if (error) { return error; } *action = rval ? 0 : 1; return 0; } /* * Move all the leaf entries from drop_blk to save_blk. * This is done as part of a join operation. */ void xfs_dir2_leafn_unbalance( xfs_da_state_t *state, /* cursor */ xfs_da_state_blk_t *drop_blk, /* dead block */ xfs_da_state_blk_t *save_blk) /* surviving block */ { xfs_da_args_t *args; /* operation arguments */ xfs_dir2_leaf_t *drop_leaf; /* dead leaf structure */ xfs_dir2_leaf_t *save_leaf; /* surviving leaf structure */ args = state->args; ASSERT(drop_blk->magic == XFS_DIR2_LEAFN_MAGIC); ASSERT(save_blk->magic == XFS_DIR2_LEAFN_MAGIC); drop_leaf = drop_blk->bp->data; save_leaf = save_blk->bp->data; ASSERT(be16_to_cpu(drop_leaf->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); ASSERT(be16_to_cpu(save_leaf->hdr.info.magic) == XFS_DIR2_LEAFN_MAGIC); /* * If there are any stale leaf entries, take this opportunity * to purge them. */ if (drop_leaf->hdr.stale) xfs_dir2_leaf_compact(args, drop_blk->bp); if (save_leaf->hdr.stale) xfs_dir2_leaf_compact(args, save_blk->bp); /* * Move the entries from drop to the appropriate end of save. */ drop_blk->hashval = be32_to_cpu(drop_leaf->ents[be16_to_cpu(drop_leaf->hdr.count) - 1].hashval); if (xfs_dir2_leafn_order(save_blk->bp, drop_blk->bp)) xfs_dir2_leafn_moveents(args, drop_blk->bp, 0, save_blk->bp, 0, be16_to_cpu(drop_leaf->hdr.count)); else xfs_dir2_leafn_moveents(args, drop_blk->bp, 0, save_blk->bp, be16_to_cpu(save_leaf->hdr.count), be16_to_cpu(drop_leaf->hdr.count)); save_blk->hashval = be32_to_cpu(save_leaf->ents[be16_to_cpu(save_leaf->hdr.count) - 1].hashval); xfs_dir2_leafn_check(args->dp, save_blk->bp); } /* * Top-level node form directory addname routine. */ int /* error */ xfs_dir2_node_addname( xfs_da_args_t *args) /* operation arguments */ { xfs_da_state_blk_t *blk; /* leaf block for insert */ int error; /* error return value */ int rval; /* sub-return value */ xfs_da_state_t *state; /* btree cursor */ trace_xfs_dir2_node_addname(args); /* * Allocate and initialize the state (btree cursor). */ state = xfs_da_state_alloc(); state->args = args; state->mp = args->dp->i_mount; state->blocksize = state->mp->m_dirblksize; state->node_ents = state->mp->m_dir_node_ents; /* * Look up the name. We're not supposed to find it, but * this gives us the insertion point. */ error = xfs_da_node_lookup_int(state, &rval); if (error) rval = error; if (rval != ENOENT) { goto done; } /* * Add the data entry to a data block. * Extravalid is set to a freeblock found by lookup. */ rval = xfs_dir2_node_addname_int(args, state->extravalid ? &state->extrablk : NULL); if (rval) { goto done; } blk = &state->path.blk[state->path.active - 1]; ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC); /* * Add the new leaf entry. */ rval = xfs_dir2_leafn_add(blk->bp, args, blk->index); if (rval == 0) { /* * It worked, fix the hash values up the btree. */ if (!(args->op_flags & XFS_DA_OP_JUSTCHECK)) xfs_da_fixhashpath(state, &state->path); } else { /* * It didn't work, we need to split the leaf block. */ if (args->total == 0) { ASSERT(rval == ENOSPC); goto done; } /* * Split the leaf block and insert the new entry. */ rval = xfs_da_split(state); } done: xfs_da_state_free(state); return rval; } /* * Add the data entry for a node-format directory name addition. * The leaf entry is added in xfs_dir2_leafn_add. * We may enter with a freespace block that the lookup found. */ static int /* error */ xfs_dir2_node_addname_int( xfs_da_args_t *args, /* operation arguments */ xfs_da_state_blk_t *fblk) /* optional freespace block */ { xfs_dir2_data_t *data; /* data block structure */ xfs_dir2_db_t dbno; /* data block number */ xfs_dabuf_t *dbp; /* data block buffer */ xfs_dir2_data_entry_t *dep; /* data entry pointer */ xfs_inode_t *dp; /* incore directory inode */ xfs_dir2_data_unused_t *dup; /* data unused entry pointer */ int error; /* error return value */ xfs_dir2_db_t fbno; /* freespace block number */ xfs_dabuf_t *fbp; /* freespace buffer */ int findex; /* freespace entry index */ xfs_dir2_free_t *free=NULL; /* freespace block structure */ xfs_dir2_db_t ifbno; /* initial freespace block no */ xfs_dir2_db_t lastfbno=0; /* highest freespace block no */ int length; /* length of the new entry */ int logfree; /* need to log free entry */ xfs_mount_t *mp; /* filesystem mount point */ int needlog; /* need to log data header */ int needscan; /* need to rescan data frees */ __be16 *tagp; /* data entry tag pointer */ xfs_trans_t *tp; /* transaction pointer */ dp = args->dp; mp = dp->i_mount; tp = args->trans; length = xfs_dir2_data_entsize(args->namelen); /* * If we came in with a freespace block that means that lookup * found an entry with our hash value. This is the freespace * block for that data entry. */ if (fblk) { fbp = fblk->bp; /* * Remember initial freespace block number. */ ifbno = fblk->blkno; free = fbp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); findex = fblk->index; /* * This means the free entry showed that the data block had * space for our entry, so we remembered it. * Use that data block. */ if (findex >= 0) { ASSERT(findex < be32_to_cpu(free->hdr.nvalid)); ASSERT(be16_to_cpu(free->bests[findex]) != NULLDATAOFF); ASSERT(be16_to_cpu(free->bests[findex]) >= length); dbno = be32_to_cpu(free->hdr.firstdb) + findex; } /* * The data block looked at didn't have enough room. * We'll start at the beginning of the freespace entries. */ else { dbno = -1; findex = 0; } } /* * Didn't come in with a freespace block, so don't have a data block. */ else { ifbno = dbno = -1; fbp = NULL; findex = 0; } /* * If we don't have a data block yet, we're going to scan the * freespace blocks looking for one. Figure out what the * highest freespace block number is. */ if (dbno == -1) { xfs_fileoff_t fo; /* freespace block number */ if ((error = xfs_bmap_last_offset(tp, dp, &fo, XFS_DATA_FORK))) return error; lastfbno = xfs_dir2_da_to_db(mp, (xfs_dablk_t)fo); fbno = ifbno; } /* * While we haven't identified a data block, search the freeblock * data for a good data block. If we find a null freeblock entry, * indicating a hole in the data blocks, remember that. */ while (dbno == -1) { /* * If we don't have a freeblock in hand, get the next one. */ if (fbp == NULL) { /* * Happens the first time through unless lookup gave * us a freespace block to start with. */ if (++fbno == 0) fbno = XFS_DIR2_FREE_FIRSTDB(mp); /* * If it's ifbno we already looked at it. */ if (fbno == ifbno) fbno++; /* * If it's off the end we're done. */ if (fbno >= lastfbno) break; /* * Read the block. There can be holes in the * freespace blocks, so this might not succeed. * This should be really rare, so there's no reason * to avoid it. */ if ((error = xfs_da_read_buf(tp, dp, xfs_dir2_db_to_da(mp, fbno), -2, &fbp, XFS_DATA_FORK))) { return error; } if (unlikely(fbp == NULL)) { continue; } free = fbp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); findex = 0; } /* * Look at the current free entry. Is it good enough? */ if (be16_to_cpu(free->bests[findex]) != NULLDATAOFF && be16_to_cpu(free->bests[findex]) >= length) dbno = be32_to_cpu(free->hdr.firstdb) + findex; else { /* * Are we done with the freeblock? */ if (++findex == be32_to_cpu(free->hdr.nvalid)) { /* * Drop the block. */ xfs_da_brelse(tp, fbp); fbp = NULL; if (fblk && fblk->bp) fblk->bp = NULL; } } } /* * If we don't have a data block, we need to allocate one and make * the freespace entries refer to it. */ if (unlikely(dbno == -1)) { /* * Not allowed to allocate, return failure. */ if ((args->op_flags & XFS_DA_OP_JUSTCHECK) || args->total == 0) { /* * Drop the freespace buffer unless it came from our * caller. */ if ((fblk == NULL || fblk->bp == NULL) && fbp != NULL) xfs_da_buf_done(fbp); return XFS_ERROR(ENOSPC); } /* * Allocate and initialize the new data block. */ if (unlikely((error = xfs_dir2_grow_inode(args, XFS_DIR2_DATA_SPACE, &dbno)) || (error = xfs_dir2_data_init(args, dbno, &dbp)))) { /* * Drop the freespace buffer unless it came from our * caller. */ if ((fblk == NULL || fblk->bp == NULL) && fbp != NULL) xfs_da_buf_done(fbp); return error; } /* * If (somehow) we have a freespace block, get rid of it. */ if (fbp) xfs_da_brelse(tp, fbp); if (fblk && fblk->bp) fblk->bp = NULL; /* * Get the freespace block corresponding to the data block * that was just allocated. */ fbno = xfs_dir2_db_to_fdb(mp, dbno); if (unlikely(error = xfs_da_read_buf(tp, dp, xfs_dir2_db_to_da(mp, fbno), -2, &fbp, XFS_DATA_FORK))) { xfs_da_buf_done(dbp); return error; } /* * If there wasn't a freespace block, the read will * return a NULL fbp. Allocate and initialize a new one. */ if( fbp == NULL ) { if ((error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fbno))) { return error; } if (unlikely(xfs_dir2_db_to_fdb(mp, dbno) != fbno)) { cmn_err(CE_ALERT, "xfs_dir2_node_addname_int: dir ino " "%llu needed freesp block %lld for\n" " data block %lld, got %lld\n" " ifbno %llu lastfbno %d\n", (unsigned long long)dp->i_ino, (long long)xfs_dir2_db_to_fdb(mp, dbno), (long long)dbno, (long long)fbno, (unsigned long long)ifbno, lastfbno); if (fblk) { cmn_err(CE_ALERT, " fblk 0x%p blkno %llu " "index %d magic 0x%x\n", fblk, (unsigned long long)fblk->blkno, fblk->index, fblk->magic); } else { cmn_err(CE_ALERT, " ... fblk is NULL\n"); } XFS_ERROR_REPORT("xfs_dir2_node_addname_int", XFS_ERRLEVEL_LOW, mp); return XFS_ERROR(EFSCORRUPTED); } /* * Get a buffer for the new block. */ if ((error = xfs_da_get_buf(tp, dp, xfs_dir2_db_to_da(mp, fbno), -1, &fbp, XFS_DATA_FORK))) { return error; } ASSERT(fbp != NULL); /* * Initialize the new block to be empty, and remember * its first slot as our empty slot. */ free = fbp->data; free->hdr.magic = cpu_to_be32(XFS_DIR2_FREE_MAGIC); free->hdr.firstdb = cpu_to_be32( (fbno - XFS_DIR2_FREE_FIRSTDB(mp)) * XFS_DIR2_MAX_FREE_BESTS(mp)); free->hdr.nvalid = 0; free->hdr.nused = 0; } else { free = fbp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); } /* * Set the freespace block index from the data block number. */ findex = xfs_dir2_db_to_fdindex(mp, dbno); /* * If it's after the end of the current entries in the * freespace block, extend that table. */ if (findex >= be32_to_cpu(free->hdr.nvalid)) { ASSERT(findex < XFS_DIR2_MAX_FREE_BESTS(mp)); free->hdr.nvalid = cpu_to_be32(findex + 1); /* * Tag new entry so nused will go up. */ free->bests[findex] = cpu_to_be16(NULLDATAOFF); } /* * If this entry was for an empty data block * (this should always be true) then update the header. */ if (be16_to_cpu(free->bests[findex]) == NULLDATAOFF) { be32_add_cpu(&free->hdr.nused, 1); xfs_dir2_free_log_header(tp, fbp); } /* * Update the real value in the table. * We haven't allocated the data entry yet so this will * change again. */ data = dbp->data; free->bests[findex] = data->hdr.bestfree[0].length; logfree = 1; } /* * We had a data block so we don't have to make a new one. */ else { /* * If just checking, we succeeded. */ if (args->op_flags & XFS_DA_OP_JUSTCHECK) { if ((fblk == NULL || fblk->bp == NULL) && fbp != NULL) xfs_da_buf_done(fbp); return 0; } /* * Read the data block in. */ if (unlikely( error = xfs_da_read_buf(tp, dp, xfs_dir2_db_to_da(mp, dbno), -1, &dbp, XFS_DATA_FORK))) { if ((fblk == NULL || fblk->bp == NULL) && fbp != NULL) xfs_da_buf_done(fbp); return error; } data = dbp->data; logfree = 0; } ASSERT(be16_to_cpu(data->hdr.bestfree[0].length) >= length); /* * Point to the existing unused space. */ dup = (xfs_dir2_data_unused_t *) ((char *)data + be16_to_cpu(data->hdr.bestfree[0].offset)); needscan = needlog = 0; /* * Mark the first part of the unused space, inuse for us. */ xfs_dir2_data_use_free(tp, dbp, dup, (xfs_dir2_data_aoff_t)((char *)dup - (char *)data), length, &needlog, &needscan); /* * Fill in the new entry and log it. */ dep = (xfs_dir2_data_entry_t *)dup; dep->inumber = cpu_to_be64(args->inumber); dep->namelen = args->namelen; memcpy(dep->name, args->name, dep->namelen); tagp = xfs_dir2_data_entry_tag_p(dep); *tagp = cpu_to_be16((char *)dep - (char *)data); xfs_dir2_data_log_entry(tp, dbp, dep); /* * Rescan the block for bestfree if needed. */ if (needscan) xfs_dir2_data_freescan(mp, data, &needlog); /* * Log the data block header if needed. */ if (needlog) xfs_dir2_data_log_header(tp, dbp); /* * If the freespace entry is now wrong, update it. */ if (be16_to_cpu(free->bests[findex]) != be16_to_cpu(data->hdr.bestfree[0].length)) { free->bests[findex] = data->hdr.bestfree[0].length; logfree = 1; } /* * Log the freespace entry if needed. */ if (logfree) xfs_dir2_free_log_bests(tp, fbp, findex, findex); /* * If the caller didn't hand us the freespace block, drop it. */ if ((fblk == NULL || fblk->bp == NULL) && fbp != NULL) xfs_da_buf_done(fbp); /* * Return the data block and offset in args, then drop the data block. */ args->blkno = (xfs_dablk_t)dbno; args->index = be16_to_cpu(*tagp); xfs_da_buf_done(dbp); return 0; } /* * Lookup an entry in a node-format directory. * All the real work happens in xfs_da_node_lookup_int. * The only real output is the inode number of the entry. */ int /* error */ xfs_dir2_node_lookup( xfs_da_args_t *args) /* operation arguments */ { int error; /* error return value */ int i; /* btree level */ int rval; /* operation return value */ xfs_da_state_t *state; /* btree cursor */ trace_xfs_dir2_node_lookup(args); /* * Allocate and initialize the btree cursor. */ state = xfs_da_state_alloc(); state->args = args; state->mp = args->dp->i_mount; state->blocksize = state->mp->m_dirblksize; state->node_ents = state->mp->m_dir_node_ents; /* * Fill in the path to the entry in the cursor. */ error = xfs_da_node_lookup_int(state, &rval); if (error) rval = error; else if (rval == ENOENT && args->cmpresult == XFS_CMP_CASE) { /* If a CI match, dup the actual name and return EEXIST */ xfs_dir2_data_entry_t *dep; dep = (xfs_dir2_data_entry_t *)((char *)state->extrablk.bp-> data + state->extrablk.index); rval = xfs_dir_cilookup_result(args, dep->name, dep->namelen); } /* * Release the btree blocks and leaf block. */ for (i = 0; i < state->path.active; i++) { xfs_da_brelse(args->trans, state->path.blk[i].bp); state->path.blk[i].bp = NULL; } /* * Release the data block if we have it. */ if (state->extravalid && state->extrablk.bp) { xfs_da_brelse(args->trans, state->extrablk.bp); state->extrablk.bp = NULL; } xfs_da_state_free(state); return rval; } /* * Remove an entry from a node-format directory. */ int /* error */ xfs_dir2_node_removename( xfs_da_args_t *args) /* operation arguments */ { xfs_da_state_blk_t *blk; /* leaf block */ int error; /* error return value */ int rval; /* operation return value */ xfs_da_state_t *state; /* btree cursor */ trace_xfs_dir2_node_removename(args); /* * Allocate and initialize the btree cursor. */ state = xfs_da_state_alloc(); state->args = args; state->mp = args->dp->i_mount; state->blocksize = state->mp->m_dirblksize; state->node_ents = state->mp->m_dir_node_ents; /* * Look up the entry we're deleting, set up the cursor. */ error = xfs_da_node_lookup_int(state, &rval); if (error) rval = error; /* * Didn't find it, upper layer screwed up. */ if (rval != EEXIST) { xfs_da_state_free(state); return rval; } blk = &state->path.blk[state->path.active - 1]; ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC); ASSERT(state->extravalid); /* * Remove the leaf and data entries. * Extrablk refers to the data block. */ error = xfs_dir2_leafn_remove(args, blk->bp, blk->index, &state->extrablk, &rval); if (error) return error; /* * Fix the hash values up the btree. */ xfs_da_fixhashpath(state, &state->path); /* * If we need to join leaf blocks, do it. */ if (rval && state->path.active > 1) error = xfs_da_join(state); /* * If no errors so far, try conversion to leaf format. */ if (!error) error = xfs_dir2_node_to_leaf(state); xfs_da_state_free(state); return error; } /* * Replace an entry's inode number in a node-format directory. */ int /* error */ xfs_dir2_node_replace( xfs_da_args_t *args) /* operation arguments */ { xfs_da_state_blk_t *blk; /* leaf block */ xfs_dir2_data_t *data; /* data block structure */ xfs_dir2_data_entry_t *dep; /* data entry changed */ int error; /* error return value */ int i; /* btree level */ xfs_ino_t inum; /* new inode number */ xfs_dir2_leaf_t *leaf; /* leaf structure */ xfs_dir2_leaf_entry_t *lep; /* leaf entry being changed */ int rval; /* internal return value */ xfs_da_state_t *state; /* btree cursor */ trace_xfs_dir2_node_replace(args); /* * Allocate and initialize the btree cursor. */ state = xfs_da_state_alloc(); state->args = args; state->mp = args->dp->i_mount; state->blocksize = state->mp->m_dirblksize; state->node_ents = state->mp->m_dir_node_ents; inum = args->inumber; /* * Lookup the entry to change in the btree. */ error = xfs_da_node_lookup_int(state, &rval); if (error) { rval = error; } /* * It should be found, since the vnodeops layer has looked it up * and locked it. But paranoia is good. */ if (rval == EEXIST) { /* * Find the leaf entry. */ blk = &state->path.blk[state->path.active - 1]; ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC); leaf = blk->bp->data; lep = &leaf->ents[blk->index]; ASSERT(state->extravalid); /* * Point to the data entry. */ data = state->extrablk.bp->data; ASSERT(be32_to_cpu(data->hdr.magic) == XFS_DIR2_DATA_MAGIC); dep = (xfs_dir2_data_entry_t *) ((char *)data + xfs_dir2_dataptr_to_off(state->mp, be32_to_cpu(lep->address))); ASSERT(inum != be64_to_cpu(dep->inumber)); /* * Fill in the new inode number and log the entry. */ dep->inumber = cpu_to_be64(inum); xfs_dir2_data_log_entry(args->trans, state->extrablk.bp, dep); rval = 0; } /* * Didn't find it, and we're holding a data block. Drop it. */ else if (state->extravalid) { xfs_da_brelse(args->trans, state->extrablk.bp); state->extrablk.bp = NULL; } /* * Release all the buffers in the cursor. */ for (i = 0; i < state->path.active; i++) { xfs_da_brelse(args->trans, state->path.blk[i].bp); state->path.blk[i].bp = NULL; } xfs_da_state_free(state); return rval; } /* * Trim off a trailing empty freespace block. * Return (in rvalp) 1 if we did it, 0 if not. */ int /* error */ xfs_dir2_node_trim_free( xfs_da_args_t *args, /* operation arguments */ xfs_fileoff_t fo, /* free block number */ int *rvalp) /* out: did something */ { xfs_dabuf_t *bp; /* freespace buffer */ xfs_inode_t *dp; /* incore directory inode */ int error; /* error return code */ xfs_dir2_free_t *free; /* freespace structure */ xfs_mount_t *mp; /* filesystem mount point */ xfs_trans_t *tp; /* transaction pointer */ dp = args->dp; mp = dp->i_mount; tp = args->trans; /* * Read the freespace block. */ if (unlikely(error = xfs_da_read_buf(tp, dp, (xfs_dablk_t)fo, -2, &bp, XFS_DATA_FORK))) { return error; } /* * There can be holes in freespace. If fo is a hole, there's * nothing to do. */ if (bp == NULL) { return 0; } free = bp->data; ASSERT(be32_to_cpu(free->hdr.magic) == XFS_DIR2_FREE_MAGIC); /* * If there are used entries, there's nothing to do. */ if (be32_to_cpu(free->hdr.nused) > 0) { xfs_da_brelse(tp, bp); *rvalp = 0; return 0; } /* * Blow the block away. */ if ((error = xfs_dir2_shrink_inode(args, xfs_dir2_da_to_db(mp, (xfs_dablk_t)fo), bp))) { /* * Can't fail with ENOSPC since that only happens with no * space reservation, when breaking up an extent into two * pieces. This is the last block of an extent. */ ASSERT(error != ENOSPC); xfs_da_brelse(tp, bp); return error; } /* * Return that we succeeded. */ *rvalp = 1; return 0; }
gpl-2.0
ywzjackal/dmmu_linux
drivers/gpio/gpio-tps65910.c
290
6075
/* * TI TPS6591x GPIO driver * * Copyright 2010 Texas Instruments Inc. * * Author: Graeme Gregory <gg@slimlogic.co.uk> * Author: Jorge Eduardo Candelaria jedu@slimlogic.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. * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/errno.h> #include <linux/gpio.h> #include <linux/i2c.h> #include <linux/platform_device.h> #include <linux/mfd/tps65910.h> #include <linux/of_device.h> struct tps65910_gpio { struct gpio_chip gpio_chip; struct tps65910 *tps65910; }; static inline struct tps65910_gpio *to_tps65910_gpio(struct gpio_chip *chip) { return container_of(chip, struct tps65910_gpio, gpio_chip); } static int tps65910_gpio_get(struct gpio_chip *gc, unsigned offset) { struct tps65910_gpio *tps65910_gpio = to_tps65910_gpio(gc); struct tps65910 *tps65910 = tps65910_gpio->tps65910; unsigned int val; tps65910_reg_read(tps65910, TPS65910_GPIO0 + offset, &val); if (val & GPIO_STS_MASK) return 1; return 0; } static void tps65910_gpio_set(struct gpio_chip *gc, unsigned offset, int value) { struct tps65910_gpio *tps65910_gpio = to_tps65910_gpio(gc); struct tps65910 *tps65910 = tps65910_gpio->tps65910; if (value) tps65910_reg_set_bits(tps65910, TPS65910_GPIO0 + offset, GPIO_SET_MASK); else tps65910_reg_clear_bits(tps65910, TPS65910_GPIO0 + offset, GPIO_SET_MASK); } static int tps65910_gpio_output(struct gpio_chip *gc, unsigned offset, int value) { struct tps65910_gpio *tps65910_gpio = to_tps65910_gpio(gc); struct tps65910 *tps65910 = tps65910_gpio->tps65910; /* Set the initial value */ tps65910_gpio_set(gc, offset, value); return tps65910_reg_set_bits(tps65910, TPS65910_GPIO0 + offset, GPIO_CFG_MASK); } static int tps65910_gpio_input(struct gpio_chip *gc, unsigned offset) { struct tps65910_gpio *tps65910_gpio = to_tps65910_gpio(gc); struct tps65910 *tps65910 = tps65910_gpio->tps65910; return tps65910_reg_clear_bits(tps65910, TPS65910_GPIO0 + offset, GPIO_CFG_MASK); } #ifdef CONFIG_OF static struct tps65910_board *tps65910_parse_dt_for_gpio(struct device *dev, struct tps65910 *tps65910, int chip_ngpio) { struct tps65910_board *tps65910_board = tps65910->of_plat_data; unsigned int prop_array[TPS6591X_MAX_NUM_GPIO]; int ngpio = min(chip_ngpio, TPS6591X_MAX_NUM_GPIO); int ret; int idx; tps65910_board->gpio_base = -1; ret = of_property_read_u32_array(tps65910->dev->of_node, "ti,en-gpio-sleep", prop_array, ngpio); if (ret < 0) { dev_dbg(dev, "ti,en-gpio-sleep not specified\n"); return tps65910_board; } for (idx = 0; idx < ngpio; idx++) tps65910_board->en_gpio_sleep[idx] = (prop_array[idx] != 0); return tps65910_board; } #else static struct tps65910_board *tps65910_parse_dt_for_gpio(struct device *dev, struct tps65910 *tps65910, int chip_ngpio) { return NULL; } #endif static int tps65910_gpio_probe(struct platform_device *pdev) { struct tps65910 *tps65910 = dev_get_drvdata(pdev->dev.parent); struct tps65910_board *pdata = dev_get_platdata(tps65910->dev); struct tps65910_gpio *tps65910_gpio; int ret; int i; tps65910_gpio = devm_kzalloc(&pdev->dev, sizeof(*tps65910_gpio), GFP_KERNEL); if (!tps65910_gpio) { dev_err(&pdev->dev, "Could not allocate tps65910_gpio\n"); return -ENOMEM; } tps65910_gpio->tps65910 = tps65910; tps65910_gpio->gpio_chip.owner = THIS_MODULE; tps65910_gpio->gpio_chip.label = tps65910->i2c_client->name; switch (tps65910_chip_id(tps65910)) { case TPS65910: tps65910_gpio->gpio_chip.ngpio = TPS65910_NUM_GPIO; break; case TPS65911: tps65910_gpio->gpio_chip.ngpio = TPS65911_NUM_GPIO; break; default: return -EINVAL; } tps65910_gpio->gpio_chip.can_sleep = true; tps65910_gpio->gpio_chip.direction_input = tps65910_gpio_input; tps65910_gpio->gpio_chip.direction_output = tps65910_gpio_output; tps65910_gpio->gpio_chip.set = tps65910_gpio_set; tps65910_gpio->gpio_chip.get = tps65910_gpio_get; tps65910_gpio->gpio_chip.dev = &pdev->dev; #ifdef CONFIG_OF_GPIO tps65910_gpio->gpio_chip.of_node = tps65910->dev->of_node; #endif if (pdata && pdata->gpio_base) tps65910_gpio->gpio_chip.base = pdata->gpio_base; else tps65910_gpio->gpio_chip.base = -1; if (!pdata && tps65910->dev->of_node) pdata = tps65910_parse_dt_for_gpio(&pdev->dev, tps65910, tps65910_gpio->gpio_chip.ngpio); if (!pdata) goto skip_init; /* Configure sleep control for gpios if provided */ for (i = 0; i < tps65910_gpio->gpio_chip.ngpio; ++i) { if (!pdata->en_gpio_sleep[i]) continue; ret = tps65910_reg_set_bits(tps65910, TPS65910_GPIO0 + i, GPIO_SLEEP_MASK); if (ret < 0) dev_warn(tps65910->dev, "GPIO Sleep setting failed with err %d\n", ret); } skip_init: ret = gpiochip_add(&tps65910_gpio->gpio_chip); if (ret < 0) { dev_err(&pdev->dev, "Could not register gpiochip, %d\n", ret); return ret; } platform_set_drvdata(pdev, tps65910_gpio); return ret; } static int tps65910_gpio_remove(struct platform_device *pdev) { struct tps65910_gpio *tps65910_gpio = platform_get_drvdata(pdev); return gpiochip_remove(&tps65910_gpio->gpio_chip); } static struct platform_driver tps65910_gpio_driver = { .driver.name = "tps65910-gpio", .driver.owner = THIS_MODULE, .probe = tps65910_gpio_probe, .remove = tps65910_gpio_remove, }; static int __init tps65910_gpio_init(void) { return platform_driver_register(&tps65910_gpio_driver); } subsys_initcall(tps65910_gpio_init); static void __exit tps65910_gpio_exit(void) { platform_driver_unregister(&tps65910_gpio_driver); } module_exit(tps65910_gpio_exit); MODULE_AUTHOR("Graeme Gregory <gg@slimlogic.co.uk>"); MODULE_AUTHOR("Jorge Eduardo Candelaria jedu@slimlogic.co.uk>"); MODULE_DESCRIPTION("GPIO interface for TPS65910/TPS6511 PMICs"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:tps65910-gpio");
gpl-2.0
talnoah/Lemur_UpdatedBase
drivers/rtc/rtc-pm8xxx.c
290
14570
/* Copyright (c) 2010-2011, 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/module.h> #include <linux/init.h> #include <linux/rtc.h> #include <linux/pm.h> #include <linux/slab.h> #include<linux/spinlock.h> #include <linux/mfd/pm8xxx/core.h> #include <linux/mfd/pm8xxx/rtc.h> #include <linux/sched.h> #define PM8XXX_ALARM_CTRL_OFFSET 0x01 #define PM8XXX_RTC_WRITE_OFFSET 0x02 #define PM8XXX_RTC_READ_OFFSET 0x06 #define PM8XXX_ALARM_RW_OFFSET 0x0A #define PM8xxx_RTC_ENABLE BIT(7) #define PM8xxx_RTC_ALARM_ENABLE BIT(1) #define PM8xxx_RTC_ABORT_ENABLE BIT(0) #define PM8xxx_RTC_ALARM_CLEAR BIT(0) #define NUM_8_BIT_RTC_REGS 0x4 struct pm8xxx_rtc { struct rtc_device *rtc; int rtc_alarm_irq; int rtc_base; int rtc_read_base; int rtc_write_base; int alarm_rw_base; u8 ctrl_reg; struct device *rtc_dev; spinlock_t ctrl_reg_lock; }; /* * The RTC registers need to be read/written one byte at a time. This is a * hardware limitation. */ static int pm8xxx_read_wrapper(struct pm8xxx_rtc *rtc_dd, u8 *rtc_val, int base, int count) { int i, rc; struct device *parent = rtc_dd->rtc_dev->parent; for (i = 0; i < count; i++) { rc = pm8xxx_readb(parent, base + i, &rtc_val[i]); if (rc < 0) { dev_err(rtc_dd->rtc_dev, "PM8xxx read failed\n"); return rc; } } return 0; } static int pm8xxx_write_wrapper(struct pm8xxx_rtc *rtc_dd, u8 *rtc_val, int base, int count) { int i, rc; struct device *parent = rtc_dd->rtc_dev->parent; for (i = 0; i < count; i++) { rc = pm8xxx_writeb(parent, base + i, rtc_val[i]); if (rc < 0) { dev_err(rtc_dd->rtc_dev, "PM8xxx write failed\n"); return rc; } } return 0; } static int pm8xxx_rtc_set_time(struct device *dev, struct rtc_time *tm) { int rc; unsigned long secs, irq_flags; u8 value[4], reg = 0, alarm_enabled = 0, ctrl_reg; struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev); rtc_tm_to_time(tm, &secs); value[0] = secs & 0xFF; value[1] = (secs >> 8) & 0xFF; value[2] = (secs >> 16) & 0xFF; value[3] = (secs >> 24) & 0xFF; dev_dbg(dev, "Seconds value to be written to RTC = %lu\n", secs); printk("[RTC_DEBUG] Seconds value to be written to RTC = %lu by pid[%d][%s]\n", secs, current->pid, current->comm); dump_stack(); spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags); ctrl_reg = rtc_dd->ctrl_reg; if (ctrl_reg & PM8xxx_RTC_ALARM_ENABLE) { alarm_enabled = 1; ctrl_reg &= ~PM8xxx_RTC_ALARM_ENABLE; rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1); if (rc < 0) { dev_err(dev, "PM8xxx write failed\n"); goto rtc_rw_fail; } } else spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags); reg = 0; rc = pm8xxx_write_wrapper(rtc_dd, &reg, rtc_dd->rtc_write_base, 1); if (rc < 0) { dev_err(dev, "PM8xxx write failed\n"); goto rtc_rw_fail; } rc = pm8xxx_write_wrapper(rtc_dd, value + 1, rtc_dd->rtc_write_base + 1, 3); if (rc < 0) { dev_err(dev, "Write to RTC registers failed\n"); goto rtc_rw_fail; } rc = pm8xxx_write_wrapper(rtc_dd, value, rtc_dd->rtc_write_base, 1); if (rc < 0) { dev_err(dev, "Write to RTC register failed\n"); goto rtc_rw_fail; } if (alarm_enabled) { ctrl_reg |= PM8xxx_RTC_ALARM_ENABLE; rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1); if (rc < 0) { dev_err(dev, "PM8xxx write failed\n"); goto rtc_rw_fail; } } rtc_dd->ctrl_reg = ctrl_reg; rtc_rw_fail: if (alarm_enabled) spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags); return rc; } static int pm8xxx_rtc_read_time(struct device *dev, struct rtc_time *tm) { int rc; u8 value[4], reg; unsigned long secs; struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev); rc = pm8xxx_read_wrapper(rtc_dd, value, rtc_dd->rtc_read_base, NUM_8_BIT_RTC_REGS); if (rc < 0) { dev_err(dev, "RTC time read failed\n"); return rc; } rc = pm8xxx_read_wrapper(rtc_dd, &reg, rtc_dd->rtc_read_base, 1); if (rc < 0) { dev_err(dev, "PM8xxx read failed\n"); return rc; } if (unlikely(reg < value[0])) { rc = pm8xxx_read_wrapper(rtc_dd, value, rtc_dd->rtc_read_base, NUM_8_BIT_RTC_REGS); if (rc < 0) { dev_err(dev, "RTC time read failed\n"); return rc; } } secs = value[0] | (value[1] << 8) | (value[2] << 16) \ | (value[3] << 24); rtc_time_to_tm(secs, tm); rc = rtc_valid_tm(tm); if (rc < 0) { dev_err(dev, "Invalid time read from PM8xxx\n"); return rc; } dev_dbg(dev, "secs = %lu, h:m:s == %d:%d:%d, d/m/y = %d/%d/%d\n", secs, tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_mday, tm->tm_mon, tm->tm_year); return 0; } static int pm8xxx_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alarm) { int rc; u8 value[4], ctrl_reg; unsigned long secs, secs_rtc, irq_flags; struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev); struct rtc_time rtc_tm; rtc_tm_to_time(&alarm->time, &secs); rc = pm8xxx_rtc_read_time(dev, &rtc_tm); if (rc < 0) { dev_err(dev, "Unamble to read RTC time\n"); return -EINVAL; } rtc_tm_to_time(&rtc_tm, &secs_rtc); if (secs < secs_rtc) { dev_err(dev, "Trying to set alarm in the past\n"); return -EINVAL; } value[0] = secs & 0xFF; value[1] = (secs >> 8) & 0xFF; value[2] = (secs >> 16) & 0xFF; value[3] = (secs >> 24) & 0xFF; spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags); rc = pm8xxx_write_wrapper(rtc_dd, value, rtc_dd->alarm_rw_base, NUM_8_BIT_RTC_REGS); if (rc < 0) { dev_err(dev, "Write to RTC ALARM registers failed\n"); goto rtc_rw_fail; } ctrl_reg = rtc_dd->ctrl_reg; ctrl_reg = (alarm->enabled) ? (ctrl_reg | PM8xxx_RTC_ALARM_ENABLE) : (ctrl_reg & ~PM8xxx_RTC_ALARM_ENABLE); rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1); if (rc < 0) { dev_err(dev, "PM8xxx write failed\n"); goto rtc_rw_fail; } rtc_dd->ctrl_reg = ctrl_reg; dev_dbg(dev, "Alarm Set for h:r:s=%d:%d:%d, d/m/y=%d/%d/%d\n", alarm->time.tm_hour, alarm->time.tm_min, alarm->time.tm_sec, alarm->time.tm_mday, alarm->time.tm_mon, alarm->time.tm_year); rtc_rw_fail: spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags); return rc; } static int pm8xxx_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alarm) { int rc; u8 value[4]; unsigned long secs; struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev); rc = pm8xxx_read_wrapper(rtc_dd, value, rtc_dd->alarm_rw_base, NUM_8_BIT_RTC_REGS); if (rc < 0) { dev_err(dev, "RTC alarm time read failed\n"); return rc; } secs = value[0] | (value[1] << 8) | (value[2] << 16) | \ (value[3] << 24); rtc_time_to_tm(secs, &alarm->time); rc = rtc_valid_tm(&alarm->time); if (rc < 0) { dev_err(dev, "Invalid time read from PM8xxx\n"); return rc; } dev_dbg(dev, "Alarm set for - h:r:s=%d:%d:%d, d/m/y=%d/%d/%d\n", alarm->time.tm_hour, alarm->time.tm_min, alarm->time.tm_sec, alarm->time.tm_mday, alarm->time.tm_mon, alarm->time.tm_year); return 0; } static int pm8xxx_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled) { int rc; unsigned long irq_flags; struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev); u8 ctrl_reg; spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags); ctrl_reg = rtc_dd->ctrl_reg; ctrl_reg = (enabled) ? (ctrl_reg | PM8xxx_RTC_ALARM_ENABLE) : (ctrl_reg & ~PM8xxx_RTC_ALARM_ENABLE); rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1); if (rc < 0) { dev_err(dev, "PM8xxx write failed\n"); goto rtc_rw_fail; } rtc_dd->ctrl_reg = ctrl_reg; rtc_rw_fail: spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags); return rc; } static struct rtc_class_ops pm8xxx_rtc_ops = { .read_time = pm8xxx_rtc_read_time, .set_alarm = pm8xxx_rtc_set_alarm, .read_alarm = pm8xxx_rtc_read_alarm, .alarm_irq_enable = pm8xxx_rtc_alarm_irq_enable, }; static irqreturn_t pm8xxx_alarm_trigger(int irq, void *dev_id) { struct pm8xxx_rtc *rtc_dd = dev_id; u8 ctrl_reg; int rc; unsigned long irq_flags; rtc_update_irq(rtc_dd->rtc, 1, RTC_IRQF | RTC_AF); spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags); ctrl_reg = rtc_dd->ctrl_reg; ctrl_reg &= ~PM8xxx_RTC_ALARM_ENABLE; rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1); if (rc < 0) { spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags); dev_err(rtc_dd->rtc_dev, "PM8xxx write failed!\n"); goto rtc_alarm_handled; } rtc_dd->ctrl_reg = ctrl_reg; spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags); rc = pm8xxx_read_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base + PM8XXX_ALARM_CTRL_OFFSET, 1); if (rc < 0) { dev_err(rtc_dd->rtc_dev, "PM8xxx write failed!\n"); goto rtc_alarm_handled; } ctrl_reg &= ~PM8xxx_RTC_ALARM_CLEAR; rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base + PM8XXX_ALARM_CTRL_OFFSET, 1); if (rc < 0) dev_err(rtc_dd->rtc_dev, "PM8xxx write failed!\n"); rtc_alarm_handled: return IRQ_HANDLED; } static int __devinit pm8xxx_rtc_probe(struct platform_device *pdev) { int rc; u8 ctrl_reg; bool rtc_write_enable = false; struct pm8xxx_rtc *rtc_dd; struct resource *rtc_resource; const struct pm8xxx_rtc_platform_data *pdata = pdev->dev.platform_data; if (pdata != NULL) rtc_write_enable = pdata->rtc_write_enable; rtc_dd = kzalloc(sizeof(*rtc_dd), GFP_KERNEL); if (rtc_dd == NULL) { dev_err(&pdev->dev, "Unable to allocate memory!\n"); return -ENOMEM; } spin_lock_init(&rtc_dd->ctrl_reg_lock); rtc_dd->rtc_alarm_irq = platform_get_irq(pdev, 0); if (rtc_dd->rtc_alarm_irq < 0) { dev_err(&pdev->dev, "Alarm IRQ resource absent!\n"); rc = -ENXIO; goto fail_rtc_enable; } rtc_resource = platform_get_resource_byname(pdev, IORESOURCE_IO, "pmic_rtc_base"); if (!(rtc_resource && rtc_resource->start)) { dev_err(&pdev->dev, "RTC IO resource absent!\n"); rc = -ENXIO; goto fail_rtc_enable; } rtc_dd->rtc_base = rtc_resource->start; rtc_dd->rtc_write_base = rtc_dd->rtc_base + PM8XXX_RTC_WRITE_OFFSET; rtc_dd->rtc_read_base = rtc_dd->rtc_base + PM8XXX_RTC_READ_OFFSET; rtc_dd->alarm_rw_base = rtc_dd->rtc_base + PM8XXX_ALARM_RW_OFFSET; rtc_dd->rtc_dev = &(pdev->dev); rc = pm8xxx_read_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1); if (rc < 0) { dev_err(&pdev->dev, "PM8xxx read failed!\n"); goto fail_rtc_enable; } if (!(ctrl_reg & PM8xxx_RTC_ENABLE)) { ctrl_reg |= PM8xxx_RTC_ENABLE; rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1); if (rc < 0) { dev_err(&pdev->dev, "PM8xxx write failed!\n"); goto fail_rtc_enable; } } ctrl_reg |= PM8xxx_RTC_ABORT_ENABLE; rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1); if (rc < 0) { dev_err(&pdev->dev, "PM8xxx write failed!\n"); goto fail_rtc_enable; } rtc_dd->ctrl_reg = ctrl_reg; if (rtc_write_enable == true) pm8xxx_rtc_ops.set_time = pm8xxx_rtc_set_time; platform_set_drvdata(pdev, rtc_dd); rtc_dd->rtc = rtc_device_register("pm8xxx_rtc", &pdev->dev, &pm8xxx_rtc_ops, THIS_MODULE); if (IS_ERR(rtc_dd->rtc)) { dev_err(&pdev->dev, "%s: RTC registration failed (%ld)\n", __func__, PTR_ERR(rtc_dd->rtc)); rc = PTR_ERR(rtc_dd->rtc); goto fail_rtc_enable; } rc = request_any_context_irq(rtc_dd->rtc_alarm_irq, pm8xxx_alarm_trigger, IRQF_TRIGGER_RISING, "pm8xxx_rtc_alarm", rtc_dd); if (rc < 0) { dev_err(&pdev->dev, "Request IRQ failed (%d)\n", rc); goto fail_req_irq; } device_init_wakeup(&pdev->dev, 1); dev_dbg(&pdev->dev, "Probe success !!\n"); return 0; fail_req_irq: rtc_device_unregister(rtc_dd->rtc); fail_rtc_enable: platform_set_drvdata(pdev, NULL); kfree(rtc_dd); return rc; } #ifdef CONFIG_PM static int pm8xxx_rtc_resume(struct device *dev) { struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev); if (device_may_wakeup(dev)) disable_irq_wake(rtc_dd->rtc_alarm_irq); return 0; } static int pm8xxx_rtc_suspend(struct device *dev) { struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev); if (device_may_wakeup(dev)) enable_irq_wake(rtc_dd->rtc_alarm_irq); return 0; } static const struct dev_pm_ops pm8xxx_rtc_pm_ops = { .suspend = pm8xxx_rtc_suspend, .resume = pm8xxx_rtc_resume, }; #endif static int __devexit pm8xxx_rtc_remove(struct platform_device *pdev) { struct pm8xxx_rtc *rtc_dd = platform_get_drvdata(pdev); device_init_wakeup(&pdev->dev, 0); free_irq(rtc_dd->rtc_alarm_irq, rtc_dd); rtc_device_unregister(rtc_dd->rtc); platform_set_drvdata(pdev, NULL); kfree(rtc_dd); return 0; } static void pm8xxx_rtc_shutdown(struct platform_device *pdev) { u8 value[4] = {0, 0, 0, 0}; u8 reg; int rc; unsigned long irq_flags; bool rtc_alarm_powerup = false; struct pm8xxx_rtc *rtc_dd = platform_get_drvdata(pdev); struct pm8xxx_rtc_platform_data *pdata = pdev->dev.platform_data; if (pdata != NULL) rtc_alarm_powerup = pdata->rtc_alarm_powerup; if (!rtc_alarm_powerup) { spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags); dev_dbg(&pdev->dev, "Disabling alarm interrupts\n"); reg = rtc_dd->ctrl_reg; reg &= ~PM8xxx_RTC_ALARM_ENABLE; rc = pm8xxx_write_wrapper(rtc_dd, &reg, rtc_dd->rtc_base, 1); if (rc < 0) { dev_err(rtc_dd->rtc_dev, "PM8xxx write failed\n"); goto fail_alarm_disable; } rc = pm8xxx_write_wrapper(rtc_dd, value, rtc_dd->alarm_rw_base, NUM_8_BIT_RTC_REGS); if (rc < 0) dev_err(rtc_dd->rtc_dev, "PM8xxx write failed\n"); fail_alarm_disable: spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags); } } static struct platform_driver pm8xxx_rtc_driver = { .probe = pm8xxx_rtc_probe, .remove = __devexit_p(pm8xxx_rtc_remove), .shutdown = pm8xxx_rtc_shutdown, .driver = { .name = PM8XXX_RTC_DEV_NAME, .owner = THIS_MODULE, #ifdef CONFIG_PM .pm = &pm8xxx_rtc_pm_ops, #endif }, }; static int __init pm8xxx_rtc_init(void) { return platform_driver_register(&pm8xxx_rtc_driver); } module_init(pm8xxx_rtc_init); static void __exit pm8xxx_rtc_exit(void) { platform_driver_unregister(&pm8xxx_rtc_driver); } module_exit(pm8xxx_rtc_exit); MODULE_ALIAS("platform:rtc-pm8xxx"); MODULE_DESCRIPTION("PMIC8xxx RTC driver"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Anirudh Ghayal <aghayal@codeaurora.org>");
gpl-2.0
rmcc/gp_one_kernel
arch/sh/mm/nommu.c
546
1619
/* * arch/sh/mm/nommu.c * * Various helper routines and stubs for MMUless SH. * * Copyright (C) 2002 - 2009 Paul Mundt * * Released under the terms of the GNU GPL v2.0. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/string.h> #include <linux/mm.h> #include <asm/pgtable.h> #include <asm/tlbflush.h> #include <asm/page.h> #include <asm/uaccess.h> /* * Nothing too terribly exciting here .. */ void copy_page(void *to, void *from) { memcpy(to, from, PAGE_SIZE); } __kernel_size_t __copy_user(void *to, const void *from, __kernel_size_t n) { memcpy(to, from, n); return 0; } __kernel_size_t __clear_user(void *to, __kernel_size_t n) { memset(to, 0, n); return 0; } void local_flush_tlb_all(void) { BUG(); } void local_flush_tlb_mm(struct mm_struct *mm) { BUG(); } void local_flush_tlb_range(struct vm_area_struct *vma, unsigned long start, unsigned long end) { BUG(); } void local_flush_tlb_page(struct vm_area_struct *vma, unsigned long page) { BUG(); } void local_flush_tlb_one(unsigned long asid, unsigned long page) { BUG(); } void local_flush_tlb_kernel_range(unsigned long start, unsigned long end) { BUG(); } void __update_tlb(struct vm_area_struct *vma, unsigned long address, pte_t pte) { } void __init kmap_coherent_init(void) { } void *kmap_coherent(struct page *page, unsigned long addr) { BUG(); return NULL; } void kunmap_coherent(void *kvaddr) { BUG(); } void __init page_table_range_init(unsigned long start, unsigned long end, pgd_t *pgd_base) { } void __set_fixmap(enum fixed_addresses idx, unsigned long phys, pgprot_t prot) { }
gpl-2.0
solring/GT-I9300_JB_Kernel_alarmAlign
arch/arm/plat-samsung/dev-ts1.c
546
1432
/* linux/arch/arm/plat-samsung/dev-ts1.c * * Copyright (c) 2008 Simtec Electronics * http://armlinux.simtec.co.uk/ * Ben Dooks <ben@simtec.co.uk>, <ben-linux@fluff.org> * * Adapted by Maurus Cuelenaere for s3c64xx * * S3C64XX series device definition for touchscreen device * * 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/string.h> #include <linux/platform_device.h> #include <mach/irqs.h> #include <mach/map.h> #include <plat/devs.h> #include <plat/ts.h> static struct resource s3c_ts_resource[] = { [0] = { .start = SAMSUNG_PA_ADC1, .end = SAMSUNG_PA_ADC1 + SZ_256 - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = IRQ_PEN1, .end = IRQ_PEN1, .flags = IORESOURCE_IRQ, }, }; struct platform_device s3c_device_ts1 = { .name = "s3c64xx-ts", .id = 1, .num_resources = ARRAY_SIZE(s3c_ts_resource), .resource = s3c_ts_resource, }; void __init s3c24xx_ts1_set_platdata(struct s3c2410_ts_mach_info *pd) { struct s3c2410_ts_mach_info *npd; if (!pd) { printk(KERN_ERR "%s: no platform data\n", __func__); return; } npd = kmemdup(pd, sizeof(struct s3c2410_ts_mach_info), GFP_KERNEL); if (!npd) printk(KERN_ERR "%s: no memory for platform data\n", __func__); s3c_device_ts1.dev.platform_data = npd; }
gpl-2.0
OSLL/linux
drivers/clk/clk-pwm.c
802
3180
/* * Copyright (C) 2014 Philipp Zabel, Pengutronix * * 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. * * PWM (mis)used as clock output */ #include <linux/clk-provider.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/pwm.h> struct clk_pwm { struct clk_hw hw; struct pwm_device *pwm; u32 fixed_rate; }; static inline struct clk_pwm *to_clk_pwm(struct clk_hw *hw) { return container_of(hw, struct clk_pwm, hw); } static int clk_pwm_prepare(struct clk_hw *hw) { struct clk_pwm *clk_pwm = to_clk_pwm(hw); return pwm_enable(clk_pwm->pwm); } static void clk_pwm_unprepare(struct clk_hw *hw) { struct clk_pwm *clk_pwm = to_clk_pwm(hw); pwm_disable(clk_pwm->pwm); } static unsigned long clk_pwm_recalc_rate(struct clk_hw *hw, unsigned long parent_rate) { struct clk_pwm *clk_pwm = to_clk_pwm(hw); return clk_pwm->fixed_rate; } static const struct clk_ops clk_pwm_ops = { .prepare = clk_pwm_prepare, .unprepare = clk_pwm_unprepare, .recalc_rate = clk_pwm_recalc_rate, }; static int clk_pwm_probe(struct platform_device *pdev) { struct device_node *node = pdev->dev.of_node; struct clk_init_data init; struct clk_pwm *clk_pwm; struct pwm_device *pwm; const char *clk_name; struct clk *clk; int ret; clk_pwm = devm_kzalloc(&pdev->dev, sizeof(*clk_pwm), GFP_KERNEL); if (!clk_pwm) return -ENOMEM; pwm = devm_pwm_get(&pdev->dev, NULL); if (IS_ERR(pwm)) return PTR_ERR(pwm); if (!pwm->period) { dev_err(&pdev->dev, "invalid PWM period\n"); return -EINVAL; } if (of_property_read_u32(node, "clock-frequency", &clk_pwm->fixed_rate)) clk_pwm->fixed_rate = NSEC_PER_SEC / pwm->period; if (pwm->period != NSEC_PER_SEC / clk_pwm->fixed_rate && pwm->period != DIV_ROUND_UP(NSEC_PER_SEC, clk_pwm->fixed_rate)) { dev_err(&pdev->dev, "clock-frequency does not match PWM period\n"); return -EINVAL; } ret = pwm_config(pwm, (pwm->period + 1) >> 1, pwm->period); if (ret < 0) return ret; clk_name = node->name; of_property_read_string(node, "clock-output-names", &clk_name); init.name = clk_name; init.ops = &clk_pwm_ops; init.flags = CLK_IS_BASIC | CLK_IS_ROOT; init.num_parents = 0; clk_pwm->pwm = pwm; clk_pwm->hw.init = &init; clk = devm_clk_register(&pdev->dev, &clk_pwm->hw); if (IS_ERR(clk)) return PTR_ERR(clk); return of_clk_add_provider(node, of_clk_src_simple_get, clk); } static int clk_pwm_remove(struct platform_device *pdev) { of_clk_del_provider(pdev->dev.of_node); return 0; } static const struct of_device_id clk_pwm_dt_ids[] = { { .compatible = "pwm-clock" }, { } }; MODULE_DEVICE_TABLE(of, clk_pwm_dt_ids); static struct platform_driver clk_pwm_driver = { .probe = clk_pwm_probe, .remove = clk_pwm_remove, .driver = { .name = "pwm-clock", .of_match_table = of_match_ptr(clk_pwm_dt_ids), }, }; module_platform_driver(clk_pwm_driver); MODULE_AUTHOR("Philipp Zabel <p.zabel@pengutronix.de>"); MODULE_DESCRIPTION("PWM clock driver"); MODULE_LICENSE("GPL");
gpl-2.0
Kernel-Saram/ef30s-ics-kernel
drivers/media/video/cs53l32a.c
802
5956
/* * cs53l32a (Adaptec AVC-2010 and AVC-2410) i2c ivtv driver. * Copyright (C) 2005 Martin Vaughan * * Audio source switching for Adaptec AVC-2410 added by Trev Jackson * * This program is free software; you can redistribute it and/or modify * it under the terms of the 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/types.h> #include <linux/slab.h> #include <linux/ioctl.h> #include <asm/uaccess.h> #include <linux/i2c.h> #include <linux/i2c-id.h> #include <linux/videodev2.h> #include <media/v4l2-device.h> #include <media/v4l2-chip-ident.h> #include <media/v4l2-i2c-drv.h> MODULE_DESCRIPTION("i2c device driver for cs53l32a Audio ADC"); MODULE_AUTHOR("Martin Vaughan"); MODULE_LICENSE("GPL"); static int debug; module_param(debug, bool, 0644); MODULE_PARM_DESC(debug, "Debugging messages, 0=Off (default), 1=On"); /* ----------------------------------------------------------------------- */ static int cs53l32a_write(struct v4l2_subdev *sd, u8 reg, u8 value) { struct i2c_client *client = v4l2_get_subdevdata(sd); return i2c_smbus_write_byte_data(client, reg, value); } static int cs53l32a_read(struct v4l2_subdev *sd, u8 reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); return i2c_smbus_read_byte_data(client, reg); } static int cs53l32a_s_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { /* There are 2 physical inputs, but the second input can be placed in two modes, the first mode bypasses the PGA (gain), the second goes through the PGA. Hence there are three possible inputs to choose from. */ if (input > 2) { v4l2_err(sd, "Invalid input %d.\n", input); return -EINVAL; } cs53l32a_write(sd, 0x01, 0x01 + (input << 4)); return 0; } static int cs53l32a_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { if (ctrl->id == V4L2_CID_AUDIO_MUTE) { ctrl->value = (cs53l32a_read(sd, 0x03) & 0xc0) != 0; return 0; } if (ctrl->id != V4L2_CID_AUDIO_VOLUME) return -EINVAL; ctrl->value = (s8)cs53l32a_read(sd, 0x04); return 0; } static int cs53l32a_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { if (ctrl->id == V4L2_CID_AUDIO_MUTE) { cs53l32a_write(sd, 0x03, ctrl->value ? 0xf0 : 0x30); return 0; } if (ctrl->id != V4L2_CID_AUDIO_VOLUME) return -EINVAL; if (ctrl->value > 12 || ctrl->value < -96) return -EINVAL; cs53l32a_write(sd, 0x04, (u8) ctrl->value); cs53l32a_write(sd, 0x05, (u8) ctrl->value); return 0; } static int cs53l32a_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip) { struct i2c_client *client = v4l2_get_subdevdata(sd); return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_CS53l32A, 0); } static int cs53l32a_log_status(struct v4l2_subdev *sd) { u8 v = cs53l32a_read(sd, 0x01); u8 m = cs53l32a_read(sd, 0x03); s8 vol = cs53l32a_read(sd, 0x04); v4l2_info(sd, "Input: %d%s\n", (v >> 4) & 3, (m & 0xC0) ? " (muted)" : ""); v4l2_info(sd, "Volume: %d dB\n", vol); return 0; } /* ----------------------------------------------------------------------- */ static const struct v4l2_subdev_core_ops cs53l32a_core_ops = { .log_status = cs53l32a_log_status, .g_chip_ident = cs53l32a_g_chip_ident, .g_ctrl = cs53l32a_g_ctrl, .s_ctrl = cs53l32a_s_ctrl, }; static const struct v4l2_subdev_audio_ops cs53l32a_audio_ops = { .s_routing = cs53l32a_s_routing, }; static const struct v4l2_subdev_ops cs53l32a_ops = { .core = &cs53l32a_core_ops, .audio = &cs53l32a_audio_ops, }; /* ----------------------------------------------------------------------- */ /* i2c implementation */ /* * Generic i2c probe * concerning the addresses: i2c wants 7 bit (without the r/w bit), so '>>1' */ static int cs53l32a_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct v4l2_subdev *sd; int i; /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; if (!id) strlcpy(client->name, "cs53l32a", sizeof(client->name)); v4l_info(client, "chip found @ 0x%x (%s)\n", client->addr << 1, client->adapter->name); sd = kmalloc(sizeof(struct v4l2_subdev), GFP_KERNEL); if (sd == NULL) return -ENOMEM; v4l2_i2c_subdev_init(sd, client, &cs53l32a_ops); for (i = 1; i <= 7; i++) { u8 v = cs53l32a_read(sd, i); v4l2_dbg(1, debug, sd, "Read Reg %d %02x\n", i, v); } /* Set cs53l32a internal register for Adaptec 2010/2410 setup */ cs53l32a_write(sd, 0x01, (u8) 0x21); cs53l32a_write(sd, 0x02, (u8) 0x29); cs53l32a_write(sd, 0x03, (u8) 0x30); cs53l32a_write(sd, 0x04, (u8) 0x00); cs53l32a_write(sd, 0x05, (u8) 0x00); cs53l32a_write(sd, 0x06, (u8) 0x00); cs53l32a_write(sd, 0x07, (u8) 0x00); /* Display results, should be 0x21,0x29,0x30,0x00,0x00,0x00,0x00 */ for (i = 1; i <= 7; i++) { u8 v = cs53l32a_read(sd, i); v4l2_dbg(1, debug, sd, "Read Reg %d %02x\n", i, v); } return 0; } static int cs53l32a_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); v4l2_device_unregister_subdev(sd); kfree(sd); return 0; } static const struct i2c_device_id cs53l32a_id[] = { { "cs53l32a", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, cs53l32a_id); static struct v4l2_i2c_driver_data v4l2_i2c_data = { .name = "cs53l32a", .remove = cs53l32a_remove, .probe = cs53l32a_probe, .id_table = cs53l32a_id, };
gpl-2.0
abgoyal/entourage_edge_kernel
fs/ocfs2/dlm/userdlm.c
802
16911
/* -*- mode: c; c-basic-offset: 8; -*- * vim: noexpandtab sw=8 ts=8 sts=0: * * userdlm.c * * Code which implements the kernel side of a minimal userspace * interface to our DLM. * * Many of the functions here are pared down versions of dlmglue.c * functions. * * Copyright (C) 2003, 2004 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 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 021110-1307, USA. */ #include <linux/signal.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/types.h> #include <linux/crc32.h> #include "cluster/nodemanager.h" #include "cluster/heartbeat.h" #include "cluster/tcp.h" #include "dlmapi.h" #include "userdlm.h" #define MLOG_MASK_PREFIX ML_DLMFS #include "cluster/masklog.h" static inline int user_check_wait_flag(struct user_lock_res *lockres, int flag) { int ret; spin_lock(&lockres->l_lock); ret = lockres->l_flags & flag; spin_unlock(&lockres->l_lock); return ret; } static inline void user_wait_on_busy_lock(struct user_lock_res *lockres) { wait_event(lockres->l_event, !user_check_wait_flag(lockres, USER_LOCK_BUSY)); } static inline void user_wait_on_blocked_lock(struct user_lock_res *lockres) { wait_event(lockres->l_event, !user_check_wait_flag(lockres, USER_LOCK_BLOCKED)); } /* I heart container_of... */ static inline struct dlm_ctxt * dlm_ctxt_from_user_lockres(struct user_lock_res *lockres) { struct dlmfs_inode_private *ip; ip = container_of(lockres, struct dlmfs_inode_private, ip_lockres); return ip->ip_dlm; } static struct inode * user_dlm_inode_from_user_lockres(struct user_lock_res *lockres) { struct dlmfs_inode_private *ip; ip = container_of(lockres, struct dlmfs_inode_private, ip_lockres); return &ip->ip_vfs_inode; } static inline void user_recover_from_dlm_error(struct user_lock_res *lockres) { spin_lock(&lockres->l_lock); lockres->l_flags &= ~USER_LOCK_BUSY; spin_unlock(&lockres->l_lock); } #define user_log_dlm_error(_func, _stat, _lockres) do { \ mlog(ML_ERROR, "Dlm error \"%s\" while calling %s on " \ "resource %.*s: %s\n", dlm_errname(_stat), _func, \ _lockres->l_namelen, _lockres->l_name, dlm_errmsg(_stat)); \ } while (0) /* WARNING: This function lives in a world where the only three lock * levels are EX, PR, and NL. It *will* have to be adjusted when more * lock types are added. */ static inline int user_highest_compat_lock_level(int level) { int new_level = LKM_EXMODE; if (level == LKM_EXMODE) new_level = LKM_NLMODE; else if (level == LKM_PRMODE) new_level = LKM_PRMODE; return new_level; } static void user_ast(void *opaque) { struct user_lock_res *lockres = opaque; struct dlm_lockstatus *lksb; mlog(0, "AST fired for lockres %.*s\n", lockres->l_namelen, lockres->l_name); spin_lock(&lockres->l_lock); lksb = &(lockres->l_lksb); if (lksb->status != DLM_NORMAL) { mlog(ML_ERROR, "lksb status value of %u on lockres %.*s\n", lksb->status, lockres->l_namelen, lockres->l_name); spin_unlock(&lockres->l_lock); return; } mlog_bug_on_msg(lockres->l_requested == LKM_IVMODE, "Lockres %.*s, requested ivmode. flags 0x%x\n", lockres->l_namelen, lockres->l_name, lockres->l_flags); /* we're downconverting. */ if (lockres->l_requested < lockres->l_level) { if (lockres->l_requested <= user_highest_compat_lock_level(lockres->l_blocking)) { lockres->l_blocking = LKM_NLMODE; lockres->l_flags &= ~USER_LOCK_BLOCKED; } } lockres->l_level = lockres->l_requested; lockres->l_requested = LKM_IVMODE; lockres->l_flags |= USER_LOCK_ATTACHED; lockres->l_flags &= ~USER_LOCK_BUSY; spin_unlock(&lockres->l_lock); wake_up(&lockres->l_event); } static inline void user_dlm_grab_inode_ref(struct user_lock_res *lockres) { struct inode *inode; inode = user_dlm_inode_from_user_lockres(lockres); if (!igrab(inode)) BUG(); } static void user_dlm_unblock_lock(struct work_struct *work); static void __user_dlm_queue_lockres(struct user_lock_res *lockres) { if (!(lockres->l_flags & USER_LOCK_QUEUED)) { user_dlm_grab_inode_ref(lockres); INIT_WORK(&lockres->l_work, user_dlm_unblock_lock); queue_work(user_dlm_worker, &lockres->l_work); lockres->l_flags |= USER_LOCK_QUEUED; } } static void __user_dlm_cond_queue_lockres(struct user_lock_res *lockres) { int queue = 0; if (!(lockres->l_flags & USER_LOCK_BLOCKED)) return; switch (lockres->l_blocking) { case LKM_EXMODE: if (!lockres->l_ex_holders && !lockres->l_ro_holders) queue = 1; break; case LKM_PRMODE: if (!lockres->l_ex_holders) queue = 1; break; default: BUG(); } if (queue) __user_dlm_queue_lockres(lockres); } static void user_bast(void *opaque, int level) { struct user_lock_res *lockres = opaque; mlog(0, "Blocking AST fired for lockres %.*s. Blocking level %d\n", lockres->l_namelen, lockres->l_name, level); spin_lock(&lockres->l_lock); lockres->l_flags |= USER_LOCK_BLOCKED; if (level > lockres->l_blocking) lockres->l_blocking = level; __user_dlm_queue_lockres(lockres); spin_unlock(&lockres->l_lock); wake_up(&lockres->l_event); } static void user_unlock_ast(void *opaque, enum dlm_status status) { struct user_lock_res *lockres = opaque; mlog(0, "UNLOCK AST called on lock %.*s\n", lockres->l_namelen, lockres->l_name); if (status != DLM_NORMAL && status != DLM_CANCELGRANT) mlog(ML_ERROR, "Dlm returns status %d\n", status); spin_lock(&lockres->l_lock); /* The teardown flag gets set early during the unlock process, * so test the cancel flag to make sure that this ast isn't * for a concurrent cancel. */ if (lockres->l_flags & USER_LOCK_IN_TEARDOWN && !(lockres->l_flags & USER_LOCK_IN_CANCEL)) { lockres->l_level = LKM_IVMODE; } else if (status == DLM_CANCELGRANT) { /* We tried to cancel a convert request, but it was * already granted. Don't clear the busy flag - the * ast should've done this already. */ BUG_ON(!(lockres->l_flags & USER_LOCK_IN_CANCEL)); lockres->l_flags &= ~USER_LOCK_IN_CANCEL; goto out_noclear; } else { BUG_ON(!(lockres->l_flags & USER_LOCK_IN_CANCEL)); /* Cancel succeeded, we want to re-queue */ lockres->l_requested = LKM_IVMODE; /* cancel an * upconvert * request. */ lockres->l_flags &= ~USER_LOCK_IN_CANCEL; /* we want the unblock thread to look at it again * now. */ if (lockres->l_flags & USER_LOCK_BLOCKED) __user_dlm_queue_lockres(lockres); } lockres->l_flags &= ~USER_LOCK_BUSY; out_noclear: spin_unlock(&lockres->l_lock); wake_up(&lockres->l_event); } static inline void user_dlm_drop_inode_ref(struct user_lock_res *lockres) { struct inode *inode; inode = user_dlm_inode_from_user_lockres(lockres); iput(inode); } static void user_dlm_unblock_lock(struct work_struct *work) { int new_level, status; struct user_lock_res *lockres = container_of(work, struct user_lock_res, l_work); struct dlm_ctxt *dlm = dlm_ctxt_from_user_lockres(lockres); mlog(0, "processing lockres %.*s\n", lockres->l_namelen, lockres->l_name); spin_lock(&lockres->l_lock); mlog_bug_on_msg(!(lockres->l_flags & USER_LOCK_QUEUED), "Lockres %.*s, flags 0x%x\n", lockres->l_namelen, lockres->l_name, lockres->l_flags); /* notice that we don't clear USER_LOCK_BLOCKED here. If it's * set, we want user_ast clear it. */ lockres->l_flags &= ~USER_LOCK_QUEUED; /* It's valid to get here and no longer be blocked - if we get * several basts in a row, we might be queued by the first * one, the unblock thread might run and clear the queued * flag, and finally we might get another bast which re-queues * us before our ast for the downconvert is called. */ if (!(lockres->l_flags & USER_LOCK_BLOCKED)) { spin_unlock(&lockres->l_lock); goto drop_ref; } if (lockres->l_flags & USER_LOCK_IN_TEARDOWN) { spin_unlock(&lockres->l_lock); goto drop_ref; } if (lockres->l_flags & USER_LOCK_BUSY) { if (lockres->l_flags & USER_LOCK_IN_CANCEL) { spin_unlock(&lockres->l_lock); goto drop_ref; } lockres->l_flags |= USER_LOCK_IN_CANCEL; spin_unlock(&lockres->l_lock); status = dlmunlock(dlm, &lockres->l_lksb, LKM_CANCEL, user_unlock_ast, lockres); if (status != DLM_NORMAL) user_log_dlm_error("dlmunlock", status, lockres); goto drop_ref; } /* If there are still incompat holders, we can exit safely * without worrying about re-queueing this lock as that will * happen on the last call to user_cluster_unlock. */ if ((lockres->l_blocking == LKM_EXMODE) && (lockres->l_ex_holders || lockres->l_ro_holders)) { spin_unlock(&lockres->l_lock); mlog(0, "can't downconvert for ex: ro = %u, ex = %u\n", lockres->l_ro_holders, lockres->l_ex_holders); goto drop_ref; } if ((lockres->l_blocking == LKM_PRMODE) && lockres->l_ex_holders) { spin_unlock(&lockres->l_lock); mlog(0, "can't downconvert for pr: ex = %u\n", lockres->l_ex_holders); goto drop_ref; } /* yay, we can downconvert now. */ new_level = user_highest_compat_lock_level(lockres->l_blocking); lockres->l_requested = new_level; lockres->l_flags |= USER_LOCK_BUSY; mlog(0, "Downconvert lock from %d to %d\n", lockres->l_level, new_level); spin_unlock(&lockres->l_lock); /* need lock downconvert request now... */ status = dlmlock(dlm, new_level, &lockres->l_lksb, LKM_CONVERT|LKM_VALBLK, lockres->l_name, lockres->l_namelen, user_ast, lockres, user_bast); if (status != DLM_NORMAL) { user_log_dlm_error("dlmlock", status, lockres); user_recover_from_dlm_error(lockres); } drop_ref: user_dlm_drop_inode_ref(lockres); } static inline void user_dlm_inc_holders(struct user_lock_res *lockres, int level) { switch(level) { case LKM_EXMODE: lockres->l_ex_holders++; break; case LKM_PRMODE: lockres->l_ro_holders++; break; default: BUG(); } } /* predict what lock level we'll be dropping down to on behalf * of another node, and return true if the currently wanted * level will be compatible with it. */ static inline int user_may_continue_on_blocked_lock(struct user_lock_res *lockres, int wanted) { BUG_ON(!(lockres->l_flags & USER_LOCK_BLOCKED)); return wanted <= user_highest_compat_lock_level(lockres->l_blocking); } int user_dlm_cluster_lock(struct user_lock_res *lockres, int level, int lkm_flags) { int status, local_flags; struct dlm_ctxt *dlm = dlm_ctxt_from_user_lockres(lockres); if (level != LKM_EXMODE && level != LKM_PRMODE) { mlog(ML_ERROR, "lockres %.*s: invalid request!\n", lockres->l_namelen, lockres->l_name); status = -EINVAL; goto bail; } mlog(0, "lockres %.*s: asking for %s lock, passed flags = 0x%x\n", lockres->l_namelen, lockres->l_name, (level == LKM_EXMODE) ? "LKM_EXMODE" : "LKM_PRMODE", lkm_flags); again: if (signal_pending(current)) { status = -ERESTARTSYS; goto bail; } spin_lock(&lockres->l_lock); /* We only compare against the currently granted level * here. If the lock is blocked waiting on a downconvert, * we'll get caught below. */ if ((lockres->l_flags & USER_LOCK_BUSY) && (level > lockres->l_level)) { /* is someone sitting in dlm_lock? If so, wait on * them. */ spin_unlock(&lockres->l_lock); user_wait_on_busy_lock(lockres); goto again; } if ((lockres->l_flags & USER_LOCK_BLOCKED) && (!user_may_continue_on_blocked_lock(lockres, level))) { /* is the lock is currently blocked on behalf of * another node */ spin_unlock(&lockres->l_lock); user_wait_on_blocked_lock(lockres); goto again; } if (level > lockres->l_level) { local_flags = lkm_flags | LKM_VALBLK; if (lockres->l_level != LKM_IVMODE) local_flags |= LKM_CONVERT; lockres->l_requested = level; lockres->l_flags |= USER_LOCK_BUSY; spin_unlock(&lockres->l_lock); BUG_ON(level == LKM_IVMODE); BUG_ON(level == LKM_NLMODE); /* call dlm_lock to upgrade lock now */ status = dlmlock(dlm, level, &lockres->l_lksb, local_flags, lockres->l_name, lockres->l_namelen, user_ast, lockres, user_bast); if (status != DLM_NORMAL) { if ((lkm_flags & LKM_NOQUEUE) && (status == DLM_NOTQUEUED)) status = -EAGAIN; else { user_log_dlm_error("dlmlock", status, lockres); status = -EINVAL; } user_recover_from_dlm_error(lockres); goto bail; } user_wait_on_busy_lock(lockres); goto again; } user_dlm_inc_holders(lockres, level); spin_unlock(&lockres->l_lock); status = 0; bail: return status; } static inline void user_dlm_dec_holders(struct user_lock_res *lockres, int level) { switch(level) { case LKM_EXMODE: BUG_ON(!lockres->l_ex_holders); lockres->l_ex_holders--; break; case LKM_PRMODE: BUG_ON(!lockres->l_ro_holders); lockres->l_ro_holders--; break; default: BUG(); } } void user_dlm_cluster_unlock(struct user_lock_res *lockres, int level) { if (level != LKM_EXMODE && level != LKM_PRMODE) { mlog(ML_ERROR, "lockres %.*s: invalid request!\n", lockres->l_namelen, lockres->l_name); return; } spin_lock(&lockres->l_lock); user_dlm_dec_holders(lockres, level); __user_dlm_cond_queue_lockres(lockres); spin_unlock(&lockres->l_lock); } void user_dlm_write_lvb(struct inode *inode, const char *val, unsigned int len) { struct user_lock_res *lockres = &DLMFS_I(inode)->ip_lockres; char *lvb = lockres->l_lksb.lvb; BUG_ON(len > DLM_LVB_LEN); spin_lock(&lockres->l_lock); BUG_ON(lockres->l_level < LKM_EXMODE); memcpy(lvb, val, len); spin_unlock(&lockres->l_lock); } void user_dlm_read_lvb(struct inode *inode, char *val, unsigned int len) { struct user_lock_res *lockres = &DLMFS_I(inode)->ip_lockres; char *lvb = lockres->l_lksb.lvb; BUG_ON(len > DLM_LVB_LEN); spin_lock(&lockres->l_lock); BUG_ON(lockres->l_level < LKM_PRMODE); memcpy(val, lvb, len); spin_unlock(&lockres->l_lock); } void user_dlm_lock_res_init(struct user_lock_res *lockres, struct dentry *dentry) { memset(lockres, 0, sizeof(*lockres)); spin_lock_init(&lockres->l_lock); init_waitqueue_head(&lockres->l_event); lockres->l_level = LKM_IVMODE; lockres->l_requested = LKM_IVMODE; lockres->l_blocking = LKM_IVMODE; /* should have been checked before getting here. */ BUG_ON(dentry->d_name.len >= USER_DLM_LOCK_ID_MAX_LEN); memcpy(lockres->l_name, dentry->d_name.name, dentry->d_name.len); lockres->l_namelen = dentry->d_name.len; } int user_dlm_destroy_lock(struct user_lock_res *lockres) { int status = -EBUSY; struct dlm_ctxt *dlm = dlm_ctxt_from_user_lockres(lockres); mlog(0, "asked to destroy %.*s\n", lockres->l_namelen, lockres->l_name); spin_lock(&lockres->l_lock); if (lockres->l_flags & USER_LOCK_IN_TEARDOWN) { spin_unlock(&lockres->l_lock); return 0; } lockres->l_flags |= USER_LOCK_IN_TEARDOWN; while (lockres->l_flags & USER_LOCK_BUSY) { spin_unlock(&lockres->l_lock); user_wait_on_busy_lock(lockres); spin_lock(&lockres->l_lock); } if (lockres->l_ro_holders || lockres->l_ex_holders) { spin_unlock(&lockres->l_lock); goto bail; } status = 0; if (!(lockres->l_flags & USER_LOCK_ATTACHED)) { spin_unlock(&lockres->l_lock); goto bail; } lockres->l_flags &= ~USER_LOCK_ATTACHED; lockres->l_flags |= USER_LOCK_BUSY; spin_unlock(&lockres->l_lock); status = dlmunlock(dlm, &lockres->l_lksb, LKM_VALBLK, user_unlock_ast, lockres); if (status != DLM_NORMAL) { user_log_dlm_error("dlmunlock", status, lockres); status = -EINVAL; goto bail; } user_wait_on_busy_lock(lockres); status = 0; bail: return status; } struct dlm_ctxt *user_dlm_register_context(struct qstr *name, struct dlm_protocol_version *proto) { struct dlm_ctxt *dlm; u32 dlm_key; char *domain; domain = kmalloc(name->len + 1, GFP_NOFS); if (!domain) { mlog_errno(-ENOMEM); return ERR_PTR(-ENOMEM); } dlm_key = crc32_le(0, name->name, name->len); snprintf(domain, name->len + 1, "%.*s", name->len, name->name); dlm = dlm_register_domain(domain, dlm_key, proto); if (IS_ERR(dlm)) mlog_errno(PTR_ERR(dlm)); kfree(domain); return dlm; } void user_dlm_unregister_context(struct dlm_ctxt *dlm) { dlm_unregister_domain(dlm); }
gpl-2.0
cattleprod/XCeLL-XV
drivers/net/arcnet/capmode.c
802
8062
/* * Linux ARCnet driver - "cap mode" packet encapsulation. * It adds sequence numbers to packets for communicating between a user space * application and the driver. After a transmit it sends a packet with protocol * byte 0 back up to the userspace containing the sequence number of the packet * plus the transmit-status on the ArcNet. * * Written 2002-4 by Esben Nielsen, Vestas Wind Systems A/S * Derived from arc-rawmode.c by Avery Pennarun. * arc-rawmode was in turned based on skeleton.c, see below. * * ********************** * * 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/module.h> #include <linux/gfp.h> #include <linux/init.h> #include <linux/if_arp.h> #include <net/arp.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/arcdevice.h> #define VERSION "arcnet: cap mode (`c') encapsulation support loaded.\n" static void rx(struct net_device *dev, int bufnum, struct archdr *pkthdr, int length); static int build_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, uint8_t daddr); static int prepare_tx(struct net_device *dev, struct archdr *pkt, int length, int bufnum); static int ack_tx(struct net_device *dev, int acked); static struct ArcProto capmode_proto = { 'r', XMTU, 0, rx, build_header, prepare_tx, NULL, ack_tx }; static void arcnet_cap_init(void) { int count; for (count = 1; count <= 8; count++) if (arc_proto_map[count] == arc_proto_default) arc_proto_map[count] = &capmode_proto; /* for cap mode, we only set the bcast proto if there's no better one */ if (arc_bcast_proto == arc_proto_default) arc_bcast_proto = &capmode_proto; arc_proto_default = &capmode_proto; arc_raw_proto = &capmode_proto; } #ifdef MODULE static int __init capmode_module_init(void) { printk(VERSION); arcnet_cap_init(); return 0; } static void __exit capmode_module_exit(void) { arcnet_unregister_proto(&capmode_proto); } module_init(capmode_module_init); module_exit(capmode_module_exit); MODULE_LICENSE("GPL"); #endif /* MODULE */ /* packet receiver */ static void rx(struct net_device *dev, int bufnum, struct archdr *pkthdr, int length) { struct arcnet_local *lp = netdev_priv(dev); struct sk_buff *skb; struct archdr *pkt = pkthdr; char *pktbuf, *pkthdrbuf; int ofs; BUGMSG(D_DURING, "it's a raw(cap) packet (length=%d)\n", length); if (length >= MinTU) ofs = 512 - length; else ofs = 256 - length; skb = alloc_skb(length + ARC_HDR_SIZE + sizeof(int), GFP_ATOMIC); if (skb == NULL) { BUGMSG(D_NORMAL, "Memory squeeze, dropping packet.\n"); dev->stats.rx_dropped++; return; } skb_put(skb, length + ARC_HDR_SIZE + sizeof(int)); skb->dev = dev; skb_reset_mac_header(skb); pkt = (struct archdr *)skb_mac_header(skb); skb_pull(skb, ARC_HDR_SIZE); /* up to sizeof(pkt->soft) has already been copied from the card */ /* squeeze in an int for the cap encapsulation */ /* use these variables to be sure we count in bytes, not in sizeof(struct archdr) */ pktbuf=(char*)pkt; pkthdrbuf=(char*)pkthdr; memcpy(pktbuf, pkthdrbuf, ARC_HDR_SIZE+sizeof(pkt->soft.cap.proto)); memcpy(pktbuf+ARC_HDR_SIZE+sizeof(pkt->soft.cap.proto)+sizeof(int), pkthdrbuf+ARC_HDR_SIZE+sizeof(pkt->soft.cap.proto), sizeof(struct archdr)-ARC_HDR_SIZE-sizeof(pkt->soft.cap.proto)); if (length > sizeof(pkt->soft)) lp->hw.copy_from_card(dev, bufnum, ofs + sizeof(pkt->soft), pkt->soft.raw + sizeof(pkt->soft) + sizeof(int), length - sizeof(pkt->soft)); BUGLVL(D_SKB) arcnet_dump_skb(dev, skb, "rx"); skb->protocol = cpu_to_be16(ETH_P_ARCNET); netif_rx(skb); } /* * Create the ARCnet hard/soft headers for cap mode. * There aren't any soft headers in cap mode - not even the protocol id. */ static int build_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, uint8_t daddr) { int hdr_size = ARC_HDR_SIZE; struct archdr *pkt = (struct archdr *) skb_push(skb, hdr_size); BUGMSG(D_PROTO, "Preparing header for cap packet %x.\n", *((int*)&pkt->soft.cap.cookie[0])); /* * Set the source hardware address. * * This is pretty pointless for most purposes, but it can help in * debugging. ARCnet does not allow us to change the source address in * the actual packet sent) */ pkt->hard.source = *dev->dev_addr; /* see linux/net/ethernet/eth.c to see where I got the following */ if (dev->flags & (IFF_LOOPBACK | IFF_NOARP)) { /* * FIXME: fill in the last byte of the dest ipaddr here to better * comply with RFC1051 in "noarp" mode. */ pkt->hard.dest = 0; return hdr_size; } /* otherwise, just fill it in and go! */ pkt->hard.dest = daddr; return hdr_size; /* success */ } static int prepare_tx(struct net_device *dev, struct archdr *pkt, int length, int bufnum) { struct arcnet_local *lp = netdev_priv(dev); struct arc_hardware *hard = &pkt->hard; int ofs; /* hard header is not included in packet length */ length -= ARC_HDR_SIZE; /* And neither is the cookie field */ length -= sizeof(int); BUGMSG(D_DURING, "prepare_tx: txbufs=%d/%d/%d\n", lp->next_tx, lp->cur_tx, bufnum); BUGMSG(D_PROTO, "Sending for cap packet %x.\n", *((int*)&pkt->soft.cap.cookie[0])); if (length > XMTU) { /* should never happen! other people already check for this. */ BUGMSG(D_NORMAL, "Bug! prepare_tx with size %d (> %d)\n", length, XMTU); length = XMTU; } if (length > MinTU) { hard->offset[0] = 0; hard->offset[1] = ofs = 512 - length; } else if (length > MTU) { hard->offset[0] = 0; hard->offset[1] = ofs = 512 - length - 3; } else hard->offset[0] = ofs = 256 - length; BUGMSG(D_DURING, "prepare_tx: length=%d ofs=%d\n", length,ofs); // Copy the arcnet-header + the protocol byte down: lp->hw.copy_to_card(dev, bufnum, 0, hard, ARC_HDR_SIZE); lp->hw.copy_to_card(dev, bufnum, ofs, &pkt->soft.cap.proto, sizeof(pkt->soft.cap.proto)); // Skip the extra integer we have written into it as a cookie // but write the rest of the message: lp->hw.copy_to_card(dev, bufnum, ofs+1, ((unsigned char*)&pkt->soft.cap.mes),length-1); lp->lastload_dest = hard->dest; return 1; /* done */ } static int ack_tx(struct net_device *dev, int acked) { struct arcnet_local *lp = netdev_priv(dev); struct sk_buff *ackskb; struct archdr *ackpkt; int length=sizeof(struct arc_cap); BUGMSG(D_DURING, "capmode: ack_tx: protocol: %x: result: %d\n", lp->outgoing.skb->protocol, acked); BUGLVL(D_SKB) arcnet_dump_skb(dev, lp->outgoing.skb, "ack_tx"); /* Now alloc a skb to send back up through the layers: */ ackskb = alloc_skb(length + ARC_HDR_SIZE , GFP_ATOMIC); if (ackskb == NULL) { BUGMSG(D_NORMAL, "Memory squeeze, can't acknowledge.\n"); goto free_outskb; } skb_put(ackskb, length + ARC_HDR_SIZE ); ackskb->dev = dev; skb_reset_mac_header(ackskb); ackpkt = (struct archdr *)skb_mac_header(ackskb); /* skb_pull(ackskb, ARC_HDR_SIZE); */ skb_copy_from_linear_data(lp->outgoing.skb, ackpkt, ARC_HDR_SIZE + sizeof(struct arc_cap)); ackpkt->soft.cap.proto=0; /* using protocol 0 for acknowledge */ ackpkt->soft.cap.mes.ack=acked; BUGMSG(D_PROTO, "Ackknowledge for cap packet %x.\n", *((int*)&ackpkt->soft.cap.cookie[0])); ackskb->protocol = cpu_to_be16(ETH_P_ARCNET); BUGLVL(D_SKB) arcnet_dump_skb(dev, ackskb, "ack_tx_recv"); netif_rx(ackskb); free_outskb: dev_kfree_skb_irq(lp->outgoing.skb); lp->outgoing.proto = NULL; /* We are always finished when in this protocol */ return 0; }
gpl-2.0
Entropy512/kernel_n8013_ics
drivers/target/tcm_fc/tfc_cmd.c
802
18282
/* * Copyright (c) 2010 Cisco Systems, Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ /* XXX TBD some includes may be extraneous */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/version.h> #include <generated/utsrelease.h> #include <linux/utsname.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/kthread.h> #include <linux/types.h> #include <linux/string.h> #include <linux/configfs.h> #include <linux/ctype.h> #include <linux/hash.h> #include <asm/unaligned.h> #include <scsi/scsi.h> #include <scsi/scsi_host.h> #include <scsi/scsi_device.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_tcq.h> #include <scsi/libfc.h> #include <scsi/fc_encode.h> #include <target/target_core_base.h> #include <target/target_core_transport.h> #include <target/target_core_fabric_ops.h> #include <target/target_core_device.h> #include <target/target_core_tpg.h> #include <target/target_core_configfs.h> #include <target/target_core_base.h> #include <target/target_core_tmr.h> #include <target/configfs_macros.h> #include "tcm_fc.h" /* * Dump cmd state for debugging. */ void ft_dump_cmd(struct ft_cmd *cmd, const char *caller) { struct fc_exch *ep; struct fc_seq *sp; struct se_cmd *se_cmd; struct se_mem *mem; struct se_transport_task *task; if (!(ft_debug_logging & FT_DEBUG_IO)) return; se_cmd = &cmd->se_cmd; printk(KERN_INFO "%s: cmd %p state %d sess %p seq %p se_cmd %p\n", caller, cmd, cmd->state, cmd->sess, cmd->seq, se_cmd); printk(KERN_INFO "%s: cmd %p cdb %p\n", caller, cmd, cmd->cdb); printk(KERN_INFO "%s: cmd %p lun %d\n", caller, cmd, cmd->lun); task = T_TASK(se_cmd); printk(KERN_INFO "%s: cmd %p task %p se_num %u buf %p len %u se_cmd_flags <0x%x>\n", caller, cmd, task, task->t_tasks_se_num, task->t_task_buf, se_cmd->data_length, se_cmd->se_cmd_flags); if (task->t_mem_list) list_for_each_entry(mem, task->t_mem_list, se_list) printk(KERN_INFO "%s: cmd %p mem %p page %p " "len 0x%x off 0x%x\n", caller, cmd, mem, mem->se_page, mem->se_len, mem->se_off); sp = cmd->seq; if (sp) { ep = fc_seq_exch(sp); printk(KERN_INFO "%s: cmd %p sid %x did %x " "ox_id %x rx_id %x seq_id %x e_stat %x\n", caller, cmd, ep->sid, ep->did, ep->oxid, ep->rxid, sp->id, ep->esb_stat); } print_hex_dump(KERN_INFO, "ft_dump_cmd ", DUMP_PREFIX_NONE, 16, 4, cmd->cdb, MAX_COMMAND_SIZE, 0); } static void ft_queue_cmd(struct ft_sess *sess, struct ft_cmd *cmd) { struct se_queue_obj *qobj; unsigned long flags; qobj = &sess->tport->tpg->qobj; spin_lock_irqsave(&qobj->cmd_queue_lock, flags); list_add_tail(&cmd->se_req.qr_list, &qobj->qobj_list); spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags); atomic_inc(&qobj->queue_cnt); wake_up_interruptible(&qobj->thread_wq); } static struct ft_cmd *ft_dequeue_cmd(struct se_queue_obj *qobj) { unsigned long flags; struct se_queue_req *qr; spin_lock_irqsave(&qobj->cmd_queue_lock, flags); if (list_empty(&qobj->qobj_list)) { spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags); return NULL; } qr = list_first_entry(&qobj->qobj_list, struct se_queue_req, qr_list); list_del(&qr->qr_list); atomic_dec(&qobj->queue_cnt); spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags); return container_of(qr, struct ft_cmd, se_req); } static void ft_free_cmd(struct ft_cmd *cmd) { struct fc_frame *fp; struct fc_lport *lport; if (!cmd) return; fp = cmd->req_frame; lport = fr_dev(fp); if (fr_seq(fp)) lport->tt.seq_release(fr_seq(fp)); fc_frame_free(fp); ft_sess_put(cmd->sess); /* undo get from lookup at recv */ kfree(cmd); } void ft_release_cmd(struct se_cmd *se_cmd) { struct ft_cmd *cmd = container_of(se_cmd, struct ft_cmd, se_cmd); ft_free_cmd(cmd); } void ft_check_stop_free(struct se_cmd *se_cmd) { transport_generic_free_cmd(se_cmd, 0, 1, 0); } /* * Send response. */ int ft_queue_status(struct se_cmd *se_cmd) { struct ft_cmd *cmd = container_of(se_cmd, struct ft_cmd, se_cmd); struct fc_frame *fp; struct fcp_resp_with_ext *fcp; struct fc_lport *lport; struct fc_exch *ep; size_t len; ft_dump_cmd(cmd, __func__); ep = fc_seq_exch(cmd->seq); lport = ep->lp; len = sizeof(*fcp) + se_cmd->scsi_sense_length; fp = fc_frame_alloc(lport, len); if (!fp) { /* XXX shouldn't just drop it - requeue and retry? */ return 0; } fcp = fc_frame_payload_get(fp, len); memset(fcp, 0, len); fcp->resp.fr_status = se_cmd->scsi_status; len = se_cmd->scsi_sense_length; if (len) { fcp->resp.fr_flags |= FCP_SNS_LEN_VAL; fcp->ext.fr_sns_len = htonl(len); memcpy((fcp + 1), se_cmd->sense_buffer, len); } /* * Test underflow and overflow with one mask. Usually both are off. * Bidirectional commands are not handled yet. */ if (se_cmd->se_cmd_flags & (SCF_OVERFLOW_BIT | SCF_UNDERFLOW_BIT)) { if (se_cmd->se_cmd_flags & SCF_OVERFLOW_BIT) fcp->resp.fr_flags |= FCP_RESID_OVER; else fcp->resp.fr_flags |= FCP_RESID_UNDER; fcp->ext.fr_resid = cpu_to_be32(se_cmd->residual_count); } /* * Send response. */ cmd->seq = lport->tt.seq_start_next(cmd->seq); fc_fill_fc_hdr(fp, FC_RCTL_DD_CMD_STATUS, ep->did, ep->sid, FC_TYPE_FCP, FC_FC_EX_CTX | FC_FC_LAST_SEQ | FC_FC_END_SEQ, 0); lport->tt.seq_send(lport, cmd->seq, fp); lport->tt.exch_done(cmd->seq); return 0; } int ft_write_pending_status(struct se_cmd *se_cmd) { struct ft_cmd *cmd = container_of(se_cmd, struct ft_cmd, se_cmd); return cmd->write_data_len != se_cmd->data_length; } /* * Send TX_RDY (transfer ready). */ int ft_write_pending(struct se_cmd *se_cmd) { struct ft_cmd *cmd = container_of(se_cmd, struct ft_cmd, se_cmd); struct fc_frame *fp; struct fcp_txrdy *txrdy; struct fc_lport *lport; struct fc_exch *ep; struct fc_frame_header *fh; u32 f_ctl; ft_dump_cmd(cmd, __func__); ep = fc_seq_exch(cmd->seq); lport = ep->lp; fp = fc_frame_alloc(lport, sizeof(*txrdy)); if (!fp) return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES; txrdy = fc_frame_payload_get(fp, sizeof(*txrdy)); memset(txrdy, 0, sizeof(*txrdy)); txrdy->ft_burst_len = htonl(se_cmd->data_length); cmd->seq = lport->tt.seq_start_next(cmd->seq); fc_fill_fc_hdr(fp, FC_RCTL_DD_DATA_DESC, ep->did, ep->sid, FC_TYPE_FCP, FC_FC_EX_CTX | FC_FC_END_SEQ | FC_FC_SEQ_INIT, 0); fh = fc_frame_header_get(fp); f_ctl = ntoh24(fh->fh_f_ctl); /* Only if it is 'Exchange Responder' */ if (f_ctl & FC_FC_EX_CTX) { /* Target is 'exchange responder' and sending XFER_READY * to 'exchange initiator (initiator)' */ if ((ep->xid <= lport->lro_xid) && (fh->fh_r_ctl == FC_RCTL_DD_DATA_DESC)) { if (se_cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) { /* * Map se_mem list to scatterlist, so that * DDP can be setup. DDP setup function require * scatterlist. se_mem_list is internal to * TCM/LIO target */ transport_do_task_sg_chain(se_cmd); cmd->sg = T_TASK(se_cmd)->t_tasks_sg_chained; cmd->sg_cnt = T_TASK(se_cmd)->t_tasks_sg_chained_no; } if (cmd->sg && lport->tt.ddp_setup(lport, ep->xid, cmd->sg, cmd->sg_cnt)) cmd->was_ddp_setup = 1; } } lport->tt.seq_send(lport, cmd->seq, fp); return 0; } u32 ft_get_task_tag(struct se_cmd *se_cmd) { struct ft_cmd *cmd = container_of(se_cmd, struct ft_cmd, se_cmd); return fc_seq_exch(cmd->seq)->rxid; } int ft_get_cmd_state(struct se_cmd *se_cmd) { struct ft_cmd *cmd = container_of(se_cmd, struct ft_cmd, se_cmd); return cmd->state; } int ft_is_state_remove(struct se_cmd *se_cmd) { return 0; /* XXX TBD */ } void ft_new_cmd_failure(struct se_cmd *se_cmd) { /* XXX TBD */ printk(KERN_INFO "%s: se_cmd %p\n", __func__, se_cmd); } /* * FC sequence response handler for follow-on sequences (data) and aborts. */ static void ft_recv_seq(struct fc_seq *sp, struct fc_frame *fp, void *arg) { struct ft_cmd *cmd = arg; struct fc_frame_header *fh; if (IS_ERR(fp)) { /* XXX need to find cmd if queued */ cmd->se_cmd.t_state = TRANSPORT_REMOVE; cmd->seq = NULL; transport_generic_free_cmd(&cmd->se_cmd, 0, 1, 0); return; } fh = fc_frame_header_get(fp); switch (fh->fh_r_ctl) { case FC_RCTL_DD_SOL_DATA: /* write data */ ft_recv_write_data(cmd, fp); break; case FC_RCTL_DD_UNSOL_CTL: /* command */ case FC_RCTL_DD_SOL_CTL: /* transfer ready */ case FC_RCTL_DD_DATA_DESC: /* transfer ready */ default: printk(KERN_INFO "%s: unhandled frame r_ctl %x\n", __func__, fh->fh_r_ctl); fc_frame_free(fp); transport_generic_free_cmd(&cmd->se_cmd, 0, 1, 0); break; } } /* * Send a FCP response including SCSI status and optional FCP rsp_code. * status is SAM_STAT_GOOD (zero) iff code is valid. * This is used in error cases, such as allocation failures. */ static void ft_send_resp_status(struct fc_lport *lport, const struct fc_frame *rx_fp, u32 status, enum fcp_resp_rsp_codes code) { struct fc_frame *fp; struct fc_seq *sp; const struct fc_frame_header *fh; size_t len; struct fcp_resp_with_ext *fcp; struct fcp_resp_rsp_info *info; fh = fc_frame_header_get(rx_fp); FT_IO_DBG("FCP error response: did %x oxid %x status %x code %x\n", ntoh24(fh->fh_s_id), ntohs(fh->fh_ox_id), status, code); len = sizeof(*fcp); if (status == SAM_STAT_GOOD) len += sizeof(*info); fp = fc_frame_alloc(lport, len); if (!fp) return; fcp = fc_frame_payload_get(fp, len); memset(fcp, 0, len); fcp->resp.fr_status = status; if (status == SAM_STAT_GOOD) { fcp->ext.fr_rsp_len = htonl(sizeof(*info)); fcp->resp.fr_flags |= FCP_RSP_LEN_VAL; info = (struct fcp_resp_rsp_info *)(fcp + 1); info->rsp_code = code; } fc_fill_reply_hdr(fp, rx_fp, FC_RCTL_DD_CMD_STATUS, 0); sp = fr_seq(fp); if (sp) lport->tt.seq_send(lport, sp, fp); else lport->tt.frame_send(lport, fp); } /* * Send error or task management response. * Always frees the cmd and associated state. */ static void ft_send_resp_code(struct ft_cmd *cmd, enum fcp_resp_rsp_codes code) { ft_send_resp_status(cmd->sess->tport->lport, cmd->req_frame, SAM_STAT_GOOD, code); ft_free_cmd(cmd); } /* * Handle Task Management Request. */ static void ft_send_tm(struct ft_cmd *cmd) { struct se_tmr_req *tmr; struct fcp_cmnd *fcp; struct ft_sess *sess; u8 tm_func; fcp = fc_frame_payload_get(cmd->req_frame, sizeof(*fcp)); switch (fcp->fc_tm_flags) { case FCP_TMF_LUN_RESET: tm_func = TMR_LUN_RESET; break; case FCP_TMF_TGT_RESET: tm_func = TMR_TARGET_WARM_RESET; break; case FCP_TMF_CLR_TASK_SET: tm_func = TMR_CLEAR_TASK_SET; break; case FCP_TMF_ABT_TASK_SET: tm_func = TMR_ABORT_TASK_SET; break; case FCP_TMF_CLR_ACA: tm_func = TMR_CLEAR_ACA; break; default: /* * FCP4r01 indicates having a combination of * tm_flags set is invalid. */ FT_TM_DBG("invalid FCP tm_flags %x\n", fcp->fc_tm_flags); ft_send_resp_code(cmd, FCP_CMND_FIELDS_INVALID); return; } FT_TM_DBG("alloc tm cmd fn %d\n", tm_func); tmr = core_tmr_alloc_req(&cmd->se_cmd, cmd, tm_func); if (!tmr) { FT_TM_DBG("alloc failed\n"); ft_send_resp_code(cmd, FCP_TMF_FAILED); return; } cmd->se_cmd.se_tmr_req = tmr; switch (fcp->fc_tm_flags) { case FCP_TMF_LUN_RESET: cmd->lun = scsilun_to_int((struct scsi_lun *)fcp->fc_lun); if (transport_get_lun_for_tmr(&cmd->se_cmd, cmd->lun) < 0) { /* * Make sure to clean up newly allocated TMR request * since "unable to handle TMR request because failed * to get to LUN" */ FT_TM_DBG("Failed to get LUN for TMR func %d, " "se_cmd %p, unpacked_lun %d\n", tm_func, &cmd->se_cmd, cmd->lun); ft_dump_cmd(cmd, __func__); sess = cmd->sess; transport_send_check_condition_and_sense(&cmd->se_cmd, cmd->se_cmd.scsi_sense_reason, 0); transport_generic_free_cmd(&cmd->se_cmd, 0, 1, 0); ft_sess_put(sess); return; } break; case FCP_TMF_TGT_RESET: case FCP_TMF_CLR_TASK_SET: case FCP_TMF_ABT_TASK_SET: case FCP_TMF_CLR_ACA: break; default: return; } transport_generic_handle_tmr(&cmd->se_cmd); } /* * Send status from completed task management request. */ int ft_queue_tm_resp(struct se_cmd *se_cmd) { struct ft_cmd *cmd = container_of(se_cmd, struct ft_cmd, se_cmd); struct se_tmr_req *tmr = se_cmd->se_tmr_req; enum fcp_resp_rsp_codes code; switch (tmr->response) { case TMR_FUNCTION_COMPLETE: code = FCP_TMF_CMPL; break; case TMR_LUN_DOES_NOT_EXIST: code = FCP_TMF_INVALID_LUN; break; case TMR_FUNCTION_REJECTED: code = FCP_TMF_REJECTED; break; case TMR_TASK_DOES_NOT_EXIST: case TMR_TASK_STILL_ALLEGIANT: case TMR_TASK_FAILOVER_NOT_SUPPORTED: case TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED: case TMR_FUNCTION_AUTHORIZATION_FAILED: default: code = FCP_TMF_FAILED; break; } FT_TM_DBG("tmr fn %d resp %d fcp code %d\n", tmr->function, tmr->response, code); ft_send_resp_code(cmd, code); return 0; } /* * Handle incoming FCP command. */ static void ft_recv_cmd(struct ft_sess *sess, struct fc_frame *fp) { struct ft_cmd *cmd; struct fc_lport *lport = sess->tport->lport; cmd = kzalloc(sizeof(*cmd), GFP_ATOMIC); if (!cmd) goto busy; cmd->sess = sess; cmd->seq = lport->tt.seq_assign(lport, fp); if (!cmd->seq) { kfree(cmd); goto busy; } cmd->req_frame = fp; /* hold frame during cmd */ ft_queue_cmd(sess, cmd); return; busy: FT_IO_DBG("cmd or seq allocation failure - sending BUSY\n"); ft_send_resp_status(lport, fp, SAM_STAT_BUSY, 0); fc_frame_free(fp); ft_sess_put(sess); /* undo get from lookup */ } /* * Handle incoming FCP frame. * Caller has verified that the frame is type FCP. */ void ft_recv_req(struct ft_sess *sess, struct fc_frame *fp) { struct fc_frame_header *fh = fc_frame_header_get(fp); switch (fh->fh_r_ctl) { case FC_RCTL_DD_UNSOL_CMD: /* command */ ft_recv_cmd(sess, fp); break; case FC_RCTL_DD_SOL_DATA: /* write data */ case FC_RCTL_DD_UNSOL_CTL: case FC_RCTL_DD_SOL_CTL: case FC_RCTL_DD_DATA_DESC: /* transfer ready */ case FC_RCTL_ELS4_REQ: /* SRR, perhaps */ default: printk(KERN_INFO "%s: unhandled frame r_ctl %x\n", __func__, fh->fh_r_ctl); fc_frame_free(fp); ft_sess_put(sess); /* undo get from lookup */ break; } } /* * Send new command to target. */ static void ft_send_cmd(struct ft_cmd *cmd) { struct fc_frame_header *fh = fc_frame_header_get(cmd->req_frame); struct se_cmd *se_cmd; struct fcp_cmnd *fcp; int data_dir; u32 data_len; int task_attr; int ret; fcp = fc_frame_payload_get(cmd->req_frame, sizeof(*fcp)); if (!fcp) goto err; if (fcp->fc_flags & FCP_CFL_LEN_MASK) goto err; /* not handling longer CDBs yet */ if (fcp->fc_tm_flags) { task_attr = FCP_PTA_SIMPLE; data_dir = DMA_NONE; data_len = 0; } else { switch (fcp->fc_flags & (FCP_CFL_RDDATA | FCP_CFL_WRDATA)) { case 0: data_dir = DMA_NONE; break; case FCP_CFL_RDDATA: data_dir = DMA_FROM_DEVICE; break; case FCP_CFL_WRDATA: data_dir = DMA_TO_DEVICE; break; case FCP_CFL_WRDATA | FCP_CFL_RDDATA: goto err; /* TBD not supported by tcm_fc yet */ } /* * Locate the SAM Task Attr from fc_pri_ta */ switch (fcp->fc_pri_ta & FCP_PTA_MASK) { case FCP_PTA_HEADQ: task_attr = MSG_HEAD_TAG; break; case FCP_PTA_ORDERED: task_attr = MSG_ORDERED_TAG; break; case FCP_PTA_ACA: task_attr = MSG_ACA_TAG; break; case FCP_PTA_SIMPLE: /* Fallthrough */ default: task_attr = MSG_SIMPLE_TAG; } task_attr = fcp->fc_pri_ta & FCP_PTA_MASK; data_len = ntohl(fcp->fc_dl); cmd->cdb = fcp->fc_cdb; } se_cmd = &cmd->se_cmd; /* * Initialize struct se_cmd descriptor from target_core_mod * infrastructure */ transport_init_se_cmd(se_cmd, &ft_configfs->tf_ops, cmd->sess->se_sess, data_len, data_dir, task_attr, &cmd->ft_sense_buffer[0]); /* * Check for FCP task management flags */ if (fcp->fc_tm_flags) { ft_send_tm(cmd); return; } fc_seq_exch(cmd->seq)->lp->tt.seq_set_resp(cmd->seq, ft_recv_seq, cmd); cmd->lun = scsilun_to_int((struct scsi_lun *)fcp->fc_lun); ret = transport_get_lun_for_cmd(&cmd->se_cmd, NULL, cmd->lun); if (ret < 0) { ft_dump_cmd(cmd, __func__); transport_send_check_condition_and_sense(&cmd->se_cmd, cmd->se_cmd.scsi_sense_reason, 0); return; } ret = transport_generic_allocate_tasks(se_cmd, cmd->cdb); FT_IO_DBG("r_ctl %x alloc task ret %d\n", fh->fh_r_ctl, ret); ft_dump_cmd(cmd, __func__); if (ret == -1) { transport_send_check_condition_and_sense(se_cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0); transport_generic_free_cmd(se_cmd, 0, 1, 0); return; } if (ret == -2) { if (se_cmd->se_cmd_flags & SCF_SCSI_RESERVATION_CONFLICT) ft_queue_status(se_cmd); else transport_send_check_condition_and_sense(se_cmd, se_cmd->scsi_sense_reason, 0); transport_generic_free_cmd(se_cmd, 0, 1, 0); return; } transport_generic_handle_cdb(se_cmd); return; err: ft_send_resp_code(cmd, FCP_CMND_FIELDS_INVALID); return; } /* * Handle request in the command thread. */ static void ft_exec_req(struct ft_cmd *cmd) { FT_IO_DBG("cmd state %x\n", cmd->state); switch (cmd->state) { case FC_CMD_ST_NEW: ft_send_cmd(cmd); break; default: break; } } /* * Processing thread. * Currently one thread per tpg. */ int ft_thread(void *arg) { struct ft_tpg *tpg = arg; struct se_queue_obj *qobj = &tpg->qobj; struct ft_cmd *cmd; int ret; set_user_nice(current, -20); while (!kthread_should_stop()) { ret = wait_event_interruptible(qobj->thread_wq, atomic_read(&qobj->queue_cnt) || kthread_should_stop()); if (ret < 0 || kthread_should_stop()) goto out; cmd = ft_dequeue_cmd(qobj); if (cmd) ft_exec_req(cmd); } out: return 0; }
gpl-2.0
chunyeow/ath
drivers/pinctrl/freescale/pinctrl-imx1.c
1058
8973
/* * i.MX1 pinctrl driver based on imx pinmux core * * Copyright (C) 2014 Alexander Shiyan <shc_work@mail.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. */ #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/pinctrl/pinctrl.h> #include "pinctrl-imx1.h" #define PAD_ID(port, pin) ((port) * 32 + (pin)) #define PA 0 #define PB 1 #define PC 2 #define PD 3 enum imx1_pads { MX1_PAD_A24 = PAD_ID(PA, 0), MX1_PAD_TIN = PAD_ID(PA, 1), MX1_PAD_PWMO = PAD_ID(PA, 2), MX1_PAD_CSI_MCLK = PAD_ID(PA, 3), MX1_PAD_CSI_D0 = PAD_ID(PA, 4), MX1_PAD_CSI_D1 = PAD_ID(PA, 5), MX1_PAD_CSI_D2 = PAD_ID(PA, 6), MX1_PAD_CSI_D3 = PAD_ID(PA, 7), MX1_PAD_CSI_D4 = PAD_ID(PA, 8), MX1_PAD_CSI_D5 = PAD_ID(PA, 9), MX1_PAD_CSI_D6 = PAD_ID(PA, 10), MX1_PAD_CSI_D7 = PAD_ID(PA, 11), MX1_PAD_CSI_VSYNC = PAD_ID(PA, 12), MX1_PAD_CSI_HSYNC = PAD_ID(PA, 13), MX1_PAD_CSI_PIXCLK = PAD_ID(PA, 14), MX1_PAD_I2C_SDA = PAD_ID(PA, 15), MX1_PAD_I2C_SCL = PAD_ID(PA, 16), MX1_PAD_DTACK = PAD_ID(PA, 17), MX1_PAD_BCLK = PAD_ID(PA, 18), MX1_PAD_LBA = PAD_ID(PA, 19), MX1_PAD_ECB = PAD_ID(PA, 20), MX1_PAD_A0 = PAD_ID(PA, 21), MX1_PAD_CS4 = PAD_ID(PA, 22), MX1_PAD_CS5 = PAD_ID(PA, 23), MX1_PAD_A16 = PAD_ID(PA, 24), MX1_PAD_A17 = PAD_ID(PA, 25), MX1_PAD_A18 = PAD_ID(PA, 26), MX1_PAD_A19 = PAD_ID(PA, 27), MX1_PAD_A20 = PAD_ID(PA, 28), MX1_PAD_A21 = PAD_ID(PA, 29), MX1_PAD_A22 = PAD_ID(PA, 30), MX1_PAD_A23 = PAD_ID(PA, 31), MX1_PAD_SD_DAT0 = PAD_ID(PB, 8), MX1_PAD_SD_DAT1 = PAD_ID(PB, 9), MX1_PAD_SD_DAT2 = PAD_ID(PB, 10), MX1_PAD_SD_DAT3 = PAD_ID(PB, 11), MX1_PAD_SD_SCLK = PAD_ID(PB, 12), MX1_PAD_SD_CMD = PAD_ID(PB, 13), MX1_PAD_SIM_SVEN = PAD_ID(PB, 14), MX1_PAD_SIM_PD = PAD_ID(PB, 15), MX1_PAD_SIM_TX = PAD_ID(PB, 16), MX1_PAD_SIM_RX = PAD_ID(PB, 17), MX1_PAD_SIM_RST = PAD_ID(PB, 18), MX1_PAD_SIM_CLK = PAD_ID(PB, 19), MX1_PAD_USBD_AFE = PAD_ID(PB, 20), MX1_PAD_USBD_OE = PAD_ID(PB, 21), MX1_PAD_USBD_RCV = PAD_ID(PB, 22), MX1_PAD_USBD_SUSPND = PAD_ID(PB, 23), MX1_PAD_USBD_VP = PAD_ID(PB, 24), MX1_PAD_USBD_VM = PAD_ID(PB, 25), MX1_PAD_USBD_VPO = PAD_ID(PB, 26), MX1_PAD_USBD_VMO = PAD_ID(PB, 27), MX1_PAD_UART2_CTS = PAD_ID(PB, 28), MX1_PAD_UART2_RTS = PAD_ID(PB, 29), MX1_PAD_UART2_TXD = PAD_ID(PB, 30), MX1_PAD_UART2_RXD = PAD_ID(PB, 31), MX1_PAD_SSI_RXFS = PAD_ID(PC, 3), MX1_PAD_SSI_RXCLK = PAD_ID(PC, 4), MX1_PAD_SSI_RXDAT = PAD_ID(PC, 5), MX1_PAD_SSI_TXDAT = PAD_ID(PC, 6), MX1_PAD_SSI_TXFS = PAD_ID(PC, 7), MX1_PAD_SSI_TXCLK = PAD_ID(PC, 8), MX1_PAD_UART1_CTS = PAD_ID(PC, 9), MX1_PAD_UART1_RTS = PAD_ID(PC, 10), MX1_PAD_UART1_TXD = PAD_ID(PC, 11), MX1_PAD_UART1_RXD = PAD_ID(PC, 12), MX1_PAD_SPI1_RDY = PAD_ID(PC, 13), MX1_PAD_SPI1_SCLK = PAD_ID(PC, 14), MX1_PAD_SPI1_SS = PAD_ID(PC, 15), MX1_PAD_SPI1_MISO = PAD_ID(PC, 16), MX1_PAD_SPI1_MOSI = PAD_ID(PC, 17), MX1_PAD_BT13 = PAD_ID(PC, 19), MX1_PAD_BT12 = PAD_ID(PC, 20), MX1_PAD_BT11 = PAD_ID(PC, 21), MX1_PAD_BT10 = PAD_ID(PC, 22), MX1_PAD_BT9 = PAD_ID(PC, 23), MX1_PAD_BT8 = PAD_ID(PC, 24), MX1_PAD_BT7 = PAD_ID(PC, 25), MX1_PAD_BT6 = PAD_ID(PC, 26), MX1_PAD_BT5 = PAD_ID(PC, 27), MX1_PAD_BT4 = PAD_ID(PC, 28), MX1_PAD_BT3 = PAD_ID(PC, 29), MX1_PAD_BT2 = PAD_ID(PC, 30), MX1_PAD_BT1 = PAD_ID(PC, 31), MX1_PAD_LSCLK = PAD_ID(PD, 6), MX1_PAD_REV = PAD_ID(PD, 7), MX1_PAD_CLS = PAD_ID(PD, 8), MX1_PAD_PS = PAD_ID(PD, 9), MX1_PAD_SPL_SPR = PAD_ID(PD, 10), MX1_PAD_CONTRAST = PAD_ID(PD, 11), MX1_PAD_ACD_OE = PAD_ID(PD, 12), MX1_PAD_LP_HSYNC = PAD_ID(PD, 13), MX1_PAD_FLM_VSYNC = PAD_ID(PD, 14), MX1_PAD_LD0 = PAD_ID(PD, 15), MX1_PAD_LD1 = PAD_ID(PD, 16), MX1_PAD_LD2 = PAD_ID(PD, 17), MX1_PAD_LD3 = PAD_ID(PD, 18), MX1_PAD_LD4 = PAD_ID(PD, 19), MX1_PAD_LD5 = PAD_ID(PD, 20), MX1_PAD_LD6 = PAD_ID(PD, 21), MX1_PAD_LD7 = PAD_ID(PD, 22), MX1_PAD_LD8 = PAD_ID(PD, 23), MX1_PAD_LD9 = PAD_ID(PD, 24), MX1_PAD_LD10 = PAD_ID(PD, 25), MX1_PAD_LD11 = PAD_ID(PD, 26), MX1_PAD_LD12 = PAD_ID(PD, 27), MX1_PAD_LD13 = PAD_ID(PD, 28), MX1_PAD_LD14 = PAD_ID(PD, 29), MX1_PAD_LD15 = PAD_ID(PD, 30), MX1_PAD_TMR2OUT = PAD_ID(PD, 31), }; /* Pad names for the pinmux subsystem */ static const struct pinctrl_pin_desc imx1_pinctrl_pads[] = { IMX_PINCTRL_PIN(MX1_PAD_A24), IMX_PINCTRL_PIN(MX1_PAD_TIN), IMX_PINCTRL_PIN(MX1_PAD_PWMO), IMX_PINCTRL_PIN(MX1_PAD_CSI_MCLK), IMX_PINCTRL_PIN(MX1_PAD_CSI_D0), IMX_PINCTRL_PIN(MX1_PAD_CSI_D1), IMX_PINCTRL_PIN(MX1_PAD_CSI_D2), IMX_PINCTRL_PIN(MX1_PAD_CSI_D3), IMX_PINCTRL_PIN(MX1_PAD_CSI_D4), IMX_PINCTRL_PIN(MX1_PAD_CSI_D5), IMX_PINCTRL_PIN(MX1_PAD_CSI_D6), IMX_PINCTRL_PIN(MX1_PAD_CSI_D7), IMX_PINCTRL_PIN(MX1_PAD_CSI_VSYNC), IMX_PINCTRL_PIN(MX1_PAD_CSI_HSYNC), IMX_PINCTRL_PIN(MX1_PAD_CSI_PIXCLK), IMX_PINCTRL_PIN(MX1_PAD_I2C_SDA), IMX_PINCTRL_PIN(MX1_PAD_I2C_SCL), IMX_PINCTRL_PIN(MX1_PAD_DTACK), IMX_PINCTRL_PIN(MX1_PAD_BCLK), IMX_PINCTRL_PIN(MX1_PAD_LBA), IMX_PINCTRL_PIN(MX1_PAD_ECB), IMX_PINCTRL_PIN(MX1_PAD_A0), IMX_PINCTRL_PIN(MX1_PAD_CS4), IMX_PINCTRL_PIN(MX1_PAD_CS5), IMX_PINCTRL_PIN(MX1_PAD_A16), IMX_PINCTRL_PIN(MX1_PAD_A17), IMX_PINCTRL_PIN(MX1_PAD_A18), IMX_PINCTRL_PIN(MX1_PAD_A19), IMX_PINCTRL_PIN(MX1_PAD_A20), IMX_PINCTRL_PIN(MX1_PAD_A21), IMX_PINCTRL_PIN(MX1_PAD_A22), IMX_PINCTRL_PIN(MX1_PAD_A23), IMX_PINCTRL_PIN(MX1_PAD_SD_DAT0), IMX_PINCTRL_PIN(MX1_PAD_SD_DAT1), IMX_PINCTRL_PIN(MX1_PAD_SD_DAT2), IMX_PINCTRL_PIN(MX1_PAD_SD_DAT3), IMX_PINCTRL_PIN(MX1_PAD_SD_SCLK), IMX_PINCTRL_PIN(MX1_PAD_SD_CMD), IMX_PINCTRL_PIN(MX1_PAD_SIM_SVEN), IMX_PINCTRL_PIN(MX1_PAD_SIM_PD), IMX_PINCTRL_PIN(MX1_PAD_SIM_TX), IMX_PINCTRL_PIN(MX1_PAD_SIM_RX), IMX_PINCTRL_PIN(MX1_PAD_SIM_CLK), IMX_PINCTRL_PIN(MX1_PAD_USBD_AFE), IMX_PINCTRL_PIN(MX1_PAD_USBD_OE), IMX_PINCTRL_PIN(MX1_PAD_USBD_RCV), IMX_PINCTRL_PIN(MX1_PAD_USBD_SUSPND), IMX_PINCTRL_PIN(MX1_PAD_USBD_VP), IMX_PINCTRL_PIN(MX1_PAD_USBD_VM), IMX_PINCTRL_PIN(MX1_PAD_USBD_VPO), IMX_PINCTRL_PIN(MX1_PAD_USBD_VMO), IMX_PINCTRL_PIN(MX1_PAD_UART2_CTS), IMX_PINCTRL_PIN(MX1_PAD_UART2_RTS), IMX_PINCTRL_PIN(MX1_PAD_UART2_TXD), IMX_PINCTRL_PIN(MX1_PAD_UART2_RXD), IMX_PINCTRL_PIN(MX1_PAD_SSI_RXFS), IMX_PINCTRL_PIN(MX1_PAD_SSI_RXCLK), IMX_PINCTRL_PIN(MX1_PAD_SSI_RXDAT), IMX_PINCTRL_PIN(MX1_PAD_SSI_TXDAT), IMX_PINCTRL_PIN(MX1_PAD_SSI_TXFS), IMX_PINCTRL_PIN(MX1_PAD_SSI_TXCLK), IMX_PINCTRL_PIN(MX1_PAD_UART1_CTS), IMX_PINCTRL_PIN(MX1_PAD_UART1_RTS), IMX_PINCTRL_PIN(MX1_PAD_UART1_TXD), IMX_PINCTRL_PIN(MX1_PAD_UART1_RXD), IMX_PINCTRL_PIN(MX1_PAD_SPI1_RDY), IMX_PINCTRL_PIN(MX1_PAD_SPI1_SCLK), IMX_PINCTRL_PIN(MX1_PAD_SPI1_SS), IMX_PINCTRL_PIN(MX1_PAD_SPI1_MISO), IMX_PINCTRL_PIN(MX1_PAD_SPI1_MOSI), IMX_PINCTRL_PIN(MX1_PAD_BT13), IMX_PINCTRL_PIN(MX1_PAD_BT12), IMX_PINCTRL_PIN(MX1_PAD_BT11), IMX_PINCTRL_PIN(MX1_PAD_BT10), IMX_PINCTRL_PIN(MX1_PAD_BT9), IMX_PINCTRL_PIN(MX1_PAD_BT8), IMX_PINCTRL_PIN(MX1_PAD_BT7), IMX_PINCTRL_PIN(MX1_PAD_BT6), IMX_PINCTRL_PIN(MX1_PAD_BT5), IMX_PINCTRL_PIN(MX1_PAD_BT4), IMX_PINCTRL_PIN(MX1_PAD_BT3), IMX_PINCTRL_PIN(MX1_PAD_BT2), IMX_PINCTRL_PIN(MX1_PAD_BT1), IMX_PINCTRL_PIN(MX1_PAD_LSCLK), IMX_PINCTRL_PIN(MX1_PAD_REV), IMX_PINCTRL_PIN(MX1_PAD_CLS), IMX_PINCTRL_PIN(MX1_PAD_PS), IMX_PINCTRL_PIN(MX1_PAD_SPL_SPR), IMX_PINCTRL_PIN(MX1_PAD_CONTRAST), IMX_PINCTRL_PIN(MX1_PAD_ACD_OE), IMX_PINCTRL_PIN(MX1_PAD_LP_HSYNC), IMX_PINCTRL_PIN(MX1_PAD_FLM_VSYNC), IMX_PINCTRL_PIN(MX1_PAD_LD0), IMX_PINCTRL_PIN(MX1_PAD_LD1), IMX_PINCTRL_PIN(MX1_PAD_LD2), IMX_PINCTRL_PIN(MX1_PAD_LD3), IMX_PINCTRL_PIN(MX1_PAD_LD4), IMX_PINCTRL_PIN(MX1_PAD_LD5), IMX_PINCTRL_PIN(MX1_PAD_LD6), IMX_PINCTRL_PIN(MX1_PAD_LD7), IMX_PINCTRL_PIN(MX1_PAD_LD8), IMX_PINCTRL_PIN(MX1_PAD_LD9), IMX_PINCTRL_PIN(MX1_PAD_LD10), IMX_PINCTRL_PIN(MX1_PAD_LD11), IMX_PINCTRL_PIN(MX1_PAD_LD12), IMX_PINCTRL_PIN(MX1_PAD_LD13), IMX_PINCTRL_PIN(MX1_PAD_LD14), IMX_PINCTRL_PIN(MX1_PAD_LD15), IMX_PINCTRL_PIN(MX1_PAD_TMR2OUT), }; static struct imx1_pinctrl_soc_info imx1_pinctrl_info = { .pins = imx1_pinctrl_pads, .npins = ARRAY_SIZE(imx1_pinctrl_pads), }; static int __init imx1_pinctrl_probe(struct platform_device *pdev) { return imx1_pinctrl_core_probe(pdev, &imx1_pinctrl_info); } static const struct of_device_id imx1_pinctrl_of_match[] = { { .compatible = "fsl,imx1-iomuxc", }, { } }; MODULE_DEVICE_TABLE(of, imx1_pinctrl_of_match); static struct platform_driver imx1_pinctrl_driver = { .driver = { .name = "imx1-pinctrl", .of_match_table = imx1_pinctrl_of_match, }, .remove = imx1_pinctrl_core_remove, }; module_platform_driver_probe(imx1_pinctrl_driver, imx1_pinctrl_probe); MODULE_AUTHOR("Alexander Shiyan <shc_work@mail.ru>"); MODULE_DESCRIPTION("Freescale i.MX1 pinctrl driver"); MODULE_LICENSE("GPL");
gpl-2.0
sch2307/android_kernel_ezboard_s100
drivers/video/omap/lcd_omap2evm.c
1314
4851
/* * LCD panel support for the MISTRAL OMAP2EVM board * * Author: Arun C <arunedarath@mistralsolutions.com> * * Derived from drivers/video/omap/lcd_omap3evm.c * 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 154 #define LCD_PANEL_LR 128 #define LCD_PANEL_UD 129 #define LCD_PANEL_INI 152 #define LCD_PANEL_QVGA 148 #define LCD_PANEL_RESB 153 #define TWL_LED_LEDEN 0x00 #define TWL_PWMA_PWMAON 0x00 #define TWL_PWMA_PWMAOFF 0x01 static unsigned int bklight_level; static int omap2evm_panel_init(struct lcd_panel *panel, struct omapfb_device *fbdev) { gpio_request(LCD_PANEL_ENABLE_GPIO, "LCD enable"); 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_QVGA, "LCD qvga"); gpio_request(LCD_PANEL_RESB, "LCD resb"); gpio_direction_output(LCD_PANEL_ENABLE_GPIO, 1); 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 omap2evm_panel_cleanup(struct lcd_panel *panel) { gpio_free(LCD_PANEL_RESB); gpio_free(LCD_PANEL_QVGA); gpio_free(LCD_PANEL_INI); gpio_free(LCD_PANEL_UD); gpio_free(LCD_PANEL_LR); gpio_free(LCD_PANEL_ENABLE_GPIO); } static int omap2evm_panel_enable(struct lcd_panel *panel) { gpio_set_value(LCD_PANEL_ENABLE_GPIO, 0); return 0; } static void omap2evm_panel_disable(struct lcd_panel *panel) { gpio_set_value(LCD_PANEL_ENABLE_GPIO, 1); } static unsigned long omap2evm_panel_get_caps(struct lcd_panel *panel) { return 0; } static int omap2evm_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 omap2evm_bklight_getlevel(struct lcd_panel *panel) { return bklight_level; } static unsigned int omap2evm_bklight_getmaxlevel(struct lcd_panel *panel) { return 100; } struct lcd_panel omap2evm_panel = { .name = "omap2evm", .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, .hfp = 0, .hbp = 28, .vsw = 2, .vfp = 1, .vbp = 0, .pixel_clock = 20000, .init = omap2evm_panel_init, .cleanup = omap2evm_panel_cleanup, .enable = omap2evm_panel_enable, .disable = omap2evm_panel_disable, .get_caps = omap2evm_panel_get_caps, .set_bklight_level = omap2evm_bklight_setlevel, .get_bklight_level = omap2evm_bklight_getlevel, .get_bklight_max = omap2evm_bklight_getmaxlevel, }; static int omap2evm_panel_probe(struct platform_device *pdev) { omapfb_register_panel(&omap2evm_panel); return 0; } static int omap2evm_panel_remove(struct platform_device *pdev) { return 0; } static int omap2evm_panel_suspend(struct platform_device *pdev, pm_message_t mesg) { return 0; } static int omap2evm_panel_resume(struct platform_device *pdev) { return 0; } struct platform_driver omap2evm_panel_driver = { .probe = omap2evm_panel_probe, .remove = omap2evm_panel_remove, .suspend = omap2evm_panel_suspend, .resume = omap2evm_panel_resume, .driver = { .name = "omap2evm_lcd", .owner = THIS_MODULE, }, }; static int __init omap2evm_panel_drv_init(void) { return platform_driver_register(&omap2evm_panel_driver); } static void __exit omap2evm_panel_drv_exit(void) { platform_driver_unregister(&omap2evm_panel_driver); } module_init(omap2evm_panel_drv_init); module_exit(omap2evm_panel_drv_exit);
gpl-2.0
mrimp/SM-G928T_Kernel
drivers/media/usb/pvrusb2/pvrusb2-hdw.c
2082
142208
/* * * * Copyright (C) 2005 Mike Isely <isely@pobox.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 * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You 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/errno.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/firmware.h> #include <linux/videodev2.h> #include <media/v4l2-common.h> #include <media/tuner.h> #include "pvrusb2.h" #include "pvrusb2-std.h" #include "pvrusb2-util.h" #include "pvrusb2-hdw.h" #include "pvrusb2-i2c-core.h" #include "pvrusb2-eeprom.h" #include "pvrusb2-hdw-internal.h" #include "pvrusb2-encoder.h" #include "pvrusb2-debug.h" #include "pvrusb2-fx2-cmd.h" #include "pvrusb2-wm8775.h" #include "pvrusb2-video-v4l.h" #include "pvrusb2-cx2584x-v4l.h" #include "pvrusb2-cs53l32a.h" #include "pvrusb2-audio.h" #define TV_MIN_FREQ 55250000L #define TV_MAX_FREQ 850000000L /* This defines a minimum interval that the decoder must remain quiet before we are allowed to start it running. */ #define TIME_MSEC_DECODER_WAIT 50 /* This defines a minimum interval that the decoder must be allowed to run before we can safely begin using its streaming output. */ #define TIME_MSEC_DECODER_STABILIZATION_WAIT 300 /* This defines a minimum interval that the encoder must remain quiet before we are allowed to configure it. */ #define TIME_MSEC_ENCODER_WAIT 50 /* This defines the minimum interval that the encoder must successfully run before we consider that the encoder has run at least once since its firmware has been loaded. This measurement is in important for cases where we can't do something until we know that the encoder has been run at least once. */ #define TIME_MSEC_ENCODER_OK 250 static struct pvr2_hdw *unit_pointers[PVR_NUM] = {[ 0 ... PVR_NUM-1 ] = NULL}; static DEFINE_MUTEX(pvr2_unit_mtx); static int ctlchg; static int procreload; static int tuner[PVR_NUM] = { [0 ... PVR_NUM-1] = -1 }; static int tolerance[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 }; static int video_std[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 }; static int init_pause_msec; module_param(ctlchg, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(ctlchg, "0=optimize ctl change 1=always accept new ctl value"); module_param(init_pause_msec, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(init_pause_msec, "hardware initialization settling delay"); module_param(procreload, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(procreload, "Attempt init failure recovery with firmware reload"); module_param_array(tuner, int, NULL, 0444); MODULE_PARM_DESC(tuner,"specify installed tuner type"); module_param_array(video_std, int, NULL, 0444); MODULE_PARM_DESC(video_std,"specify initial video standard"); module_param_array(tolerance, int, NULL, 0444); MODULE_PARM_DESC(tolerance,"specify stream error tolerance"); /* US Broadcast channel 3 (61.25 MHz), to help with testing */ static int default_tv_freq = 61250000L; /* 104.3 MHz, a usable FM station for my area */ static int default_radio_freq = 104300000L; module_param_named(tv_freq, default_tv_freq, int, 0444); MODULE_PARM_DESC(tv_freq, "specify initial television frequency"); module_param_named(radio_freq, default_radio_freq, int, 0444); MODULE_PARM_DESC(radio_freq, "specify initial radio frequency"); #define PVR2_CTL_WRITE_ENDPOINT 0x01 #define PVR2_CTL_READ_ENDPOINT 0x81 #define PVR2_GPIO_IN 0x9008 #define PVR2_GPIO_OUT 0x900c #define PVR2_GPIO_DIR 0x9020 #define trace_firmware(...) pvr2_trace(PVR2_TRACE_FIRMWARE,__VA_ARGS__) #define PVR2_FIRMWARE_ENDPOINT 0x02 /* size of a firmware chunk */ #define FIRMWARE_CHUNK_SIZE 0x2000 typedef void (*pvr2_subdev_update_func)(struct pvr2_hdw *, struct v4l2_subdev *); static const pvr2_subdev_update_func pvr2_module_update_functions[] = { [PVR2_CLIENT_ID_WM8775] = pvr2_wm8775_subdev_update, [PVR2_CLIENT_ID_SAA7115] = pvr2_saa7115_subdev_update, [PVR2_CLIENT_ID_MSP3400] = pvr2_msp3400_subdev_update, [PVR2_CLIENT_ID_CX25840] = pvr2_cx25840_subdev_update, [PVR2_CLIENT_ID_CS53L32A] = pvr2_cs53l32a_subdev_update, }; static const char *module_names[] = { [PVR2_CLIENT_ID_MSP3400] = "msp3400", [PVR2_CLIENT_ID_CX25840] = "cx25840", [PVR2_CLIENT_ID_SAA7115] = "saa7115", [PVR2_CLIENT_ID_TUNER] = "tuner", [PVR2_CLIENT_ID_DEMOD] = "tuner", [PVR2_CLIENT_ID_CS53L32A] = "cs53l32a", [PVR2_CLIENT_ID_WM8775] = "wm8775", }; static const unsigned char *module_i2c_addresses[] = { [PVR2_CLIENT_ID_TUNER] = "\x60\x61\x62\x63", [PVR2_CLIENT_ID_DEMOD] = "\x43", [PVR2_CLIENT_ID_MSP3400] = "\x40", [PVR2_CLIENT_ID_SAA7115] = "\x21", [PVR2_CLIENT_ID_WM8775] = "\x1b", [PVR2_CLIENT_ID_CX25840] = "\x44", [PVR2_CLIENT_ID_CS53L32A] = "\x11", }; static const char *ir_scheme_names[] = { [PVR2_IR_SCHEME_NONE] = "none", [PVR2_IR_SCHEME_29XXX] = "29xxx", [PVR2_IR_SCHEME_24XXX] = "24xxx (29xxx emulation)", [PVR2_IR_SCHEME_24XXX_MCE] = "24xxx (MCE device)", [PVR2_IR_SCHEME_ZILOG] = "Zilog", }; /* Define the list of additional controls we'll dynamically construct based on query of the cx2341x module. */ struct pvr2_mpeg_ids { const char *strid; int id; }; static const struct pvr2_mpeg_ids mpeg_ids[] = { { .strid = "audio_layer", .id = V4L2_CID_MPEG_AUDIO_ENCODING, },{ .strid = "audio_bitrate", .id = V4L2_CID_MPEG_AUDIO_L2_BITRATE, },{ /* Already using audio_mode elsewhere :-( */ .strid = "mpeg_audio_mode", .id = V4L2_CID_MPEG_AUDIO_MODE, },{ .strid = "mpeg_audio_mode_extension", .id = V4L2_CID_MPEG_AUDIO_MODE_EXTENSION, },{ .strid = "audio_emphasis", .id = V4L2_CID_MPEG_AUDIO_EMPHASIS, },{ .strid = "audio_crc", .id = V4L2_CID_MPEG_AUDIO_CRC, },{ .strid = "video_aspect", .id = V4L2_CID_MPEG_VIDEO_ASPECT, },{ .strid = "video_b_frames", .id = V4L2_CID_MPEG_VIDEO_B_FRAMES, },{ .strid = "video_gop_size", .id = V4L2_CID_MPEG_VIDEO_GOP_SIZE, },{ .strid = "video_gop_closure", .id = V4L2_CID_MPEG_VIDEO_GOP_CLOSURE, },{ .strid = "video_bitrate_mode", .id = V4L2_CID_MPEG_VIDEO_BITRATE_MODE, },{ .strid = "video_bitrate", .id = V4L2_CID_MPEG_VIDEO_BITRATE, },{ .strid = "video_bitrate_peak", .id = V4L2_CID_MPEG_VIDEO_BITRATE_PEAK, },{ .strid = "video_temporal_decimation", .id = V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION, },{ .strid = "stream_type", .id = V4L2_CID_MPEG_STREAM_TYPE, },{ .strid = "video_spatial_filter_mode", .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE, },{ .strid = "video_spatial_filter", .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER, },{ .strid = "video_luma_spatial_filter_type", .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE, },{ .strid = "video_chroma_spatial_filter_type", .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE, },{ .strid = "video_temporal_filter_mode", .id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE, },{ .strid = "video_temporal_filter", .id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER, },{ .strid = "video_median_filter_type", .id = V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE, },{ .strid = "video_luma_median_filter_top", .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP, },{ .strid = "video_luma_median_filter_bottom", .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM, },{ .strid = "video_chroma_median_filter_top", .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP, },{ .strid = "video_chroma_median_filter_bottom", .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM, } }; #define MPEGDEF_COUNT ARRAY_SIZE(mpeg_ids) static const char *control_values_srate[] = { [V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100] = "44.1 kHz", [V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000] = "48 kHz", [V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000] = "32 kHz", }; static const char *control_values_input[] = { [PVR2_CVAL_INPUT_TV] = "television", /*xawtv needs this name*/ [PVR2_CVAL_INPUT_DTV] = "dtv", [PVR2_CVAL_INPUT_RADIO] = "radio", [PVR2_CVAL_INPUT_SVIDEO] = "s-video", [PVR2_CVAL_INPUT_COMPOSITE] = "composite", }; static const char *control_values_audiomode[] = { [V4L2_TUNER_MODE_MONO] = "Mono", [V4L2_TUNER_MODE_STEREO] = "Stereo", [V4L2_TUNER_MODE_LANG1] = "Lang1", [V4L2_TUNER_MODE_LANG2] = "Lang2", [V4L2_TUNER_MODE_LANG1_LANG2] = "Lang1+Lang2", }; static const char *control_values_hsm[] = { [PVR2_CVAL_HSM_FAIL] = "Fail", [PVR2_CVAL_HSM_HIGH] = "High", [PVR2_CVAL_HSM_FULL] = "Full", }; static const char *pvr2_state_names[] = { [PVR2_STATE_NONE] = "none", [PVR2_STATE_DEAD] = "dead", [PVR2_STATE_COLD] = "cold", [PVR2_STATE_WARM] = "warm", [PVR2_STATE_ERROR] = "error", [PVR2_STATE_READY] = "ready", [PVR2_STATE_RUN] = "run", }; struct pvr2_fx2cmd_descdef { unsigned char id; unsigned char *desc; }; static const struct pvr2_fx2cmd_descdef pvr2_fx2cmd_desc[] = { {FX2CMD_MEM_WRITE_DWORD, "write encoder dword"}, {FX2CMD_MEM_READ_DWORD, "read encoder dword"}, {FX2CMD_HCW_ZILOG_RESET, "zilog IR reset control"}, {FX2CMD_MEM_READ_64BYTES, "read encoder 64bytes"}, {FX2CMD_REG_WRITE, "write encoder register"}, {FX2CMD_REG_READ, "read encoder register"}, {FX2CMD_MEMSEL, "encoder memsel"}, {FX2CMD_I2C_WRITE, "i2c write"}, {FX2CMD_I2C_READ, "i2c read"}, {FX2CMD_GET_USB_SPEED, "get USB speed"}, {FX2CMD_STREAMING_ON, "stream on"}, {FX2CMD_STREAMING_OFF, "stream off"}, {FX2CMD_FWPOST1, "fwpost1"}, {FX2CMD_POWER_OFF, "power off"}, {FX2CMD_POWER_ON, "power on"}, {FX2CMD_DEEP_RESET, "deep reset"}, {FX2CMD_GET_EEPROM_ADDR, "get rom addr"}, {FX2CMD_GET_IR_CODE, "get IR code"}, {FX2CMD_HCW_DEMOD_RESETIN, "hcw demod resetin"}, {FX2CMD_HCW_DTV_STREAMING_ON, "hcw dtv stream on"}, {FX2CMD_HCW_DTV_STREAMING_OFF, "hcw dtv stream off"}, {FX2CMD_ONAIR_DTV_STREAMING_ON, "onair dtv stream on"}, {FX2CMD_ONAIR_DTV_STREAMING_OFF, "onair dtv stream off"}, {FX2CMD_ONAIR_DTV_POWER_ON, "onair dtv power on"}, {FX2CMD_ONAIR_DTV_POWER_OFF, "onair dtv power off"}, }; static int pvr2_hdw_set_input(struct pvr2_hdw *hdw,int v); static void pvr2_hdw_state_sched(struct pvr2_hdw *); static int pvr2_hdw_state_eval(struct pvr2_hdw *); static void pvr2_hdw_set_cur_freq(struct pvr2_hdw *,unsigned long); static void pvr2_hdw_worker_poll(struct work_struct *work); static int pvr2_hdw_wait(struct pvr2_hdw *,int state); static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *); static void pvr2_hdw_state_log_state(struct pvr2_hdw *); static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl); static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw); static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw); static void pvr2_hdw_quiescent_timeout(unsigned long); static void pvr2_hdw_decoder_stabilization_timeout(unsigned long); static void pvr2_hdw_encoder_wait_timeout(unsigned long); static void pvr2_hdw_encoder_run_timeout(unsigned long); static int pvr2_issue_simple_cmd(struct pvr2_hdw *,u32); static int pvr2_send_request_ex(struct pvr2_hdw *hdw, unsigned int timeout,int probe_fl, void *write_data,unsigned int write_len, void *read_data,unsigned int read_len); static int pvr2_hdw_check_cropcap(struct pvr2_hdw *hdw); static v4l2_std_id pvr2_hdw_get_detected_std(struct pvr2_hdw *hdw); static void trace_stbit(const char *name,int val) { pvr2_trace(PVR2_TRACE_STBITS, "State bit %s <-- %s", name,(val ? "true" : "false")); } static int ctrl_channelfreq_get(struct pvr2_ctrl *cptr,int *vp) { struct pvr2_hdw *hdw = cptr->hdw; if ((hdw->freqProgSlot > 0) && (hdw->freqProgSlot <= FREQTABLE_SIZE)) { *vp = hdw->freqTable[hdw->freqProgSlot-1]; } else { *vp = 0; } return 0; } static int ctrl_channelfreq_set(struct pvr2_ctrl *cptr,int m,int v) { struct pvr2_hdw *hdw = cptr->hdw; unsigned int slotId = hdw->freqProgSlot; if ((slotId > 0) && (slotId <= FREQTABLE_SIZE)) { hdw->freqTable[slotId-1] = v; /* Handle side effects correctly - if we're tuned to this slot, then forgot the slot id relation since the stored frequency has been changed. */ if (hdw->freqSelector) { if (hdw->freqSlotRadio == slotId) { hdw->freqSlotRadio = 0; } } else { if (hdw->freqSlotTelevision == slotId) { hdw->freqSlotTelevision = 0; } } } return 0; } static int ctrl_channelprog_get(struct pvr2_ctrl *cptr,int *vp) { *vp = cptr->hdw->freqProgSlot; return 0; } static int ctrl_channelprog_set(struct pvr2_ctrl *cptr,int m,int v) { struct pvr2_hdw *hdw = cptr->hdw; if ((v >= 0) && (v <= FREQTABLE_SIZE)) { hdw->freqProgSlot = v; } return 0; } static int ctrl_channel_get(struct pvr2_ctrl *cptr,int *vp) { struct pvr2_hdw *hdw = cptr->hdw; *vp = hdw->freqSelector ? hdw->freqSlotRadio : hdw->freqSlotTelevision; return 0; } static int ctrl_channel_set(struct pvr2_ctrl *cptr,int m,int slotId) { unsigned freq = 0; struct pvr2_hdw *hdw = cptr->hdw; if ((slotId < 0) || (slotId > FREQTABLE_SIZE)) return 0; if (slotId > 0) { freq = hdw->freqTable[slotId-1]; if (!freq) return 0; pvr2_hdw_set_cur_freq(hdw,freq); } if (hdw->freqSelector) { hdw->freqSlotRadio = slotId; } else { hdw->freqSlotTelevision = slotId; } return 0; } static int ctrl_freq_get(struct pvr2_ctrl *cptr,int *vp) { *vp = pvr2_hdw_get_cur_freq(cptr->hdw); return 0; } static int ctrl_freq_is_dirty(struct pvr2_ctrl *cptr) { return cptr->hdw->freqDirty != 0; } static void ctrl_freq_clear_dirty(struct pvr2_ctrl *cptr) { cptr->hdw->freqDirty = 0; } static int ctrl_freq_set(struct pvr2_ctrl *cptr,int m,int v) { pvr2_hdw_set_cur_freq(cptr->hdw,v); return 0; } static int ctrl_cropl_min_get(struct pvr2_ctrl *cptr, int *left) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *left = cap->bounds.left; return 0; } static int ctrl_cropl_max_get(struct pvr2_ctrl *cptr, int *left) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *left = cap->bounds.left; if (cap->bounds.width > cptr->hdw->cropw_val) { *left += cap->bounds.width - cptr->hdw->cropw_val; } return 0; } static int ctrl_cropt_min_get(struct pvr2_ctrl *cptr, int *top) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *top = cap->bounds.top; return 0; } static int ctrl_cropt_max_get(struct pvr2_ctrl *cptr, int *top) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *top = cap->bounds.top; if (cap->bounds.height > cptr->hdw->croph_val) { *top += cap->bounds.height - cptr->hdw->croph_val; } return 0; } static int ctrl_cropw_max_get(struct pvr2_ctrl *cptr, int *width) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat, bleftend, cleft; stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } bleftend = cap->bounds.left+cap->bounds.width; cleft = cptr->hdw->cropl_val; *width = cleft < bleftend ? bleftend-cleft : 0; return 0; } static int ctrl_croph_max_get(struct pvr2_ctrl *cptr, int *height) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat, btopend, ctop; stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } btopend = cap->bounds.top+cap->bounds.height; ctop = cptr->hdw->cropt_val; *height = ctop < btopend ? btopend-ctop : 0; return 0; } static int ctrl_get_cropcapbl(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->bounds.left; return 0; } static int ctrl_get_cropcapbt(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->bounds.top; return 0; } static int ctrl_get_cropcapbw(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->bounds.width; return 0; } static int ctrl_get_cropcapbh(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->bounds.height; return 0; } static int ctrl_get_cropcapdl(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->defrect.left; return 0; } static int ctrl_get_cropcapdt(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->defrect.top; return 0; } static int ctrl_get_cropcapdw(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->defrect.width; return 0; } static int ctrl_get_cropcapdh(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->defrect.height; return 0; } static int ctrl_get_cropcappan(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->pixelaspect.numerator; return 0; } static int ctrl_get_cropcappad(struct pvr2_ctrl *cptr, int *val) { struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info; int stat = pvr2_hdw_check_cropcap(cptr->hdw); if (stat != 0) { return stat; } *val = cap->pixelaspect.denominator; return 0; } static int ctrl_vres_max_get(struct pvr2_ctrl *cptr,int *vp) { /* Actual maximum depends on the video standard in effect. */ if (cptr->hdw->std_mask_cur & V4L2_STD_525_60) { *vp = 480; } else { *vp = 576; } return 0; } static int ctrl_vres_min_get(struct pvr2_ctrl *cptr,int *vp) { /* Actual minimum depends on device digitizer type. */ if (cptr->hdw->hdw_desc->flag_has_cx25840) { *vp = 75; } else { *vp = 17; } return 0; } static int ctrl_get_input(struct pvr2_ctrl *cptr,int *vp) { *vp = cptr->hdw->input_val; return 0; } static int ctrl_check_input(struct pvr2_ctrl *cptr,int v) { return ((1 << v) & cptr->hdw->input_allowed_mask) != 0; } static int ctrl_set_input(struct pvr2_ctrl *cptr,int m,int v) { return pvr2_hdw_set_input(cptr->hdw,v); } static int ctrl_isdirty_input(struct pvr2_ctrl *cptr) { return cptr->hdw->input_dirty != 0; } static void ctrl_cleardirty_input(struct pvr2_ctrl *cptr) { cptr->hdw->input_dirty = 0; } static int ctrl_freq_max_get(struct pvr2_ctrl *cptr, int *vp) { unsigned long fv; struct pvr2_hdw *hdw = cptr->hdw; if (hdw->tuner_signal_stale) { pvr2_hdw_status_poll(hdw); } fv = hdw->tuner_signal_info.rangehigh; if (!fv) { /* Safety fallback */ *vp = TV_MAX_FREQ; return 0; } if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) { fv = (fv * 125) / 2; } else { fv = fv * 62500; } *vp = fv; return 0; } static int ctrl_freq_min_get(struct pvr2_ctrl *cptr, int *vp) { unsigned long fv; struct pvr2_hdw *hdw = cptr->hdw; if (hdw->tuner_signal_stale) { pvr2_hdw_status_poll(hdw); } fv = hdw->tuner_signal_info.rangelow; if (!fv) { /* Safety fallback */ *vp = TV_MIN_FREQ; return 0; } if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) { fv = (fv * 125) / 2; } else { fv = fv * 62500; } *vp = fv; return 0; } static int ctrl_cx2341x_is_dirty(struct pvr2_ctrl *cptr) { return cptr->hdw->enc_stale != 0; } static void ctrl_cx2341x_clear_dirty(struct pvr2_ctrl *cptr) { cptr->hdw->enc_stale = 0; cptr->hdw->enc_unsafe_stale = 0; } static int ctrl_cx2341x_get(struct pvr2_ctrl *cptr,int *vp) { int ret; struct v4l2_ext_controls cs; struct v4l2_ext_control c1; memset(&cs,0,sizeof(cs)); memset(&c1,0,sizeof(c1)); cs.controls = &c1; cs.count = 1; c1.id = cptr->info->v4l_id; ret = cx2341x_ext_ctrls(&cptr->hdw->enc_ctl_state, 0, &cs, VIDIOC_G_EXT_CTRLS); if (ret) return ret; *vp = c1.value; return 0; } static int ctrl_cx2341x_set(struct pvr2_ctrl *cptr,int m,int v) { int ret; struct pvr2_hdw *hdw = cptr->hdw; struct v4l2_ext_controls cs; struct v4l2_ext_control c1; memset(&cs,0,sizeof(cs)); memset(&c1,0,sizeof(c1)); cs.controls = &c1; cs.count = 1; c1.id = cptr->info->v4l_id; c1.value = v; ret = cx2341x_ext_ctrls(&hdw->enc_ctl_state, hdw->state_encoder_run, &cs, VIDIOC_S_EXT_CTRLS); if (ret == -EBUSY) { /* Oops. cx2341x is telling us it's not safe to change this control while we're capturing. Make a note of this fact so that the pipeline will be stopped the next time controls are committed. Then go on ahead and store this change anyway. */ ret = cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs, VIDIOC_S_EXT_CTRLS); if (!ret) hdw->enc_unsafe_stale = !0; } if (ret) return ret; hdw->enc_stale = !0; return 0; } static unsigned int ctrl_cx2341x_getv4lflags(struct pvr2_ctrl *cptr) { struct v4l2_queryctrl qctrl; struct pvr2_ctl_info *info; qctrl.id = cptr->info->v4l_id; cx2341x_ctrl_query(&cptr->hdw->enc_ctl_state,&qctrl); /* Strip out the const so we can adjust a function pointer. It's OK to do this here because we know this is a dynamically created control, so the underlying storage for the info pointer is (a) private to us, and (b) not in read-only storage. Either we do this or we significantly complicate the underlying control implementation. */ info = (struct pvr2_ctl_info *)(cptr->info); if (qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY) { if (info->set_value) { info->set_value = NULL; } } else { if (!(info->set_value)) { info->set_value = ctrl_cx2341x_set; } } return qctrl.flags; } static int ctrl_streamingenabled_get(struct pvr2_ctrl *cptr,int *vp) { *vp = cptr->hdw->state_pipeline_req; return 0; } static int ctrl_masterstate_get(struct pvr2_ctrl *cptr,int *vp) { *vp = cptr->hdw->master_state; return 0; } static int ctrl_hsm_get(struct pvr2_ctrl *cptr,int *vp) { int result = pvr2_hdw_is_hsm(cptr->hdw); *vp = PVR2_CVAL_HSM_FULL; if (result < 0) *vp = PVR2_CVAL_HSM_FAIL; if (result) *vp = PVR2_CVAL_HSM_HIGH; return 0; } static int ctrl_stddetect_get(struct pvr2_ctrl *cptr, int *vp) { *vp = pvr2_hdw_get_detected_std(cptr->hdw); return 0; } static int ctrl_stdavail_get(struct pvr2_ctrl *cptr,int *vp) { *vp = cptr->hdw->std_mask_avail; return 0; } static int ctrl_stdavail_set(struct pvr2_ctrl *cptr,int m,int v) { struct pvr2_hdw *hdw = cptr->hdw; v4l2_std_id ns; ns = hdw->std_mask_avail; ns = (ns & ~m) | (v & m); if (ns == hdw->std_mask_avail) return 0; hdw->std_mask_avail = ns; hdw->std_info_cur.def.type_bitmask.valid_bits = hdw->std_mask_avail; return 0; } static int ctrl_std_val_to_sym(struct pvr2_ctrl *cptr,int msk,int val, char *bufPtr,unsigned int bufSize, unsigned int *len) { *len = pvr2_std_id_to_str(bufPtr,bufSize,msk & val); return 0; } static int ctrl_std_sym_to_val(struct pvr2_ctrl *cptr, const char *bufPtr,unsigned int bufSize, int *mskp,int *valp) { int ret; v4l2_std_id id; ret = pvr2_std_str_to_id(&id,bufPtr,bufSize); if (ret < 0) return ret; if (mskp) *mskp = id; if (valp) *valp = id; return 0; } static int ctrl_stdcur_get(struct pvr2_ctrl *cptr,int *vp) { *vp = cptr->hdw->std_mask_cur; return 0; } static int ctrl_stdcur_set(struct pvr2_ctrl *cptr,int m,int v) { struct pvr2_hdw *hdw = cptr->hdw; v4l2_std_id ns; ns = hdw->std_mask_cur; ns = (ns & ~m) | (v & m); if (ns == hdw->std_mask_cur) return 0; hdw->std_mask_cur = ns; hdw->std_dirty = !0; return 0; } static int ctrl_stdcur_is_dirty(struct pvr2_ctrl *cptr) { return cptr->hdw->std_dirty != 0; } static void ctrl_stdcur_clear_dirty(struct pvr2_ctrl *cptr) { cptr->hdw->std_dirty = 0; } static int ctrl_signal_get(struct pvr2_ctrl *cptr,int *vp) { struct pvr2_hdw *hdw = cptr->hdw; pvr2_hdw_status_poll(hdw); *vp = hdw->tuner_signal_info.signal; return 0; } static int ctrl_audio_modes_present_get(struct pvr2_ctrl *cptr,int *vp) { int val = 0; unsigned int subchan; struct pvr2_hdw *hdw = cptr->hdw; pvr2_hdw_status_poll(hdw); subchan = hdw->tuner_signal_info.rxsubchans; if (subchan & V4L2_TUNER_SUB_MONO) { val |= (1 << V4L2_TUNER_MODE_MONO); } if (subchan & V4L2_TUNER_SUB_STEREO) { val |= (1 << V4L2_TUNER_MODE_STEREO); } if (subchan & V4L2_TUNER_SUB_LANG1) { val |= (1 << V4L2_TUNER_MODE_LANG1); } if (subchan & V4L2_TUNER_SUB_LANG2) { val |= (1 << V4L2_TUNER_MODE_LANG2); } *vp = val; return 0; } #define DEFINT(vmin,vmax) \ .type = pvr2_ctl_int, \ .def.type_int.min_value = vmin, \ .def.type_int.max_value = vmax #define DEFENUM(tab) \ .type = pvr2_ctl_enum, \ .def.type_enum.count = ARRAY_SIZE(tab), \ .def.type_enum.value_names = tab #define DEFBOOL \ .type = pvr2_ctl_bool #define DEFMASK(msk,tab) \ .type = pvr2_ctl_bitmask, \ .def.type_bitmask.valid_bits = msk, \ .def.type_bitmask.bit_names = tab #define DEFREF(vname) \ .set_value = ctrl_set_##vname, \ .get_value = ctrl_get_##vname, \ .is_dirty = ctrl_isdirty_##vname, \ .clear_dirty = ctrl_cleardirty_##vname #define VCREATE_FUNCS(vname) \ static int ctrl_get_##vname(struct pvr2_ctrl *cptr,int *vp) \ {*vp = cptr->hdw->vname##_val; return 0;} \ static int ctrl_set_##vname(struct pvr2_ctrl *cptr,int m,int v) \ {cptr->hdw->vname##_val = v; cptr->hdw->vname##_dirty = !0; return 0;} \ static int ctrl_isdirty_##vname(struct pvr2_ctrl *cptr) \ {return cptr->hdw->vname##_dirty != 0;} \ static void ctrl_cleardirty_##vname(struct pvr2_ctrl *cptr) \ {cptr->hdw->vname##_dirty = 0;} VCREATE_FUNCS(brightness) VCREATE_FUNCS(contrast) VCREATE_FUNCS(saturation) VCREATE_FUNCS(hue) VCREATE_FUNCS(volume) VCREATE_FUNCS(balance) VCREATE_FUNCS(bass) VCREATE_FUNCS(treble) VCREATE_FUNCS(mute) VCREATE_FUNCS(cropl) VCREATE_FUNCS(cropt) VCREATE_FUNCS(cropw) VCREATE_FUNCS(croph) VCREATE_FUNCS(audiomode) VCREATE_FUNCS(res_hor) VCREATE_FUNCS(res_ver) VCREATE_FUNCS(srate) /* Table definition of all controls which can be manipulated */ static const struct pvr2_ctl_info control_defs[] = { { .v4l_id = V4L2_CID_BRIGHTNESS, .desc = "Brightness", .name = "brightness", .default_value = 128, DEFREF(brightness), DEFINT(0,255), },{ .v4l_id = V4L2_CID_CONTRAST, .desc = "Contrast", .name = "contrast", .default_value = 68, DEFREF(contrast), DEFINT(0,127), },{ .v4l_id = V4L2_CID_SATURATION, .desc = "Saturation", .name = "saturation", .default_value = 64, DEFREF(saturation), DEFINT(0,127), },{ .v4l_id = V4L2_CID_HUE, .desc = "Hue", .name = "hue", .default_value = 0, DEFREF(hue), DEFINT(-128,127), },{ .v4l_id = V4L2_CID_AUDIO_VOLUME, .desc = "Volume", .name = "volume", .default_value = 62000, DEFREF(volume), DEFINT(0,65535), },{ .v4l_id = V4L2_CID_AUDIO_BALANCE, .desc = "Balance", .name = "balance", .default_value = 0, DEFREF(balance), DEFINT(-32768,32767), },{ .v4l_id = V4L2_CID_AUDIO_BASS, .desc = "Bass", .name = "bass", .default_value = 0, DEFREF(bass), DEFINT(-32768,32767), },{ .v4l_id = V4L2_CID_AUDIO_TREBLE, .desc = "Treble", .name = "treble", .default_value = 0, DEFREF(treble), DEFINT(-32768,32767), },{ .v4l_id = V4L2_CID_AUDIO_MUTE, .desc = "Mute", .name = "mute", .default_value = 0, DEFREF(mute), DEFBOOL, }, { .desc = "Capture crop left margin", .name = "crop_left", .internal_id = PVR2_CID_CROPL, .default_value = 0, DEFREF(cropl), DEFINT(-129, 340), .get_min_value = ctrl_cropl_min_get, .get_max_value = ctrl_cropl_max_get, .get_def_value = ctrl_get_cropcapdl, }, { .desc = "Capture crop top margin", .name = "crop_top", .internal_id = PVR2_CID_CROPT, .default_value = 0, DEFREF(cropt), DEFINT(-35, 544), .get_min_value = ctrl_cropt_min_get, .get_max_value = ctrl_cropt_max_get, .get_def_value = ctrl_get_cropcapdt, }, { .desc = "Capture crop width", .name = "crop_width", .internal_id = PVR2_CID_CROPW, .default_value = 720, DEFREF(cropw), DEFINT(0, 864), .get_max_value = ctrl_cropw_max_get, .get_def_value = ctrl_get_cropcapdw, }, { .desc = "Capture crop height", .name = "crop_height", .internal_id = PVR2_CID_CROPH, .default_value = 480, DEFREF(croph), DEFINT(0, 576), .get_max_value = ctrl_croph_max_get, .get_def_value = ctrl_get_cropcapdh, }, { .desc = "Capture capability pixel aspect numerator", .name = "cropcap_pixel_numerator", .internal_id = PVR2_CID_CROPCAPPAN, .get_value = ctrl_get_cropcappan, }, { .desc = "Capture capability pixel aspect denominator", .name = "cropcap_pixel_denominator", .internal_id = PVR2_CID_CROPCAPPAD, .get_value = ctrl_get_cropcappad, }, { .desc = "Capture capability bounds top", .name = "cropcap_bounds_top", .internal_id = PVR2_CID_CROPCAPBT, .get_value = ctrl_get_cropcapbt, }, { .desc = "Capture capability bounds left", .name = "cropcap_bounds_left", .internal_id = PVR2_CID_CROPCAPBL, .get_value = ctrl_get_cropcapbl, }, { .desc = "Capture capability bounds width", .name = "cropcap_bounds_width", .internal_id = PVR2_CID_CROPCAPBW, .get_value = ctrl_get_cropcapbw, }, { .desc = "Capture capability bounds height", .name = "cropcap_bounds_height", .internal_id = PVR2_CID_CROPCAPBH, .get_value = ctrl_get_cropcapbh, },{ .desc = "Video Source", .name = "input", .internal_id = PVR2_CID_INPUT, .default_value = PVR2_CVAL_INPUT_TV, .check_value = ctrl_check_input, DEFREF(input), DEFENUM(control_values_input), },{ .desc = "Audio Mode", .name = "audio_mode", .internal_id = PVR2_CID_AUDIOMODE, .default_value = V4L2_TUNER_MODE_STEREO, DEFREF(audiomode), DEFENUM(control_values_audiomode), },{ .desc = "Horizontal capture resolution", .name = "resolution_hor", .internal_id = PVR2_CID_HRES, .default_value = 720, DEFREF(res_hor), DEFINT(19,720), },{ .desc = "Vertical capture resolution", .name = "resolution_ver", .internal_id = PVR2_CID_VRES, .default_value = 480, DEFREF(res_ver), DEFINT(17,576), /* Hook in check for video standard and adjust maximum depending on the standard. */ .get_max_value = ctrl_vres_max_get, .get_min_value = ctrl_vres_min_get, },{ .v4l_id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ, .default_value = V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000, .desc = "Audio Sampling Frequency", .name = "srate", DEFREF(srate), DEFENUM(control_values_srate), },{ .desc = "Tuner Frequency (Hz)", .name = "frequency", .internal_id = PVR2_CID_FREQUENCY, .default_value = 0, .set_value = ctrl_freq_set, .get_value = ctrl_freq_get, .is_dirty = ctrl_freq_is_dirty, .clear_dirty = ctrl_freq_clear_dirty, DEFINT(0,0), /* Hook in check for input value (tv/radio) and adjust max/min values accordingly */ .get_max_value = ctrl_freq_max_get, .get_min_value = ctrl_freq_min_get, },{ .desc = "Channel", .name = "channel", .set_value = ctrl_channel_set, .get_value = ctrl_channel_get, DEFINT(0,FREQTABLE_SIZE), },{ .desc = "Channel Program Frequency", .name = "freq_table_value", .set_value = ctrl_channelfreq_set, .get_value = ctrl_channelfreq_get, DEFINT(0,0), /* Hook in check for input value (tv/radio) and adjust max/min values accordingly */ .get_max_value = ctrl_freq_max_get, .get_min_value = ctrl_freq_min_get, },{ .desc = "Channel Program ID", .name = "freq_table_channel", .set_value = ctrl_channelprog_set, .get_value = ctrl_channelprog_get, DEFINT(0,FREQTABLE_SIZE), },{ .desc = "Streaming Enabled", .name = "streaming_enabled", .get_value = ctrl_streamingenabled_get, DEFBOOL, },{ .desc = "USB Speed", .name = "usb_speed", .get_value = ctrl_hsm_get, DEFENUM(control_values_hsm), },{ .desc = "Master State", .name = "master_state", .get_value = ctrl_masterstate_get, DEFENUM(pvr2_state_names), },{ .desc = "Signal Present", .name = "signal_present", .get_value = ctrl_signal_get, DEFINT(0,65535), },{ .desc = "Audio Modes Present", .name = "audio_modes_present", .get_value = ctrl_audio_modes_present_get, /* For this type we "borrow" the V4L2_TUNER_MODE enum from v4l. Nothing outside of this module cares about this, but I reuse it in order to also reuse the control_values_audiomode string table. */ DEFMASK(((1 << V4L2_TUNER_MODE_MONO)| (1 << V4L2_TUNER_MODE_STEREO)| (1 << V4L2_TUNER_MODE_LANG1)| (1 << V4L2_TUNER_MODE_LANG2)), control_values_audiomode), },{ .desc = "Video Standards Available Mask", .name = "video_standard_mask_available", .internal_id = PVR2_CID_STDAVAIL, .skip_init = !0, .get_value = ctrl_stdavail_get, .set_value = ctrl_stdavail_set, .val_to_sym = ctrl_std_val_to_sym, .sym_to_val = ctrl_std_sym_to_val, .type = pvr2_ctl_bitmask, },{ .desc = "Video Standards In Use Mask", .name = "video_standard_mask_active", .internal_id = PVR2_CID_STDCUR, .skip_init = !0, .get_value = ctrl_stdcur_get, .set_value = ctrl_stdcur_set, .is_dirty = ctrl_stdcur_is_dirty, .clear_dirty = ctrl_stdcur_clear_dirty, .val_to_sym = ctrl_std_val_to_sym, .sym_to_val = ctrl_std_sym_to_val, .type = pvr2_ctl_bitmask, },{ .desc = "Video Standards Detected Mask", .name = "video_standard_mask_detected", .internal_id = PVR2_CID_STDDETECT, .skip_init = !0, .get_value = ctrl_stddetect_get, .val_to_sym = ctrl_std_val_to_sym, .sym_to_val = ctrl_std_sym_to_val, .type = pvr2_ctl_bitmask, } }; #define CTRLDEF_COUNT ARRAY_SIZE(control_defs) const char *pvr2_config_get_name(enum pvr2_config cfg) { switch (cfg) { case pvr2_config_empty: return "empty"; case pvr2_config_mpeg: return "mpeg"; case pvr2_config_vbi: return "vbi"; case pvr2_config_pcm: return "pcm"; case pvr2_config_rawvideo: return "raw video"; } return "<unknown>"; } struct usb_device *pvr2_hdw_get_dev(struct pvr2_hdw *hdw) { return hdw->usb_dev; } unsigned long pvr2_hdw_get_sn(struct pvr2_hdw *hdw) { return hdw->serial_number; } const char *pvr2_hdw_get_bus_info(struct pvr2_hdw *hdw) { return hdw->bus_info; } const char *pvr2_hdw_get_device_identifier(struct pvr2_hdw *hdw) { return hdw->identifier; } unsigned long pvr2_hdw_get_cur_freq(struct pvr2_hdw *hdw) { return hdw->freqSelector ? hdw->freqValTelevision : hdw->freqValRadio; } /* Set the currently tuned frequency and account for all possible driver-core side effects of this action. */ static void pvr2_hdw_set_cur_freq(struct pvr2_hdw *hdw,unsigned long val) { if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) { if (hdw->freqSelector) { /* Swing over to radio frequency selection */ hdw->freqSelector = 0; hdw->freqDirty = !0; } if (hdw->freqValRadio != val) { hdw->freqValRadio = val; hdw->freqSlotRadio = 0; hdw->freqDirty = !0; } } else { if (!(hdw->freqSelector)) { /* Swing over to television frequency selection */ hdw->freqSelector = 1; hdw->freqDirty = !0; } if (hdw->freqValTelevision != val) { hdw->freqValTelevision = val; hdw->freqSlotTelevision = 0; hdw->freqDirty = !0; } } } int pvr2_hdw_get_unit_number(struct pvr2_hdw *hdw) { return hdw->unit_number; } /* Attempt to locate one of the given set of files. Messages are logged appropriate to what has been found. The return value will be 0 or greater on success (it will be the index of the file name found) and fw_entry will be filled in. Otherwise a negative error is returned on failure. If the return value is -ENOENT then no viable firmware file could be located. */ static int pvr2_locate_firmware(struct pvr2_hdw *hdw, const struct firmware **fw_entry, const char *fwtypename, unsigned int fwcount, const char *fwnames[]) { unsigned int idx; int ret = -EINVAL; for (idx = 0; idx < fwcount; idx++) { ret = request_firmware(fw_entry, fwnames[idx], &hdw->usb_dev->dev); if (!ret) { trace_firmware("Located %s firmware: %s;" " uploading...", fwtypename, fwnames[idx]); return idx; } if (ret == -ENOENT) continue; pvr2_trace(PVR2_TRACE_ERROR_LEGS, "request_firmware fatal error with code=%d",ret); return ret; } pvr2_trace(PVR2_TRACE_ERROR_LEGS, "***WARNING***" " Device %s firmware" " seems to be missing.", fwtypename); pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Did you install the pvrusb2 firmware files" " in their proper location?"); if (fwcount == 1) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "request_firmware unable to locate %s file %s", fwtypename,fwnames[0]); } else { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "request_firmware unable to locate" " one of the following %s files:", fwtypename); for (idx = 0; idx < fwcount; idx++) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "request_firmware: Failed to find %s", fwnames[idx]); } } return ret; } /* * pvr2_upload_firmware1(). * * Send the 8051 firmware to the device. After the upload, arrange for * device to re-enumerate. * * NOTE : the pointer to the firmware data given by request_firmware() * is not suitable for an usb transaction. * */ static int pvr2_upload_firmware1(struct pvr2_hdw *hdw) { const struct firmware *fw_entry = NULL; void *fw_ptr; unsigned int pipe; unsigned int fwsize; int ret; u16 address; if (!hdw->hdw_desc->fx2_firmware.cnt) { hdw->fw1_state = FW1_STATE_OK; pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Connected device type defines" " no firmware to upload; ignoring firmware"); return -ENOTTY; } hdw->fw1_state = FW1_STATE_FAILED; // default result trace_firmware("pvr2_upload_firmware1"); ret = pvr2_locate_firmware(hdw,&fw_entry,"fx2 controller", hdw->hdw_desc->fx2_firmware.cnt, hdw->hdw_desc->fx2_firmware.lst); if (ret < 0) { if (ret == -ENOENT) hdw->fw1_state = FW1_STATE_MISSING; return ret; } usb_clear_halt(hdw->usb_dev, usb_sndbulkpipe(hdw->usb_dev, 0 & 0x7f)); pipe = usb_sndctrlpipe(hdw->usb_dev, 0); fwsize = fw_entry->size; if ((fwsize != 0x2000) && (!(hdw->hdw_desc->flag_fx2_16kb && (fwsize == 0x4000)))) { if (hdw->hdw_desc->flag_fx2_16kb) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Wrong fx2 firmware size" " (expected 8192 or 16384, got %u)", fwsize); } else { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Wrong fx2 firmware size" " (expected 8192, got %u)", fwsize); } release_firmware(fw_entry); return -ENOMEM; } fw_ptr = kmalloc(0x800, GFP_KERNEL); if (fw_ptr == NULL){ release_firmware(fw_entry); return -ENOMEM; } /* We have to hold the CPU during firmware upload. */ pvr2_hdw_cpureset_assert(hdw,1); /* upload the firmware to address 0000-1fff in 2048 (=0x800) bytes chunk. */ ret = 0; for (address = 0; address < fwsize; address += 0x800) { memcpy(fw_ptr, fw_entry->data + address, 0x800); ret += usb_control_msg(hdw->usb_dev, pipe, 0xa0, 0x40, address, 0, fw_ptr, 0x800, HZ); } trace_firmware("Upload done, releasing device's CPU"); /* Now release the CPU. It will disconnect and reconnect later. */ pvr2_hdw_cpureset_assert(hdw,0); kfree(fw_ptr); release_firmware(fw_entry); trace_firmware("Upload done (%d bytes sent)",ret); /* We should have written fwsize bytes */ if (ret == fwsize) { hdw->fw1_state = FW1_STATE_RELOAD; return 0; } return -EIO; } /* * pvr2_upload_firmware2() * * This uploads encoder firmware on endpoint 2. * */ int pvr2_upload_firmware2(struct pvr2_hdw *hdw) { const struct firmware *fw_entry = NULL; void *fw_ptr; unsigned int pipe, fw_len, fw_done, bcnt, icnt; int actual_length; int ret = 0; int fwidx; static const char *fw_files[] = { CX2341X_FIRM_ENC_FILENAME, }; if (hdw->hdw_desc->flag_skip_cx23416_firmware) { return 0; } trace_firmware("pvr2_upload_firmware2"); ret = pvr2_locate_firmware(hdw,&fw_entry,"encoder", ARRAY_SIZE(fw_files), fw_files); if (ret < 0) return ret; fwidx = ret; ret = 0; /* Since we're about to completely reinitialize the encoder, invalidate our cached copy of its configuration state. Next time we configure the encoder, then we'll fully configure it. */ hdw->enc_cur_valid = 0; /* Encoder is about to be reset so note that as far as we're concerned now, the encoder has never been run. */ del_timer_sync(&hdw->encoder_run_timer); if (hdw->state_encoder_runok) { hdw->state_encoder_runok = 0; trace_stbit("state_encoder_runok",hdw->state_encoder_runok); } /* First prepare firmware loading */ ret |= pvr2_write_register(hdw, 0x0048, 0xffffffff); /*interrupt mask*/ ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000088); /*gpio dir*/ ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/ ret |= pvr2_hdw_cmd_deep_reset(hdw); ret |= pvr2_write_register(hdw, 0xa064, 0x00000000); /*APU command*/ ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000408); /*gpio dir*/ ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/ ret |= pvr2_write_register(hdw, 0x9058, 0xffffffed); /*VPU ctrl*/ ret |= pvr2_write_register(hdw, 0x9054, 0xfffffffd); /*reset hw blocks*/ ret |= pvr2_write_register(hdw, 0x07f8, 0x80000800); /*encoder SDRAM refresh*/ ret |= pvr2_write_register(hdw, 0x07fc, 0x0000001a); /*encoder SDRAM pre-charge*/ ret |= pvr2_write_register(hdw, 0x0700, 0x00000000); /*I2C clock*/ ret |= pvr2_write_register(hdw, 0xaa00, 0x00000000); /*unknown*/ ret |= pvr2_write_register(hdw, 0xaa04, 0x00057810); /*unknown*/ ret |= pvr2_write_register(hdw, 0xaa10, 0x00148500); /*unknown*/ ret |= pvr2_write_register(hdw, 0xaa18, 0x00840000); /*unknown*/ ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_FWPOST1); ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_MEMSEL | (1 << 8) | (0 << 16)); if (ret) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "firmware2 upload prep failed, ret=%d",ret); release_firmware(fw_entry); goto done; } /* Now send firmware */ fw_len = fw_entry->size; if (fw_len % sizeof(u32)) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "size of %s firmware" " must be a multiple of %zu bytes", fw_files[fwidx],sizeof(u32)); release_firmware(fw_entry); ret = -EINVAL; goto done; } fw_ptr = kmalloc(FIRMWARE_CHUNK_SIZE, GFP_KERNEL); if (fw_ptr == NULL){ release_firmware(fw_entry); pvr2_trace(PVR2_TRACE_ERROR_LEGS, "failed to allocate memory for firmware2 upload"); ret = -ENOMEM; goto done; } pipe = usb_sndbulkpipe(hdw->usb_dev, PVR2_FIRMWARE_ENDPOINT); fw_done = 0; for (fw_done = 0; fw_done < fw_len;) { bcnt = fw_len - fw_done; if (bcnt > FIRMWARE_CHUNK_SIZE) bcnt = FIRMWARE_CHUNK_SIZE; memcpy(fw_ptr, fw_entry->data + fw_done, bcnt); /* Usbsnoop log shows that we must swap bytes... */ /* Some background info: The data being swapped here is a firmware image destined for the mpeg encoder chip that lives at the other end of a USB endpoint. The encoder chip always talks in 32 bit chunks and its storage is organized into 32 bit words. However from the file system to the encoder chip everything is purely a byte stream. The firmware file's contents are always 32 bit swapped from what the encoder expects. Thus the need always exists to swap the bytes regardless of the endian type of the host processor and therefore swab32() makes the most sense. */ for (icnt = 0; icnt < bcnt/4 ; icnt++) ((u32 *)fw_ptr)[icnt] = swab32(((u32 *)fw_ptr)[icnt]); ret |= usb_bulk_msg(hdw->usb_dev, pipe, fw_ptr,bcnt, &actual_length, HZ); ret |= (actual_length != bcnt); if (ret) break; fw_done += bcnt; } trace_firmware("upload of %s : %i / %i ", fw_files[fwidx],fw_done,fw_len); kfree(fw_ptr); release_firmware(fw_entry); if (ret) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "firmware2 upload transfer failure"); goto done; } /* Finish upload */ ret |= pvr2_write_register(hdw, 0x9054, 0xffffffff); /*reset hw blocks*/ ret |= pvr2_write_register(hdw, 0x9058, 0xffffffe8); /*VPU ctrl*/ ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_MEMSEL | (1 << 8) | (0 << 16)); if (ret) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "firmware2 upload post-proc failure"); } done: if (hdw->hdw_desc->signal_routing_scheme == PVR2_ROUTING_SCHEME_GOTVIEW) { /* Ensure that GPIO 11 is set to output for GOTVIEW hardware. */ pvr2_hdw_gpio_chg_dir(hdw,(1 << 11),~0); } return ret; } static const char *pvr2_get_state_name(unsigned int st) { if (st < ARRAY_SIZE(pvr2_state_names)) { return pvr2_state_names[st]; } return "???"; } static int pvr2_decoder_enable(struct pvr2_hdw *hdw,int enablefl) { /* Even though we really only care about the video decoder chip at this point, we'll broadcast stream on/off to all sub-devices anyway, just in case somebody else wants to hear the command... */ pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 stream=%s", (enablefl ? "on" : "off")); v4l2_device_call_all(&hdw->v4l2_dev, 0, video, s_stream, enablefl); v4l2_device_call_all(&hdw->v4l2_dev, 0, audio, s_stream, enablefl); if (hdw->decoder_client_id) { /* We get here if the encoder has been noticed. Otherwise we'll issue a warning to the user (which should normally never happen). */ return 0; } if (!hdw->flag_decoder_missed) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "WARNING: No decoder present"); hdw->flag_decoder_missed = !0; trace_stbit("flag_decoder_missed", hdw->flag_decoder_missed); } return -EIO; } int pvr2_hdw_get_state(struct pvr2_hdw *hdw) { return hdw->master_state; } static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *hdw) { if (!hdw->flag_tripped) return 0; hdw->flag_tripped = 0; pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Clearing driver error statuss"); return !0; } int pvr2_hdw_untrip(struct pvr2_hdw *hdw) { int fl; LOCK_TAKE(hdw->big_lock); do { fl = pvr2_hdw_untrip_unlocked(hdw); } while (0); LOCK_GIVE(hdw->big_lock); if (fl) pvr2_hdw_state_sched(hdw); return 0; } int pvr2_hdw_get_streaming(struct pvr2_hdw *hdw) { return hdw->state_pipeline_req != 0; } int pvr2_hdw_set_streaming(struct pvr2_hdw *hdw,int enable_flag) { int ret,st; LOCK_TAKE(hdw->big_lock); do { pvr2_hdw_untrip_unlocked(hdw); if ((!enable_flag) != !(hdw->state_pipeline_req)) { hdw->state_pipeline_req = enable_flag != 0; pvr2_trace(PVR2_TRACE_START_STOP, "/*--TRACE_STREAM--*/ %s", enable_flag ? "enable" : "disable"); } pvr2_hdw_state_sched(hdw); } while (0); LOCK_GIVE(hdw->big_lock); if ((ret = pvr2_hdw_wait(hdw,0)) < 0) return ret; if (enable_flag) { while ((st = hdw->master_state) != PVR2_STATE_RUN) { if (st != PVR2_STATE_READY) return -EIO; if ((ret = pvr2_hdw_wait(hdw,st)) < 0) return ret; } } return 0; } int pvr2_hdw_set_stream_type(struct pvr2_hdw *hdw,enum pvr2_config config) { int fl; LOCK_TAKE(hdw->big_lock); if ((fl = (hdw->desired_stream_type != config)) != 0) { hdw->desired_stream_type = config; hdw->state_pipeline_config = 0; trace_stbit("state_pipeline_config", hdw->state_pipeline_config); pvr2_hdw_state_sched(hdw); } LOCK_GIVE(hdw->big_lock); if (fl) return 0; return pvr2_hdw_wait(hdw,0); } static int get_default_tuner_type(struct pvr2_hdw *hdw) { int unit_number = hdw->unit_number; int tp = -1; if ((unit_number >= 0) && (unit_number < PVR_NUM)) { tp = tuner[unit_number]; } if (tp < 0) return -EINVAL; hdw->tuner_type = tp; hdw->tuner_updated = !0; return 0; } static v4l2_std_id get_default_standard(struct pvr2_hdw *hdw) { int unit_number = hdw->unit_number; int tp = 0; if ((unit_number >= 0) && (unit_number < PVR_NUM)) { tp = video_std[unit_number]; if (tp) return tp; } return 0; } static unsigned int get_default_error_tolerance(struct pvr2_hdw *hdw) { int unit_number = hdw->unit_number; int tp = 0; if ((unit_number >= 0) && (unit_number < PVR_NUM)) { tp = tolerance[unit_number]; } return tp; } static int pvr2_hdw_check_firmware(struct pvr2_hdw *hdw) { /* Try a harmless request to fetch the eeprom's address over endpoint 1. See what happens. Only the full FX2 image can respond to this. If this probe fails then likely the FX2 firmware needs be loaded. */ int result; LOCK_TAKE(hdw->ctl_lock); do { hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR; result = pvr2_send_request_ex(hdw,HZ*1,!0, hdw->cmd_buffer,1, hdw->cmd_buffer,1); if (result < 0) break; } while(0); LOCK_GIVE(hdw->ctl_lock); if (result) { pvr2_trace(PVR2_TRACE_INIT, "Probe of device endpoint 1 result status %d", result); } else { pvr2_trace(PVR2_TRACE_INIT, "Probe of device endpoint 1 succeeded"); } return result == 0; } struct pvr2_std_hack { v4l2_std_id pat; /* Pattern to match */ v4l2_std_id msk; /* Which bits we care about */ v4l2_std_id std; /* What additional standards or default to set */ }; /* This data structure labels specific combinations of standards from tveeprom that we'll try to recognize. If we recognize one, then assume a specified default standard to use. This is here because tveeprom only tells us about available standards not the intended default standard (if any) for the device in question. We guess the default based on what has been reported as available. Note that this is only for guessing a default - which can always be overridden explicitly - and if the user has otherwise named a default then that default will always be used in place of this table. */ static const struct pvr2_std_hack std_eeprom_maps[] = { { /* PAL(B/G) */ .pat = V4L2_STD_B|V4L2_STD_GH, .std = V4L2_STD_PAL_B|V4L2_STD_PAL_B1|V4L2_STD_PAL_G, }, { /* NTSC(M) */ .pat = V4L2_STD_MN, .std = V4L2_STD_NTSC_M, }, { /* PAL(I) */ .pat = V4L2_STD_PAL_I, .std = V4L2_STD_PAL_I, }, { /* SECAM(L/L') */ .pat = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC, .std = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC, }, { /* PAL(D/D1/K) */ .pat = V4L2_STD_DK, .std = V4L2_STD_PAL_D|V4L2_STD_PAL_D1|V4L2_STD_PAL_K, }, }; static void pvr2_hdw_setup_std(struct pvr2_hdw *hdw) { char buf[40]; unsigned int bcnt; v4l2_std_id std1,std2,std3; std1 = get_default_standard(hdw); std3 = std1 ? 0 : hdw->hdw_desc->default_std_mask; bcnt = pvr2_std_id_to_str(buf,sizeof(buf),hdw->std_mask_eeprom); pvr2_trace(PVR2_TRACE_STD, "Supported video standard(s) reported available" " in hardware: %.*s", bcnt,buf); hdw->std_mask_avail = hdw->std_mask_eeprom; std2 = (std1|std3) & ~hdw->std_mask_avail; if (std2) { bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std2); pvr2_trace(PVR2_TRACE_STD, "Expanding supported video standards" " to include: %.*s", bcnt,buf); hdw->std_mask_avail |= std2; } hdw->std_info_cur.def.type_bitmask.valid_bits = hdw->std_mask_avail; if (std1) { bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std1); pvr2_trace(PVR2_TRACE_STD, "Initial video standard forced to %.*s", bcnt,buf); hdw->std_mask_cur = std1; hdw->std_dirty = !0; return; } if (std3) { bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std3); pvr2_trace(PVR2_TRACE_STD, "Initial video standard" " (determined by device type): %.*s",bcnt,buf); hdw->std_mask_cur = std3; hdw->std_dirty = !0; return; } { unsigned int idx; for (idx = 0; idx < ARRAY_SIZE(std_eeprom_maps); idx++) { if (std_eeprom_maps[idx].msk ? ((std_eeprom_maps[idx].pat ^ hdw->std_mask_eeprom) & std_eeprom_maps[idx].msk) : (std_eeprom_maps[idx].pat != hdw->std_mask_eeprom)) continue; bcnt = pvr2_std_id_to_str(buf,sizeof(buf), std_eeprom_maps[idx].std); pvr2_trace(PVR2_TRACE_STD, "Initial video standard guessed as %.*s", bcnt,buf); hdw->std_mask_cur = std_eeprom_maps[idx].std; hdw->std_dirty = !0; return; } } } static unsigned int pvr2_copy_i2c_addr_list( unsigned short *dst, const unsigned char *src, unsigned int dst_max) { unsigned int cnt = 0; if (!src) return 0; while (src[cnt] && (cnt + 1) < dst_max) { dst[cnt] = src[cnt]; cnt++; } dst[cnt] = I2C_CLIENT_END; return cnt; } static void pvr2_hdw_cx25840_vbi_hack(struct pvr2_hdw *hdw) { /* Mike Isely <isely@pobox.com> 19-Nov-2006 - This bit of nuttiness for cx25840 causes that module to correctly set up its video scaling. This is really a problem in the cx25840 module itself, but we work around it here. The problem has not been seen in ivtv because there VBI is supported and set up. We don't do VBI here (at least not yet) and thus we never attempted to even set it up. */ struct v4l2_format fmt; if (hdw->decoder_client_id != PVR2_CLIENT_ID_CX25840) { /* We're not using a cx25840 so don't enable the hack */ return; } pvr2_trace(PVR2_TRACE_INIT, "Module ID %u:" " Executing cx25840 VBI hack", hdw->decoder_client_id); memset(&fmt, 0, sizeof(fmt)); fmt.type = V4L2_BUF_TYPE_SLICED_VBI_CAPTURE; fmt.fmt.sliced.service_lines[0][21] = V4L2_SLICED_CAPTION_525; fmt.fmt.sliced.service_lines[1][21] = V4L2_SLICED_CAPTION_525; v4l2_device_call_all(&hdw->v4l2_dev, hdw->decoder_client_id, vbi, s_sliced_fmt, &fmt.fmt.sliced); } static int pvr2_hdw_load_subdev(struct pvr2_hdw *hdw, const struct pvr2_device_client_desc *cd) { const char *fname; unsigned char mid; struct v4l2_subdev *sd; unsigned int i2ccnt; const unsigned char *p; /* Arbitrary count - max # i2c addresses we will probe */ unsigned short i2caddr[25]; mid = cd->module_id; fname = (mid < ARRAY_SIZE(module_names)) ? module_names[mid] : NULL; if (!fname) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Module ID %u for device %s has no name?" " The driver might have a configuration problem.", mid, hdw->hdw_desc->description); return -EINVAL; } pvr2_trace(PVR2_TRACE_INIT, "Module ID %u (%s) for device %s being loaded...", mid, fname, hdw->hdw_desc->description); i2ccnt = pvr2_copy_i2c_addr_list(i2caddr, cd->i2c_address_list, ARRAY_SIZE(i2caddr)); if (!i2ccnt && ((p = (mid < ARRAY_SIZE(module_i2c_addresses)) ? module_i2c_addresses[mid] : NULL) != NULL)) { /* Second chance: Try default i2c address list */ i2ccnt = pvr2_copy_i2c_addr_list(i2caddr, p, ARRAY_SIZE(i2caddr)); if (i2ccnt) { pvr2_trace(PVR2_TRACE_INIT, "Module ID %u:" " Using default i2c address list", mid); } } if (!i2ccnt) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Module ID %u (%s) for device %s:" " No i2c addresses." " The driver might have a configuration problem.", mid, fname, hdw->hdw_desc->description); return -EINVAL; } if (i2ccnt == 1) { pvr2_trace(PVR2_TRACE_INIT, "Module ID %u:" " Setting up with specified i2c address 0x%x", mid, i2caddr[0]); sd = v4l2_i2c_new_subdev(&hdw->v4l2_dev, &hdw->i2c_adap, fname, i2caddr[0], NULL); } else { pvr2_trace(PVR2_TRACE_INIT, "Module ID %u:" " Setting up with address probe list", mid); sd = v4l2_i2c_new_subdev(&hdw->v4l2_dev, &hdw->i2c_adap, fname, 0, i2caddr); } if (!sd) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Module ID %u (%s) for device %s failed to load." " Possible missing sub-device kernel module or" " initialization failure within module.", mid, fname, hdw->hdw_desc->description); return -EIO; } /* Tag this sub-device instance with the module ID we know about. In other places we'll use that tag to determine if the instance requires special handling. */ sd->grp_id = mid; pvr2_trace(PVR2_TRACE_INFO, "Attached sub-driver %s", fname); /* client-specific setup... */ switch (mid) { case PVR2_CLIENT_ID_CX25840: case PVR2_CLIENT_ID_SAA7115: hdw->decoder_client_id = mid; break; default: break; } return 0; } static void pvr2_hdw_load_modules(struct pvr2_hdw *hdw) { unsigned int idx; const struct pvr2_string_table *cm; const struct pvr2_device_client_table *ct; int okFl = !0; cm = &hdw->hdw_desc->client_modules; for (idx = 0; idx < cm->cnt; idx++) { request_module(cm->lst[idx]); } ct = &hdw->hdw_desc->client_table; for (idx = 0; idx < ct->cnt; idx++) { if (pvr2_hdw_load_subdev(hdw, &ct->lst[idx]) < 0) okFl = 0; } if (!okFl) { hdw->flag_modulefail = !0; pvr2_hdw_render_useless(hdw); } } static void pvr2_hdw_setup_low(struct pvr2_hdw *hdw) { int ret; unsigned int idx; struct pvr2_ctrl *cptr; int reloadFl = 0; if (hdw->hdw_desc->fx2_firmware.cnt) { if (!reloadFl) { reloadFl = (hdw->usb_intf->cur_altsetting->desc.bNumEndpoints == 0); if (reloadFl) { pvr2_trace(PVR2_TRACE_INIT, "USB endpoint config looks strange" "; possibly firmware needs to be" " loaded"); } } if (!reloadFl) { reloadFl = !pvr2_hdw_check_firmware(hdw); if (reloadFl) { pvr2_trace(PVR2_TRACE_INIT, "Check for FX2 firmware failed" "; possibly firmware needs to be" " loaded"); } } if (reloadFl) { if (pvr2_upload_firmware1(hdw) != 0) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Failure uploading firmware1"); } return; } } hdw->fw1_state = FW1_STATE_OK; if (!pvr2_hdw_dev_ok(hdw)) return; hdw->force_dirty = !0; if (!hdw->hdw_desc->flag_no_powerup) { pvr2_hdw_cmd_powerup(hdw); if (!pvr2_hdw_dev_ok(hdw)) return; } /* Take the IR chip out of reset, if appropriate */ if (hdw->ir_scheme_active == PVR2_IR_SCHEME_ZILOG) { pvr2_issue_simple_cmd(hdw, FX2CMD_HCW_ZILOG_RESET | (1 << 8) | ((0) << 16)); } // This step MUST happen after the earlier powerup step. pvr2_i2c_core_init(hdw); if (!pvr2_hdw_dev_ok(hdw)) return; pvr2_hdw_load_modules(hdw); if (!pvr2_hdw_dev_ok(hdw)) return; v4l2_device_call_all(&hdw->v4l2_dev, 0, core, load_fw); for (idx = 0; idx < CTRLDEF_COUNT; idx++) { cptr = hdw->controls + idx; if (cptr->info->skip_init) continue; if (!cptr->info->set_value) continue; cptr->info->set_value(cptr,~0,cptr->info->default_value); } pvr2_hdw_cx25840_vbi_hack(hdw); /* Set up special default values for the television and radio frequencies here. It's not really important what these defaults are, but I set them to something usable in the Chicago area just to make driver testing a little easier. */ hdw->freqValTelevision = default_tv_freq; hdw->freqValRadio = default_radio_freq; // Do not use pvr2_reset_ctl_endpoints() here. It is not // thread-safe against the normal pvr2_send_request() mechanism. // (We should make it thread safe). if (hdw->hdw_desc->flag_has_hauppauge_rom) { ret = pvr2_hdw_get_eeprom_addr(hdw); if (!pvr2_hdw_dev_ok(hdw)) return; if (ret < 0) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Unable to determine location of eeprom," " skipping"); } else { hdw->eeprom_addr = ret; pvr2_eeprom_analyze(hdw); if (!pvr2_hdw_dev_ok(hdw)) return; } } else { hdw->tuner_type = hdw->hdw_desc->default_tuner_type; hdw->tuner_updated = !0; hdw->std_mask_eeprom = V4L2_STD_ALL; } if (hdw->serial_number) { idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1, "sn-%lu", hdw->serial_number); } else if (hdw->unit_number >= 0) { idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1, "unit-%c", hdw->unit_number + 'a'); } else { idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1, "unit-??"); } hdw->identifier[idx] = 0; pvr2_hdw_setup_std(hdw); if (!get_default_tuner_type(hdw)) { pvr2_trace(PVR2_TRACE_INIT, "pvr2_hdw_setup: Tuner type overridden to %d", hdw->tuner_type); } if (!pvr2_hdw_dev_ok(hdw)) return; if (hdw->hdw_desc->signal_routing_scheme == PVR2_ROUTING_SCHEME_GOTVIEW) { /* Ensure that GPIO 11 is set to output for GOTVIEW hardware. */ pvr2_hdw_gpio_chg_dir(hdw,(1 << 11),~0); } pvr2_hdw_commit_setup(hdw); hdw->vid_stream = pvr2_stream_create(); if (!pvr2_hdw_dev_ok(hdw)) return; pvr2_trace(PVR2_TRACE_INIT, "pvr2_hdw_setup: video stream is %p",hdw->vid_stream); if (hdw->vid_stream) { idx = get_default_error_tolerance(hdw); if (idx) { pvr2_trace(PVR2_TRACE_INIT, "pvr2_hdw_setup: video stream %p" " setting tolerance %u", hdw->vid_stream,idx); } pvr2_stream_setup(hdw->vid_stream,hdw->usb_dev, PVR2_VID_ENDPOINT,idx); } if (!pvr2_hdw_dev_ok(hdw)) return; hdw->flag_init_ok = !0; pvr2_hdw_state_sched(hdw); } /* Set up the structure and attempt to put the device into a usable state. This can be a time-consuming operation, which is why it is not done internally as part of the create() step. */ static void pvr2_hdw_setup(struct pvr2_hdw *hdw) { pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) begin",hdw); do { pvr2_hdw_setup_low(hdw); pvr2_trace(PVR2_TRACE_INIT, "pvr2_hdw_setup(hdw=%p) done, ok=%d init_ok=%d", hdw,pvr2_hdw_dev_ok(hdw),hdw->flag_init_ok); if (pvr2_hdw_dev_ok(hdw)) { if (hdw->flag_init_ok) { pvr2_trace( PVR2_TRACE_INFO, "Device initialization" " completed successfully."); break; } if (hdw->fw1_state == FW1_STATE_RELOAD) { pvr2_trace( PVR2_TRACE_INFO, "Device microcontroller firmware" " (re)loaded; it should now reset" " and reconnect."); break; } pvr2_trace( PVR2_TRACE_ERROR_LEGS, "Device initialization was not successful."); if (hdw->fw1_state == FW1_STATE_MISSING) { pvr2_trace( PVR2_TRACE_ERROR_LEGS, "Giving up since device" " microcontroller firmware" " appears to be missing."); break; } } if (hdw->flag_modulefail) { pvr2_trace( PVR2_TRACE_ERROR_LEGS, "***WARNING*** pvrusb2 driver initialization" " failed due to the failure of one or more" " sub-device kernel modules."); pvr2_trace( PVR2_TRACE_ERROR_LEGS, "You need to resolve the failing condition" " before this driver can function. There" " should be some earlier messages giving more" " information about the problem."); break; } if (procreload) { pvr2_trace( PVR2_TRACE_ERROR_LEGS, "Attempting pvrusb2 recovery by reloading" " primary firmware."); pvr2_trace( PVR2_TRACE_ERROR_LEGS, "If this works, device should disconnect" " and reconnect in a sane state."); hdw->fw1_state = FW1_STATE_UNKNOWN; pvr2_upload_firmware1(hdw); } else { pvr2_trace( PVR2_TRACE_ERROR_LEGS, "***WARNING*** pvrusb2 device hardware" " appears to be jammed" " and I can't clear it."); pvr2_trace( PVR2_TRACE_ERROR_LEGS, "You might need to power cycle" " the pvrusb2 device" " in order to recover."); } } while (0); pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) end",hdw); } /* Perform second stage initialization. Set callback pointer first so that we can avoid a possible initialization race (if the kernel thread runs before the callback has been set). */ int pvr2_hdw_initialize(struct pvr2_hdw *hdw, void (*callback_func)(void *), void *callback_data) { LOCK_TAKE(hdw->big_lock); do { if (hdw->flag_disconnected) { /* Handle a race here: If we're already disconnected by this point, then give up. If we get past this then we'll remain connected for the duration of initialization since the entire initialization sequence is now protected by the big_lock. */ break; } hdw->state_data = callback_data; hdw->state_func = callback_func; pvr2_hdw_setup(hdw); } while (0); LOCK_GIVE(hdw->big_lock); return hdw->flag_init_ok; } /* Create, set up, and return a structure for interacting with the underlying hardware. */ struct pvr2_hdw *pvr2_hdw_create(struct usb_interface *intf, const struct usb_device_id *devid) { unsigned int idx,cnt1,cnt2,m; struct pvr2_hdw *hdw = NULL; int valid_std_mask; struct pvr2_ctrl *cptr; struct usb_device *usb_dev; const struct pvr2_device_desc *hdw_desc; __u8 ifnum; struct v4l2_queryctrl qctrl; struct pvr2_ctl_info *ciptr; usb_dev = interface_to_usbdev(intf); hdw_desc = (const struct pvr2_device_desc *)(devid->driver_info); if (hdw_desc == NULL) { pvr2_trace(PVR2_TRACE_INIT, "pvr2_hdw_create:" " No device description pointer," " unable to continue."); pvr2_trace(PVR2_TRACE_INIT, "If you have a new device type," " please contact Mike Isely <isely@pobox.com>" " to get it included in the driver\n"); goto fail; } hdw = kzalloc(sizeof(*hdw),GFP_KERNEL); pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_create: hdw=%p, type \"%s\"", hdw,hdw_desc->description); pvr2_trace(PVR2_TRACE_INFO, "Hardware description: %s", hdw_desc->description); if (hdw_desc->flag_is_experimental) { pvr2_trace(PVR2_TRACE_INFO, "**********"); pvr2_trace(PVR2_TRACE_INFO, "WARNING: Support for this device (%s) is" " experimental.", hdw_desc->description); pvr2_trace(PVR2_TRACE_INFO, "Important functionality might not be" " entirely working."); pvr2_trace(PVR2_TRACE_INFO, "Please consider contacting the driver author to" " help with further stabilization of the driver."); pvr2_trace(PVR2_TRACE_INFO, "**********"); } if (!hdw) goto fail; init_timer(&hdw->quiescent_timer); hdw->quiescent_timer.data = (unsigned long)hdw; hdw->quiescent_timer.function = pvr2_hdw_quiescent_timeout; init_timer(&hdw->decoder_stabilization_timer); hdw->decoder_stabilization_timer.data = (unsigned long)hdw; hdw->decoder_stabilization_timer.function = pvr2_hdw_decoder_stabilization_timeout; init_timer(&hdw->encoder_wait_timer); hdw->encoder_wait_timer.data = (unsigned long)hdw; hdw->encoder_wait_timer.function = pvr2_hdw_encoder_wait_timeout; init_timer(&hdw->encoder_run_timer); hdw->encoder_run_timer.data = (unsigned long)hdw; hdw->encoder_run_timer.function = pvr2_hdw_encoder_run_timeout; hdw->master_state = PVR2_STATE_DEAD; init_waitqueue_head(&hdw->state_wait_data); hdw->tuner_signal_stale = !0; cx2341x_fill_defaults(&hdw->enc_ctl_state); /* Calculate which inputs are OK */ m = 0; if (hdw_desc->flag_has_analogtuner) m |= 1 << PVR2_CVAL_INPUT_TV; if (hdw_desc->digital_control_scheme != PVR2_DIGITAL_SCHEME_NONE) { m |= 1 << PVR2_CVAL_INPUT_DTV; } if (hdw_desc->flag_has_svideo) m |= 1 << PVR2_CVAL_INPUT_SVIDEO; if (hdw_desc->flag_has_composite) m |= 1 << PVR2_CVAL_INPUT_COMPOSITE; if (hdw_desc->flag_has_fmradio) m |= 1 << PVR2_CVAL_INPUT_RADIO; hdw->input_avail_mask = m; hdw->input_allowed_mask = hdw->input_avail_mask; /* If not a hybrid device, pathway_state never changes. So initialize it here to what it should forever be. */ if (!(hdw->input_avail_mask & (1 << PVR2_CVAL_INPUT_DTV))) { hdw->pathway_state = PVR2_PATHWAY_ANALOG; } else if (!(hdw->input_avail_mask & (1 << PVR2_CVAL_INPUT_TV))) { hdw->pathway_state = PVR2_PATHWAY_DIGITAL; } hdw->control_cnt = CTRLDEF_COUNT; hdw->control_cnt += MPEGDEF_COUNT; hdw->controls = kzalloc(sizeof(struct pvr2_ctrl) * hdw->control_cnt, GFP_KERNEL); if (!hdw->controls) goto fail; hdw->hdw_desc = hdw_desc; hdw->ir_scheme_active = hdw->hdw_desc->ir_scheme; for (idx = 0; idx < hdw->control_cnt; idx++) { cptr = hdw->controls + idx; cptr->hdw = hdw; } for (idx = 0; idx < 32; idx++) { hdw->std_mask_ptrs[idx] = hdw->std_mask_names[idx]; } for (idx = 0; idx < CTRLDEF_COUNT; idx++) { cptr = hdw->controls + idx; cptr->info = control_defs+idx; } /* Ensure that default input choice is a valid one. */ m = hdw->input_avail_mask; if (m) for (idx = 0; idx < (sizeof(m) << 3); idx++) { if (!((1 << idx) & m)) continue; hdw->input_val = idx; break; } /* Define and configure additional controls from cx2341x module. */ hdw->mpeg_ctrl_info = kcalloc(MPEGDEF_COUNT, sizeof(*(hdw->mpeg_ctrl_info)), GFP_KERNEL); if (!hdw->mpeg_ctrl_info) goto fail; for (idx = 0; idx < MPEGDEF_COUNT; idx++) { cptr = hdw->controls + idx + CTRLDEF_COUNT; ciptr = &(hdw->mpeg_ctrl_info[idx].info); ciptr->desc = hdw->mpeg_ctrl_info[idx].desc; ciptr->name = mpeg_ids[idx].strid; ciptr->v4l_id = mpeg_ids[idx].id; ciptr->skip_init = !0; ciptr->get_value = ctrl_cx2341x_get; ciptr->get_v4lflags = ctrl_cx2341x_getv4lflags; ciptr->is_dirty = ctrl_cx2341x_is_dirty; if (!idx) ciptr->clear_dirty = ctrl_cx2341x_clear_dirty; qctrl.id = ciptr->v4l_id; cx2341x_ctrl_query(&hdw->enc_ctl_state,&qctrl); if (!(qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY)) { ciptr->set_value = ctrl_cx2341x_set; } strncpy(hdw->mpeg_ctrl_info[idx].desc,qctrl.name, PVR2_CTLD_INFO_DESC_SIZE); hdw->mpeg_ctrl_info[idx].desc[PVR2_CTLD_INFO_DESC_SIZE-1] = 0; ciptr->default_value = qctrl.default_value; switch (qctrl.type) { default: case V4L2_CTRL_TYPE_INTEGER: ciptr->type = pvr2_ctl_int; ciptr->def.type_int.min_value = qctrl.minimum; ciptr->def.type_int.max_value = qctrl.maximum; break; case V4L2_CTRL_TYPE_BOOLEAN: ciptr->type = pvr2_ctl_bool; break; case V4L2_CTRL_TYPE_MENU: ciptr->type = pvr2_ctl_enum; ciptr->def.type_enum.value_names = cx2341x_ctrl_get_menu(&hdw->enc_ctl_state, ciptr->v4l_id); for (cnt1 = 0; ciptr->def.type_enum.value_names[cnt1] != NULL; cnt1++) { } ciptr->def.type_enum.count = cnt1; break; } cptr->info = ciptr; } // Initialize control data regarding video standard masks valid_std_mask = pvr2_std_get_usable(); for (idx = 0; idx < 32; idx++) { if (!(valid_std_mask & (1 << idx))) continue; cnt1 = pvr2_std_id_to_str( hdw->std_mask_names[idx], sizeof(hdw->std_mask_names[idx])-1, 1 << idx); hdw->std_mask_names[idx][cnt1] = 0; } cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDAVAIL); if (cptr) { memcpy(&hdw->std_info_avail,cptr->info, sizeof(hdw->std_info_avail)); cptr->info = &hdw->std_info_avail; hdw->std_info_avail.def.type_bitmask.bit_names = hdw->std_mask_ptrs; hdw->std_info_avail.def.type_bitmask.valid_bits = valid_std_mask; } cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDCUR); if (cptr) { memcpy(&hdw->std_info_cur,cptr->info, sizeof(hdw->std_info_cur)); cptr->info = &hdw->std_info_cur; hdw->std_info_cur.def.type_bitmask.bit_names = hdw->std_mask_ptrs; hdw->std_info_cur.def.type_bitmask.valid_bits = valid_std_mask; } cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDDETECT); if (cptr) { memcpy(&hdw->std_info_detect,cptr->info, sizeof(hdw->std_info_detect)); cptr->info = &hdw->std_info_detect; hdw->std_info_detect.def.type_bitmask.bit_names = hdw->std_mask_ptrs; hdw->std_info_detect.def.type_bitmask.valid_bits = valid_std_mask; } hdw->cropcap_stale = !0; hdw->eeprom_addr = -1; hdw->unit_number = -1; hdw->v4l_minor_number_video = -1; hdw->v4l_minor_number_vbi = -1; hdw->v4l_minor_number_radio = -1; hdw->ctl_write_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL); if (!hdw->ctl_write_buffer) goto fail; hdw->ctl_read_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL); if (!hdw->ctl_read_buffer) goto fail; hdw->ctl_write_urb = usb_alloc_urb(0,GFP_KERNEL); if (!hdw->ctl_write_urb) goto fail; hdw->ctl_read_urb = usb_alloc_urb(0,GFP_KERNEL); if (!hdw->ctl_read_urb) goto fail; if (v4l2_device_register(&intf->dev, &hdw->v4l2_dev) != 0) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Error registering with v4l core, giving up"); goto fail; } mutex_lock(&pvr2_unit_mtx); do { for (idx = 0; idx < PVR_NUM; idx++) { if (unit_pointers[idx]) continue; hdw->unit_number = idx; unit_pointers[idx] = hdw; break; } } while (0); mutex_unlock(&pvr2_unit_mtx); cnt1 = 0; cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"pvrusb2"); cnt1 += cnt2; if (hdw->unit_number >= 0) { cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"_%c", ('a' + hdw->unit_number)); cnt1 += cnt2; } if (cnt1 >= sizeof(hdw->name)) cnt1 = sizeof(hdw->name)-1; hdw->name[cnt1] = 0; hdw->workqueue = create_singlethread_workqueue(hdw->name); INIT_WORK(&hdw->workpoll,pvr2_hdw_worker_poll); pvr2_trace(PVR2_TRACE_INIT,"Driver unit number is %d, name is %s", hdw->unit_number,hdw->name); hdw->tuner_type = -1; hdw->flag_ok = !0; hdw->usb_intf = intf; hdw->usb_dev = usb_dev; usb_make_path(hdw->usb_dev, hdw->bus_info, sizeof(hdw->bus_info)); ifnum = hdw->usb_intf->cur_altsetting->desc.bInterfaceNumber; usb_set_interface(hdw->usb_dev,ifnum,0); mutex_init(&hdw->ctl_lock_mutex); mutex_init(&hdw->big_lock_mutex); return hdw; fail: if (hdw) { del_timer_sync(&hdw->quiescent_timer); del_timer_sync(&hdw->decoder_stabilization_timer); del_timer_sync(&hdw->encoder_run_timer); del_timer_sync(&hdw->encoder_wait_timer); if (hdw->workqueue) { flush_workqueue(hdw->workqueue); destroy_workqueue(hdw->workqueue); hdw->workqueue = NULL; } usb_free_urb(hdw->ctl_read_urb); usb_free_urb(hdw->ctl_write_urb); kfree(hdw->ctl_read_buffer); kfree(hdw->ctl_write_buffer); kfree(hdw->controls); kfree(hdw->mpeg_ctrl_info); kfree(hdw); } return NULL; } /* Remove _all_ associations between this driver and the underlying USB layer. */ static void pvr2_hdw_remove_usb_stuff(struct pvr2_hdw *hdw) { if (hdw->flag_disconnected) return; pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_remove_usb_stuff: hdw=%p",hdw); if (hdw->ctl_read_urb) { usb_kill_urb(hdw->ctl_read_urb); usb_free_urb(hdw->ctl_read_urb); hdw->ctl_read_urb = NULL; } if (hdw->ctl_write_urb) { usb_kill_urb(hdw->ctl_write_urb); usb_free_urb(hdw->ctl_write_urb); hdw->ctl_write_urb = NULL; } if (hdw->ctl_read_buffer) { kfree(hdw->ctl_read_buffer); hdw->ctl_read_buffer = NULL; } if (hdw->ctl_write_buffer) { kfree(hdw->ctl_write_buffer); hdw->ctl_write_buffer = NULL; } hdw->flag_disconnected = !0; /* If we don't do this, then there will be a dangling struct device reference to our disappearing device persisting inside the V4L core... */ v4l2_device_disconnect(&hdw->v4l2_dev); hdw->usb_dev = NULL; hdw->usb_intf = NULL; pvr2_hdw_render_useless(hdw); } /* Destroy hardware interaction structure */ void pvr2_hdw_destroy(struct pvr2_hdw *hdw) { if (!hdw) return; pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_destroy: hdw=%p",hdw); if (hdw->workqueue) { flush_workqueue(hdw->workqueue); destroy_workqueue(hdw->workqueue); hdw->workqueue = NULL; } del_timer_sync(&hdw->quiescent_timer); del_timer_sync(&hdw->decoder_stabilization_timer); del_timer_sync(&hdw->encoder_run_timer); del_timer_sync(&hdw->encoder_wait_timer); if (hdw->fw_buffer) { kfree(hdw->fw_buffer); hdw->fw_buffer = NULL; } if (hdw->vid_stream) { pvr2_stream_destroy(hdw->vid_stream); hdw->vid_stream = NULL; } pvr2_i2c_core_done(hdw); v4l2_device_unregister(&hdw->v4l2_dev); pvr2_hdw_remove_usb_stuff(hdw); mutex_lock(&pvr2_unit_mtx); do { if ((hdw->unit_number >= 0) && (hdw->unit_number < PVR_NUM) && (unit_pointers[hdw->unit_number] == hdw)) { unit_pointers[hdw->unit_number] = NULL; } } while (0); mutex_unlock(&pvr2_unit_mtx); kfree(hdw->controls); kfree(hdw->mpeg_ctrl_info); kfree(hdw); } int pvr2_hdw_dev_ok(struct pvr2_hdw *hdw) { return (hdw && hdw->flag_ok); } /* Called when hardware has been unplugged */ void pvr2_hdw_disconnect(struct pvr2_hdw *hdw) { pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_disconnect(hdw=%p)",hdw); LOCK_TAKE(hdw->big_lock); LOCK_TAKE(hdw->ctl_lock); pvr2_hdw_remove_usb_stuff(hdw); LOCK_GIVE(hdw->ctl_lock); LOCK_GIVE(hdw->big_lock); } /* Get the number of defined controls */ unsigned int pvr2_hdw_get_ctrl_count(struct pvr2_hdw *hdw) { return hdw->control_cnt; } /* Retrieve a control handle given its index (0..count-1) */ struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_index(struct pvr2_hdw *hdw, unsigned int idx) { if (idx >= hdw->control_cnt) return NULL; return hdw->controls + idx; } /* Retrieve a control handle given its index (0..count-1) */ struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_id(struct pvr2_hdw *hdw, unsigned int ctl_id) { struct pvr2_ctrl *cptr; unsigned int idx; int i; /* This could be made a lot more efficient, but for now... */ for (idx = 0; idx < hdw->control_cnt; idx++) { cptr = hdw->controls + idx; i = cptr->info->internal_id; if (i && (i == ctl_id)) return cptr; } return NULL; } /* Given a V4L ID, retrieve the control structure associated with it. */ struct pvr2_ctrl *pvr2_hdw_get_ctrl_v4l(struct pvr2_hdw *hdw,unsigned int ctl_id) { struct pvr2_ctrl *cptr; unsigned int idx; int i; /* This could be made a lot more efficient, but for now... */ for (idx = 0; idx < hdw->control_cnt; idx++) { cptr = hdw->controls + idx; i = cptr->info->v4l_id; if (i && (i == ctl_id)) return cptr; } return NULL; } /* Given a V4L ID for its immediate predecessor, retrieve the control structure associated with it. */ struct pvr2_ctrl *pvr2_hdw_get_ctrl_nextv4l(struct pvr2_hdw *hdw, unsigned int ctl_id) { struct pvr2_ctrl *cptr,*cp2; unsigned int idx; int i; /* This could be made a lot more efficient, but for now... */ cp2 = NULL; for (idx = 0; idx < hdw->control_cnt; idx++) { cptr = hdw->controls + idx; i = cptr->info->v4l_id; if (!i) continue; if (i <= ctl_id) continue; if (cp2 && (cp2->info->v4l_id < i)) continue; cp2 = cptr; } return cp2; return NULL; } static const char *get_ctrl_typename(enum pvr2_ctl_type tp) { switch (tp) { case pvr2_ctl_int: return "integer"; case pvr2_ctl_enum: return "enum"; case pvr2_ctl_bool: return "boolean"; case pvr2_ctl_bitmask: return "bitmask"; } return ""; } static void pvr2_subdev_set_control(struct pvr2_hdw *hdw, int id, const char *name, int val) { struct v4l2_control ctrl; pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 %s=%d", name, val); memset(&ctrl, 0, sizeof(ctrl)); ctrl.id = id; ctrl.value = val; v4l2_device_call_all(&hdw->v4l2_dev, 0, core, s_ctrl, &ctrl); } #define PVR2_SUBDEV_SET_CONTROL(hdw, id, lab) \ if ((hdw)->lab##_dirty || (hdw)->force_dirty) { \ pvr2_subdev_set_control(hdw, id, #lab, (hdw)->lab##_val); \ } v4l2_std_id pvr2_hdw_get_detected_std(struct pvr2_hdw *hdw) { v4l2_std_id std; std = (v4l2_std_id)hdw->std_mask_avail; v4l2_device_call_all(&hdw->v4l2_dev, 0, video, querystd, &std); return std; } /* Execute whatever commands are required to update the state of all the sub-devices so that they match our current control values. */ static void pvr2_subdev_update(struct pvr2_hdw *hdw) { struct v4l2_subdev *sd; unsigned int id; pvr2_subdev_update_func fp; pvr2_trace(PVR2_TRACE_CHIPS, "subdev update..."); if (hdw->tuner_updated || hdw->force_dirty) { struct tuner_setup setup; pvr2_trace(PVR2_TRACE_CHIPS, "subdev tuner set_type(%d)", hdw->tuner_type); if (((int)(hdw->tuner_type)) >= 0) { memset(&setup, 0, sizeof(setup)); setup.addr = ADDR_UNSET; setup.type = hdw->tuner_type; setup.mode_mask = T_RADIO | T_ANALOG_TV; v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, s_type_addr, &setup); } } if (hdw->input_dirty || hdw->std_dirty || hdw->force_dirty) { pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_standard"); if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) { v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, s_radio); } else { v4l2_std_id vs; vs = hdw->std_mask_cur; v4l2_device_call_all(&hdw->v4l2_dev, 0, core, s_std, vs); pvr2_hdw_cx25840_vbi_hack(hdw); } hdw->tuner_signal_stale = !0; hdw->cropcap_stale = !0; } PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_BRIGHTNESS, brightness); PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_CONTRAST, contrast); PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_SATURATION, saturation); PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_HUE, hue); PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_MUTE, mute); PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_VOLUME, volume); PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_BALANCE, balance); PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_BASS, bass); PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_TREBLE, treble); if (hdw->input_dirty || hdw->audiomode_dirty || hdw->force_dirty) { struct v4l2_tuner vt; memset(&vt, 0, sizeof(vt)); vt.type = (hdw->input_val == PVR2_CVAL_INPUT_RADIO) ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV; vt.audmode = hdw->audiomode_val; v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, s_tuner, &vt); } if (hdw->freqDirty || hdw->force_dirty) { unsigned long fv; struct v4l2_frequency freq; fv = pvr2_hdw_get_cur_freq(hdw); pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_freq(%lu)", fv); if (hdw->tuner_signal_stale) pvr2_hdw_status_poll(hdw); memset(&freq, 0, sizeof(freq)); if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) { /* ((fv * 1000) / 62500) */ freq.frequency = (fv * 2) / 125; } else { freq.frequency = fv / 62500; } /* tuner-core currently doesn't seem to care about this, but let's set it anyway for completeness. */ if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) { freq.type = V4L2_TUNER_RADIO; } else { freq.type = V4L2_TUNER_ANALOG_TV; } freq.tuner = 0; v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, s_frequency, &freq); } if (hdw->res_hor_dirty || hdw->res_ver_dirty || hdw->force_dirty) { struct v4l2_mbus_framefmt fmt; memset(&fmt, 0, sizeof(fmt)); fmt.width = hdw->res_hor_val; fmt.height = hdw->res_ver_val; fmt.code = V4L2_MBUS_FMT_FIXED; pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_size(%dx%d)", fmt.width, fmt.height); v4l2_device_call_all(&hdw->v4l2_dev, 0, video, s_mbus_fmt, &fmt); } if (hdw->srate_dirty || hdw->force_dirty) { u32 val; pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_audio %d", hdw->srate_val); switch (hdw->srate_val) { default: case V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000: val = 48000; break; case V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100: val = 44100; break; case V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000: val = 32000; break; } v4l2_device_call_all(&hdw->v4l2_dev, 0, audio, s_clock_freq, val); } /* Unable to set crop parameters; there is apparently no equivalent for VIDIOC_S_CROP */ v4l2_device_for_each_subdev(sd, &hdw->v4l2_dev) { id = sd->grp_id; if (id >= ARRAY_SIZE(pvr2_module_update_functions)) continue; fp = pvr2_module_update_functions[id]; if (!fp) continue; (*fp)(hdw, sd); } if (hdw->tuner_signal_stale || hdw->cropcap_stale) { pvr2_hdw_status_poll(hdw); } } /* Figure out if we need to commit control changes. If so, mark internal state flags to indicate this fact and return true. Otherwise do nothing else and return false. */ static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw) { unsigned int idx; struct pvr2_ctrl *cptr; int value; int commit_flag = hdw->force_dirty; char buf[100]; unsigned int bcnt,ccnt; for (idx = 0; idx < hdw->control_cnt; idx++) { cptr = hdw->controls + idx; if (!cptr->info->is_dirty) continue; if (!cptr->info->is_dirty(cptr)) continue; commit_flag = !0; if (!(pvrusb2_debug & PVR2_TRACE_CTL)) continue; bcnt = scnprintf(buf,sizeof(buf),"\"%s\" <-- ", cptr->info->name); value = 0; cptr->info->get_value(cptr,&value); pvr2_ctrl_value_to_sym_internal(cptr,~0,value, buf+bcnt, sizeof(buf)-bcnt,&ccnt); bcnt += ccnt; bcnt += scnprintf(buf+bcnt,sizeof(buf)-bcnt," <%s>", get_ctrl_typename(cptr->info->type)); pvr2_trace(PVR2_TRACE_CTL, "/*--TRACE_COMMIT--*/ %.*s", bcnt,buf); } if (!commit_flag) { /* Nothing has changed */ return 0; } hdw->state_pipeline_config = 0; trace_stbit("state_pipeline_config",hdw->state_pipeline_config); pvr2_hdw_state_sched(hdw); return !0; } /* Perform all operations needed to commit all control changes. This must be performed in synchronization with the pipeline state and is thus expected to be called as part of the driver's worker thread. Return true if commit successful, otherwise return false to indicate that commit isn't possible at this time. */ static int pvr2_hdw_commit_execute(struct pvr2_hdw *hdw) { unsigned int idx; struct pvr2_ctrl *cptr; int disruptive_change; if (hdw->input_dirty && hdw->state_pathway_ok && (((hdw->input_val == PVR2_CVAL_INPUT_DTV) ? PVR2_PATHWAY_DIGITAL : PVR2_PATHWAY_ANALOG) != hdw->pathway_state)) { /* Change of mode being asked for... */ hdw->state_pathway_ok = 0; trace_stbit("state_pathway_ok", hdw->state_pathway_ok); } if (!hdw->state_pathway_ok) { /* Can't commit anything until pathway is ok. */ return 0; } /* Handle some required side effects when the video standard is changed.... */ if (hdw->std_dirty) { int nvres; int gop_size; if (hdw->std_mask_cur & V4L2_STD_525_60) { nvres = 480; gop_size = 15; } else { nvres = 576; gop_size = 12; } /* Rewrite the vertical resolution to be appropriate to the video standard that has been selected. */ if (nvres != hdw->res_ver_val) { hdw->res_ver_val = nvres; hdw->res_ver_dirty = !0; } /* Rewrite the GOP size to be appropriate to the video standard that has been selected. */ if (gop_size != hdw->enc_ctl_state.video_gop_size) { struct v4l2_ext_controls cs; struct v4l2_ext_control c1; memset(&cs, 0, sizeof(cs)); memset(&c1, 0, sizeof(c1)); cs.controls = &c1; cs.count = 1; c1.id = V4L2_CID_MPEG_VIDEO_GOP_SIZE; c1.value = gop_size; cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs, VIDIOC_S_EXT_CTRLS); } } /* The broadcast decoder can only scale down, so if * res_*_dirty && crop window < output format ==> enlarge crop. * * The mpeg encoder receives fields of res_hor_val dots and * res_ver_val halflines. Limits: hor<=720, ver<=576. */ if (hdw->res_hor_dirty && hdw->cropw_val < hdw->res_hor_val) { hdw->cropw_val = hdw->res_hor_val; hdw->cropw_dirty = !0; } else if (hdw->cropw_dirty) { hdw->res_hor_dirty = !0; /* must rescale */ hdw->res_hor_val = min(720, hdw->cropw_val); } if (hdw->res_ver_dirty && hdw->croph_val < hdw->res_ver_val) { hdw->croph_val = hdw->res_ver_val; hdw->croph_dirty = !0; } else if (hdw->croph_dirty) { int nvres = hdw->std_mask_cur & V4L2_STD_525_60 ? 480 : 576; hdw->res_ver_dirty = !0; hdw->res_ver_val = min(nvres, hdw->croph_val); } /* If any of the below has changed, then we can't do the update while the pipeline is running. Pipeline must be paused first and decoder -> encoder connection be made quiescent before we can proceed. */ disruptive_change = (hdw->std_dirty || hdw->enc_unsafe_stale || hdw->srate_dirty || hdw->res_ver_dirty || hdw->res_hor_dirty || hdw->cropw_dirty || hdw->croph_dirty || hdw->input_dirty || (hdw->active_stream_type != hdw->desired_stream_type)); if (disruptive_change && !hdw->state_pipeline_idle) { /* Pipeline is not idle; we can't proceed. Arrange to cause pipeline to stop so that we can try this again later.... */ hdw->state_pipeline_pause = !0; return 0; } if (hdw->srate_dirty) { /* Write new sample rate into control structure since * the master copy is stale. We must track srate * separate from the mpeg control structure because * other logic also uses this value. */ struct v4l2_ext_controls cs; struct v4l2_ext_control c1; memset(&cs,0,sizeof(cs)); memset(&c1,0,sizeof(c1)); cs.controls = &c1; cs.count = 1; c1.id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ; c1.value = hdw->srate_val; cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs,VIDIOC_S_EXT_CTRLS); } if (hdw->active_stream_type != hdw->desired_stream_type) { /* Handle any side effects of stream config here */ hdw->active_stream_type = hdw->desired_stream_type; } if (hdw->hdw_desc->signal_routing_scheme == PVR2_ROUTING_SCHEME_GOTVIEW) { u32 b; /* Handle GOTVIEW audio switching */ pvr2_hdw_gpio_get_out(hdw,&b); if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) { /* Set GPIO 11 */ pvr2_hdw_gpio_chg_out(hdw,(1 << 11),~0); } else { /* Clear GPIO 11 */ pvr2_hdw_gpio_chg_out(hdw,(1 << 11),0); } } /* Check and update state for all sub-devices. */ pvr2_subdev_update(hdw); hdw->tuner_updated = 0; hdw->force_dirty = 0; for (idx = 0; idx < hdw->control_cnt; idx++) { cptr = hdw->controls + idx; if (!cptr->info->clear_dirty) continue; cptr->info->clear_dirty(cptr); } if ((hdw->pathway_state == PVR2_PATHWAY_ANALOG) && hdw->state_encoder_run) { /* If encoder isn't running or it can't be touched, then this will get worked out later when we start the encoder. */ if (pvr2_encoder_adjust(hdw) < 0) return !0; } hdw->state_pipeline_config = !0; /* Hardware state may have changed in a way to cause the cropping capabilities to have changed. So mark it stale, which will cause a later re-fetch. */ trace_stbit("state_pipeline_config",hdw->state_pipeline_config); return !0; } int pvr2_hdw_commit_ctl(struct pvr2_hdw *hdw) { int fl; LOCK_TAKE(hdw->big_lock); fl = pvr2_hdw_commit_setup(hdw); LOCK_GIVE(hdw->big_lock); if (!fl) return 0; return pvr2_hdw_wait(hdw,0); } static void pvr2_hdw_worker_poll(struct work_struct *work) { int fl = 0; struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,workpoll); LOCK_TAKE(hdw->big_lock); do { fl = pvr2_hdw_state_eval(hdw); } while (0); LOCK_GIVE(hdw->big_lock); if (fl && hdw->state_func) { hdw->state_func(hdw->state_data); } } static int pvr2_hdw_wait(struct pvr2_hdw *hdw,int state) { return wait_event_interruptible( hdw->state_wait_data, (hdw->state_stale == 0) && (!state || (hdw->master_state != state))); } /* Return name for this driver instance */ const char *pvr2_hdw_get_driver_name(struct pvr2_hdw *hdw) { return hdw->name; } const char *pvr2_hdw_get_desc(struct pvr2_hdw *hdw) { return hdw->hdw_desc->description; } const char *pvr2_hdw_get_type(struct pvr2_hdw *hdw) { return hdw->hdw_desc->shortname; } int pvr2_hdw_is_hsm(struct pvr2_hdw *hdw) { int result; LOCK_TAKE(hdw->ctl_lock); do { hdw->cmd_buffer[0] = FX2CMD_GET_USB_SPEED; result = pvr2_send_request(hdw, hdw->cmd_buffer,1, hdw->cmd_buffer,1); if (result < 0) break; result = (hdw->cmd_buffer[0] != 0); } while(0); LOCK_GIVE(hdw->ctl_lock); return result; } /* Execute poll of tuner status */ void pvr2_hdw_execute_tuner_poll(struct pvr2_hdw *hdw) { LOCK_TAKE(hdw->big_lock); do { pvr2_hdw_status_poll(hdw); } while (0); LOCK_GIVE(hdw->big_lock); } static int pvr2_hdw_check_cropcap(struct pvr2_hdw *hdw) { if (!hdw->cropcap_stale) { return 0; } pvr2_hdw_status_poll(hdw); if (hdw->cropcap_stale) { return -EIO; } return 0; } /* Return information about cropping capabilities */ int pvr2_hdw_get_cropcap(struct pvr2_hdw *hdw, struct v4l2_cropcap *pp) { int stat = 0; LOCK_TAKE(hdw->big_lock); stat = pvr2_hdw_check_cropcap(hdw); if (!stat) { memcpy(pp, &hdw->cropcap_info, sizeof(hdw->cropcap_info)); } LOCK_GIVE(hdw->big_lock); return stat; } /* Return information about the tuner */ int pvr2_hdw_get_tuner_status(struct pvr2_hdw *hdw,struct v4l2_tuner *vtp) { LOCK_TAKE(hdw->big_lock); do { if (hdw->tuner_signal_stale) { pvr2_hdw_status_poll(hdw); } memcpy(vtp,&hdw->tuner_signal_info,sizeof(struct v4l2_tuner)); } while (0); LOCK_GIVE(hdw->big_lock); return 0; } /* Get handle to video output stream */ struct pvr2_stream *pvr2_hdw_get_video_stream(struct pvr2_hdw *hp) { return hp->vid_stream; } void pvr2_hdw_trigger_module_log(struct pvr2_hdw *hdw) { int nr = pvr2_hdw_get_unit_number(hdw); LOCK_TAKE(hdw->big_lock); do { printk(KERN_INFO "pvrusb2: ================= START STATUS CARD #%d =================\n", nr); v4l2_device_call_all(&hdw->v4l2_dev, 0, core, log_status); pvr2_trace(PVR2_TRACE_INFO,"cx2341x config:"); cx2341x_log_status(&hdw->enc_ctl_state, "pvrusb2"); pvr2_hdw_state_log_state(hdw); printk(KERN_INFO "pvrusb2: ================== END STATUS CARD #%d ==================\n", nr); } while (0); LOCK_GIVE(hdw->big_lock); } /* Grab EEPROM contents, needed for direct method. */ #define EEPROM_SIZE 8192 #define trace_eeprom(...) pvr2_trace(PVR2_TRACE_EEPROM,__VA_ARGS__) static u8 *pvr2_full_eeprom_fetch(struct pvr2_hdw *hdw) { struct i2c_msg msg[2]; u8 *eeprom; u8 iadd[2]; u8 addr; u16 eepromSize; unsigned int offs; int ret; int mode16 = 0; unsigned pcnt,tcnt; eeprom = kmalloc(EEPROM_SIZE,GFP_KERNEL); if (!eeprom) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Failed to allocate memory" " required to read eeprom"); return NULL; } trace_eeprom("Value for eeprom addr from controller was 0x%x", hdw->eeprom_addr); addr = hdw->eeprom_addr; /* Seems that if the high bit is set, then the *real* eeprom address is shifted right now bit position (noticed this in newer PVR USB2 hardware) */ if (addr & 0x80) addr >>= 1; /* FX2 documentation states that a 16bit-addressed eeprom is expected if the I2C address is an odd number (yeah, this is strange but it's what they do) */ mode16 = (addr & 1); eepromSize = (mode16 ? EEPROM_SIZE : 256); trace_eeprom("Examining %d byte eeprom at location 0x%x" " using %d bit addressing",eepromSize,addr, mode16 ? 16 : 8); msg[0].addr = addr; msg[0].flags = 0; msg[0].len = mode16 ? 2 : 1; msg[0].buf = iadd; msg[1].addr = addr; msg[1].flags = I2C_M_RD; /* We have to do the actual eeprom data fetch ourselves, because (1) we're only fetching part of the eeprom, and (2) if we were getting the whole thing our I2C driver can't grab it in one pass - which is what tveeprom is otherwise going to attempt */ memset(eeprom,0,EEPROM_SIZE); for (tcnt = 0; tcnt < EEPROM_SIZE; tcnt += pcnt) { pcnt = 16; if (pcnt + tcnt > EEPROM_SIZE) pcnt = EEPROM_SIZE-tcnt; offs = tcnt + (eepromSize - EEPROM_SIZE); if (mode16) { iadd[0] = offs >> 8; iadd[1] = offs; } else { iadd[0] = offs; } msg[1].len = pcnt; msg[1].buf = eeprom+tcnt; if ((ret = i2c_transfer(&hdw->i2c_adap, msg,ARRAY_SIZE(msg))) != 2) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "eeprom fetch set offs err=%d",ret); kfree(eeprom); return NULL; } } return eeprom; } void pvr2_hdw_cpufw_set_enabled(struct pvr2_hdw *hdw, int mode, int enable_flag) { int ret; u16 address; unsigned int pipe; LOCK_TAKE(hdw->big_lock); do { if ((hdw->fw_buffer == NULL) == !enable_flag) break; if (!enable_flag) { pvr2_trace(PVR2_TRACE_FIRMWARE, "Cleaning up after CPU firmware fetch"); kfree(hdw->fw_buffer); hdw->fw_buffer = NULL; hdw->fw_size = 0; if (hdw->fw_cpu_flag) { /* Now release the CPU. It will disconnect and reconnect later. */ pvr2_hdw_cpureset_assert(hdw,0); } break; } hdw->fw_cpu_flag = (mode != 2); if (hdw->fw_cpu_flag) { hdw->fw_size = (mode == 1) ? 0x4000 : 0x2000; pvr2_trace(PVR2_TRACE_FIRMWARE, "Preparing to suck out CPU firmware" " (size=%u)", hdw->fw_size); hdw->fw_buffer = kzalloc(hdw->fw_size,GFP_KERNEL); if (!hdw->fw_buffer) { hdw->fw_size = 0; break; } /* We have to hold the CPU during firmware upload. */ pvr2_hdw_cpureset_assert(hdw,1); /* download the firmware from address 0000-1fff in 2048 (=0x800) bytes chunk. */ pvr2_trace(PVR2_TRACE_FIRMWARE, "Grabbing CPU firmware"); pipe = usb_rcvctrlpipe(hdw->usb_dev, 0); for(address = 0; address < hdw->fw_size; address += 0x800) { ret = usb_control_msg(hdw->usb_dev,pipe, 0xa0,0xc0, address,0, hdw->fw_buffer+address, 0x800,HZ); if (ret < 0) break; } pvr2_trace(PVR2_TRACE_FIRMWARE, "Done grabbing CPU firmware"); } else { pvr2_trace(PVR2_TRACE_FIRMWARE, "Sucking down EEPROM contents"); hdw->fw_buffer = pvr2_full_eeprom_fetch(hdw); if (!hdw->fw_buffer) { pvr2_trace(PVR2_TRACE_FIRMWARE, "EEPROM content suck failed."); break; } hdw->fw_size = EEPROM_SIZE; pvr2_trace(PVR2_TRACE_FIRMWARE, "Done sucking down EEPROM contents"); } } while (0); LOCK_GIVE(hdw->big_lock); } /* Return true if we're in a mode for retrieval CPU firmware */ int pvr2_hdw_cpufw_get_enabled(struct pvr2_hdw *hdw) { return hdw->fw_buffer != NULL; } int pvr2_hdw_cpufw_get(struct pvr2_hdw *hdw,unsigned int offs, char *buf,unsigned int cnt) { int ret = -EINVAL; LOCK_TAKE(hdw->big_lock); do { if (!buf) break; if (!cnt) break; if (!hdw->fw_buffer) { ret = -EIO; break; } if (offs >= hdw->fw_size) { pvr2_trace(PVR2_TRACE_FIRMWARE, "Read firmware data offs=%d EOF", offs); ret = 0; break; } if (offs + cnt > hdw->fw_size) cnt = hdw->fw_size - offs; memcpy(buf,hdw->fw_buffer+offs,cnt); pvr2_trace(PVR2_TRACE_FIRMWARE, "Read firmware data offs=%d cnt=%d", offs,cnt); ret = cnt; } while (0); LOCK_GIVE(hdw->big_lock); return ret; } int pvr2_hdw_v4l_get_minor_number(struct pvr2_hdw *hdw, enum pvr2_v4l_type index) { switch (index) { case pvr2_v4l_type_video: return hdw->v4l_minor_number_video; case pvr2_v4l_type_vbi: return hdw->v4l_minor_number_vbi; case pvr2_v4l_type_radio: return hdw->v4l_minor_number_radio; default: return -1; } } /* Store a v4l minor device number */ void pvr2_hdw_v4l_store_minor_number(struct pvr2_hdw *hdw, enum pvr2_v4l_type index,int v) { switch (index) { case pvr2_v4l_type_video: hdw->v4l_minor_number_video = v;break; case pvr2_v4l_type_vbi: hdw->v4l_minor_number_vbi = v;break; case pvr2_v4l_type_radio: hdw->v4l_minor_number_radio = v;break; default: break; } } static void pvr2_ctl_write_complete(struct urb *urb) { struct pvr2_hdw *hdw = urb->context; hdw->ctl_write_pend_flag = 0; if (hdw->ctl_read_pend_flag) return; complete(&hdw->ctl_done); } static void pvr2_ctl_read_complete(struct urb *urb) { struct pvr2_hdw *hdw = urb->context; hdw->ctl_read_pend_flag = 0; if (hdw->ctl_write_pend_flag) return; complete(&hdw->ctl_done); } static void pvr2_ctl_timeout(unsigned long data) { struct pvr2_hdw *hdw = (struct pvr2_hdw *)data; if (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) { hdw->ctl_timeout_flag = !0; if (hdw->ctl_write_pend_flag) usb_unlink_urb(hdw->ctl_write_urb); if (hdw->ctl_read_pend_flag) usb_unlink_urb(hdw->ctl_read_urb); } } /* Issue a command and get a response from the device. This extended version includes a probe flag (which if set means that device errors should not be logged or treated as fatal) and a timeout in jiffies. This can be used to non-lethally probe the health of endpoint 1. */ static int pvr2_send_request_ex(struct pvr2_hdw *hdw, unsigned int timeout,int probe_fl, void *write_data,unsigned int write_len, void *read_data,unsigned int read_len) { unsigned int idx; int status = 0; struct timer_list timer; if (!hdw->ctl_lock_held) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Attempted to execute control transfer" " without lock!!"); return -EDEADLK; } if (!hdw->flag_ok && !probe_fl) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Attempted to execute control transfer" " when device not ok"); return -EIO; } if (!(hdw->ctl_read_urb && hdw->ctl_write_urb)) { if (!probe_fl) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Attempted to execute control transfer" " when USB is disconnected"); } return -ENOTTY; } /* Ensure that we have sane parameters */ if (!write_data) write_len = 0; if (!read_data) read_len = 0; if (write_len > PVR2_CTL_BUFFSIZE) { pvr2_trace( PVR2_TRACE_ERROR_LEGS, "Attempted to execute %d byte" " control-write transfer (limit=%d)", write_len,PVR2_CTL_BUFFSIZE); return -EINVAL; } if (read_len > PVR2_CTL_BUFFSIZE) { pvr2_trace( PVR2_TRACE_ERROR_LEGS, "Attempted to execute %d byte" " control-read transfer (limit=%d)", write_len,PVR2_CTL_BUFFSIZE); return -EINVAL; } if ((!write_len) && (!read_len)) { pvr2_trace( PVR2_TRACE_ERROR_LEGS, "Attempted to execute null control transfer?"); return -EINVAL; } hdw->cmd_debug_state = 1; if (write_len) { hdw->cmd_debug_code = ((unsigned char *)write_data)[0]; } else { hdw->cmd_debug_code = 0; } hdw->cmd_debug_write_len = write_len; hdw->cmd_debug_read_len = read_len; /* Initialize common stuff */ init_completion(&hdw->ctl_done); hdw->ctl_timeout_flag = 0; hdw->ctl_write_pend_flag = 0; hdw->ctl_read_pend_flag = 0; init_timer(&timer); timer.expires = jiffies + timeout; timer.data = (unsigned long)hdw; timer.function = pvr2_ctl_timeout; if (write_len) { hdw->cmd_debug_state = 2; /* Transfer write data to internal buffer */ for (idx = 0; idx < write_len; idx++) { hdw->ctl_write_buffer[idx] = ((unsigned char *)write_data)[idx]; } /* Initiate a write request */ usb_fill_bulk_urb(hdw->ctl_write_urb, hdw->usb_dev, usb_sndbulkpipe(hdw->usb_dev, PVR2_CTL_WRITE_ENDPOINT), hdw->ctl_write_buffer, write_len, pvr2_ctl_write_complete, hdw); hdw->ctl_write_urb->actual_length = 0; hdw->ctl_write_pend_flag = !0; status = usb_submit_urb(hdw->ctl_write_urb,GFP_KERNEL); if (status < 0) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Failed to submit write-control" " URB status=%d",status); hdw->ctl_write_pend_flag = 0; goto done; } } if (read_len) { hdw->cmd_debug_state = 3; memset(hdw->ctl_read_buffer,0x43,read_len); /* Initiate a read request */ usb_fill_bulk_urb(hdw->ctl_read_urb, hdw->usb_dev, usb_rcvbulkpipe(hdw->usb_dev, PVR2_CTL_READ_ENDPOINT), hdw->ctl_read_buffer, read_len, pvr2_ctl_read_complete, hdw); hdw->ctl_read_urb->actual_length = 0; hdw->ctl_read_pend_flag = !0; status = usb_submit_urb(hdw->ctl_read_urb,GFP_KERNEL); if (status < 0) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Failed to submit read-control" " URB status=%d",status); hdw->ctl_read_pend_flag = 0; goto done; } } /* Start timer */ add_timer(&timer); /* Now wait for all I/O to complete */ hdw->cmd_debug_state = 4; while (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) { wait_for_completion(&hdw->ctl_done); } hdw->cmd_debug_state = 5; /* Stop timer */ del_timer_sync(&timer); hdw->cmd_debug_state = 6; status = 0; if (hdw->ctl_timeout_flag) { status = -ETIMEDOUT; if (!probe_fl) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Timed out control-write"); } goto done; } if (write_len) { /* Validate results of write request */ if ((hdw->ctl_write_urb->status != 0) && (hdw->ctl_write_urb->status != -ENOENT) && (hdw->ctl_write_urb->status != -ESHUTDOWN) && (hdw->ctl_write_urb->status != -ECONNRESET)) { /* USB subsystem is reporting some kind of failure on the write */ status = hdw->ctl_write_urb->status; if (!probe_fl) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "control-write URB failure," " status=%d", status); } goto done; } if (hdw->ctl_write_urb->actual_length < write_len) { /* Failed to write enough data */ status = -EIO; if (!probe_fl) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "control-write URB short," " expected=%d got=%d", write_len, hdw->ctl_write_urb->actual_length); } goto done; } } if (read_len) { /* Validate results of read request */ if ((hdw->ctl_read_urb->status != 0) && (hdw->ctl_read_urb->status != -ENOENT) && (hdw->ctl_read_urb->status != -ESHUTDOWN) && (hdw->ctl_read_urb->status != -ECONNRESET)) { /* USB subsystem is reporting some kind of failure on the read */ status = hdw->ctl_read_urb->status; if (!probe_fl) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "control-read URB failure," " status=%d", status); } goto done; } if (hdw->ctl_read_urb->actual_length < read_len) { /* Failed to read enough data */ status = -EIO; if (!probe_fl) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "control-read URB short," " expected=%d got=%d", read_len, hdw->ctl_read_urb->actual_length); } goto done; } /* Transfer retrieved data out from internal buffer */ for (idx = 0; idx < read_len; idx++) { ((unsigned char *)read_data)[idx] = hdw->ctl_read_buffer[idx]; } } done: hdw->cmd_debug_state = 0; if ((status < 0) && (!probe_fl)) { pvr2_hdw_render_useless(hdw); } return status; } int pvr2_send_request(struct pvr2_hdw *hdw, void *write_data,unsigned int write_len, void *read_data,unsigned int read_len) { return pvr2_send_request_ex(hdw,HZ*4,0, write_data,write_len, read_data,read_len); } static int pvr2_issue_simple_cmd(struct pvr2_hdw *hdw,u32 cmdcode) { int ret; unsigned int cnt = 1; unsigned int args = 0; LOCK_TAKE(hdw->ctl_lock); hdw->cmd_buffer[0] = cmdcode & 0xffu; args = (cmdcode >> 8) & 0xffu; args = (args > 2) ? 2 : args; if (args) { cnt += args; hdw->cmd_buffer[1] = (cmdcode >> 16) & 0xffu; if (args > 1) { hdw->cmd_buffer[2] = (cmdcode >> 24) & 0xffu; } } if (pvrusb2_debug & PVR2_TRACE_INIT) { unsigned int idx; unsigned int ccnt,bcnt; char tbuf[50]; cmdcode &= 0xffu; bcnt = 0; ccnt = scnprintf(tbuf+bcnt, sizeof(tbuf)-bcnt, "Sending FX2 command 0x%x",cmdcode); bcnt += ccnt; for (idx = 0; idx < ARRAY_SIZE(pvr2_fx2cmd_desc); idx++) { if (pvr2_fx2cmd_desc[idx].id == cmdcode) { ccnt = scnprintf(tbuf+bcnt, sizeof(tbuf)-bcnt, " \"%s\"", pvr2_fx2cmd_desc[idx].desc); bcnt += ccnt; break; } } if (args) { ccnt = scnprintf(tbuf+bcnt, sizeof(tbuf)-bcnt, " (%u",hdw->cmd_buffer[1]); bcnt += ccnt; if (args > 1) { ccnt = scnprintf(tbuf+bcnt, sizeof(tbuf)-bcnt, ",%u",hdw->cmd_buffer[2]); bcnt += ccnt; } ccnt = scnprintf(tbuf+bcnt, sizeof(tbuf)-bcnt, ")"); bcnt += ccnt; } pvr2_trace(PVR2_TRACE_INIT,"%.*s",bcnt,tbuf); } ret = pvr2_send_request(hdw,hdw->cmd_buffer,cnt,NULL,0); LOCK_GIVE(hdw->ctl_lock); return ret; } int pvr2_write_register(struct pvr2_hdw *hdw, u16 reg, u32 data) { int ret; LOCK_TAKE(hdw->ctl_lock); hdw->cmd_buffer[0] = FX2CMD_REG_WRITE; /* write register prefix */ PVR2_DECOMPOSE_LE(hdw->cmd_buffer,1,data); hdw->cmd_buffer[5] = 0; hdw->cmd_buffer[6] = (reg >> 8) & 0xff; hdw->cmd_buffer[7] = reg & 0xff; ret = pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 0); LOCK_GIVE(hdw->ctl_lock); return ret; } static int pvr2_read_register(struct pvr2_hdw *hdw, u16 reg, u32 *data) { int ret = 0; LOCK_TAKE(hdw->ctl_lock); hdw->cmd_buffer[0] = FX2CMD_REG_READ; /* read register prefix */ hdw->cmd_buffer[1] = 0; hdw->cmd_buffer[2] = 0; hdw->cmd_buffer[3] = 0; hdw->cmd_buffer[4] = 0; hdw->cmd_buffer[5] = 0; hdw->cmd_buffer[6] = (reg >> 8) & 0xff; hdw->cmd_buffer[7] = reg & 0xff; ret |= pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 4); *data = PVR2_COMPOSE_LE(hdw->cmd_buffer,0); LOCK_GIVE(hdw->ctl_lock); return ret; } void pvr2_hdw_render_useless(struct pvr2_hdw *hdw) { if (!hdw->flag_ok) return; pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Device being rendered inoperable"); if (hdw->vid_stream) { pvr2_stream_setup(hdw->vid_stream,NULL,0,0); } hdw->flag_ok = 0; trace_stbit("flag_ok",hdw->flag_ok); pvr2_hdw_state_sched(hdw); } void pvr2_hdw_device_reset(struct pvr2_hdw *hdw) { int ret; pvr2_trace(PVR2_TRACE_INIT,"Performing a device reset..."); ret = usb_lock_device_for_reset(hdw->usb_dev,NULL); if (ret == 0) { ret = usb_reset_device(hdw->usb_dev); usb_unlock_device(hdw->usb_dev); } else { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Failed to lock USB device ret=%d",ret); } if (init_pause_msec) { pvr2_trace(PVR2_TRACE_INFO, "Waiting %u msec for hardware to settle", init_pause_msec); msleep(init_pause_msec); } } void pvr2_hdw_cpureset_assert(struct pvr2_hdw *hdw,int val) { char *da; unsigned int pipe; int ret; if (!hdw->usb_dev) return; da = kmalloc(16, GFP_KERNEL); if (da == NULL) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Unable to allocate memory to control CPU reset"); return; } pvr2_trace(PVR2_TRACE_INIT,"cpureset_assert(%d)",val); da[0] = val ? 0x01 : 0x00; /* Write the CPUCS register on the 8051. The lsb of the register is the reset bit; a 1 asserts reset while a 0 clears it. */ pipe = usb_sndctrlpipe(hdw->usb_dev, 0); ret = usb_control_msg(hdw->usb_dev,pipe,0xa0,0x40,0xe600,0,da,1,HZ); if (ret < 0) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "cpureset_assert(%d) error=%d",val,ret); pvr2_hdw_render_useless(hdw); } kfree(da); } int pvr2_hdw_cmd_deep_reset(struct pvr2_hdw *hdw) { return pvr2_issue_simple_cmd(hdw,FX2CMD_DEEP_RESET); } int pvr2_hdw_cmd_powerup(struct pvr2_hdw *hdw) { return pvr2_issue_simple_cmd(hdw,FX2CMD_POWER_ON); } int pvr2_hdw_cmd_powerdown(struct pvr2_hdw *hdw) { return pvr2_issue_simple_cmd(hdw,FX2CMD_POWER_OFF); } int pvr2_hdw_cmd_decoder_reset(struct pvr2_hdw *hdw) { pvr2_trace(PVR2_TRACE_INIT, "Requesting decoder reset"); if (hdw->decoder_client_id) { v4l2_device_call_all(&hdw->v4l2_dev, hdw->decoder_client_id, core, reset, 0); pvr2_hdw_cx25840_vbi_hack(hdw); return 0; } pvr2_trace(PVR2_TRACE_INIT, "Unable to reset decoder: nothing attached"); return -ENOTTY; } static int pvr2_hdw_cmd_hcw_demod_reset(struct pvr2_hdw *hdw, int onoff) { hdw->flag_ok = !0; return pvr2_issue_simple_cmd(hdw, FX2CMD_HCW_DEMOD_RESETIN | (1 << 8) | ((onoff ? 1 : 0) << 16)); } static int pvr2_hdw_cmd_onair_fe_power_ctrl(struct pvr2_hdw *hdw, int onoff) { hdw->flag_ok = !0; return pvr2_issue_simple_cmd(hdw,(onoff ? FX2CMD_ONAIR_DTV_POWER_ON : FX2CMD_ONAIR_DTV_POWER_OFF)); } static int pvr2_hdw_cmd_onair_digital_path_ctrl(struct pvr2_hdw *hdw, int onoff) { return pvr2_issue_simple_cmd(hdw,(onoff ? FX2CMD_ONAIR_DTV_STREAMING_ON : FX2CMD_ONAIR_DTV_STREAMING_OFF)); } static void pvr2_hdw_cmd_modeswitch(struct pvr2_hdw *hdw,int digitalFl) { int cmode; /* Compare digital/analog desired setting with current setting. If they don't match, fix it... */ cmode = (digitalFl ? PVR2_PATHWAY_DIGITAL : PVR2_PATHWAY_ANALOG); if (cmode == hdw->pathway_state) { /* They match; nothing to do */ return; } switch (hdw->hdw_desc->digital_control_scheme) { case PVR2_DIGITAL_SCHEME_HAUPPAUGE: pvr2_hdw_cmd_hcw_demod_reset(hdw,digitalFl); if (cmode == PVR2_PATHWAY_ANALOG) { /* If moving to analog mode, also force the decoder to reset. If no decoder is attached, then it's ok to ignore this because if/when the decoder attaches, it will reset itself at that time. */ pvr2_hdw_cmd_decoder_reset(hdw); } break; case PVR2_DIGITAL_SCHEME_ONAIR: /* Supposedly we should always have the power on whether in digital or analog mode. But for now do what appears to work... */ pvr2_hdw_cmd_onair_fe_power_ctrl(hdw,digitalFl); break; default: break; } pvr2_hdw_untrip_unlocked(hdw); hdw->pathway_state = cmode; } static void pvr2_led_ctrl_hauppauge(struct pvr2_hdw *hdw, int onoff) { /* change some GPIO data * * note: bit d7 of dir appears to control the LED, * so we shut it off here. * */ if (onoff) { pvr2_hdw_gpio_chg_dir(hdw, 0xffffffff, 0x00000481); } else { pvr2_hdw_gpio_chg_dir(hdw, 0xffffffff, 0x00000401); } pvr2_hdw_gpio_chg_out(hdw, 0xffffffff, 0x00000000); } typedef void (*led_method_func)(struct pvr2_hdw *,int); static led_method_func led_methods[] = { [PVR2_LED_SCHEME_HAUPPAUGE] = pvr2_led_ctrl_hauppauge, }; /* Toggle LED */ static void pvr2_led_ctrl(struct pvr2_hdw *hdw,int onoff) { unsigned int scheme_id; led_method_func fp; if ((!onoff) == (!hdw->led_on)) return; hdw->led_on = onoff != 0; scheme_id = hdw->hdw_desc->led_scheme; if (scheme_id < ARRAY_SIZE(led_methods)) { fp = led_methods[scheme_id]; } else { fp = NULL; } if (fp) (*fp)(hdw,onoff); } /* Stop / start video stream transport */ static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl) { int ret; /* If we're in analog mode, then just issue the usual analog command. */ if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) { return pvr2_issue_simple_cmd(hdw, (runFl ? FX2CMD_STREAMING_ON : FX2CMD_STREAMING_OFF)); /*Note: Not reached */ } if (hdw->pathway_state != PVR2_PATHWAY_DIGITAL) { /* Whoops, we don't know what mode we're in... */ return -EINVAL; } /* To get here we have to be in digital mode. The mechanism here is unfortunately different for different vendors. So we switch on the device's digital scheme attribute in order to figure out what to do. */ switch (hdw->hdw_desc->digital_control_scheme) { case PVR2_DIGITAL_SCHEME_HAUPPAUGE: return pvr2_issue_simple_cmd(hdw, (runFl ? FX2CMD_HCW_DTV_STREAMING_ON : FX2CMD_HCW_DTV_STREAMING_OFF)); case PVR2_DIGITAL_SCHEME_ONAIR: ret = pvr2_issue_simple_cmd(hdw, (runFl ? FX2CMD_STREAMING_ON : FX2CMD_STREAMING_OFF)); if (ret) return ret; return pvr2_hdw_cmd_onair_digital_path_ctrl(hdw,runFl); default: return -EINVAL; } } /* Evaluate whether or not state_pathway_ok can change */ static int state_eval_pathway_ok(struct pvr2_hdw *hdw) { if (hdw->state_pathway_ok) { /* Nothing to do if pathway is already ok */ return 0; } if (!hdw->state_pipeline_idle) { /* Not allowed to change anything if pipeline is not idle */ return 0; } pvr2_hdw_cmd_modeswitch(hdw,hdw->input_val == PVR2_CVAL_INPUT_DTV); hdw->state_pathway_ok = !0; trace_stbit("state_pathway_ok",hdw->state_pathway_ok); return !0; } /* Evaluate whether or not state_encoder_ok can change */ static int state_eval_encoder_ok(struct pvr2_hdw *hdw) { if (hdw->state_encoder_ok) return 0; if (hdw->flag_tripped) return 0; if (hdw->state_encoder_run) return 0; if (hdw->state_encoder_config) return 0; if (hdw->state_decoder_run) return 0; if (hdw->state_usbstream_run) return 0; if (hdw->pathway_state == PVR2_PATHWAY_DIGITAL) { if (!hdw->hdw_desc->flag_digital_requires_cx23416) return 0; } else if (hdw->pathway_state != PVR2_PATHWAY_ANALOG) { return 0; } if (pvr2_upload_firmware2(hdw) < 0) { hdw->flag_tripped = !0; trace_stbit("flag_tripped",hdw->flag_tripped); return !0; } hdw->state_encoder_ok = !0; trace_stbit("state_encoder_ok",hdw->state_encoder_ok); return !0; } /* Evaluate whether or not state_encoder_config can change */ static int state_eval_encoder_config(struct pvr2_hdw *hdw) { if (hdw->state_encoder_config) { if (hdw->state_encoder_ok) { if (hdw->state_pipeline_req && !hdw->state_pipeline_pause) return 0; } hdw->state_encoder_config = 0; hdw->state_encoder_waitok = 0; trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok); /* paranoia - solve race if timer just completed */ del_timer_sync(&hdw->encoder_wait_timer); } else { if (!hdw->state_pathway_ok || (hdw->pathway_state != PVR2_PATHWAY_ANALOG) || !hdw->state_encoder_ok || !hdw->state_pipeline_idle || hdw->state_pipeline_pause || !hdw->state_pipeline_req || !hdw->state_pipeline_config) { /* We must reset the enforced wait interval if anything has happened that might have disturbed the encoder. This should be a rare case. */ if (timer_pending(&hdw->encoder_wait_timer)) { del_timer_sync(&hdw->encoder_wait_timer); } if (hdw->state_encoder_waitok) { /* Must clear the state - therefore we did something to a state bit and must also return true. */ hdw->state_encoder_waitok = 0; trace_stbit("state_encoder_waitok", hdw->state_encoder_waitok); return !0; } return 0; } if (!hdw->state_encoder_waitok) { if (!timer_pending(&hdw->encoder_wait_timer)) { /* waitok flag wasn't set and timer isn't running. Check flag once more to avoid a race then start the timer. This is the point when we measure out a minimal quiet interval before doing something to the encoder. */ if (!hdw->state_encoder_waitok) { hdw->encoder_wait_timer.expires = jiffies + (HZ * TIME_MSEC_ENCODER_WAIT / 1000); add_timer(&hdw->encoder_wait_timer); } } /* We can't continue until we know we have been quiet for the interval measured by this timer. */ return 0; } pvr2_encoder_configure(hdw); if (hdw->state_encoder_ok) hdw->state_encoder_config = !0; } trace_stbit("state_encoder_config",hdw->state_encoder_config); return !0; } /* Return true if the encoder should not be running. */ static int state_check_disable_encoder_run(struct pvr2_hdw *hdw) { if (!hdw->state_encoder_ok) { /* Encoder isn't healthy at the moment, so stop it. */ return !0; } if (!hdw->state_pathway_ok) { /* Mode is not understood at the moment (i.e. it wants to change), so encoder must be stopped. */ return !0; } switch (hdw->pathway_state) { case PVR2_PATHWAY_ANALOG: if (!hdw->state_decoder_run) { /* We're in analog mode and the decoder is not running; thus the encoder should be stopped as well. */ return !0; } break; case PVR2_PATHWAY_DIGITAL: if (hdw->state_encoder_runok) { /* This is a funny case. We're in digital mode so really the encoder should be stopped. However if it really is running, only kill it after runok has been set. This gives a chance for the onair quirk to function (encoder must run briefly first, at least once, before onair digital streaming can work). */ return !0; } break; default: /* Unknown mode; so encoder should be stopped. */ return !0; } /* If we get here, we haven't found a reason to stop the encoder. */ return 0; } /* Return true if the encoder should be running. */ static int state_check_enable_encoder_run(struct pvr2_hdw *hdw) { if (!hdw->state_encoder_ok) { /* Don't run the encoder if it isn't healthy... */ return 0; } if (!hdw->state_pathway_ok) { /* Don't run the encoder if we don't (yet) know what mode we need to be in... */ return 0; } switch (hdw->pathway_state) { case PVR2_PATHWAY_ANALOG: if (hdw->state_decoder_run && hdw->state_decoder_ready) { /* In analog mode, if the decoder is running, then run the encoder. */ return !0; } break; case PVR2_PATHWAY_DIGITAL: if ((hdw->hdw_desc->digital_control_scheme == PVR2_DIGITAL_SCHEME_ONAIR) && !hdw->state_encoder_runok) { /* This is a quirk. OnAir hardware won't stream digital until the encoder has been run at least once, for a minimal period of time (empiricially measured to be 1/4 second). So if we're on OnAir hardware and the encoder has never been run at all, then start the encoder. Normal state machine logic in the driver will automatically handle the remaining bits. */ return !0; } break; default: /* For completeness (unknown mode; encoder won't run ever) */ break; } /* If we get here, then we haven't found any reason to run the encoder, so don't run it. */ return 0; } /* Evaluate whether or not state_encoder_run can change */ static int state_eval_encoder_run(struct pvr2_hdw *hdw) { if (hdw->state_encoder_run) { if (!state_check_disable_encoder_run(hdw)) return 0; if (hdw->state_encoder_ok) { del_timer_sync(&hdw->encoder_run_timer); if (pvr2_encoder_stop(hdw) < 0) return !0; } hdw->state_encoder_run = 0; } else { if (!state_check_enable_encoder_run(hdw)) return 0; if (pvr2_encoder_start(hdw) < 0) return !0; hdw->state_encoder_run = !0; if (!hdw->state_encoder_runok) { hdw->encoder_run_timer.expires = jiffies + (HZ * TIME_MSEC_ENCODER_OK / 1000); add_timer(&hdw->encoder_run_timer); } } trace_stbit("state_encoder_run",hdw->state_encoder_run); return !0; } /* Timeout function for quiescent timer. */ static void pvr2_hdw_quiescent_timeout(unsigned long data) { struct pvr2_hdw *hdw = (struct pvr2_hdw *)data; hdw->state_decoder_quiescent = !0; trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent); hdw->state_stale = !0; queue_work(hdw->workqueue,&hdw->workpoll); } /* Timeout function for decoder stabilization timer. */ static void pvr2_hdw_decoder_stabilization_timeout(unsigned long data) { struct pvr2_hdw *hdw = (struct pvr2_hdw *)data; hdw->state_decoder_ready = !0; trace_stbit("state_decoder_ready", hdw->state_decoder_ready); hdw->state_stale = !0; queue_work(hdw->workqueue, &hdw->workpoll); } /* Timeout function for encoder wait timer. */ static void pvr2_hdw_encoder_wait_timeout(unsigned long data) { struct pvr2_hdw *hdw = (struct pvr2_hdw *)data; hdw->state_encoder_waitok = !0; trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok); hdw->state_stale = !0; queue_work(hdw->workqueue,&hdw->workpoll); } /* Timeout function for encoder run timer. */ static void pvr2_hdw_encoder_run_timeout(unsigned long data) { struct pvr2_hdw *hdw = (struct pvr2_hdw *)data; if (!hdw->state_encoder_runok) { hdw->state_encoder_runok = !0; trace_stbit("state_encoder_runok",hdw->state_encoder_runok); hdw->state_stale = !0; queue_work(hdw->workqueue,&hdw->workpoll); } } /* Evaluate whether or not state_decoder_run can change */ static int state_eval_decoder_run(struct pvr2_hdw *hdw) { if (hdw->state_decoder_run) { if (hdw->state_encoder_ok) { if (hdw->state_pipeline_req && !hdw->state_pipeline_pause && hdw->state_pathway_ok) return 0; } if (!hdw->flag_decoder_missed) { pvr2_decoder_enable(hdw,0); } hdw->state_decoder_quiescent = 0; hdw->state_decoder_run = 0; /* paranoia - solve race if timer(s) just completed */ del_timer_sync(&hdw->quiescent_timer); /* Kill the stabilization timer, in case we're killing the encoder before the previous stabilization interval has been properly timed. */ del_timer_sync(&hdw->decoder_stabilization_timer); hdw->state_decoder_ready = 0; } else { if (!hdw->state_decoder_quiescent) { if (!timer_pending(&hdw->quiescent_timer)) { /* We don't do something about the quiescent timer until right here because we also want to catch cases where the decoder was already not running (like after initialization) as opposed to knowing that we had just stopped it. The second flag check is here to cover a race - the timer could have run and set this flag just after the previous check but before we did the pending check. */ if (!hdw->state_decoder_quiescent) { hdw->quiescent_timer.expires = jiffies + (HZ * TIME_MSEC_DECODER_WAIT / 1000); add_timer(&hdw->quiescent_timer); } } /* Don't allow decoder to start again until it has been quiesced first. This little detail should hopefully further stabilize the encoder. */ return 0; } if (!hdw->state_pathway_ok || (hdw->pathway_state != PVR2_PATHWAY_ANALOG) || !hdw->state_pipeline_req || hdw->state_pipeline_pause || !hdw->state_pipeline_config || !hdw->state_encoder_config || !hdw->state_encoder_ok) return 0; del_timer_sync(&hdw->quiescent_timer); if (hdw->flag_decoder_missed) return 0; if (pvr2_decoder_enable(hdw,!0) < 0) return 0; hdw->state_decoder_quiescent = 0; hdw->state_decoder_ready = 0; hdw->state_decoder_run = !0; if (hdw->decoder_client_id == PVR2_CLIENT_ID_SAA7115) { hdw->decoder_stabilization_timer.expires = jiffies + (HZ * TIME_MSEC_DECODER_STABILIZATION_WAIT / 1000); add_timer(&hdw->decoder_stabilization_timer); } else { hdw->state_decoder_ready = !0; } } trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent); trace_stbit("state_decoder_run",hdw->state_decoder_run); trace_stbit("state_decoder_ready", hdw->state_decoder_ready); return !0; } /* Evaluate whether or not state_usbstream_run can change */ static int state_eval_usbstream_run(struct pvr2_hdw *hdw) { if (hdw->state_usbstream_run) { int fl = !0; if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) { fl = (hdw->state_encoder_ok && hdw->state_encoder_run); } else if ((hdw->pathway_state == PVR2_PATHWAY_DIGITAL) && (hdw->hdw_desc->flag_digital_requires_cx23416)) { fl = hdw->state_encoder_ok; } if (fl && hdw->state_pipeline_req && !hdw->state_pipeline_pause && hdw->state_pathway_ok) { return 0; } pvr2_hdw_cmd_usbstream(hdw,0); hdw->state_usbstream_run = 0; } else { if (!hdw->state_pipeline_req || hdw->state_pipeline_pause || !hdw->state_pathway_ok) return 0; if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) { if (!hdw->state_encoder_ok || !hdw->state_encoder_run) return 0; } else if ((hdw->pathway_state == PVR2_PATHWAY_DIGITAL) && (hdw->hdw_desc->flag_digital_requires_cx23416)) { if (!hdw->state_encoder_ok) return 0; if (hdw->state_encoder_run) return 0; if (hdw->hdw_desc->digital_control_scheme == PVR2_DIGITAL_SCHEME_ONAIR) { /* OnAir digital receivers won't stream unless the analog encoder has run first. Why? I have no idea. But don't even try until we know the analog side is known to have run. */ if (!hdw->state_encoder_runok) return 0; } } if (pvr2_hdw_cmd_usbstream(hdw,!0) < 0) return 0; hdw->state_usbstream_run = !0; } trace_stbit("state_usbstream_run",hdw->state_usbstream_run); return !0; } /* Attempt to configure pipeline, if needed */ static int state_eval_pipeline_config(struct pvr2_hdw *hdw) { if (hdw->state_pipeline_config || hdw->state_pipeline_pause) return 0; pvr2_hdw_commit_execute(hdw); return !0; } /* Update pipeline idle and pipeline pause tracking states based on other inputs. This must be called whenever the other relevant inputs have changed. */ static int state_update_pipeline_state(struct pvr2_hdw *hdw) { unsigned int st; int updatedFl = 0; /* Update pipeline state */ st = !(hdw->state_encoder_run || hdw->state_decoder_run || hdw->state_usbstream_run || (!hdw->state_decoder_quiescent)); if (!st != !hdw->state_pipeline_idle) { hdw->state_pipeline_idle = st; updatedFl = !0; } if (hdw->state_pipeline_idle && hdw->state_pipeline_pause) { hdw->state_pipeline_pause = 0; updatedFl = !0; } return updatedFl; } typedef int (*state_eval_func)(struct pvr2_hdw *); /* Set of functions to be run to evaluate various states in the driver. */ static const state_eval_func eval_funcs[] = { state_eval_pathway_ok, state_eval_pipeline_config, state_eval_encoder_ok, state_eval_encoder_config, state_eval_decoder_run, state_eval_encoder_run, state_eval_usbstream_run, }; /* Process various states and return true if we did anything interesting. */ static int pvr2_hdw_state_update(struct pvr2_hdw *hdw) { unsigned int i; int state_updated = 0; int check_flag; if (!hdw->state_stale) return 0; if ((hdw->fw1_state != FW1_STATE_OK) || !hdw->flag_ok) { hdw->state_stale = 0; return !0; } /* This loop is the heart of the entire driver. It keeps trying to evaluate various bits of driver state until nothing changes for one full iteration. Each "bit of state" tracks some global aspect of the driver, e.g. whether decoder should run, if pipeline is configured, usb streaming is on, etc. We separately evaluate each of those questions based on other driver state to arrive at the correct running configuration. */ do { check_flag = 0; state_update_pipeline_state(hdw); /* Iterate over each bit of state */ for (i = 0; (i<ARRAY_SIZE(eval_funcs)) && hdw->flag_ok; i++) { if ((*eval_funcs[i])(hdw)) { check_flag = !0; state_updated = !0; state_update_pipeline_state(hdw); } } } while (check_flag && hdw->flag_ok); hdw->state_stale = 0; trace_stbit("state_stale",hdw->state_stale); return state_updated; } static unsigned int print_input_mask(unsigned int msk, char *buf,unsigned int acnt) { unsigned int idx,ccnt; unsigned int tcnt = 0; for (idx = 0; idx < ARRAY_SIZE(control_values_input); idx++) { if (!((1 << idx) & msk)) continue; ccnt = scnprintf(buf+tcnt, acnt-tcnt, "%s%s", (tcnt ? ", " : ""), control_values_input[idx]); tcnt += ccnt; } return tcnt; } static const char *pvr2_pathway_state_name(int id) { switch (id) { case PVR2_PATHWAY_ANALOG: return "analog"; case PVR2_PATHWAY_DIGITAL: return "digital"; default: return "unknown"; } } static unsigned int pvr2_hdw_report_unlocked(struct pvr2_hdw *hdw,int which, char *buf,unsigned int acnt) { switch (which) { case 0: return scnprintf( buf,acnt, "driver:%s%s%s%s%s <mode=%s>", (hdw->flag_ok ? " <ok>" : " <fail>"), (hdw->flag_init_ok ? " <init>" : " <uninitialized>"), (hdw->flag_disconnected ? " <disconnected>" : " <connected>"), (hdw->flag_tripped ? " <tripped>" : ""), (hdw->flag_decoder_missed ? " <no decoder>" : ""), pvr2_pathway_state_name(hdw->pathway_state)); case 1: return scnprintf( buf,acnt, "pipeline:%s%s%s%s", (hdw->state_pipeline_idle ? " <idle>" : ""), (hdw->state_pipeline_config ? " <configok>" : " <stale>"), (hdw->state_pipeline_req ? " <req>" : ""), (hdw->state_pipeline_pause ? " <pause>" : "")); case 2: return scnprintf( buf,acnt, "worker:%s%s%s%s%s%s%s", (hdw->state_decoder_run ? (hdw->state_decoder_ready ? "<decode:run>" : " <decode:start>") : (hdw->state_decoder_quiescent ? "" : " <decode:stop>")), (hdw->state_decoder_quiescent ? " <decode:quiescent>" : ""), (hdw->state_encoder_ok ? "" : " <encode:init>"), (hdw->state_encoder_run ? (hdw->state_encoder_runok ? " <encode:run>" : " <encode:firstrun>") : (hdw->state_encoder_runok ? " <encode:stop>" : " <encode:virgin>")), (hdw->state_encoder_config ? " <encode:configok>" : (hdw->state_encoder_waitok ? "" : " <encode:waitok>")), (hdw->state_usbstream_run ? " <usb:run>" : " <usb:stop>"), (hdw->state_pathway_ok ? " <pathway:ok>" : "")); case 3: return scnprintf( buf,acnt, "state: %s", pvr2_get_state_name(hdw->master_state)); case 4: { unsigned int tcnt = 0; unsigned int ccnt; ccnt = scnprintf(buf, acnt, "Hardware supported inputs: "); tcnt += ccnt; tcnt += print_input_mask(hdw->input_avail_mask, buf+tcnt, acnt-tcnt); if (hdw->input_avail_mask != hdw->input_allowed_mask) { ccnt = scnprintf(buf+tcnt, acnt-tcnt, "; allowed inputs: "); tcnt += ccnt; tcnt += print_input_mask(hdw->input_allowed_mask, buf+tcnt, acnt-tcnt); } return tcnt; } case 5: { struct pvr2_stream_stats stats; if (!hdw->vid_stream) break; pvr2_stream_get_stats(hdw->vid_stream, &stats, 0); return scnprintf( buf,acnt, "Bytes streamed=%u" " URBs: queued=%u idle=%u ready=%u" " processed=%u failed=%u", stats.bytes_processed, stats.buffers_in_queue, stats.buffers_in_idle, stats.buffers_in_ready, stats.buffers_processed, stats.buffers_failed); } case 6: { unsigned int id = hdw->ir_scheme_active; return scnprintf(buf, acnt, "ir scheme: id=%d %s", id, (id >= ARRAY_SIZE(ir_scheme_names) ? "?" : ir_scheme_names[id])); } default: break; } return 0; } /* Generate report containing info about attached sub-devices and attached i2c clients, including an indication of which attached i2c clients are actually sub-devices. */ static unsigned int pvr2_hdw_report_clients(struct pvr2_hdw *hdw, char *buf, unsigned int acnt) { struct v4l2_subdev *sd; unsigned int tcnt = 0; unsigned int ccnt; struct i2c_client *client; const char *p; unsigned int id; ccnt = scnprintf(buf, acnt, "Associated v4l2-subdev drivers and I2C clients:\n"); tcnt += ccnt; v4l2_device_for_each_subdev(sd, &hdw->v4l2_dev) { id = sd->grp_id; p = NULL; if (id < ARRAY_SIZE(module_names)) p = module_names[id]; if (p) { ccnt = scnprintf(buf + tcnt, acnt - tcnt, " %s:", p); tcnt += ccnt; } else { ccnt = scnprintf(buf + tcnt, acnt - tcnt, " (unknown id=%u):", id); tcnt += ccnt; } client = v4l2_get_subdevdata(sd); if (client) { ccnt = scnprintf(buf + tcnt, acnt - tcnt, " %s @ %02x\n", client->name, client->addr); tcnt += ccnt; } else { ccnt = scnprintf(buf + tcnt, acnt - tcnt, " no i2c client\n"); tcnt += ccnt; } } return tcnt; } unsigned int pvr2_hdw_state_report(struct pvr2_hdw *hdw, char *buf,unsigned int acnt) { unsigned int bcnt,ccnt,idx; bcnt = 0; LOCK_TAKE(hdw->big_lock); for (idx = 0; ; idx++) { ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,acnt); if (!ccnt) break; bcnt += ccnt; acnt -= ccnt; buf += ccnt; if (!acnt) break; buf[0] = '\n'; ccnt = 1; bcnt += ccnt; acnt -= ccnt; buf += ccnt; } ccnt = pvr2_hdw_report_clients(hdw, buf, acnt); bcnt += ccnt; acnt -= ccnt; buf += ccnt; LOCK_GIVE(hdw->big_lock); return bcnt; } static void pvr2_hdw_state_log_state(struct pvr2_hdw *hdw) { char buf[256]; unsigned int idx, ccnt; unsigned int lcnt, ucnt; for (idx = 0; ; idx++) { ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,sizeof(buf)); if (!ccnt) break; printk(KERN_INFO "%s %.*s\n",hdw->name,ccnt,buf); } ccnt = pvr2_hdw_report_clients(hdw, buf, sizeof(buf)); ucnt = 0; while (ucnt < ccnt) { lcnt = 0; while ((lcnt + ucnt < ccnt) && (buf[lcnt + ucnt] != '\n')) { lcnt++; } printk(KERN_INFO "%s %.*s\n", hdw->name, lcnt, buf + ucnt); ucnt += lcnt + 1; } } /* Evaluate and update the driver's current state, taking various actions as appropriate for the update. */ static int pvr2_hdw_state_eval(struct pvr2_hdw *hdw) { unsigned int st; int state_updated = 0; int callback_flag = 0; int analog_mode; pvr2_trace(PVR2_TRACE_STBITS, "Drive state check START"); if (pvrusb2_debug & PVR2_TRACE_STBITS) { pvr2_hdw_state_log_state(hdw); } /* Process all state and get back over disposition */ state_updated = pvr2_hdw_state_update(hdw); analog_mode = (hdw->pathway_state != PVR2_PATHWAY_DIGITAL); /* Update master state based upon all other states. */ if (!hdw->flag_ok) { st = PVR2_STATE_DEAD; } else if (hdw->fw1_state != FW1_STATE_OK) { st = PVR2_STATE_COLD; } else if ((analog_mode || hdw->hdw_desc->flag_digital_requires_cx23416) && !hdw->state_encoder_ok) { st = PVR2_STATE_WARM; } else if (hdw->flag_tripped || (analog_mode && hdw->flag_decoder_missed)) { st = PVR2_STATE_ERROR; } else if (hdw->state_usbstream_run && (!analog_mode || (hdw->state_encoder_run && hdw->state_decoder_run))) { st = PVR2_STATE_RUN; } else { st = PVR2_STATE_READY; } if (hdw->master_state != st) { pvr2_trace(PVR2_TRACE_STATE, "Device state change from %s to %s", pvr2_get_state_name(hdw->master_state), pvr2_get_state_name(st)); pvr2_led_ctrl(hdw,st == PVR2_STATE_RUN); hdw->master_state = st; state_updated = !0; callback_flag = !0; } if (state_updated) { /* Trigger anyone waiting on any state changes here. */ wake_up(&hdw->state_wait_data); } if (pvrusb2_debug & PVR2_TRACE_STBITS) { pvr2_hdw_state_log_state(hdw); } pvr2_trace(PVR2_TRACE_STBITS, "Drive state check DONE callback=%d",callback_flag); return callback_flag; } /* Cause kernel thread to check / update driver state */ static void pvr2_hdw_state_sched(struct pvr2_hdw *hdw) { if (hdw->state_stale) return; hdw->state_stale = !0; trace_stbit("state_stale",hdw->state_stale); queue_work(hdw->workqueue,&hdw->workpoll); } int pvr2_hdw_gpio_get_dir(struct pvr2_hdw *hdw,u32 *dp) { return pvr2_read_register(hdw,PVR2_GPIO_DIR,dp); } int pvr2_hdw_gpio_get_out(struct pvr2_hdw *hdw,u32 *dp) { return pvr2_read_register(hdw,PVR2_GPIO_OUT,dp); } int pvr2_hdw_gpio_get_in(struct pvr2_hdw *hdw,u32 *dp) { return pvr2_read_register(hdw,PVR2_GPIO_IN,dp); } int pvr2_hdw_gpio_chg_dir(struct pvr2_hdw *hdw,u32 msk,u32 val) { u32 cval,nval; int ret; if (~msk) { ret = pvr2_read_register(hdw,PVR2_GPIO_DIR,&cval); if (ret) return ret; nval = (cval & ~msk) | (val & msk); pvr2_trace(PVR2_TRACE_GPIO, "GPIO direction changing 0x%x:0x%x" " from 0x%x to 0x%x", msk,val,cval,nval); } else { nval = val; pvr2_trace(PVR2_TRACE_GPIO, "GPIO direction changing to 0x%x",nval); } return pvr2_write_register(hdw,PVR2_GPIO_DIR,nval); } int pvr2_hdw_gpio_chg_out(struct pvr2_hdw *hdw,u32 msk,u32 val) { u32 cval,nval; int ret; if (~msk) { ret = pvr2_read_register(hdw,PVR2_GPIO_OUT,&cval); if (ret) return ret; nval = (cval & ~msk) | (val & msk); pvr2_trace(PVR2_TRACE_GPIO, "GPIO output changing 0x%x:0x%x from 0x%x to 0x%x", msk,val,cval,nval); } else { nval = val; pvr2_trace(PVR2_TRACE_GPIO, "GPIO output changing to 0x%x",nval); } return pvr2_write_register(hdw,PVR2_GPIO_OUT,nval); } void pvr2_hdw_status_poll(struct pvr2_hdw *hdw) { struct v4l2_tuner *vtp = &hdw->tuner_signal_info; memset(vtp, 0, sizeof(*vtp)); vtp->type = (hdw->input_val == PVR2_CVAL_INPUT_RADIO) ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV; hdw->tuner_signal_stale = 0; /* Note: There apparently is no replacement for VIDIOC_CROPCAP using v4l2-subdev - therefore we can't support that AT ALL right now. (Of course, no sub-drivers seem to implement it either. But now it's a a chicken and egg problem...) */ v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, g_tuner, vtp); pvr2_trace(PVR2_TRACE_CHIPS, "subdev status poll" " type=%u strength=%u audio=0x%x cap=0x%x" " low=%u hi=%u", vtp->type, vtp->signal, vtp->rxsubchans, vtp->capability, vtp->rangelow, vtp->rangehigh); /* We have to do this to avoid getting into constant polling if there's nobody to answer a poll of cropcap info. */ hdw->cropcap_stale = 0; } unsigned int pvr2_hdw_get_input_available(struct pvr2_hdw *hdw) { return hdw->input_avail_mask; } unsigned int pvr2_hdw_get_input_allowed(struct pvr2_hdw *hdw) { return hdw->input_allowed_mask; } static int pvr2_hdw_set_input(struct pvr2_hdw *hdw,int v) { if (hdw->input_val != v) { hdw->input_val = v; hdw->input_dirty = !0; } /* Handle side effects - if we switch to a mode that needs the RF tuner, then select the right frequency choice as well and mark it dirty. */ if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) { hdw->freqSelector = 0; hdw->freqDirty = !0; } else if ((hdw->input_val == PVR2_CVAL_INPUT_TV) || (hdw->input_val == PVR2_CVAL_INPUT_DTV)) { hdw->freqSelector = 1; hdw->freqDirty = !0; } return 0; } int pvr2_hdw_set_input_allowed(struct pvr2_hdw *hdw, unsigned int change_mask, unsigned int change_val) { int ret = 0; unsigned int nv,m,idx; LOCK_TAKE(hdw->big_lock); do { nv = hdw->input_allowed_mask & ~change_mask; nv |= (change_val & change_mask); nv &= hdw->input_avail_mask; if (!nv) { /* No legal modes left; return error instead. */ ret = -EPERM; break; } hdw->input_allowed_mask = nv; if ((1 << hdw->input_val) & hdw->input_allowed_mask) { /* Current mode is still in the allowed mask, so we're done. */ break; } /* Select and switch to a mode that is still in the allowed mask */ if (!hdw->input_allowed_mask) { /* Nothing legal; give up */ break; } m = hdw->input_allowed_mask; for (idx = 0; idx < (sizeof(m) << 3); idx++) { if (!((1 << idx) & m)) continue; pvr2_hdw_set_input(hdw,idx); break; } } while (0); LOCK_GIVE(hdw->big_lock); return ret; } /* Find I2C address of eeprom */ static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw) { int result; LOCK_TAKE(hdw->ctl_lock); do { hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR; result = pvr2_send_request(hdw, hdw->cmd_buffer,1, hdw->cmd_buffer,1); if (result < 0) break; result = hdw->cmd_buffer[0]; } while(0); LOCK_GIVE(hdw->ctl_lock); return result; } int pvr2_hdw_register_access(struct pvr2_hdw *hdw, const struct v4l2_dbg_match *match, u64 reg_id, int setFl, u64 *val_ptr) { #ifdef CONFIG_VIDEO_ADV_DEBUG struct v4l2_dbg_register req; int stat = 0; int okFl = 0; if (!capable(CAP_SYS_ADMIN)) return -EPERM; req.match = *match; req.reg = reg_id; if (setFl) req.val = *val_ptr; /* It would be nice to know if a sub-device answered the request */ v4l2_device_call_all(&hdw->v4l2_dev, 0, core, g_register, &req); if (!setFl) *val_ptr = req.val; if (okFl) { return stat; } return -EINVAL; #else return -ENOSYS; #endif } /* Stuff for Emacs to see, in order to encourage consistent editing style: *** Local Variables: *** *** mode: c *** *** fill-column: 75 *** *** tab-width: 8 *** *** c-basic-offset: 8 *** *** End: *** */
gpl-2.0
chucktr/android_kernel_htc_msm8960
drivers/video/msm/vidc/720p/ddl/vcd_ddl_interrupt_handler.c
3618
29418
/* 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. * */ #include <media/msm/vidc_type.h> #include "vidc.h" #include "vcd_ddl_utils.h" #include "vcd_ddl_metadata.h" #if DEBUG #define DBG(x...) printk(KERN_DEBUG x) #else #define DBG(x...) #endif static void ddl_decoder_input_done_callback( struct ddl_client_context *ddl, u32 frame_transact_end); static u32 ddl_decoder_output_done_callback( struct ddl_client_context *ddl, u32 frame_transact_end); static u32 ddl_get_frame (struct vcd_frame_data *frame, u32 frame_type); static void ddl_getdec_profilelevel (struct ddl_decoder_data *decoder, u32 profile, u32 level); static void ddl_dma_done_callback(struct ddl_context *ddl_context) { if (!DDLCOMMAND_STATE_IS(ddl_context, DDL_CMD_DMA_INIT)) { VIDC_LOGERR_STRING("UNKWN_DMADONE"); return; } ddl_move_command_state(ddl_context, DDL_CMD_INVALID); VIDC_LOG_STRING("DMA_DONE"); ddl_core_start_cpu(ddl_context); } static void ddl_cpu_started_callback(struct ddl_context *ddl_context) { ddl_move_command_state(ddl_context, DDL_CMD_INVALID); VIDC_LOG_STRING("CPU-STARTED"); if (!vidc_720p_cpu_start()) { ddl_hw_fatal_cb(ddl_context); return; } vidc_720p_set_deblock_line_buffer( ddl_context->db_line_buffer.align_physical_addr, ddl_context->db_line_buffer.buffer_size); ddl_context->device_state = DDL_DEVICE_INITED; ddl_context->ddl_callback(VCD_EVT_RESP_DEVICE_INIT, VCD_S_SUCCESS, NULL, 0, NULL, ddl_context->client_data); DDL_IDLE(ddl_context); } static u32 ddl_eos_done_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl = ddl_context->current_ddl; u32 displaystatus, resl_change; if (!DDLCOMMAND_STATE_IS(ddl_context, DDL_CMD_EOS)) { VIDC_LOGERR_STRING("UNKWN_EOSDONE"); ddl_client_fatal_cb(ddl_context); return true; } if (!ddl || !ddl->decoding || !DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_EOS_DONE) ) { VIDC_LOG_STRING("STATE-CRITICAL-EOSDONE"); ddl_client_fatal_cb(ddl_context); return true; } ddl_move_command_state(ddl_context, DDL_CMD_INVALID); vidc_720p_eos_info(&displaystatus, &resl_change); if ((enum vidc_720p_display_status)displaystatus != VIDC_720P_EMPTY_BUFFER) { VIDC_LOG_STRING("EOSDONE-EMPTYBUF-ISSUE"); } ddl_decode_dynamic_property(ddl, false); if (resl_change == 0x1) { ddl->codec_data.decoder.header_in_start = false; ddl->codec_data.decoder.decode_config.sequence_header = ddl->input_frame.vcd_frm.physical; ddl->codec_data.decoder.decode_config.sequence_header_len = ddl->input_frame.vcd_frm.data_len; ddl_decode_init_codec(ddl); return false; } ddl_move_client_state(ddl, DDL_CLIENT_WAIT_FOR_FRAME); VIDC_LOG_STRING("EOS_DONE"); ddl_context->ddl_callback(VCD_EVT_RESP_EOS_DONE, VCD_S_SUCCESS, NULL, 0, (u32 *) ddl, ddl_context->client_data); DDL_IDLE(ddl_context); return true; } static u32 ddl_channel_set_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl = ddl_context->current_ddl; u32 return_status = false; ddl_move_command_state(ddl_context, DDL_CMD_INVALID); VIDC_DEBUG_REGISTER_LOG; if (!ddl || !DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_CHDONE) ) { VIDC_LOG_STRING("STATE-CRITICAL-CHSET"); DDL_IDLE(ddl_context); return return_status; } VIDC_LOG_STRING("Channel-set"); ddl_move_client_state(ddl, DDL_CLIENT_WAIT_FOR_INITCODEC); if (ddl->decoding) { if (vidc_msg_timing) ddl_calc_core_proc_time(__func__, DEC_OP_TIME); if (ddl->codec_data.decoder.header_in_start) { ddl_decode_init_codec(ddl); } else { ddl_context->ddl_callback(VCD_EVT_RESP_START, VCD_S_SUCCESS, NULL, 0, (u32 *) ddl, ddl_context->client_data); DDL_IDLE(ddl_context); return_status = true; } } else { ddl_encode_init_codec(ddl); } return return_status; } static void ddl_init_codec_done_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl = ddl_context->current_ddl; struct ddl_encoder_data *encoder; if (!ddl || ddl->decoding || !DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_INITCODECDONE) ) { VIDC_LOG_STRING("STATE-CRITICAL-INITCODEC"); ddl_client_fatal_cb(ddl_context); return; } ddl_move_command_state(ddl_context, DDL_CMD_INVALID); ddl_move_client_state(ddl, DDL_CLIENT_WAIT_FOR_FRAME); VIDC_LOG_STRING("INIT_CODEC_DONE"); encoder = &ddl->codec_data.encoder; if (encoder->seq_header.virtual_base_addr) { vidc_720p_encode_get_header(&encoder->seq_header. buffer_size); } ddl_context->ddl_callback(VCD_EVT_RESP_START, VCD_S_SUCCESS, NULL, 0, (u32 *) ddl, ddl_context->client_data); DDL_IDLE(ddl_context); } static u32 ddl_header_done_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl = ddl_context->current_ddl; struct ddl_decoder_data *decoder; struct vidc_720p_seq_hdr_info seq_hdr_info; u32 process_further = true; u32 seq_hdr_only_frame = false; u32 need_reconfig = true; struct vcd_frame_data *input_vcd_frm; struct ddl_frame_data_tag *reconfig_payload = NULL; u32 reconfig_payload_size = 0; if (!ddl || !ddl->decoding || !DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_INITCODECDONE) ) { VIDC_LOG_STRING("STATE-CRITICAL-HDDONE"); ddl_client_fatal_cb(ddl_context); return true; } if (vidc_msg_timing) ddl_calc_core_proc_time(__func__, DEC_OP_TIME); ddl_move_command_state(ddl_context, DDL_CMD_INVALID); ddl_move_client_state(ddl, DDL_CLIENT_WAIT_FOR_DPB); VIDC_LOG_STRING("HEADER_DONE"); VIDC_DEBUG_REGISTER_LOG; vidc_720p_decode_get_seq_hdr_info(&seq_hdr_info); decoder = &(ddl->codec_data.decoder); decoder->frame_size.width = seq_hdr_info.img_size_x; decoder->frame_size.height = seq_hdr_info.img_size_y; decoder->min_dpb_num = seq_hdr_info.min_num_dpb; decoder->y_cb_cr_size = seq_hdr_info.min_dpb_size; decoder->progressive_only = 1 - seq_hdr_info.progressive; if (!seq_hdr_info.img_size_x || !seq_hdr_info.img_size_y) { VIDC_LOGERR_STRING("FATAL: ZeroImageSize"); ddl_client_fatal_cb(ddl_context); return process_further; } if (seq_hdr_info.data_partitioned == 0x1 && decoder->codec.codec == VCD_CODEC_MPEG4 && seq_hdr_info.img_size_x > DDL_MAX_DP_FRAME_WIDTH && seq_hdr_info.img_size_y > DDL_MAX_DP_FRAME_HEIGHT) { ddl_client_fatal_cb(ddl_context); return process_further; } ddl_getdec_profilelevel(decoder, seq_hdr_info.profile, seq_hdr_info.level); ddl_calculate_stride(&decoder->frame_size, !decoder->progressive_only, decoder->codec.codec); if (decoder->buf_format.buffer_format == VCD_BUFFER_FORMAT_TILE_4x2) { decoder->frame_size.stride = DDL_TILE_ALIGN(decoder->frame_size.width, DDL_TILE_ALIGN_WIDTH); decoder->frame_size.scan_lines = DDL_TILE_ALIGN(decoder->frame_size.height, DDL_TILE_ALIGN_HEIGHT); } if (seq_hdr_info.crop_exists) { decoder->frame_size.width -= (seq_hdr_info.crop_right_offset + seq_hdr_info.crop_left_offset); decoder->frame_size.height -= (seq_hdr_info.crop_top_offset + seq_hdr_info.crop_bottom_offset); } ddl_set_default_decoder_buffer_req(decoder, false); if (decoder->header_in_start) { decoder->client_frame_size = decoder->frame_size; decoder->client_output_buf_req = decoder->actual_output_buf_req; decoder->client_input_buf_req = decoder->actual_input_buf_req; ddl_context->ddl_callback(VCD_EVT_RESP_START, VCD_S_SUCCESS, NULL, 0, (u32 *) ddl, ddl_context->client_data); DDL_IDLE(ddl_context); } else { DBG("%s(): Client data: WxH(%u x %u) SxSL(%u x %u) Sz(%u)\n", __func__, decoder->client_frame_size.width, decoder->client_frame_size.height, decoder->client_frame_size.stride, decoder->client_frame_size.scan_lines, decoder->client_output_buf_req.sz); DBG("%s(): DDL data: WxH(%u x %u) SxSL(%u x %u) Sz(%u)\n", __func__, decoder->frame_size.width, decoder->frame_size.height, decoder->frame_size.stride, decoder->frame_size.scan_lines, decoder->actual_output_buf_req.sz); DBG("%s(): min_dpb_num = %d actual_count = %d\n", __func__, decoder->min_dpb_num, decoder->client_output_buf_req.actual_count); input_vcd_frm = &(ddl->input_frame.vcd_frm); if (decoder->frame_size.width == decoder->client_frame_size.width && decoder->frame_size.height == decoder->client_frame_size.height && decoder->frame_size.stride == decoder->client_frame_size.stride && decoder->frame_size.scan_lines == decoder->client_frame_size.scan_lines && decoder->actual_output_buf_req.sz <= decoder->client_output_buf_req.sz && decoder->actual_output_buf_req.actual_count <= decoder->client_output_buf_req.actual_count && decoder->progressive_only) need_reconfig = false; if ((input_vcd_frm->data_len <= seq_hdr_info.dec_frm_size || (input_vcd_frm->flags & VCD_FRAME_FLAG_CODECCONFIG)) && (!need_reconfig || !(input_vcd_frm->flags & VCD_FRAME_FLAG_EOS))) { input_vcd_frm->flags |= VCD_FRAME_FLAG_CODECCONFIG; seq_hdr_only_frame = true; input_vcd_frm->data_len = 0; ddl->input_frame.frm_trans_end = !need_reconfig; ddl_context->ddl_callback( VCD_EVT_RESP_INPUT_DONE, VCD_S_SUCCESS, &ddl->input_frame, sizeof(struct ddl_frame_data_tag), (u32 *) ddl, ddl->ddl_context->client_data); } else if (decoder->codec.codec != VCD_CODEC_H263) { input_vcd_frm->offset += seq_hdr_info.dec_frm_size; input_vcd_frm->data_len -= seq_hdr_info.dec_frm_size; } if (need_reconfig) { decoder->client_frame_size = decoder->frame_size; decoder->client_output_buf_req = decoder->actual_output_buf_req; decoder->client_input_buf_req = decoder->actual_input_buf_req; if (!seq_hdr_only_frame) { reconfig_payload = &ddl->input_frame; reconfig_payload_size = sizeof(struct ddl_frame_data_tag); } ddl_context->ddl_callback(VCD_EVT_IND_OUTPUT_RECONFIG, VCD_S_SUCCESS, reconfig_payload, reconfig_payload_size, (u32 *) ddl, ddl_context->client_data); } if (!need_reconfig && !seq_hdr_only_frame) { if (ddl_decode_set_buffers(ddl) == VCD_S_SUCCESS) process_further = false; else ddl_client_fatal_cb(ddl_context); } else DDL_IDLE(ddl_context); } return process_further; } static u32 ddl_dpb_buffers_set_done_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl = ddl_context->current_ddl; ddl_move_command_state(ddl_context, DDL_CMD_INVALID); if (!ddl || !DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_DPBDONE) ) { VIDC_LOG_STRING("STATE-CRITICAL-DPBDONE"); ddl_client_fatal_cb(ddl_context); return true; } if (vidc_msg_timing) { ddl_calc_core_proc_time(__func__, DEC_OP_TIME); ddl_reset_core_time_variables(DEC_OP_TIME); } VIDC_LOG_STRING("INTR_DPBDONE"); ddl_move_client_state(ddl, DDL_CLIENT_WAIT_FOR_FRAME); ddl->codec_data.decoder.dec_disp_info.img_size_x = 0; ddl->codec_data.decoder.dec_disp_info.img_size_y = 0; ddl_decode_frame_run(ddl); return false; } static void ddl_encoder_frame_run_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl = ddl_context->current_ddl; struct ddl_encoder_data *encoder = &(ddl->codec_data.encoder); u32 eos_present = false; if (!DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_FRAME_DONE) ) { VIDC_LOG_STRING("STATE-CRITICAL-ENCFRMRUN"); ddl_client_fatal_cb(ddl_context); return; } VIDC_LOG_STRING("ENC_FRM_RUN_DONE"); ddl_move_command_state(ddl_context, DDL_CMD_INVALID); vidc_720p_enc_frame_info(&encoder->enc_frame_info); ddl->output_frame.vcd_frm.ip_frm_tag = ddl->input_frame.vcd_frm.ip_frm_tag; ddl->output_frame.vcd_frm.data_len = encoder->enc_frame_info.enc_size; ddl->output_frame.vcd_frm.flags |= VCD_FRAME_FLAG_ENDOFFRAME; ddl_get_frame (&(ddl->output_frame.vcd_frm), encoder->enc_frame_info.frame); ddl_process_encoder_metadata(ddl); ddl_encode_dynamic_property(ddl, false); ddl->input_frame.frm_trans_end = false; ddl_context->ddl_callback(VCD_EVT_RESP_INPUT_DONE, VCD_S_SUCCESS, &(ddl->input_frame), sizeof(struct ddl_frame_data_tag), (u32 *) ddl, ddl_context->client_data); if (vidc_msg_timing) ddl_calc_core_proc_time(__func__, ENC_OP_TIME); /* check the presence of EOS */ eos_present = ((VCD_FRAME_FLAG_EOS & ddl->input_frame.vcd_frm.flags)); ddl->output_frame.frm_trans_end = !eos_present; ddl_context->ddl_callback(VCD_EVT_RESP_OUTPUT_DONE, VCD_S_SUCCESS, &(ddl->output_frame), sizeof(struct ddl_frame_data_tag), (u32 *) ddl, ddl_context->client_data); if (eos_present) { VIDC_LOG_STRING("ENC-EOS_DONE"); ddl_context->ddl_callback(VCD_EVT_RESP_EOS_DONE, VCD_S_SUCCESS, NULL, 0, (u32 *)ddl, ddl_context->client_data); } ddl_move_client_state(ddl, DDL_CLIENT_WAIT_FOR_FRAME); DDL_IDLE(ddl_context); } static u32 ddl_decoder_frame_run_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl = ddl_context->current_ddl; struct vidc_720p_dec_disp_info *dec_disp_info = &(ddl->codec_data.decoder.dec_disp_info); u32 callback_end = false; u32 status = true, eos_present = false;; if (!DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_FRAME_DONE)) { VIDC_LOG_STRING("STATE-CRITICAL-DECFRMRUN"); ddl_client_fatal_cb(ddl_context); return true; } VIDC_LOG_STRING("DEC_FRM_RUN_DONE"); ddl_move_command_state(ddl_context, DDL_CMD_INVALID); vidc_720p_decode_display_info(dec_disp_info); ddl_decode_dynamic_property(ddl, false); if (dec_disp_info->resl_change) { VIDC_LOG_STRING ("DEC_FRM_RUN_DONE: RECONFIG"); ddl_move_client_state(ddl, DDL_CLIENT_WAIT_FOR_EOS_DONE); ddl_move_command_state(ddl_context, DDL_CMD_EOS); vidc_720p_submit_command(ddl->channel_id, VIDC_720P_CMD_FRAMERUN_REALLOCATE); return false; } if ((VCD_FRAME_FLAG_EOS & ddl->input_frame.vcd_frm.flags)) { callback_end = false; eos_present = true; } if (dec_disp_info->disp_status == VIDC_720P_DECODE_ONLY || dec_disp_info->disp_status == VIDC_720P_DECODE_AND_DISPLAY) { if (!eos_present) callback_end = (dec_disp_info->disp_status == VIDC_720P_DECODE_ONLY); ddl_decoder_input_done_callback(ddl, callback_end); } if (dec_disp_info->disp_status == VIDC_720P_DECODE_AND_DISPLAY || dec_disp_info->disp_status == VIDC_720P_DISPLAY_ONLY) { if (!eos_present) callback_end = (dec_disp_info->disp_status == VIDC_720P_DECODE_AND_DISPLAY); if (ddl_decoder_output_done_callback(ddl, callback_end) != VCD_S_SUCCESS) return true; } if (dec_disp_info->disp_status == VIDC_720P_DISPLAY_ONLY || dec_disp_info->disp_status == VIDC_720P_EMPTY_BUFFER) { /* send the same input once again for decoding */ ddl_decode_frame_run(ddl); /* client need to ignore the interrupt */ status = false; } else if (eos_present) { /* send EOS command to HW */ ddl_decode_eos_run(ddl); /* client need to ignore the interrupt */ status = false; } else { ddl_move_client_state(ddl, DDL_CLIENT_WAIT_FOR_FRAME); /* move to Idle */ DDL_IDLE(ddl_context); } return status; } static u32 ddl_eos_frame_done_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl = ddl_context->current_ddl; struct ddl_decoder_data *decoder = &(ddl->codec_data.decoder); struct vidc_720p_dec_disp_info *dec_disp_info = &(decoder->dec_disp_info); if (!DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_EOS_DONE)) { VIDC_LOGERR_STRING("STATE-CRITICAL-EOSFRMRUN"); ddl_client_fatal_cb(ddl_context); return true; } VIDC_LOG_STRING("EOS_FRM_RUN_DONE"); ddl_move_command_state(ddl_context, DDL_CMD_INVALID); vidc_720p_decode_display_info(dec_disp_info); ddl_decode_dynamic_property(ddl, false); if (dec_disp_info->disp_status == VIDC_720P_DISPLAY_ONLY) { if (ddl_decoder_output_done_callback(ddl, false) != VCD_S_SUCCESS) return true; } else VIDC_LOG_STRING("STATE-CRITICAL-WRONG-DISP-STATUS"); ddl_decoder_dpb_transact(decoder, NULL, DDL_DPB_OP_SET_MASK); ddl_move_command_state(ddl_context, DDL_CMD_EOS); vidc_720p_submit_command(ddl->channel_id, VIDC_720P_CMD_FRAMERUN); return false; } static void ddl_channel_end_callback(struct ddl_context *ddl_context) { struct ddl_client_context *ddl; ddl_move_command_state(ddl_context, DDL_CMD_INVALID); VIDC_LOG_STRING("CH_END_DONE"); ddl = ddl_context->current_ddl; if (!ddl || !DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_CHEND) ) { VIDC_LOG_STRING("STATE-CRITICAL-CHEND"); DDL_IDLE(ddl_context); return; } ddl_release_client_internal_buffers(ddl); ddl_context->ddl_callback(VCD_EVT_RESP_STOP, VCD_S_SUCCESS, NULL, 0, (u32 *) ddl, ddl_context->client_data); ddl_move_client_state(ddl, DDL_CLIENT_OPEN); DDL_IDLE(ddl_context); } static u32 ddl_operation_done_callback(struct ddl_context *ddl_context) { u32 return_status = true; switch (ddl_context->cmd_state) { case DDL_CMD_DECODE_FRAME: { return_status = ddl_decoder_frame_run_callback( ddl_context); break; } case DDL_CMD_ENCODE_FRAME: { ddl_encoder_frame_run_callback(ddl_context); break; } case DDL_CMD_CHANNEL_SET: { return_status = ddl_channel_set_callback( ddl_context); break; } case DDL_CMD_INIT_CODEC: { ddl_init_codec_done_callback(ddl_context); break; } case DDL_CMD_HEADER_PARSE: { return_status = ddl_header_done_callback( ddl_context); break; } case DDL_CMD_DECODE_SET_DPB: { return_status = ddl_dpb_buffers_set_done_callback( ddl_context); break; } case DDL_CMD_CHANNEL_END: { ddl_channel_end_callback(ddl_context); break; } case DDL_CMD_EOS: { return_status = ddl_eos_frame_done_callback( ddl_context); break; } case DDL_CMD_CPU_RESET: { ddl_cpu_started_callback(ddl_context); break; } default: { VIDC_LOG_STRING("UNKWN_OPDONE"); return_status = false; break; } } return return_status; } static u32 ddl_process_intr_status(struct ddl_context *ddl_context, u32 int_status) { u32 status = true; switch (int_status) { case VIDC_720P_INTR_FRAME_DONE: { status = ddl_operation_done_callback(ddl_context); break; } case VIDC_720P_INTR_DMA_DONE: { ddl_dma_done_callback(ddl_context); status = false; break; } case VIDC_720P_INTR_FW_DONE: { status = ddl_eos_done_callback(ddl_context); break; } case VIDC_720P_INTR_BUFFER_FULL: { VIDC_LOGERR_STRING("BUF_FULL_INTR"); ddl_hw_fatal_cb(ddl_context); break; } default: { VIDC_LOGERR_STRING("UNKWN_INTR"); break; } } return status; } void ddl_read_and_clear_interrupt(void) { struct ddl_context *ddl_context; ddl_context = ddl_get_context(); if (!ddl_context->core_virtual_base_addr) { VIDC_LOGERR_STRING("SPURIOUS_INTERRUPT"); return; } vidc_720p_get_interrupt_status(&ddl_context->intr_status, &ddl_context->cmd_err_status, &ddl_context->disp_pic_err_status, &ddl_context->op_failed ); vidc_720p_interrupt_done_clear(); } u32 ddl_process_core_response(void) { struct ddl_context *ddl_context; u32 return_status = true; ddl_context = ddl_get_context(); if (!ddl_context->core_virtual_base_addr) { VIDC_LOGERR_STRING("UNKWN_INTR"); return false; } if (!ddl_handle_core_errors(ddl_context)) { return_status = ddl_process_intr_status(ddl_context, ddl_context->intr_status); } if (ddl_context->interrupt_clr) (*ddl_context->interrupt_clr)(); return return_status; } static void ddl_decoder_input_done_callback( struct ddl_client_context *ddl, u32 frame_transact_end) { struct vidc_720p_dec_disp_info *dec_disp_info = &(ddl->codec_data.decoder.dec_disp_info); struct vcd_frame_data *input_vcd_frm = &(ddl->input_frame.vcd_frm); ddl_get_frame(input_vcd_frm, dec_disp_info-> input_frame); input_vcd_frm->interlaced = (dec_disp_info-> input_is_interlace); input_vcd_frm->offset += dec_disp_info->input_bytes_consumed; input_vcd_frm->data_len -= dec_disp_info->input_bytes_consumed; ddl->input_frame.frm_trans_end = frame_transact_end; if (vidc_msg_timing) ddl_calc_core_proc_time(__func__, DEC_IP_TIME); ddl->ddl_context->ddl_callback( VCD_EVT_RESP_INPUT_DONE, VCD_S_SUCCESS, &ddl->input_frame, sizeof(struct ddl_frame_data_tag), (void *)ddl, ddl->ddl_context->client_data); } static u32 ddl_decoder_output_done_callback( struct ddl_client_context *ddl, u32 frame_transact_end) { struct ddl_decoder_data *decoder = &(ddl->codec_data.decoder); struct vidc_720p_dec_disp_info *dec_disp_info = &(decoder->dec_disp_info); struct ddl_frame_data_tag *output_frame = &ddl->output_frame; struct vcd_frame_data *output_vcd_frm = &(output_frame->vcd_frm); u32 vcd_status; u32 free_luma_dpb = 0; output_vcd_frm->physical = (u8 *)dec_disp_info->y_addr; if (decoder->codec.codec == VCD_CODEC_MPEG4 || decoder->codec.codec == VCD_CODEC_VC1 || decoder->codec.codec == VCD_CODEC_VC1_RCV || (decoder->codec.codec >= VCD_CODEC_DIVX_3 && decoder->codec.codec <= VCD_CODEC_XVID)){ vidc_720p_decode_skip_frm_details(&free_luma_dpb); if (free_luma_dpb) output_vcd_frm->physical = (u8 *) free_luma_dpb; } vcd_status = ddl_decoder_dpb_transact( decoder, output_frame, DDL_DPB_OP_MARK_BUSY); if (vcd_status != VCD_S_SUCCESS) { VIDC_LOGERR_STRING("CorruptedOutputBufferAddress"); ddl_hw_fatal_cb(ddl->ddl_context); return vcd_status; } output_vcd_frm->ip_frm_tag = dec_disp_info->tag_top; if (dec_disp_info->crop_exists == 0x1) { output_vcd_frm->dec_op_prop.disp_frm.left = dec_disp_info->crop_left_offset; output_vcd_frm->dec_op_prop.disp_frm.top = dec_disp_info->crop_top_offset; output_vcd_frm->dec_op_prop.disp_frm.right = dec_disp_info->img_size_x - dec_disp_info->crop_right_offset; output_vcd_frm->dec_op_prop.disp_frm.bottom = dec_disp_info->img_size_y - dec_disp_info->crop_bottom_offset; } else { output_vcd_frm->dec_op_prop.disp_frm.left = 0; output_vcd_frm->dec_op_prop.disp_frm.top = 0; output_vcd_frm->dec_op_prop.disp_frm.right = dec_disp_info->img_size_x; output_vcd_frm->dec_op_prop.disp_frm.bottom = dec_disp_info->img_size_y; } if (!dec_disp_info->disp_is_interlace) { output_vcd_frm->interlaced = false; output_vcd_frm->intrlcd_ip_frm_tag = VCD_FRAMETAG_INVALID; } else { output_vcd_frm->interlaced = true; output_vcd_frm->intrlcd_ip_frm_tag = dec_disp_info->tag_bottom; } output_vcd_frm->offset = 0; output_vcd_frm->data_len = decoder->y_cb_cr_size; if (free_luma_dpb) { output_vcd_frm->data_len = 0; output_vcd_frm->flags |= VCD_FRAME_FLAG_DECODEONLY; } output_vcd_frm->flags |= VCD_FRAME_FLAG_ENDOFFRAME; ddl_process_decoder_metadata(ddl); output_frame->frm_trans_end = frame_transact_end; if (vidc_msg_timing) ddl_calc_core_proc_time(__func__, DEC_OP_TIME); ddl->ddl_context->ddl_callback( VCD_EVT_RESP_OUTPUT_DONE, vcd_status, output_frame, sizeof(struct ddl_frame_data_tag), (void *)ddl, ddl->ddl_context->client_data); return vcd_status; } static u32 ddl_get_frame (struct vcd_frame_data *frame, u32 frametype) { enum vidc_720p_frame vidc_frame = (enum vidc_720p_frame)frametype; u32 status = true; switch (vidc_frame) { case VIDC_720P_IFRAME: { frame->flags |= VCD_FRAME_FLAG_SYNCFRAME; frame->frame = VCD_FRAME_I; break; } case VIDC_720P_PFRAME: { frame->frame = VCD_FRAME_P; break; } case VIDC_720P_BFRAME: { frame->frame = VCD_FRAME_B; break; } case VIDC_720P_NOTCODED: { frame->frame = VCD_FRAME_NOTCODED; frame->data_len = 0; break; } case VIDC_720P_IDRFRAME: { frame->flags |= VCD_FRAME_FLAG_SYNCFRAME; frame->frame = VCD_FRAME_IDR; break; } default: { VIDC_LOG_STRING("CRITICAL-FRAMETYPE"); status = false; break; } } return status; } static void ddl_getmpeg4_declevel(enum vcd_codec_level *codec_level, u32 level) { switch (level) { case VIDC_720P_MPEG4_LEVEL0: { *codec_level = VCD_LEVEL_MPEG4_0; break; } case VIDC_720P_MPEG4_LEVEL0b: { *codec_level = VCD_LEVEL_MPEG4_0b; break; } case VIDC_720P_MPEG4_LEVEL1: { *codec_level = VCD_LEVEL_MPEG4_1; break; } case VIDC_720P_MPEG4_LEVEL2: { *codec_level = VCD_LEVEL_MPEG4_2; break; } case VIDC_720P_MPEG4_LEVEL3: { *codec_level = VCD_LEVEL_MPEG4_3; break; } case VIDC_720P_MPEG4_LEVEL3b: { *codec_level = VCD_LEVEL_MPEG4_3b; break; } case VIDC_720P_MPEG4_LEVEL4a: { *codec_level = VCD_LEVEL_MPEG4_4a; break; } case VIDC_720P_MPEG4_LEVEL5: { *codec_level = VCD_LEVEL_MPEG4_5; break; } case VIDC_720P_MPEG4_LEVEL6: { *codec_level = VCD_LEVEL_MPEG4_6; break; } } } static void ddl_geth264_declevel(enum vcd_codec_level *codec_level, u32 level) { switch (level) { case VIDC_720P_H264_LEVEL1: { *codec_level = VCD_LEVEL_H264_1; break; } case VIDC_720P_H264_LEVEL1b: { *codec_level = VCD_LEVEL_H264_1b; break; } case VIDC_720P_H264_LEVEL1p1: { *codec_level = VCD_LEVEL_H264_1p1; break; } case VIDC_720P_H264_LEVEL1p2: { *codec_level = VCD_LEVEL_H264_1p2; break; } case VIDC_720P_H264_LEVEL1p3: { *codec_level = VCD_LEVEL_H264_1p3; break; } case VIDC_720P_H264_LEVEL2: { *codec_level = VCD_LEVEL_H264_2; break; } case VIDC_720P_H264_LEVEL2p1: { *codec_level = VCD_LEVEL_H264_2p1; break; } case VIDC_720P_H264_LEVEL2p2: { *codec_level = VCD_LEVEL_H264_2p2; break; } case VIDC_720P_H264_LEVEL3: { *codec_level = VCD_LEVEL_H264_3; break; } case VIDC_720P_H264_LEVEL3p1: { *codec_level = VCD_LEVEL_H264_3p1; break; } case VIDC_720P_H264_LEVEL3p2: { *codec_level = VCD_LEVEL_H264_3p2; break; } } } static void ddl_get_vc1_dec_level( enum vcd_codec_level *codec_level, u32 level, enum vcd_codec_profile vc1_profile) { if (vc1_profile == VCD_PROFILE_VC1_ADVANCE) { switch (level) { case VIDC_720P_VC1_LEVEL0: { *codec_level = VCD_LEVEL_VC1_A_0; break; } case VIDC_720P_VC1_LEVEL1: { *codec_level = VCD_LEVEL_VC1_A_1; break; } case VIDC_720P_VC1_LEVEL2: { *codec_level = VCD_LEVEL_VC1_A_2; break; } case VIDC_720P_VC1_LEVEL3: { *codec_level = VCD_LEVEL_VC1_A_3; break; } case VIDC_720P_VC1_LEVEL4: { *codec_level = VCD_LEVEL_VC1_A_4; break; } } return; } else if (vc1_profile == VCD_PROFILE_VC1_MAIN) { switch (level) { case VIDC_720P_VC1_LEVEL_LOW: { *codec_level = VCD_LEVEL_VC1_M_LOW; break; } case VIDC_720P_VC1_LEVEL_MED: { *codec_level = VCD_LEVEL_VC1_M_MEDIUM; break; } case VIDC_720P_VC1_LEVEL_HIGH: { *codec_level = VCD_LEVEL_VC1_M_HIGH; break; } } } else if (vc1_profile == VCD_PROFILE_VC1_SIMPLE) { switch (level) { case VIDC_720P_VC1_LEVEL_LOW: { *codec_level = VCD_LEVEL_VC1_S_LOW; break; } case VIDC_720P_VC1_LEVEL_MED: { *codec_level = VCD_LEVEL_VC1_S_MEDIUM; break; } } } } static void ddl_get_mpeg2_dec_level(enum vcd_codec_level *codec_level, u32 level) { switch (level) { case VIDCL_720P_MPEG2_LEVEL_LOW: { *codec_level = VCD_LEVEL_MPEG2_LOW; break; } case VIDCL_720P_MPEG2_LEVEL_MAIN: { *codec_level = VCD_LEVEL_MPEG2_MAIN; break; } case VIDCL_720P_MPEG2_LEVEL_HIGH14: { *codec_level = VCD_LEVEL_MPEG2_HIGH_14; break; } } } static void ddl_getdec_profilelevel(struct ddl_decoder_data *decoder, u32 profile, u32 level) { enum vcd_codec_profile codec_profile = VCD_PROFILE_UNKNOWN; enum vcd_codec_level codec_level = VCD_LEVEL_UNKNOWN; switch (decoder->codec.codec) { case VCD_CODEC_MPEG4: { if (profile == VIDC_720P_PROFILE_MPEG4_SP) codec_profile = VCD_PROFILE_MPEG4_SP; else if (profile == VIDC_720P_PROFILE_MPEG4_ASP) codec_profile = VCD_PROFILE_MPEG4_ASP; ddl_getmpeg4_declevel(&codec_level, level); break; } case VCD_CODEC_H264: { if (profile == VIDC_720P_PROFILE_H264_BASELINE) codec_profile = VCD_PROFILE_H264_BASELINE; else if (profile == VIDC_720P_PROFILE_H264_MAIN) codec_profile = VCD_PROFILE_H264_MAIN; else if (profile == VIDC_720P_PROFILE_H264_HIGH) codec_profile = VCD_PROFILE_H264_HIGH; ddl_geth264_declevel(&codec_level, level); break; } default: case VCD_CODEC_H263: { break; } case VCD_CODEC_VC1: case VCD_CODEC_VC1_RCV: { if (profile == VIDC_720P_PROFILE_VC1_SP) codec_profile = VCD_PROFILE_VC1_SIMPLE; else if (profile == VIDC_720P_PROFILE_VC1_MAIN) codec_profile = VCD_PROFILE_VC1_MAIN; else if (profile == VIDC_720P_PROFILE_VC1_ADV) codec_profile = VCD_PROFILE_VC1_ADVANCE; ddl_get_vc1_dec_level(&codec_level, level, profile); break; } case VCD_CODEC_MPEG2: { if (profile == VIDC_720P_PROFILE_MPEG2_MAIN) codec_profile = VCD_PROFILE_MPEG2_MAIN; else if (profile == VIDC_720P_PROFILE_MPEG2_SP) codec_profile = VCD_PROFILE_MPEG2_SIMPLE; ddl_get_mpeg2_dec_level(&codec_level, level); break; } } decoder->profile.profile = codec_profile; decoder->level.level = codec_level; }
gpl-2.0
maxwen/primou-kernel-HELLBOY
lib/rwsem-spinlock.c
3874
7103
/* rwsem-spinlock.c: R/W semaphores: contention handling functions for * generic spinlock implementation * * Copyright (c) 2001 David Howells (dhowells@redhat.com). * - Derived partially from idea by Andrea Arcangeli <andrea@suse.de> * - Derived also from comments by Linus */ #include <linux/rwsem.h> #include <linux/sched.h> #include <linux/module.h> struct rwsem_waiter { struct list_head list; struct task_struct *task; unsigned int flags; #define RWSEM_WAITING_FOR_READ 0x00000001 #define RWSEM_WAITING_FOR_WRITE 0x00000002 }; int rwsem_is_locked(struct rw_semaphore *sem) { int ret = 1; unsigned long flags; if (spin_trylock_irqsave(&sem->wait_lock, flags)) { ret = (sem->activity != 0); spin_unlock_irqrestore(&sem->wait_lock, flags); } return ret; } EXPORT_SYMBOL(rwsem_is_locked); /* * initialise the semaphore */ void __init_rwsem(struct rw_semaphore *sem, const char *name, struct lock_class_key *key) { #ifdef CONFIG_DEBUG_LOCK_ALLOC /* * Make sure we are not reinitializing a held semaphore: */ debug_check_no_locks_freed((void *)sem, sizeof(*sem)); lockdep_init_map(&sem->dep_map, name, key, 0); #endif sem->activity = 0; spin_lock_init(&sem->wait_lock); INIT_LIST_HEAD(&sem->wait_list); } EXPORT_SYMBOL(__init_rwsem); /* * handle the lock release when processes blocked on it that can now run * - if we come here, then: * - the 'active count' _reached_ zero * - the 'waiting count' is non-zero * - the spinlock must be held by the caller * - woken process blocks are discarded from the list after having task zeroed * - writers are only woken if wakewrite is non-zero */ static inline struct rw_semaphore * __rwsem_do_wake(struct rw_semaphore *sem, int wakewrite) { struct rwsem_waiter *waiter; struct task_struct *tsk; int woken; waiter = list_entry(sem->wait_list.next, struct rwsem_waiter, list); if (!wakewrite) { if (waiter->flags & RWSEM_WAITING_FOR_WRITE) goto out; goto dont_wake_writers; } /* if we are allowed to wake writers try to grant a single write lock * if there's a writer at the front of the queue * - we leave the 'waiting count' incremented to signify potential * contention */ if (waiter->flags & RWSEM_WAITING_FOR_WRITE) { sem->activity = -1; list_del(&waiter->list); tsk = waiter->task; /* Don't touch waiter after ->task has been NULLed */ smp_mb(); waiter->task = NULL; wake_up_process(tsk); put_task_struct(tsk); goto out; } /* grant an infinite number of read locks to the front of the queue */ dont_wake_writers: woken = 0; while (waiter->flags & RWSEM_WAITING_FOR_READ) { struct list_head *next = waiter->list.next; list_del(&waiter->list); tsk = waiter->task; smp_mb(); waiter->task = NULL; wake_up_process(tsk); put_task_struct(tsk); woken++; if (list_empty(&sem->wait_list)) break; waiter = list_entry(next, struct rwsem_waiter, list); } sem->activity += woken; out: return sem; } /* * wake a single writer */ static inline struct rw_semaphore * __rwsem_wake_one_writer(struct rw_semaphore *sem) { struct rwsem_waiter *waiter; struct task_struct *tsk; sem->activity = -1; waiter = list_entry(sem->wait_list.next, struct rwsem_waiter, list); list_del(&waiter->list); tsk = waiter->task; smp_mb(); waiter->task = NULL; wake_up_process(tsk); put_task_struct(tsk); return sem; } /* * get a read lock on the semaphore */ void __sched __down_read(struct rw_semaphore *sem) { struct rwsem_waiter waiter; struct task_struct *tsk; unsigned long flags; spin_lock_irqsave(&sem->wait_lock, flags); if (sem->activity >= 0 && list_empty(&sem->wait_list)) { /* granted */ sem->activity++; spin_unlock_irqrestore(&sem->wait_lock, flags); goto out; } tsk = current; set_task_state(tsk, TASK_UNINTERRUPTIBLE); /* set up my own style of waitqueue */ waiter.task = tsk; waiter.flags = RWSEM_WAITING_FOR_READ; get_task_struct(tsk); list_add_tail(&waiter.list, &sem->wait_list); /* we don't need to touch the semaphore struct anymore */ spin_unlock_irqrestore(&sem->wait_lock, flags); /* wait to be given the lock */ for (;;) { if (!waiter.task) break; schedule(); set_task_state(tsk, TASK_UNINTERRUPTIBLE); } tsk->state = TASK_RUNNING; out: ; } /* * trylock for reading -- returns 1 if successful, 0 if contention */ int __down_read_trylock(struct rw_semaphore *sem) { unsigned long flags; int ret = 0; spin_lock_irqsave(&sem->wait_lock, flags); if (sem->activity >= 0 && list_empty(&sem->wait_list)) { /* granted */ sem->activity++; ret = 1; } spin_unlock_irqrestore(&sem->wait_lock, flags); return ret; } /* * get a write lock on the semaphore * - we increment the waiting count anyway to indicate an exclusive lock */ void __sched __down_write_nested(struct rw_semaphore *sem, int subclass) { struct rwsem_waiter waiter; struct task_struct *tsk; unsigned long flags; spin_lock_irqsave(&sem->wait_lock, flags); if (sem->activity == 0 && list_empty(&sem->wait_list)) { /* granted */ sem->activity = -1; spin_unlock_irqrestore(&sem->wait_lock, flags); goto out; } tsk = current; set_task_state(tsk, TASK_UNINTERRUPTIBLE); /* set up my own style of waitqueue */ waiter.task = tsk; waiter.flags = RWSEM_WAITING_FOR_WRITE; get_task_struct(tsk); list_add_tail(&waiter.list, &sem->wait_list); /* we don't need to touch the semaphore struct anymore */ spin_unlock_irqrestore(&sem->wait_lock, flags); /* wait to be given the lock */ for (;;) { if (!waiter.task) break; schedule(); set_task_state(tsk, TASK_UNINTERRUPTIBLE); } tsk->state = TASK_RUNNING; out: ; } void __sched __down_write(struct rw_semaphore *sem) { __down_write_nested(sem, 0); } /* * trylock for writing -- returns 1 if successful, 0 if contention */ int __down_write_trylock(struct rw_semaphore *sem) { unsigned long flags; int ret = 0; spin_lock_irqsave(&sem->wait_lock, flags); if (sem->activity == 0 && list_empty(&sem->wait_list)) { /* granted */ sem->activity = -1; ret = 1; } spin_unlock_irqrestore(&sem->wait_lock, flags); return ret; } /* * release a read lock on the semaphore */ void __up_read(struct rw_semaphore *sem) { unsigned long flags; spin_lock_irqsave(&sem->wait_lock, flags); if (--sem->activity == 0 && !list_empty(&sem->wait_list)) sem = __rwsem_wake_one_writer(sem); spin_unlock_irqrestore(&sem->wait_lock, flags); } /* * release a write lock on the semaphore */ void __up_write(struct rw_semaphore *sem) { unsigned long flags; spin_lock_irqsave(&sem->wait_lock, flags); sem->activity = 0; if (!list_empty(&sem->wait_list)) sem = __rwsem_do_wake(sem, 1); spin_unlock_irqrestore(&sem->wait_lock, flags); } /* * downgrade a write lock into a read lock * - just wake up any readers at the front of the queue */ void __downgrade_write(struct rw_semaphore *sem) { unsigned long flags; spin_lock_irqsave(&sem->wait_lock, flags); sem->activity = 1; if (!list_empty(&sem->wait_list)) sem = __rwsem_do_wake(sem, 0); spin_unlock_irqrestore(&sem->wait_lock, flags); }
gpl-2.0
jyunyen/Nexus7_Kernal
fs/ubifs/lprops.c
3874
36697
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Adrian Hunter * Artem Bityutskiy (Битюцкий Артём) */ /* * This file implements the functions that access LEB properties and their * categories. LEBs are categorized based on the needs of UBIFS, and the * categories are stored as either heaps or lists to provide a fast way of * finding a LEB in a particular category. For example, UBIFS may need to find * an empty LEB for the journal, or a very dirty LEB for garbage collection. */ #include "ubifs.h" /** * get_heap_comp_val - get the LEB properties value for heap comparisons. * @lprops: LEB properties * @cat: LEB category */ static int get_heap_comp_val(struct ubifs_lprops *lprops, int cat) { switch (cat) { case LPROPS_FREE: return lprops->free; case LPROPS_DIRTY_IDX: return lprops->free + lprops->dirty; default: return lprops->dirty; } } /** * move_up_lpt_heap - move a new heap entry up as far as possible. * @c: UBIFS file-system description object * @heap: LEB category heap * @lprops: LEB properties to move * @cat: LEB category * * New entries to a heap are added at the bottom and then moved up until the * parent's value is greater. In the case of LPT's category heaps, the value * is either the amount of free space or the amount of dirty space, depending * on the category. */ static void move_up_lpt_heap(struct ubifs_info *c, struct ubifs_lpt_heap *heap, struct ubifs_lprops *lprops, int cat) { int val1, val2, hpos; hpos = lprops->hpos; if (!hpos) return; /* Already top of the heap */ val1 = get_heap_comp_val(lprops, cat); /* Compare to parent and, if greater, move up the heap */ do { int ppos = (hpos - 1) / 2; val2 = get_heap_comp_val(heap->arr[ppos], cat); if (val2 >= val1) return; /* Greater than parent so move up */ heap->arr[ppos]->hpos = hpos; heap->arr[hpos] = heap->arr[ppos]; heap->arr[ppos] = lprops; lprops->hpos = ppos; hpos = ppos; } while (hpos); } /** * adjust_lpt_heap - move a changed heap entry up or down the heap. * @c: UBIFS file-system description object * @heap: LEB category heap * @lprops: LEB properties to move * @hpos: heap position of @lprops * @cat: LEB category * * Changed entries in a heap are moved up or down until the parent's value is * greater. In the case of LPT's category heaps, the value is either the amount * of free space or the amount of dirty space, depending on the category. */ static void adjust_lpt_heap(struct ubifs_info *c, struct ubifs_lpt_heap *heap, struct ubifs_lprops *lprops, int hpos, int cat) { int val1, val2, val3, cpos; val1 = get_heap_comp_val(lprops, cat); /* Compare to parent and, if greater than parent, move up the heap */ if (hpos) { int ppos = (hpos - 1) / 2; val2 = get_heap_comp_val(heap->arr[ppos], cat); if (val1 > val2) { /* Greater than parent so move up */ while (1) { heap->arr[ppos]->hpos = hpos; heap->arr[hpos] = heap->arr[ppos]; heap->arr[ppos] = lprops; lprops->hpos = ppos; hpos = ppos; if (!hpos) return; ppos = (hpos - 1) / 2; val2 = get_heap_comp_val(heap->arr[ppos], cat); if (val1 <= val2) return; /* Still greater than parent so keep going */ } } } /* Not greater than parent, so compare to children */ while (1) { /* Compare to left child */ cpos = hpos * 2 + 1; if (cpos >= heap->cnt) return; val2 = get_heap_comp_val(heap->arr[cpos], cat); if (val1 < val2) { /* Less than left child, so promote biggest child */ if (cpos + 1 < heap->cnt) { val3 = get_heap_comp_val(heap->arr[cpos + 1], cat); if (val3 > val2) cpos += 1; /* Right child is bigger */ } heap->arr[cpos]->hpos = hpos; heap->arr[hpos] = heap->arr[cpos]; heap->arr[cpos] = lprops; lprops->hpos = cpos; hpos = cpos; continue; } /* Compare to right child */ cpos += 1; if (cpos >= heap->cnt) return; val3 = get_heap_comp_val(heap->arr[cpos], cat); if (val1 < val3) { /* Less than right child, so promote right child */ heap->arr[cpos]->hpos = hpos; heap->arr[hpos] = heap->arr[cpos]; heap->arr[cpos] = lprops; lprops->hpos = cpos; hpos = cpos; continue; } return; } } /** * add_to_lpt_heap - add LEB properties to a LEB category heap. * @c: UBIFS file-system description object * @lprops: LEB properties to add * @cat: LEB category * * This function returns %1 if @lprops is added to the heap for LEB category * @cat, otherwise %0 is returned because the heap is full. */ static int add_to_lpt_heap(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat) { struct ubifs_lpt_heap *heap = &c->lpt_heap[cat - 1]; if (heap->cnt >= heap->max_cnt) { const int b = LPT_HEAP_SZ / 2 - 1; int cpos, val1, val2; /* Compare to some other LEB on the bottom of heap */ /* Pick a position kind of randomly */ cpos = (((size_t)lprops >> 4) & b) + b; ubifs_assert(cpos >= b); ubifs_assert(cpos < LPT_HEAP_SZ); ubifs_assert(cpos < heap->cnt); val1 = get_heap_comp_val(lprops, cat); val2 = get_heap_comp_val(heap->arr[cpos], cat); if (val1 > val2) { struct ubifs_lprops *lp; lp = heap->arr[cpos]; lp->flags &= ~LPROPS_CAT_MASK; lp->flags |= LPROPS_UNCAT; list_add(&lp->list, &c->uncat_list); lprops->hpos = cpos; heap->arr[cpos] = lprops; move_up_lpt_heap(c, heap, lprops, cat); dbg_check_heap(c, heap, cat, lprops->hpos); return 1; /* Added to heap */ } dbg_check_heap(c, heap, cat, -1); return 0; /* Not added to heap */ } else { lprops->hpos = heap->cnt++; heap->arr[lprops->hpos] = lprops; move_up_lpt_heap(c, heap, lprops, cat); dbg_check_heap(c, heap, cat, lprops->hpos); return 1; /* Added to heap */ } } /** * remove_from_lpt_heap - remove LEB properties from a LEB category heap. * @c: UBIFS file-system description object * @lprops: LEB properties to remove * @cat: LEB category */ static void remove_from_lpt_heap(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat) { struct ubifs_lpt_heap *heap; int hpos = lprops->hpos; heap = &c->lpt_heap[cat - 1]; ubifs_assert(hpos >= 0 && hpos < heap->cnt); ubifs_assert(heap->arr[hpos] == lprops); heap->cnt -= 1; if (hpos < heap->cnt) { heap->arr[hpos] = heap->arr[heap->cnt]; heap->arr[hpos]->hpos = hpos; adjust_lpt_heap(c, heap, heap->arr[hpos], hpos, cat); } dbg_check_heap(c, heap, cat, -1); } /** * lpt_heap_replace - replace lprops in a category heap. * @c: UBIFS file-system description object * @old_lprops: LEB properties to replace * @new_lprops: LEB properties with which to replace * @cat: LEB category * * During commit it is sometimes necessary to copy a pnode (see dirty_cow_pnode) * and the lprops that the pnode contains. When that happens, references in * the category heaps to those lprops must be updated to point to the new * lprops. This function does that. */ static void lpt_heap_replace(struct ubifs_info *c, struct ubifs_lprops *old_lprops, struct ubifs_lprops *new_lprops, int cat) { struct ubifs_lpt_heap *heap; int hpos = new_lprops->hpos; heap = &c->lpt_heap[cat - 1]; heap->arr[hpos] = new_lprops; } /** * ubifs_add_to_cat - add LEB properties to a category list or heap. * @c: UBIFS file-system description object * @lprops: LEB properties to add * @cat: LEB category to which to add * * LEB properties are categorized to enable fast find operations. */ void ubifs_add_to_cat(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat) { switch (cat) { case LPROPS_DIRTY: case LPROPS_DIRTY_IDX: case LPROPS_FREE: if (add_to_lpt_heap(c, lprops, cat)) break; /* No more room on heap so make it un-categorized */ cat = LPROPS_UNCAT; /* Fall through */ case LPROPS_UNCAT: list_add(&lprops->list, &c->uncat_list); break; case LPROPS_EMPTY: list_add(&lprops->list, &c->empty_list); break; case LPROPS_FREEABLE: list_add(&lprops->list, &c->freeable_list); c->freeable_cnt += 1; break; case LPROPS_FRDI_IDX: list_add(&lprops->list, &c->frdi_idx_list); break; default: ubifs_assert(0); } lprops->flags &= ~LPROPS_CAT_MASK; lprops->flags |= cat; } /** * ubifs_remove_from_cat - remove LEB properties from a category list or heap. * @c: UBIFS file-system description object * @lprops: LEB properties to remove * @cat: LEB category from which to remove * * LEB properties are categorized to enable fast find operations. */ static void ubifs_remove_from_cat(struct ubifs_info *c, struct ubifs_lprops *lprops, int cat) { switch (cat) { case LPROPS_DIRTY: case LPROPS_DIRTY_IDX: case LPROPS_FREE: remove_from_lpt_heap(c, lprops, cat); break; case LPROPS_FREEABLE: c->freeable_cnt -= 1; ubifs_assert(c->freeable_cnt >= 0); /* Fall through */ case LPROPS_UNCAT: case LPROPS_EMPTY: case LPROPS_FRDI_IDX: ubifs_assert(!list_empty(&lprops->list)); list_del(&lprops->list); break; default: ubifs_assert(0); } } /** * ubifs_replace_cat - replace lprops in a category list or heap. * @c: UBIFS file-system description object * @old_lprops: LEB properties to replace * @new_lprops: LEB properties with which to replace * * During commit it is sometimes necessary to copy a pnode (see dirty_cow_pnode) * and the lprops that the pnode contains. When that happens, references in * category lists and heaps must be replaced. This function does that. */ void ubifs_replace_cat(struct ubifs_info *c, struct ubifs_lprops *old_lprops, struct ubifs_lprops *new_lprops) { int cat; cat = new_lprops->flags & LPROPS_CAT_MASK; switch (cat) { case LPROPS_DIRTY: case LPROPS_DIRTY_IDX: case LPROPS_FREE: lpt_heap_replace(c, old_lprops, new_lprops, cat); break; case LPROPS_UNCAT: case LPROPS_EMPTY: case LPROPS_FREEABLE: case LPROPS_FRDI_IDX: list_replace(&old_lprops->list, &new_lprops->list); break; default: ubifs_assert(0); } } /** * ubifs_ensure_cat - ensure LEB properties are categorized. * @c: UBIFS file-system description object * @lprops: LEB properties * * A LEB may have fallen off of the bottom of a heap, and ended up as * un-categorized even though it has enough space for us now. If that is the * case this function will put the LEB back onto a heap. */ void ubifs_ensure_cat(struct ubifs_info *c, struct ubifs_lprops *lprops) { int cat = lprops->flags & LPROPS_CAT_MASK; if (cat != LPROPS_UNCAT) return; cat = ubifs_categorize_lprops(c, lprops); if (cat == LPROPS_UNCAT) return; ubifs_remove_from_cat(c, lprops, LPROPS_UNCAT); ubifs_add_to_cat(c, lprops, cat); } /** * ubifs_categorize_lprops - categorize LEB properties. * @c: UBIFS file-system description object * @lprops: LEB properties to categorize * * LEB properties are categorized to enable fast find operations. This function * returns the LEB category to which the LEB properties belong. Note however * that if the LEB category is stored as a heap and the heap is full, the * LEB properties may have their category changed to %LPROPS_UNCAT. */ int ubifs_categorize_lprops(const struct ubifs_info *c, const struct ubifs_lprops *lprops) { if (lprops->flags & LPROPS_TAKEN) return LPROPS_UNCAT; if (lprops->free == c->leb_size) { ubifs_assert(!(lprops->flags & LPROPS_INDEX)); return LPROPS_EMPTY; } if (lprops->free + lprops->dirty == c->leb_size) { if (lprops->flags & LPROPS_INDEX) return LPROPS_FRDI_IDX; else return LPROPS_FREEABLE; } if (lprops->flags & LPROPS_INDEX) { if (lprops->dirty + lprops->free >= c->min_idx_node_sz) return LPROPS_DIRTY_IDX; } else { if (lprops->dirty >= c->dead_wm && lprops->dirty > lprops->free) return LPROPS_DIRTY; if (lprops->free > 0) return LPROPS_FREE; } return LPROPS_UNCAT; } /** * change_category - change LEB properties category. * @c: UBIFS file-system description object * @lprops: LEB properties to re-categorize * * LEB properties are categorized to enable fast find operations. When the LEB * properties change they must be re-categorized. */ static void change_category(struct ubifs_info *c, struct ubifs_lprops *lprops) { int old_cat = lprops->flags & LPROPS_CAT_MASK; int new_cat = ubifs_categorize_lprops(c, lprops); if (old_cat == new_cat) { struct ubifs_lpt_heap *heap = &c->lpt_heap[new_cat - 1]; /* lprops on a heap now must be moved up or down */ if (new_cat < 1 || new_cat > LPROPS_HEAP_CNT) return; /* Not on a heap */ heap = &c->lpt_heap[new_cat - 1]; adjust_lpt_heap(c, heap, lprops, lprops->hpos, new_cat); } else { ubifs_remove_from_cat(c, lprops, old_cat); ubifs_add_to_cat(c, lprops, new_cat); } } /** * ubifs_calc_dark - calculate LEB dark space size. * @c: the UBIFS file-system description object * @spc: amount of free and dirty space in the LEB * * This function calculates and returns amount of dark space in an LEB which * has @spc bytes of free and dirty space. * * UBIFS is trying to account the space which might not be usable, and this * space is called "dark space". For example, if an LEB has only %512 free * bytes, it is dark space, because it cannot fit a large data node. */ int ubifs_calc_dark(const struct ubifs_info *c, int spc) { ubifs_assert(!(spc & 7)); if (spc < c->dark_wm) return spc; /* * If we have slightly more space then the dark space watermark, we can * anyway safely assume it we'll be able to write a node of the * smallest size there. */ if (spc - c->dark_wm < MIN_WRITE_SZ) return spc - MIN_WRITE_SZ; return c->dark_wm; } /** * is_lprops_dirty - determine if LEB properties are dirty. * @c: the UBIFS file-system description object * @lprops: LEB properties to test */ static int is_lprops_dirty(struct ubifs_info *c, struct ubifs_lprops *lprops) { struct ubifs_pnode *pnode; int pos; pos = (lprops->lnum - c->main_first) & (UBIFS_LPT_FANOUT - 1); pnode = (struct ubifs_pnode *)container_of(lprops - pos, struct ubifs_pnode, lprops[0]); return !test_bit(COW_CNODE, &pnode->flags) && test_bit(DIRTY_CNODE, &pnode->flags); } /** * ubifs_change_lp - change LEB properties. * @c: the UBIFS file-system description object * @lp: LEB properties to change * @free: new free space amount * @dirty: new dirty space amount * @flags: new flags * @idx_gc_cnt: change to the count of @idx_gc list * * This function changes LEB properties (@free, @dirty or @flag). However, the * property which has the %LPROPS_NC value is not changed. Returns a pointer to * the updated LEB properties on success and a negative error code on failure. * * Note, the LEB properties may have had to be copied (due to COW) and * consequently the pointer returned may not be the same as the pointer * passed. */ const struct ubifs_lprops *ubifs_change_lp(struct ubifs_info *c, const struct ubifs_lprops *lp, int free, int dirty, int flags, int idx_gc_cnt) { /* * This is the only function that is allowed to change lprops, so we * discard the "const" qualifier. */ struct ubifs_lprops *lprops = (struct ubifs_lprops *)lp; dbg_lp("LEB %d, free %d, dirty %d, flags %d", lprops->lnum, free, dirty, flags); ubifs_assert(mutex_is_locked(&c->lp_mutex)); ubifs_assert(c->lst.empty_lebs >= 0 && c->lst.empty_lebs <= c->main_lebs); ubifs_assert(c->freeable_cnt >= 0); ubifs_assert(c->freeable_cnt <= c->main_lebs); ubifs_assert(c->lst.taken_empty_lebs >= 0); ubifs_assert(c->lst.taken_empty_lebs <= c->lst.empty_lebs); ubifs_assert(!(c->lst.total_free & 7) && !(c->lst.total_dirty & 7)); ubifs_assert(!(c->lst.total_dead & 7) && !(c->lst.total_dark & 7)); ubifs_assert(!(c->lst.total_used & 7)); ubifs_assert(free == LPROPS_NC || free >= 0); ubifs_assert(dirty == LPROPS_NC || dirty >= 0); if (!is_lprops_dirty(c, lprops)) { lprops = ubifs_lpt_lookup_dirty(c, lprops->lnum); if (IS_ERR(lprops)) return lprops; } else ubifs_assert(lprops == ubifs_lpt_lookup_dirty(c, lprops->lnum)); ubifs_assert(!(lprops->free & 7) && !(lprops->dirty & 7)); spin_lock(&c->space_lock); if ((lprops->flags & LPROPS_TAKEN) && lprops->free == c->leb_size) c->lst.taken_empty_lebs -= 1; if (!(lprops->flags & LPROPS_INDEX)) { int old_spc; old_spc = lprops->free + lprops->dirty; if (old_spc < c->dead_wm) c->lst.total_dead -= old_spc; else c->lst.total_dark -= ubifs_calc_dark(c, old_spc); c->lst.total_used -= c->leb_size - old_spc; } if (free != LPROPS_NC) { free = ALIGN(free, 8); c->lst.total_free += free - lprops->free; /* Increase or decrease empty LEBs counter if needed */ if (free == c->leb_size) { if (lprops->free != c->leb_size) c->lst.empty_lebs += 1; } else if (lprops->free == c->leb_size) c->lst.empty_lebs -= 1; lprops->free = free; } if (dirty != LPROPS_NC) { dirty = ALIGN(dirty, 8); c->lst.total_dirty += dirty - lprops->dirty; lprops->dirty = dirty; } if (flags != LPROPS_NC) { /* Take care about indexing LEBs counter if needed */ if ((lprops->flags & LPROPS_INDEX)) { if (!(flags & LPROPS_INDEX)) c->lst.idx_lebs -= 1; } else if (flags & LPROPS_INDEX) c->lst.idx_lebs += 1; lprops->flags = flags; } if (!(lprops->flags & LPROPS_INDEX)) { int new_spc; new_spc = lprops->free + lprops->dirty; if (new_spc < c->dead_wm) c->lst.total_dead += new_spc; else c->lst.total_dark += ubifs_calc_dark(c, new_spc); c->lst.total_used += c->leb_size - new_spc; } if ((lprops->flags & LPROPS_TAKEN) && lprops->free == c->leb_size) c->lst.taken_empty_lebs += 1; change_category(c, lprops); c->idx_gc_cnt += idx_gc_cnt; spin_unlock(&c->space_lock); return lprops; } /** * ubifs_get_lp_stats - get lprops statistics. * @c: UBIFS file-system description object * @st: return statistics */ void ubifs_get_lp_stats(struct ubifs_info *c, struct ubifs_lp_stats *lst) { spin_lock(&c->space_lock); memcpy(lst, &c->lst, sizeof(struct ubifs_lp_stats)); spin_unlock(&c->space_lock); } /** * ubifs_change_one_lp - change LEB properties. * @c: the UBIFS file-system description object * @lnum: LEB to change properties for * @free: amount of free space * @dirty: amount of dirty space * @flags_set: flags to set * @flags_clean: flags to clean * @idx_gc_cnt: change to the count of idx_gc list * * This function changes properties of LEB @lnum. It is a helper wrapper over * 'ubifs_change_lp()' which hides lprops get/release. The arguments are the * same as in case of 'ubifs_change_lp()'. Returns zero in case of success and * a negative error code in case of failure. */ int ubifs_change_one_lp(struct ubifs_info *c, int lnum, int free, int dirty, int flags_set, int flags_clean, int idx_gc_cnt) { int err = 0, flags; const struct ubifs_lprops *lp; ubifs_get_lprops(c); lp = ubifs_lpt_lookup_dirty(c, lnum); if (IS_ERR(lp)) { err = PTR_ERR(lp); goto out; } flags = (lp->flags | flags_set) & ~flags_clean; lp = ubifs_change_lp(c, lp, free, dirty, flags, idx_gc_cnt); if (IS_ERR(lp)) err = PTR_ERR(lp); out: ubifs_release_lprops(c); if (err) ubifs_err("cannot change properties of LEB %d, error %d", lnum, err); return err; } /** * ubifs_update_one_lp - update LEB properties. * @c: the UBIFS file-system description object * @lnum: LEB to change properties for * @free: amount of free space * @dirty: amount of dirty space to add * @flags_set: flags to set * @flags_clean: flags to clean * * This function is the same as 'ubifs_change_one_lp()' but @dirty is added to * current dirty space, not substitutes it. */ int ubifs_update_one_lp(struct ubifs_info *c, int lnum, int free, int dirty, int flags_set, int flags_clean) { int err = 0, flags; const struct ubifs_lprops *lp; ubifs_get_lprops(c); lp = ubifs_lpt_lookup_dirty(c, lnum); if (IS_ERR(lp)) { err = PTR_ERR(lp); goto out; } flags = (lp->flags | flags_set) & ~flags_clean; lp = ubifs_change_lp(c, lp, free, lp->dirty + dirty, flags, 0); if (IS_ERR(lp)) err = PTR_ERR(lp); out: ubifs_release_lprops(c); if (err) ubifs_err("cannot update properties of LEB %d, error %d", lnum, err); return err; } /** * ubifs_read_one_lp - read LEB properties. * @c: the UBIFS file-system description object * @lnum: LEB to read properties for * @lp: where to store read properties * * This helper function reads properties of a LEB @lnum and stores them in @lp. * Returns zero in case of success and a negative error code in case of * failure. */ int ubifs_read_one_lp(struct ubifs_info *c, int lnum, struct ubifs_lprops *lp) { int err = 0; const struct ubifs_lprops *lpp; ubifs_get_lprops(c); lpp = ubifs_lpt_lookup(c, lnum); if (IS_ERR(lpp)) { err = PTR_ERR(lpp); ubifs_err("cannot read properties of LEB %d, error %d", lnum, err); goto out; } memcpy(lp, lpp, sizeof(struct ubifs_lprops)); out: ubifs_release_lprops(c); return err; } /** * ubifs_fast_find_free - try to find a LEB with free space quickly. * @c: the UBIFS file-system description object * * This function returns LEB properties for a LEB with free space or %NULL if * the function is unable to find a LEB quickly. */ const struct ubifs_lprops *ubifs_fast_find_free(struct ubifs_info *c) { struct ubifs_lprops *lprops; struct ubifs_lpt_heap *heap; ubifs_assert(mutex_is_locked(&c->lp_mutex)); heap = &c->lpt_heap[LPROPS_FREE - 1]; if (heap->cnt == 0) return NULL; lprops = heap->arr[0]; ubifs_assert(!(lprops->flags & LPROPS_TAKEN)); ubifs_assert(!(lprops->flags & LPROPS_INDEX)); return lprops; } /** * ubifs_fast_find_empty - try to find an empty LEB quickly. * @c: the UBIFS file-system description object * * This function returns LEB properties for an empty LEB or %NULL if the * function is unable to find an empty LEB quickly. */ const struct ubifs_lprops *ubifs_fast_find_empty(struct ubifs_info *c) { struct ubifs_lprops *lprops; ubifs_assert(mutex_is_locked(&c->lp_mutex)); if (list_empty(&c->empty_list)) return NULL; lprops = list_entry(c->empty_list.next, struct ubifs_lprops, list); ubifs_assert(!(lprops->flags & LPROPS_TAKEN)); ubifs_assert(!(lprops->flags & LPROPS_INDEX)); ubifs_assert(lprops->free == c->leb_size); return lprops; } /** * ubifs_fast_find_freeable - try to find a freeable LEB quickly. * @c: the UBIFS file-system description object * * This function returns LEB properties for a freeable LEB or %NULL if the * function is unable to find a freeable LEB quickly. */ const struct ubifs_lprops *ubifs_fast_find_freeable(struct ubifs_info *c) { struct ubifs_lprops *lprops; ubifs_assert(mutex_is_locked(&c->lp_mutex)); if (list_empty(&c->freeable_list)) return NULL; lprops = list_entry(c->freeable_list.next, struct ubifs_lprops, list); ubifs_assert(!(lprops->flags & LPROPS_TAKEN)); ubifs_assert(!(lprops->flags & LPROPS_INDEX)); ubifs_assert(lprops->free + lprops->dirty == c->leb_size); ubifs_assert(c->freeable_cnt > 0); return lprops; } /** * ubifs_fast_find_frdi_idx - try to find a freeable index LEB quickly. * @c: the UBIFS file-system description object * * This function returns LEB properties for a freeable index LEB or %NULL if the * function is unable to find a freeable index LEB quickly. */ const struct ubifs_lprops *ubifs_fast_find_frdi_idx(struct ubifs_info *c) { struct ubifs_lprops *lprops; ubifs_assert(mutex_is_locked(&c->lp_mutex)); if (list_empty(&c->frdi_idx_list)) return NULL; lprops = list_entry(c->frdi_idx_list.next, struct ubifs_lprops, list); ubifs_assert(!(lprops->flags & LPROPS_TAKEN)); ubifs_assert((lprops->flags & LPROPS_INDEX)); ubifs_assert(lprops->free + lprops->dirty == c->leb_size); return lprops; } #ifdef CONFIG_UBIFS_FS_DEBUG /** * dbg_check_cats - check category heaps and lists. * @c: UBIFS file-system description object * * This function returns %0 on success and a negative error code on failure. */ int dbg_check_cats(struct ubifs_info *c) { struct ubifs_lprops *lprops; struct list_head *pos; int i, cat; if (!dbg_is_chk_gen(c) && !dbg_is_chk_lprops(c)) return 0; list_for_each_entry(lprops, &c->empty_list, list) { if (lprops->free != c->leb_size) { ubifs_err("non-empty LEB %d on empty list " "(free %d dirty %d flags %d)", lprops->lnum, lprops->free, lprops->dirty, lprops->flags); return -EINVAL; } if (lprops->flags & LPROPS_TAKEN) { ubifs_err("taken LEB %d on empty list " "(free %d dirty %d flags %d)", lprops->lnum, lprops->free, lprops->dirty, lprops->flags); return -EINVAL; } } i = 0; list_for_each_entry(lprops, &c->freeable_list, list) { if (lprops->free + lprops->dirty != c->leb_size) { ubifs_err("non-freeable LEB %d on freeable list " "(free %d dirty %d flags %d)", lprops->lnum, lprops->free, lprops->dirty, lprops->flags); return -EINVAL; } if (lprops->flags & LPROPS_TAKEN) { ubifs_err("taken LEB %d on freeable list " "(free %d dirty %d flags %d)", lprops->lnum, lprops->free, lprops->dirty, lprops->flags); return -EINVAL; } i += 1; } if (i != c->freeable_cnt) { ubifs_err("freeable list count %d expected %d", i, c->freeable_cnt); return -EINVAL; } i = 0; list_for_each(pos, &c->idx_gc) i += 1; if (i != c->idx_gc_cnt) { ubifs_err("idx_gc list count %d expected %d", i, c->idx_gc_cnt); return -EINVAL; } list_for_each_entry(lprops, &c->frdi_idx_list, list) { if (lprops->free + lprops->dirty != c->leb_size) { ubifs_err("non-freeable LEB %d on frdi_idx list " "(free %d dirty %d flags %d)", lprops->lnum, lprops->free, lprops->dirty, lprops->flags); return -EINVAL; } if (lprops->flags & LPROPS_TAKEN) { ubifs_err("taken LEB %d on frdi_idx list " "(free %d dirty %d flags %d)", lprops->lnum, lprops->free, lprops->dirty, lprops->flags); return -EINVAL; } if (!(lprops->flags & LPROPS_INDEX)) { ubifs_err("non-index LEB %d on frdi_idx list " "(free %d dirty %d flags %d)", lprops->lnum, lprops->free, lprops->dirty, lprops->flags); return -EINVAL; } } for (cat = 1; cat <= LPROPS_HEAP_CNT; cat++) { struct ubifs_lpt_heap *heap = &c->lpt_heap[cat - 1]; for (i = 0; i < heap->cnt; i++) { lprops = heap->arr[i]; if (!lprops) { ubifs_err("null ptr in LPT heap cat %d", cat); return -EINVAL; } if (lprops->hpos != i) { ubifs_err("bad ptr in LPT heap cat %d", cat); return -EINVAL; } if (lprops->flags & LPROPS_TAKEN) { ubifs_err("taken LEB in LPT heap cat %d", cat); return -EINVAL; } } } return 0; } void dbg_check_heap(struct ubifs_info *c, struct ubifs_lpt_heap *heap, int cat, int add_pos) { int i = 0, j, err = 0; if (!dbg_is_chk_gen(c) && !dbg_is_chk_lprops(c)) return; for (i = 0; i < heap->cnt; i++) { struct ubifs_lprops *lprops = heap->arr[i]; struct ubifs_lprops *lp; if (i != add_pos) if ((lprops->flags & LPROPS_CAT_MASK) != cat) { err = 1; goto out; } if (lprops->hpos != i) { err = 2; goto out; } lp = ubifs_lpt_lookup(c, lprops->lnum); if (IS_ERR(lp)) { err = 3; goto out; } if (lprops != lp) { dbg_msg("lprops %zx lp %zx lprops->lnum %d lp->lnum %d", (size_t)lprops, (size_t)lp, lprops->lnum, lp->lnum); err = 4; goto out; } for (j = 0; j < i; j++) { lp = heap->arr[j]; if (lp == lprops) { err = 5; goto out; } if (lp->lnum == lprops->lnum) { err = 6; goto out; } } } out: if (err) { dbg_msg("failed cat %d hpos %d err %d", cat, i, err); dbg_dump_stack(); dbg_dump_heap(c, heap, cat); } } /** * scan_check_cb - scan callback. * @c: the UBIFS file-system description object * @lp: LEB properties to scan * @in_tree: whether the LEB properties are in main memory * @lst: lprops statistics to update * * This function returns a code that indicates whether the scan should continue * (%LPT_SCAN_CONTINUE), whether the LEB properties should be added to the tree * in main memory (%LPT_SCAN_ADD), or whether the scan should stop * (%LPT_SCAN_STOP). */ static int scan_check_cb(struct ubifs_info *c, const struct ubifs_lprops *lp, int in_tree, struct ubifs_lp_stats *lst) { struct ubifs_scan_leb *sleb; struct ubifs_scan_node *snod; int cat, lnum = lp->lnum, is_idx = 0, used = 0, free, dirty, ret; void *buf = NULL; cat = lp->flags & LPROPS_CAT_MASK; if (cat != LPROPS_UNCAT) { cat = ubifs_categorize_lprops(c, lp); if (cat != (lp->flags & LPROPS_CAT_MASK)) { ubifs_err("bad LEB category %d expected %d", (lp->flags & LPROPS_CAT_MASK), cat); return -EINVAL; } } /* Check lp is on its category list (if it has one) */ if (in_tree) { struct list_head *list = NULL; switch (cat) { case LPROPS_EMPTY: list = &c->empty_list; break; case LPROPS_FREEABLE: list = &c->freeable_list; break; case LPROPS_FRDI_IDX: list = &c->frdi_idx_list; break; case LPROPS_UNCAT: list = &c->uncat_list; break; } if (list) { struct ubifs_lprops *lprops; int found = 0; list_for_each_entry(lprops, list, list) { if (lprops == lp) { found = 1; break; } } if (!found) { ubifs_err("bad LPT list (category %d)", cat); return -EINVAL; } } } /* Check lp is on its category heap (if it has one) */ if (in_tree && cat > 0 && cat <= LPROPS_HEAP_CNT) { struct ubifs_lpt_heap *heap = &c->lpt_heap[cat - 1]; if ((lp->hpos != -1 && heap->arr[lp->hpos]->lnum != lnum) || lp != heap->arr[lp->hpos]) { ubifs_err("bad LPT heap (category %d)", cat); return -EINVAL; } } buf = __vmalloc(c->leb_size, GFP_NOFS, PAGE_KERNEL); if (!buf) return -ENOMEM; /* * After an unclean unmount, empty and freeable LEBs * may contain garbage - do not scan them. */ if (lp->free == c->leb_size) { lst->empty_lebs += 1; lst->total_free += c->leb_size; lst->total_dark += ubifs_calc_dark(c, c->leb_size); return LPT_SCAN_CONTINUE; } if (lp->free + lp->dirty == c->leb_size && !(lp->flags & LPROPS_INDEX)) { lst->total_free += lp->free; lst->total_dirty += lp->dirty; lst->total_dark += ubifs_calc_dark(c, c->leb_size); return LPT_SCAN_CONTINUE; } sleb = ubifs_scan(c, lnum, 0, buf, 0); if (IS_ERR(sleb)) { ret = PTR_ERR(sleb); if (ret == -EUCLEAN) { dbg_dump_lprops(c); dbg_dump_budg(c, &c->bi); } goto out; } is_idx = -1; list_for_each_entry(snod, &sleb->nodes, list) { int found, level = 0; cond_resched(); if (is_idx == -1) is_idx = (snod->type == UBIFS_IDX_NODE) ? 1 : 0; if (is_idx && snod->type != UBIFS_IDX_NODE) { ubifs_err("indexing node in data LEB %d:%d", lnum, snod->offs); goto out_destroy; } if (snod->type == UBIFS_IDX_NODE) { struct ubifs_idx_node *idx = snod->node; key_read(c, ubifs_idx_key(c, idx), &snod->key); level = le16_to_cpu(idx->level); } found = ubifs_tnc_has_node(c, &snod->key, level, lnum, snod->offs, is_idx); if (found) { if (found < 0) goto out_destroy; used += ALIGN(snod->len, 8); } } free = c->leb_size - sleb->endpt; dirty = sleb->endpt - used; if (free > c->leb_size || free < 0 || dirty > c->leb_size || dirty < 0) { ubifs_err("bad calculated accounting for LEB %d: " "free %d, dirty %d", lnum, free, dirty); goto out_destroy; } if (lp->free + lp->dirty == c->leb_size && free + dirty == c->leb_size) if ((is_idx && !(lp->flags & LPROPS_INDEX)) || (!is_idx && free == c->leb_size) || lp->free == c->leb_size) { /* * Empty or freeable LEBs could contain index * nodes from an uncompleted commit due to an * unclean unmount. Or they could be empty for * the same reason. Or it may simply not have been * unmapped. */ free = lp->free; dirty = lp->dirty; is_idx = 0; } if (is_idx && lp->free + lp->dirty == free + dirty && lnum != c->ihead_lnum) { /* * After an unclean unmount, an index LEB could have a different * amount of free space than the value recorded by lprops. That * is because the in-the-gaps method may use free space or * create free space (as a side-effect of using ubi_leb_change * and not writing the whole LEB). The incorrect free space * value is not a problem because the index is only ever * allocated empty LEBs, so there will never be an attempt to * write to the free space at the end of an index LEB - except * by the in-the-gaps method for which it is not a problem. */ free = lp->free; dirty = lp->dirty; } if (lp->free != free || lp->dirty != dirty) goto out_print; if (is_idx && !(lp->flags & LPROPS_INDEX)) { if (free == c->leb_size) /* Free but not unmapped LEB, it's fine */ is_idx = 0; else { ubifs_err("indexing node without indexing " "flag"); goto out_print; } } if (!is_idx && (lp->flags & LPROPS_INDEX)) { ubifs_err("data node with indexing flag"); goto out_print; } if (free == c->leb_size) lst->empty_lebs += 1; if (is_idx) lst->idx_lebs += 1; if (!(lp->flags & LPROPS_INDEX)) lst->total_used += c->leb_size - free - dirty; lst->total_free += free; lst->total_dirty += dirty; if (!(lp->flags & LPROPS_INDEX)) { int spc = free + dirty; if (spc < c->dead_wm) lst->total_dead += spc; else lst->total_dark += ubifs_calc_dark(c, spc); } ubifs_scan_destroy(sleb); vfree(buf); return LPT_SCAN_CONTINUE; out_print: ubifs_err("bad accounting of LEB %d: free %d, dirty %d flags %#x, " "should be free %d, dirty %d", lnum, lp->free, lp->dirty, lp->flags, free, dirty); dbg_dump_leb(c, lnum); out_destroy: ubifs_scan_destroy(sleb); ret = -EINVAL; out: vfree(buf); return ret; } /** * dbg_check_lprops - check all LEB properties. * @c: UBIFS file-system description object * * This function checks all LEB properties and makes sure they are all correct. * It returns zero if everything is fine, %-EINVAL if there is an inconsistency * and other negative error codes in case of other errors. This function is * called while the file system is locked (because of commit start), so no * additional locking is required. Note that locking the LPT mutex would cause * a circular lock dependency with the TNC mutex. */ int dbg_check_lprops(struct ubifs_info *c) { int i, err; struct ubifs_lp_stats lst; if (!dbg_is_chk_lprops(c)) return 0; /* * As we are going to scan the media, the write buffers have to be * synchronized. */ for (i = 0; i < c->jhead_cnt; i++) { err = ubifs_wbuf_sync(&c->jheads[i].wbuf); if (err) return err; } memset(&lst, 0, sizeof(struct ubifs_lp_stats)); err = ubifs_lpt_scan_nolock(c, c->main_first, c->leb_cnt - 1, (ubifs_lpt_scan_callback)scan_check_cb, &lst); if (err && err != -ENOSPC) goto out; if (lst.empty_lebs != c->lst.empty_lebs || lst.idx_lebs != c->lst.idx_lebs || lst.total_free != c->lst.total_free || lst.total_dirty != c->lst.total_dirty || lst.total_used != c->lst.total_used) { ubifs_err("bad overall accounting"); ubifs_err("calculated: empty_lebs %d, idx_lebs %d, " "total_free %lld, total_dirty %lld, total_used %lld", lst.empty_lebs, lst.idx_lebs, lst.total_free, lst.total_dirty, lst.total_used); ubifs_err("read from lprops: empty_lebs %d, idx_lebs %d, " "total_free %lld, total_dirty %lld, total_used %lld", c->lst.empty_lebs, c->lst.idx_lebs, c->lst.total_free, c->lst.total_dirty, c->lst.total_used); err = -EINVAL; goto out; } if (lst.total_dead != c->lst.total_dead || lst.total_dark != c->lst.total_dark) { ubifs_err("bad dead/dark space accounting"); ubifs_err("calculated: total_dead %lld, total_dark %lld", lst.total_dead, lst.total_dark); ubifs_err("read from lprops: total_dead %lld, total_dark %lld", c->lst.total_dead, c->lst.total_dark); err = -EINVAL; goto out; } err = dbg_check_cats(c); out: return err; } #endif /* CONFIG_UBIFS_FS_DEBUG */
gpl-2.0
aqua-project/Linux-Minimal-x86-Reimplementation
arch/arm/mach-gemini/board-wbd111.c
3874
2822
/* * Support for Wiliboard WBD-111 * * Copyright (C) 2009 Imre Kaloz <kaloz@openwrt.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. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/leds.h> #include <linux/input.h> #include <linux/skbuff.h> #include <linux/gpio_keys.h> #include <linux/mdio-gpio.h> #include <linux/mtd/mtd.h> #include <linux/mtd/partitions.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/time.h> #include "common.h" static struct gpio_keys_button wbd111_keys[] = { { .code = KEY_SETUP, .gpio = 5, .active_low = 1, .desc = "reset", .type = EV_KEY, }, }; static struct gpio_keys_platform_data wbd111_keys_data = { .buttons = wbd111_keys, .nbuttons = ARRAY_SIZE(wbd111_keys), }; static struct platform_device wbd111_keys_device = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &wbd111_keys_data, }, }; static struct gpio_led wbd111_leds[] = { { .name = "L3red", .gpio = 1, }, { .name = "L4green", .gpio = 2, }, { .name = "L4red", .gpio = 3, }, { .name = "L3green", .gpio = 5, }, }; static struct gpio_led_platform_data wbd111_leds_data = { .num_leds = ARRAY_SIZE(wbd111_leds), .leds = wbd111_leds, }; static struct platform_device wbd111_leds_device = { .name = "leds-gpio", .id = -1, .dev = { .platform_data = &wbd111_leds_data, }, }; static struct mtd_partition wbd111_partitions[] = { { .name = "RedBoot", .offset = 0, .size = 0x020000, .mask_flags = MTD_WRITEABLE, } , { .name = "kernel", .offset = 0x020000, .size = 0x100000, } , { .name = "rootfs", .offset = 0x120000, .size = 0x6a0000, } , { .name = "VCTL", .offset = 0x7c0000, .size = 0x010000, .mask_flags = MTD_WRITEABLE, } , { .name = "cfg", .offset = 0x7d0000, .size = 0x010000, .mask_flags = MTD_WRITEABLE, } , { .name = "FIS", .offset = 0x7e0000, .size = 0x010000, .mask_flags = MTD_WRITEABLE, } }; #define wbd111_num_partitions ARRAY_SIZE(wbd111_partitions) static void __init wbd111_init(void) { gemini_gpio_init(); platform_register_uart(); platform_register_pflash(SZ_8M, wbd111_partitions, wbd111_num_partitions); platform_device_register(&wbd111_leds_device); platform_device_register(&wbd111_keys_device); platform_register_rtc(); } MACHINE_START(WBD111, "Wiliboard WBD-111") .atag_offset = 0x100, .map_io = gemini_map_io, .init_irq = gemini_init_irq, .init_time = gemini_timer_init, .init_machine = wbd111_init, .restart = gemini_restart, MACHINE_END
gpl-2.0
pedestre/Kernel-Apolo-ICS-4.0.4
net/bridge/netfilter/ebt_log.c
4130
5750
/* * ebt_log * * Authors: * Bart De Schuymer <bdschuym@pandora.be> * Harald Welte <laforge@netfilter.org> * * April, 2002 * */ #include <linux/module.h> #include <linux/ip.h> #include <linux/in.h> #include <linux/if_arp.h> #include <linux/spinlock.h> #include <net/netfilter/nf_log.h> #include <linux/ipv6.h> #include <net/ipv6.h> #include <linux/in6.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_bridge/ebtables.h> #include <linux/netfilter_bridge/ebt_log.h> #include <linux/netfilter.h> static DEFINE_SPINLOCK(ebt_log_lock); static int ebt_log_tg_check(const struct xt_tgchk_param *par) { struct ebt_log_info *info = par->targinfo; if (info->bitmask & ~EBT_LOG_MASK) return -EINVAL; if (info->loglevel >= 8) return -EINVAL; info->prefix[EBT_LOG_PREFIX_SIZE - 1] = '\0'; return 0; } struct tcpudphdr { __be16 src; __be16 dst; }; struct arppayload { unsigned char mac_src[ETH_ALEN]; unsigned char ip_src[4]; unsigned char mac_dst[ETH_ALEN]; unsigned char ip_dst[4]; }; static void print_ports(const struct sk_buff *skb, uint8_t protocol, int offset) { if (protocol == IPPROTO_TCP || protocol == IPPROTO_UDP || protocol == IPPROTO_UDPLITE || protocol == IPPROTO_SCTP || protocol == IPPROTO_DCCP) { const struct tcpudphdr *pptr; struct tcpudphdr _ports; pptr = skb_header_pointer(skb, offset, sizeof(_ports), &_ports); if (pptr == NULL) { printk(" INCOMPLETE TCP/UDP header"); return; } printk(" SPT=%u DPT=%u", ntohs(pptr->src), ntohs(pptr->dst)); } } static void ebt_log_packet(u_int8_t pf, unsigned int hooknum, const struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const struct nf_loginfo *loginfo, const char *prefix) { unsigned int bitmask; spin_lock_bh(&ebt_log_lock); printk("<%c>%s IN=%s OUT=%s MAC source = %pM MAC dest = %pM proto = 0x%04x", '0' + loginfo->u.log.level, prefix, in ? in->name : "", out ? out->name : "", eth_hdr(skb)->h_source, eth_hdr(skb)->h_dest, ntohs(eth_hdr(skb)->h_proto)); if (loginfo->type == NF_LOG_TYPE_LOG) bitmask = loginfo->u.log.logflags; else bitmask = NF_LOG_MASK; if ((bitmask & EBT_LOG_IP) && eth_hdr(skb)->h_proto == htons(ETH_P_IP)){ const struct iphdr *ih; struct iphdr _iph; ih = skb_header_pointer(skb, 0, sizeof(_iph), &_iph); if (ih == NULL) { printk(" INCOMPLETE IP header"); goto out; } printk(" IP SRC=%pI4 IP DST=%pI4, IP tos=0x%02X, IP proto=%d", &ih->saddr, &ih->daddr, ih->tos, ih->protocol); print_ports(skb, ih->protocol, ih->ihl*4); goto out; } #if defined(CONFIG_BRIDGE_EBT_IP6) || defined(CONFIG_BRIDGE_EBT_IP6_MODULE) if ((bitmask & EBT_LOG_IP6) && eth_hdr(skb)->h_proto == htons(ETH_P_IPV6)) { const struct ipv6hdr *ih; struct ipv6hdr _iph; uint8_t nexthdr; int offset_ph; ih = skb_header_pointer(skb, 0, sizeof(_iph), &_iph); if (ih == NULL) { printk(" INCOMPLETE IPv6 header"); goto out; } printk(" IPv6 SRC=%pI6 IPv6 DST=%pI6, IPv6 priority=0x%01X, Next Header=%d", &ih->saddr, &ih->daddr, ih->priority, ih->nexthdr); nexthdr = ih->nexthdr; offset_ph = ipv6_skip_exthdr(skb, sizeof(_iph), &nexthdr); if (offset_ph == -1) goto out; print_ports(skb, nexthdr, offset_ph); goto out; } #endif if ((bitmask & EBT_LOG_ARP) && ((eth_hdr(skb)->h_proto == htons(ETH_P_ARP)) || (eth_hdr(skb)->h_proto == htons(ETH_P_RARP)))) { const struct arphdr *ah; struct arphdr _arph; ah = skb_header_pointer(skb, 0, sizeof(_arph), &_arph); if (ah == NULL) { printk(" INCOMPLETE ARP header"); goto out; } printk(" ARP HTYPE=%d, PTYPE=0x%04x, OPCODE=%d", ntohs(ah->ar_hrd), ntohs(ah->ar_pro), ntohs(ah->ar_op)); /* If it's for Ethernet and the lengths are OK, * then log the ARP payload */ if (ah->ar_hrd == htons(1) && ah->ar_hln == ETH_ALEN && ah->ar_pln == sizeof(__be32)) { const struct arppayload *ap; struct arppayload _arpp; ap = skb_header_pointer(skb, sizeof(_arph), sizeof(_arpp), &_arpp); if (ap == NULL) { printk(" INCOMPLETE ARP payload"); goto out; } printk(" ARP MAC SRC=%pM ARP IP SRC=%pI4 ARP MAC DST=%pM ARP IP DST=%pI4", ap->mac_src, ap->ip_src, ap->mac_dst, ap->ip_dst); } } out: printk("\n"); spin_unlock_bh(&ebt_log_lock); } static unsigned int ebt_log_tg(struct sk_buff *skb, const struct xt_action_param *par) { const struct ebt_log_info *info = par->targinfo; struct nf_loginfo li; li.type = NF_LOG_TYPE_LOG; li.u.log.level = info->loglevel; li.u.log.logflags = info->bitmask; if (info->bitmask & EBT_LOG_NFLOG) nf_log_packet(NFPROTO_BRIDGE, par->hooknum, skb, par->in, par->out, &li, "%s", info->prefix); else ebt_log_packet(NFPROTO_BRIDGE, par->hooknum, skb, par->in, par->out, &li, info->prefix); return EBT_CONTINUE; } static struct xt_target ebt_log_tg_reg __read_mostly = { .name = "log", .revision = 0, .family = NFPROTO_BRIDGE, .target = ebt_log_tg, .checkentry = ebt_log_tg_check, .targetsize = sizeof(struct ebt_log_info), .me = THIS_MODULE, }; static struct nf_logger ebt_log_logger __read_mostly = { .name = "ebt_log", .logfn = &ebt_log_packet, .me = THIS_MODULE, }; static int __init ebt_log_init(void) { int ret; ret = xt_register_target(&ebt_log_tg_reg); if (ret < 0) return ret; nf_log_register(NFPROTO_BRIDGE, &ebt_log_logger); return 0; } static void __exit ebt_log_fini(void) { nf_log_unregister(&ebt_log_logger); xt_unregister_target(&ebt_log_tg_reg); } module_init(ebt_log_init); module_exit(ebt_log_fini); MODULE_DESCRIPTION("Ebtables: Packet logging to syslog"); MODULE_LICENSE("GPL");
gpl-2.0
cphelps76/DEMENTED_kernel_n8013
net/bridge/netfilter/ebt_log.c
4130
5750
/* * ebt_log * * Authors: * Bart De Schuymer <bdschuym@pandora.be> * Harald Welte <laforge@netfilter.org> * * April, 2002 * */ #include <linux/module.h> #include <linux/ip.h> #include <linux/in.h> #include <linux/if_arp.h> #include <linux/spinlock.h> #include <net/netfilter/nf_log.h> #include <linux/ipv6.h> #include <net/ipv6.h> #include <linux/in6.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_bridge/ebtables.h> #include <linux/netfilter_bridge/ebt_log.h> #include <linux/netfilter.h> static DEFINE_SPINLOCK(ebt_log_lock); static int ebt_log_tg_check(const struct xt_tgchk_param *par) { struct ebt_log_info *info = par->targinfo; if (info->bitmask & ~EBT_LOG_MASK) return -EINVAL; if (info->loglevel >= 8) return -EINVAL; info->prefix[EBT_LOG_PREFIX_SIZE - 1] = '\0'; return 0; } struct tcpudphdr { __be16 src; __be16 dst; }; struct arppayload { unsigned char mac_src[ETH_ALEN]; unsigned char ip_src[4]; unsigned char mac_dst[ETH_ALEN]; unsigned char ip_dst[4]; }; static void print_ports(const struct sk_buff *skb, uint8_t protocol, int offset) { if (protocol == IPPROTO_TCP || protocol == IPPROTO_UDP || protocol == IPPROTO_UDPLITE || protocol == IPPROTO_SCTP || protocol == IPPROTO_DCCP) { const struct tcpudphdr *pptr; struct tcpudphdr _ports; pptr = skb_header_pointer(skb, offset, sizeof(_ports), &_ports); if (pptr == NULL) { printk(" INCOMPLETE TCP/UDP header"); return; } printk(" SPT=%u DPT=%u", ntohs(pptr->src), ntohs(pptr->dst)); } } static void ebt_log_packet(u_int8_t pf, unsigned int hooknum, const struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const struct nf_loginfo *loginfo, const char *prefix) { unsigned int bitmask; spin_lock_bh(&ebt_log_lock); printk("<%c>%s IN=%s OUT=%s MAC source = %pM MAC dest = %pM proto = 0x%04x", '0' + loginfo->u.log.level, prefix, in ? in->name : "", out ? out->name : "", eth_hdr(skb)->h_source, eth_hdr(skb)->h_dest, ntohs(eth_hdr(skb)->h_proto)); if (loginfo->type == NF_LOG_TYPE_LOG) bitmask = loginfo->u.log.logflags; else bitmask = NF_LOG_MASK; if ((bitmask & EBT_LOG_IP) && eth_hdr(skb)->h_proto == htons(ETH_P_IP)){ const struct iphdr *ih; struct iphdr _iph; ih = skb_header_pointer(skb, 0, sizeof(_iph), &_iph); if (ih == NULL) { printk(" INCOMPLETE IP header"); goto out; } printk(" IP SRC=%pI4 IP DST=%pI4, IP tos=0x%02X, IP proto=%d", &ih->saddr, &ih->daddr, ih->tos, ih->protocol); print_ports(skb, ih->protocol, ih->ihl*4); goto out; } #if defined(CONFIG_BRIDGE_EBT_IP6) || defined(CONFIG_BRIDGE_EBT_IP6_MODULE) if ((bitmask & EBT_LOG_IP6) && eth_hdr(skb)->h_proto == htons(ETH_P_IPV6)) { const struct ipv6hdr *ih; struct ipv6hdr _iph; uint8_t nexthdr; int offset_ph; ih = skb_header_pointer(skb, 0, sizeof(_iph), &_iph); if (ih == NULL) { printk(" INCOMPLETE IPv6 header"); goto out; } printk(" IPv6 SRC=%pI6 IPv6 DST=%pI6, IPv6 priority=0x%01X, Next Header=%d", &ih->saddr, &ih->daddr, ih->priority, ih->nexthdr); nexthdr = ih->nexthdr; offset_ph = ipv6_skip_exthdr(skb, sizeof(_iph), &nexthdr); if (offset_ph == -1) goto out; print_ports(skb, nexthdr, offset_ph); goto out; } #endif if ((bitmask & EBT_LOG_ARP) && ((eth_hdr(skb)->h_proto == htons(ETH_P_ARP)) || (eth_hdr(skb)->h_proto == htons(ETH_P_RARP)))) { const struct arphdr *ah; struct arphdr _arph; ah = skb_header_pointer(skb, 0, sizeof(_arph), &_arph); if (ah == NULL) { printk(" INCOMPLETE ARP header"); goto out; } printk(" ARP HTYPE=%d, PTYPE=0x%04x, OPCODE=%d", ntohs(ah->ar_hrd), ntohs(ah->ar_pro), ntohs(ah->ar_op)); /* If it's for Ethernet and the lengths are OK, * then log the ARP payload */ if (ah->ar_hrd == htons(1) && ah->ar_hln == ETH_ALEN && ah->ar_pln == sizeof(__be32)) { const struct arppayload *ap; struct arppayload _arpp; ap = skb_header_pointer(skb, sizeof(_arph), sizeof(_arpp), &_arpp); if (ap == NULL) { printk(" INCOMPLETE ARP payload"); goto out; } printk(" ARP MAC SRC=%pM ARP IP SRC=%pI4 ARP MAC DST=%pM ARP IP DST=%pI4", ap->mac_src, ap->ip_src, ap->mac_dst, ap->ip_dst); } } out: printk("\n"); spin_unlock_bh(&ebt_log_lock); } static unsigned int ebt_log_tg(struct sk_buff *skb, const struct xt_action_param *par) { const struct ebt_log_info *info = par->targinfo; struct nf_loginfo li; li.type = NF_LOG_TYPE_LOG; li.u.log.level = info->loglevel; li.u.log.logflags = info->bitmask; if (info->bitmask & EBT_LOG_NFLOG) nf_log_packet(NFPROTO_BRIDGE, par->hooknum, skb, par->in, par->out, &li, "%s", info->prefix); else ebt_log_packet(NFPROTO_BRIDGE, par->hooknum, skb, par->in, par->out, &li, info->prefix); return EBT_CONTINUE; } static struct xt_target ebt_log_tg_reg __read_mostly = { .name = "log", .revision = 0, .family = NFPROTO_BRIDGE, .target = ebt_log_tg, .checkentry = ebt_log_tg_check, .targetsize = sizeof(struct ebt_log_info), .me = THIS_MODULE, }; static struct nf_logger ebt_log_logger __read_mostly = { .name = "ebt_log", .logfn = &ebt_log_packet, .me = THIS_MODULE, }; static int __init ebt_log_init(void) { int ret; ret = xt_register_target(&ebt_log_tg_reg); if (ret < 0) return ret; nf_log_register(NFPROTO_BRIDGE, &ebt_log_logger); return 0; } static void __exit ebt_log_fini(void) { nf_log_unregister(&ebt_log_logger); xt_unregister_target(&ebt_log_tg_reg); } module_init(ebt_log_init); module_exit(ebt_log_fini); MODULE_DESCRIPTION("Ebtables: Packet logging to syslog"); MODULE_LICENSE("GPL");
gpl-2.0
xtrymind/android_kernel_msm
drivers/power/z2_battery.c
4898
8017
/* * Battery measurement code for Zipit Z2 * * Copyright (C) 2009 Peter Edwards <sweetlilmre@gmail.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/gpio.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/power_supply.h> #include <linux/slab.h> #include <linux/z2_battery.h> #define Z2_DEFAULT_NAME "Z2" struct z2_charger { struct z2_battery_info *info; int bat_status; struct i2c_client *client; struct power_supply batt_ps; struct mutex work_lock; struct work_struct bat_work; }; static unsigned long z2_read_bat(struct z2_charger *charger) { int data; data = i2c_smbus_read_byte_data(charger->client, charger->info->batt_I2C_reg); if (data < 0) return 0; return data * charger->info->batt_mult / charger->info->batt_div; } static int z2_batt_get_property(struct power_supply *batt_ps, enum power_supply_property psp, union power_supply_propval *val) { struct z2_charger *charger = container_of(batt_ps, struct z2_charger, batt_ps); struct z2_battery_info *info = charger->info; switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = charger->bat_status; break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = info->batt_tech; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: if (info->batt_I2C_reg >= 0) val->intval = z2_read_bat(charger); else return -EINVAL; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: if (info->max_voltage >= 0) val->intval = info->max_voltage; else return -EINVAL; break; case POWER_SUPPLY_PROP_VOLTAGE_MIN: if (info->min_voltage >= 0) val->intval = info->min_voltage; else return -EINVAL; break; case POWER_SUPPLY_PROP_PRESENT: val->intval = 1; break; default: return -EINVAL; } return 0; } static void z2_batt_ext_power_changed(struct power_supply *batt_ps) { struct z2_charger *charger = container_of(batt_ps, struct z2_charger, batt_ps); schedule_work(&charger->bat_work); } static void z2_batt_update(struct z2_charger *charger) { int old_status = charger->bat_status; struct z2_battery_info *info; info = charger->info; mutex_lock(&charger->work_lock); charger->bat_status = (info->charge_gpio >= 0) ? (gpio_get_value(info->charge_gpio) ? POWER_SUPPLY_STATUS_CHARGING : POWER_SUPPLY_STATUS_DISCHARGING) : POWER_SUPPLY_STATUS_UNKNOWN; if (old_status != charger->bat_status) { pr_debug("%s: %i -> %i\n", charger->batt_ps.name, old_status, charger->bat_status); power_supply_changed(&charger->batt_ps); } mutex_unlock(&charger->work_lock); } static void z2_batt_work(struct work_struct *work) { struct z2_charger *charger; charger = container_of(work, struct z2_charger, bat_work); z2_batt_update(charger); } static irqreturn_t z2_charge_switch_irq(int irq, void *devid) { struct z2_charger *charger = devid; schedule_work(&charger->bat_work); return IRQ_HANDLED; } static int z2_batt_ps_init(struct z2_charger *charger, int props) { int i = 0; enum power_supply_property *prop; struct z2_battery_info *info = charger->info; if (info->charge_gpio >= 0) props++; /* POWER_SUPPLY_PROP_STATUS */ if (info->batt_tech >= 0) props++; /* POWER_SUPPLY_PROP_TECHNOLOGY */ if (info->batt_I2C_reg >= 0) props++; /* POWER_SUPPLY_PROP_VOLTAGE_NOW */ if (info->max_voltage >= 0) props++; /* POWER_SUPPLY_PROP_VOLTAGE_MAX */ if (info->min_voltage >= 0) props++; /* POWER_SUPPLY_PROP_VOLTAGE_MIN */ prop = kzalloc(props * sizeof(*prop), GFP_KERNEL); if (!prop) return -ENOMEM; prop[i++] = POWER_SUPPLY_PROP_PRESENT; if (info->charge_gpio >= 0) prop[i++] = POWER_SUPPLY_PROP_STATUS; if (info->batt_tech >= 0) prop[i++] = POWER_SUPPLY_PROP_TECHNOLOGY; if (info->batt_I2C_reg >= 0) prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_NOW; if (info->max_voltage >= 0) prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_MAX; if (info->min_voltage >= 0) prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_MIN; if (!info->batt_name) { dev_info(&charger->client->dev, "Please consider setting proper battery " "name in platform definition file, falling " "back to name \" Z2_DEFAULT_NAME \"\n"); charger->batt_ps.name = Z2_DEFAULT_NAME; } else charger->batt_ps.name = info->batt_name; charger->batt_ps.properties = prop; charger->batt_ps.num_properties = props; charger->batt_ps.type = POWER_SUPPLY_TYPE_BATTERY; charger->batt_ps.get_property = z2_batt_get_property; charger->batt_ps.external_power_changed = z2_batt_ext_power_changed; charger->batt_ps.use_for_apm = 1; return 0; } static int __devinit z2_batt_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret = 0; int props = 1; /* POWER_SUPPLY_PROP_PRESENT */ struct z2_charger *charger; struct z2_battery_info *info = client->dev.platform_data; if (info == NULL) { dev_err(&client->dev, "Please set platform device platform_data" " to a valid z2_battery_info pointer!\n"); return -EINVAL; } charger = kzalloc(sizeof(*charger), GFP_KERNEL); if (charger == NULL) return -ENOMEM; charger->bat_status = POWER_SUPPLY_STATUS_UNKNOWN; charger->info = info; charger->client = client; i2c_set_clientdata(client, charger); mutex_init(&charger->work_lock); if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) { ret = gpio_request(info->charge_gpio, "BATT CHRG"); if (ret) goto err; ret = gpio_direction_input(info->charge_gpio); if (ret) goto err2; irq_set_irq_type(gpio_to_irq(info->charge_gpio), IRQ_TYPE_EDGE_BOTH); ret = request_irq(gpio_to_irq(info->charge_gpio), z2_charge_switch_irq, 0, "AC Detect", charger); if (ret) goto err3; } ret = z2_batt_ps_init(charger, props); if (ret) goto err3; INIT_WORK(&charger->bat_work, z2_batt_work); ret = power_supply_register(&client->dev, &charger->batt_ps); if (ret) goto err4; schedule_work(&charger->bat_work); return 0; err4: kfree(charger->batt_ps.properties); err3: if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) free_irq(gpio_to_irq(info->charge_gpio), charger); err2: if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) gpio_free(info->charge_gpio); err: kfree(charger); return ret; } static int __devexit z2_batt_remove(struct i2c_client *client) { struct z2_charger *charger = i2c_get_clientdata(client); struct z2_battery_info *info = charger->info; cancel_work_sync(&charger->bat_work); power_supply_unregister(&charger->batt_ps); kfree(charger->batt_ps.properties); if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) { free_irq(gpio_to_irq(info->charge_gpio), charger); gpio_free(info->charge_gpio); } kfree(charger); return 0; } #ifdef CONFIG_PM static int z2_batt_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct z2_charger *charger = i2c_get_clientdata(client); flush_work_sync(&charger->bat_work); return 0; } static int z2_batt_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct z2_charger *charger = i2c_get_clientdata(client); schedule_work(&charger->bat_work); return 0; } static const struct dev_pm_ops z2_battery_pm_ops = { .suspend = z2_batt_suspend, .resume = z2_batt_resume, }; #define Z2_BATTERY_PM_OPS (&z2_battery_pm_ops) #else #define Z2_BATTERY_PM_OPS (NULL) #endif static const struct i2c_device_id z2_batt_id[] = { { "aer915", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, z2_batt_id); static struct i2c_driver z2_batt_driver = { .driver = { .name = "z2-battery", .owner = THIS_MODULE, .pm = Z2_BATTERY_PM_OPS }, .probe = z2_batt_probe, .remove = __devexit_p(z2_batt_remove), .id_table = z2_batt_id, }; module_i2c_driver(z2_batt_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Peter Edwards <sweetlilmre@gmail.com>"); MODULE_DESCRIPTION("Zipit Z2 battery driver");
gpl-2.0
Renzo-Olivares/android_kernel_htc_vigor
drivers/media/video/omap3isp/ispvideo.c
4898
39056
/* * ispvideo.c * * TI OMAP3 ISP - Generic video node * * Copyright (C) 2009-2010 Nokia Corporation * * Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com> * Sakari Ailus <sakari.ailus@iki.fi> * * 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 <asm/cacheflush.h> #include <linux/clk.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/pagemap.h> #include <linux/scatterlist.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <media/v4l2-dev.h> #include <media/v4l2-ioctl.h> #include <plat/iommu.h> #include <plat/iovmm.h> #include <plat/omap-pm.h> #include "ispvideo.h" #include "isp.h" /* ----------------------------------------------------------------------------- * Helper functions */ static struct isp_format_info formats[] = { { V4L2_MBUS_FMT_Y8_1X8, V4L2_MBUS_FMT_Y8_1X8, V4L2_MBUS_FMT_Y8_1X8, V4L2_MBUS_FMT_Y8_1X8, V4L2_PIX_FMT_GREY, 8, }, { V4L2_MBUS_FMT_Y10_1X10, V4L2_MBUS_FMT_Y10_1X10, V4L2_MBUS_FMT_Y10_1X10, V4L2_MBUS_FMT_Y8_1X8, V4L2_PIX_FMT_Y10, 10, }, { V4L2_MBUS_FMT_Y12_1X12, V4L2_MBUS_FMT_Y10_1X10, V4L2_MBUS_FMT_Y12_1X12, V4L2_MBUS_FMT_Y8_1X8, V4L2_PIX_FMT_Y12, 12, }, { V4L2_MBUS_FMT_SBGGR8_1X8, V4L2_MBUS_FMT_SBGGR8_1X8, V4L2_MBUS_FMT_SBGGR8_1X8, V4L2_MBUS_FMT_SBGGR8_1X8, V4L2_PIX_FMT_SBGGR8, 8, }, { V4L2_MBUS_FMT_SGBRG8_1X8, V4L2_MBUS_FMT_SGBRG8_1X8, V4L2_MBUS_FMT_SGBRG8_1X8, V4L2_MBUS_FMT_SGBRG8_1X8, V4L2_PIX_FMT_SGBRG8, 8, }, { V4L2_MBUS_FMT_SGRBG8_1X8, V4L2_MBUS_FMT_SGRBG8_1X8, V4L2_MBUS_FMT_SGRBG8_1X8, V4L2_MBUS_FMT_SGRBG8_1X8, V4L2_PIX_FMT_SGRBG8, 8, }, { V4L2_MBUS_FMT_SRGGB8_1X8, V4L2_MBUS_FMT_SRGGB8_1X8, V4L2_MBUS_FMT_SRGGB8_1X8, V4L2_MBUS_FMT_SRGGB8_1X8, V4L2_PIX_FMT_SRGGB8, 8, }, { V4L2_MBUS_FMT_SGRBG10_DPCM8_1X8, V4L2_MBUS_FMT_SGRBG10_DPCM8_1X8, V4L2_MBUS_FMT_SGRBG10_1X10, 0, V4L2_PIX_FMT_SGRBG10DPCM8, 8, }, { V4L2_MBUS_FMT_SBGGR10_1X10, V4L2_MBUS_FMT_SBGGR10_1X10, V4L2_MBUS_FMT_SBGGR10_1X10, V4L2_MBUS_FMT_SBGGR8_1X8, V4L2_PIX_FMT_SBGGR10, 10, }, { V4L2_MBUS_FMT_SGBRG10_1X10, V4L2_MBUS_FMT_SGBRG10_1X10, V4L2_MBUS_FMT_SGBRG10_1X10, V4L2_MBUS_FMT_SGBRG8_1X8, V4L2_PIX_FMT_SGBRG10, 10, }, { V4L2_MBUS_FMT_SGRBG10_1X10, V4L2_MBUS_FMT_SGRBG10_1X10, V4L2_MBUS_FMT_SGRBG10_1X10, V4L2_MBUS_FMT_SGRBG8_1X8, V4L2_PIX_FMT_SGRBG10, 10, }, { V4L2_MBUS_FMT_SRGGB10_1X10, V4L2_MBUS_FMT_SRGGB10_1X10, V4L2_MBUS_FMT_SRGGB10_1X10, V4L2_MBUS_FMT_SRGGB8_1X8, V4L2_PIX_FMT_SRGGB10, 10, }, { V4L2_MBUS_FMT_SBGGR12_1X12, V4L2_MBUS_FMT_SBGGR10_1X10, V4L2_MBUS_FMT_SBGGR12_1X12, V4L2_MBUS_FMT_SBGGR8_1X8, V4L2_PIX_FMT_SBGGR12, 12, }, { V4L2_MBUS_FMT_SGBRG12_1X12, V4L2_MBUS_FMT_SGBRG10_1X10, V4L2_MBUS_FMT_SGBRG12_1X12, V4L2_MBUS_FMT_SGBRG8_1X8, V4L2_PIX_FMT_SGBRG12, 12, }, { V4L2_MBUS_FMT_SGRBG12_1X12, V4L2_MBUS_FMT_SGRBG10_1X10, V4L2_MBUS_FMT_SGRBG12_1X12, V4L2_MBUS_FMT_SGRBG8_1X8, V4L2_PIX_FMT_SGRBG12, 12, }, { V4L2_MBUS_FMT_SRGGB12_1X12, V4L2_MBUS_FMT_SRGGB10_1X10, V4L2_MBUS_FMT_SRGGB12_1X12, V4L2_MBUS_FMT_SRGGB8_1X8, V4L2_PIX_FMT_SRGGB12, 12, }, { V4L2_MBUS_FMT_UYVY8_1X16, V4L2_MBUS_FMT_UYVY8_1X16, V4L2_MBUS_FMT_UYVY8_1X16, 0, V4L2_PIX_FMT_UYVY, 16, }, { V4L2_MBUS_FMT_YUYV8_1X16, V4L2_MBUS_FMT_YUYV8_1X16, V4L2_MBUS_FMT_YUYV8_1X16, 0, V4L2_PIX_FMT_YUYV, 16, }, }; const struct isp_format_info * omap3isp_video_format_info(enum v4l2_mbus_pixelcode code) { unsigned int i; for (i = 0; i < ARRAY_SIZE(formats); ++i) { if (formats[i].code == code) return &formats[i]; } return NULL; } /* * Decide whether desired output pixel code can be obtained with * the lane shifter by shifting the input pixel code. * @in: input pixelcode to shifter * @out: output pixelcode from shifter * @additional_shift: # of bits the sensor's LSB is offset from CAMEXT[0] * * return true if the combination is possible * return false otherwise */ static bool isp_video_is_shiftable(enum v4l2_mbus_pixelcode in, enum v4l2_mbus_pixelcode out, unsigned int additional_shift) { const struct isp_format_info *in_info, *out_info; if (in == out) return true; in_info = omap3isp_video_format_info(in); out_info = omap3isp_video_format_info(out); if ((in_info->flavor == 0) || (out_info->flavor == 0)) return false; if (in_info->flavor != out_info->flavor) return false; return in_info->bpp - out_info->bpp + additional_shift <= 6; } /* * isp_video_mbus_to_pix - Convert v4l2_mbus_framefmt to v4l2_pix_format * @video: ISP video instance * @mbus: v4l2_mbus_framefmt format (input) * @pix: v4l2_pix_format format (output) * * Fill the output pix structure with information from the input mbus format. * The bytesperline and sizeimage fields are computed from the requested bytes * per line value in the pix format and information from the video instance. * * Return the number of padding bytes at end of line. */ static unsigned int isp_video_mbus_to_pix(const struct isp_video *video, const struct v4l2_mbus_framefmt *mbus, struct v4l2_pix_format *pix) { unsigned int bpl = pix->bytesperline; unsigned int min_bpl; unsigned int i; memset(pix, 0, sizeof(*pix)); pix->width = mbus->width; pix->height = mbus->height; for (i = 0; i < ARRAY_SIZE(formats); ++i) { if (formats[i].code == mbus->code) break; } if (WARN_ON(i == ARRAY_SIZE(formats))) return 0; min_bpl = pix->width * ALIGN(formats[i].bpp, 8) / 8; /* Clamp the requested bytes per line value. If the maximum bytes per * line value is zero, the module doesn't support user configurable line * sizes. Override the requested value with the minimum in that case. */ if (video->bpl_max) bpl = clamp(bpl, min_bpl, video->bpl_max); else bpl = min_bpl; if (!video->bpl_zero_padding || bpl != min_bpl) bpl = ALIGN(bpl, video->bpl_alignment); pix->pixelformat = formats[i].pixelformat; pix->bytesperline = bpl; pix->sizeimage = pix->bytesperline * pix->height; pix->colorspace = mbus->colorspace; pix->field = mbus->field; return bpl - min_bpl; } static void isp_video_pix_to_mbus(const struct v4l2_pix_format *pix, struct v4l2_mbus_framefmt *mbus) { unsigned int i; memset(mbus, 0, sizeof(*mbus)); mbus->width = pix->width; mbus->height = pix->height; /* Skip the last format in the loop so that it will be selected if no * match is found. */ for (i = 0; i < ARRAY_SIZE(formats) - 1; ++i) { if (formats[i].pixelformat == pix->pixelformat) break; } mbus->code = formats[i].code; mbus->colorspace = pix->colorspace; mbus->field = pix->field; } static struct v4l2_subdev * isp_video_remote_subdev(struct isp_video *video, u32 *pad) { struct media_pad *remote; remote = media_entity_remote_source(&video->pad); if (remote == NULL || media_entity_type(remote->entity) != MEDIA_ENT_T_V4L2_SUBDEV) return NULL; if (pad) *pad = remote->index; return media_entity_to_v4l2_subdev(remote->entity); } /* Return a pointer to the ISP video instance at the far end of the pipeline. */ static struct isp_video * isp_video_far_end(struct isp_video *video) { struct media_entity_graph graph; struct media_entity *entity = &video->video.entity; struct media_device *mdev = entity->parent; struct isp_video *far_end = NULL; mutex_lock(&mdev->graph_mutex); media_entity_graph_walk_start(&graph, entity); while ((entity = media_entity_graph_walk_next(&graph))) { if (entity == &video->video.entity) continue; if (media_entity_type(entity) != MEDIA_ENT_T_DEVNODE) continue; far_end = to_isp_video(media_entity_to_video_device(entity)); if (far_end->type != video->type) break; far_end = NULL; } mutex_unlock(&mdev->graph_mutex); return far_end; } /* * Validate a pipeline by checking both ends of all links for format * discrepancies. * * Compute the minimum time per frame value as the maximum of time per frame * limits reported by every block in the pipeline. * * Return 0 if all formats match, or -EPIPE if at least one link is found with * different formats on its two ends or if the pipeline doesn't start with a * video source (either a subdev with no input pad, or a non-subdev entity). */ static int isp_video_validate_pipeline(struct isp_pipeline *pipe) { struct isp_device *isp = pipe->output->isp; struct v4l2_subdev_format fmt_source; struct v4l2_subdev_format fmt_sink; struct media_pad *pad; struct v4l2_subdev *subdev; int ret; pipe->max_rate = pipe->l3_ick; subdev = isp_video_remote_subdev(pipe->output, NULL); if (subdev == NULL) return -EPIPE; while (1) { unsigned int shifter_link; /* Retrieve the sink format */ pad = &subdev->entity.pads[0]; if (!(pad->flags & MEDIA_PAD_FL_SINK)) break; fmt_sink.pad = pad->index; fmt_sink.which = V4L2_SUBDEV_FORMAT_ACTIVE; ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt_sink); if (ret < 0 && ret != -ENOIOCTLCMD) return -EPIPE; /* Update the maximum frame rate */ if (subdev == &isp->isp_res.subdev) omap3isp_resizer_max_rate(&isp->isp_res, &pipe->max_rate); /* Check ccdc maximum data rate when data comes from sensor * TODO: Include ccdc rate in pipe->max_rate and compare the * total pipe rate with the input data rate from sensor. */ if (subdev == &isp->isp_ccdc.subdev && pipe->input == NULL) { unsigned int rate = UINT_MAX; omap3isp_ccdc_max_rate(&isp->isp_ccdc, &rate); if (isp->isp_ccdc.vpcfg.pixelclk > rate) return -ENOSPC; } /* If sink pad is on CCDC, the link has the lane shifter * in the middle of it. */ shifter_link = subdev == &isp->isp_ccdc.subdev; /* Retrieve the source format. Return an error if no source * entity can be found, and stop checking the pipeline if the * source entity isn't a subdev. */ pad = media_entity_remote_source(pad); if (pad == NULL) return -EPIPE; if (media_entity_type(pad->entity) != MEDIA_ENT_T_V4L2_SUBDEV) break; subdev = media_entity_to_v4l2_subdev(pad->entity); fmt_source.pad = pad->index; fmt_source.which = V4L2_SUBDEV_FORMAT_ACTIVE; ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt_source); if (ret < 0 && ret != -ENOIOCTLCMD) return -EPIPE; /* Check if the two ends match */ if (fmt_source.format.width != fmt_sink.format.width || fmt_source.format.height != fmt_sink.format.height) return -EPIPE; if (shifter_link) { unsigned int parallel_shift = 0; if (isp->isp_ccdc.input == CCDC_INPUT_PARALLEL) { struct isp_parallel_platform_data *pdata = &((struct isp_v4l2_subdevs_group *) subdev->host_priv)->bus.parallel; parallel_shift = pdata->data_lane_shift * 2; } if (!isp_video_is_shiftable(fmt_source.format.code, fmt_sink.format.code, parallel_shift)) return -EPIPE; } else if (fmt_source.format.code != fmt_sink.format.code) return -EPIPE; } return 0; } static int __isp_video_get_format(struct isp_video *video, struct v4l2_format *format) { struct v4l2_subdev_format fmt; struct v4l2_subdev *subdev; u32 pad; int ret; subdev = isp_video_remote_subdev(video, &pad); if (subdev == NULL) return -EINVAL; mutex_lock(&video->mutex); fmt.pad = pad; fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE; ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt); if (ret == -ENOIOCTLCMD) ret = -EINVAL; mutex_unlock(&video->mutex); if (ret) return ret; format->type = video->type; return isp_video_mbus_to_pix(video, &fmt.format, &format->fmt.pix); } static int isp_video_check_format(struct isp_video *video, struct isp_video_fh *vfh) { struct v4l2_format format; int ret; memcpy(&format, &vfh->format, sizeof(format)); ret = __isp_video_get_format(video, &format); if (ret < 0) return ret; if (vfh->format.fmt.pix.pixelformat != format.fmt.pix.pixelformat || vfh->format.fmt.pix.height != format.fmt.pix.height || vfh->format.fmt.pix.width != format.fmt.pix.width || vfh->format.fmt.pix.bytesperline != format.fmt.pix.bytesperline || vfh->format.fmt.pix.sizeimage != format.fmt.pix.sizeimage) return -EINVAL; return ret; } /* ----------------------------------------------------------------------------- * IOMMU management */ #define IOMMU_FLAG (IOVMF_ENDIAN_LITTLE | IOVMF_ELSZ_8) /* * ispmmu_vmap - Wrapper for Virtual memory mapping of a scatter gather list * @dev: Device pointer specific to the OMAP3 ISP. * @sglist: Pointer to source Scatter gather list to allocate. * @sglen: Number of elements of the scatter-gatter list. * * Returns a resulting mapped device address by the ISP MMU, or -ENOMEM if * we ran out of memory. */ static dma_addr_t ispmmu_vmap(struct isp_device *isp, const struct scatterlist *sglist, int sglen) { struct sg_table *sgt; u32 da; sgt = kmalloc(sizeof(*sgt), GFP_KERNEL); if (sgt == NULL) return -ENOMEM; sgt->sgl = (struct scatterlist *)sglist; sgt->nents = sglen; sgt->orig_nents = sglen; da = omap_iommu_vmap(isp->domain, isp->dev, 0, sgt, IOMMU_FLAG); if (IS_ERR_VALUE(da)) kfree(sgt); return da; } /* * ispmmu_vunmap - Unmap a device address from the ISP MMU * @dev: Device pointer specific to the OMAP3 ISP. * @da: Device address generated from a ispmmu_vmap call. */ static void ispmmu_vunmap(struct isp_device *isp, dma_addr_t da) { struct sg_table *sgt; sgt = omap_iommu_vunmap(isp->domain, isp->dev, (u32)da); kfree(sgt); } /* ----------------------------------------------------------------------------- * Video queue operations */ static void isp_video_queue_prepare(struct isp_video_queue *queue, unsigned int *nbuffers, unsigned int *size) { struct isp_video_fh *vfh = container_of(queue, struct isp_video_fh, queue); struct isp_video *video = vfh->video; *size = vfh->format.fmt.pix.sizeimage; if (*size == 0) return; *nbuffers = min(*nbuffers, video->capture_mem / PAGE_ALIGN(*size)); } static void isp_video_buffer_cleanup(struct isp_video_buffer *buf) { struct isp_video_fh *vfh = isp_video_queue_to_isp_video_fh(buf->queue); struct isp_buffer *buffer = to_isp_buffer(buf); struct isp_video *video = vfh->video; if (buffer->isp_addr) { ispmmu_vunmap(video->isp, buffer->isp_addr); buffer->isp_addr = 0; } } static int isp_video_buffer_prepare(struct isp_video_buffer *buf) { struct isp_video_fh *vfh = isp_video_queue_to_isp_video_fh(buf->queue); struct isp_buffer *buffer = to_isp_buffer(buf); struct isp_video *video = vfh->video; unsigned long addr; addr = ispmmu_vmap(video->isp, buf->sglist, buf->sglen); if (IS_ERR_VALUE(addr)) return -EIO; if (!IS_ALIGNED(addr, 32)) { dev_dbg(video->isp->dev, "Buffer address must be " "aligned to 32 bytes boundary.\n"); ispmmu_vunmap(video->isp, buffer->isp_addr); return -EINVAL; } buf->vbuf.bytesused = vfh->format.fmt.pix.sizeimage; buffer->isp_addr = addr; return 0; } /* * isp_video_buffer_queue - Add buffer to streaming queue * @buf: Video buffer * * In memory-to-memory mode, start streaming on the pipeline if buffers are * queued on both the input and the output, if the pipeline isn't already busy. * If the pipeline is busy, it will be restarted in the output module interrupt * handler. */ static void isp_video_buffer_queue(struct isp_video_buffer *buf) { struct isp_video_fh *vfh = isp_video_queue_to_isp_video_fh(buf->queue); struct isp_buffer *buffer = to_isp_buffer(buf); struct isp_video *video = vfh->video; struct isp_pipeline *pipe = to_isp_pipeline(&video->video.entity); enum isp_pipeline_state state; unsigned long flags; unsigned int empty; unsigned int start; empty = list_empty(&video->dmaqueue); list_add_tail(&buffer->buffer.irqlist, &video->dmaqueue); if (empty) { if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) state = ISP_PIPELINE_QUEUE_OUTPUT; else state = ISP_PIPELINE_QUEUE_INPUT; spin_lock_irqsave(&pipe->lock, flags); pipe->state |= state; video->ops->queue(video, buffer); video->dmaqueue_flags |= ISP_VIDEO_DMAQUEUE_QUEUED; start = isp_pipeline_ready(pipe); if (start) pipe->state |= ISP_PIPELINE_STREAM; spin_unlock_irqrestore(&pipe->lock, flags); if (start) omap3isp_pipeline_set_stream(pipe, ISP_PIPELINE_STREAM_SINGLESHOT); } } static const struct isp_video_queue_operations isp_video_queue_ops = { .queue_prepare = &isp_video_queue_prepare, .buffer_prepare = &isp_video_buffer_prepare, .buffer_queue = &isp_video_buffer_queue, .buffer_cleanup = &isp_video_buffer_cleanup, }; /* * omap3isp_video_buffer_next - Complete the current buffer and return the next * @video: ISP video object * * Remove the current video buffer from the DMA queue and fill its timestamp, * field count and state fields before waking up its completion handler. * * For capture video nodes the buffer state is set to ISP_BUF_STATE_DONE if no * error has been flagged in the pipeline, or to ISP_BUF_STATE_ERROR otherwise. * For video output nodes the buffer state is always set to ISP_BUF_STATE_DONE. * * The DMA queue is expected to contain at least one buffer. * * Return a pointer to the next buffer in the DMA queue, or NULL if the queue is * empty. */ struct isp_buffer *omap3isp_video_buffer_next(struct isp_video *video) { struct isp_pipeline *pipe = to_isp_pipeline(&video->video.entity); struct isp_video_queue *queue = video->queue; enum isp_pipeline_state state; struct isp_video_buffer *buf; unsigned long flags; struct timespec ts; spin_lock_irqsave(&queue->irqlock, flags); if (WARN_ON(list_empty(&video->dmaqueue))) { spin_unlock_irqrestore(&queue->irqlock, flags); return NULL; } buf = list_first_entry(&video->dmaqueue, struct isp_video_buffer, irqlist); list_del(&buf->irqlist); spin_unlock_irqrestore(&queue->irqlock, flags); ktime_get_ts(&ts); buf->vbuf.timestamp.tv_sec = ts.tv_sec; buf->vbuf.timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC; /* Do frame number propagation only if this is the output video node. * Frame number either comes from the CSI receivers or it gets * incremented here if H3A is not active. * Note: There is no guarantee that the output buffer will finish * first, so the input number might lag behind by 1 in some cases. */ if (video == pipe->output && !pipe->do_propagation) buf->vbuf.sequence = atomic_inc_return(&pipe->frame_number); else buf->vbuf.sequence = atomic_read(&pipe->frame_number); /* Report pipeline errors to userspace on the capture device side. */ if (queue->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && pipe->error) { buf->state = ISP_BUF_STATE_ERROR; pipe->error = false; } else { buf->state = ISP_BUF_STATE_DONE; } wake_up(&buf->wait); if (list_empty(&video->dmaqueue)) { if (queue->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) state = ISP_PIPELINE_QUEUE_OUTPUT | ISP_PIPELINE_STREAM; else state = ISP_PIPELINE_QUEUE_INPUT | ISP_PIPELINE_STREAM; spin_lock_irqsave(&pipe->lock, flags); pipe->state &= ~state; if (video->pipe.stream_state == ISP_PIPELINE_STREAM_CONTINUOUS) video->dmaqueue_flags |= ISP_VIDEO_DMAQUEUE_UNDERRUN; spin_unlock_irqrestore(&pipe->lock, flags); return NULL; } if (queue->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && pipe->input != NULL) { spin_lock_irqsave(&pipe->lock, flags); pipe->state &= ~ISP_PIPELINE_STREAM; spin_unlock_irqrestore(&pipe->lock, flags); } buf = list_first_entry(&video->dmaqueue, struct isp_video_buffer, irqlist); buf->state = ISP_BUF_STATE_ACTIVE; return to_isp_buffer(buf); } /* * omap3isp_video_resume - Perform resume operation on the buffers * @video: ISP video object * @continuous: Pipeline is in single shot mode if 0 or continuous mode otherwise * * This function is intended to be used on suspend/resume scenario. It * requests video queue layer to discard buffers marked as DONE if it's in * continuous mode and requests ISP modules to queue again the ACTIVE buffer * if there's any. */ void omap3isp_video_resume(struct isp_video *video, int continuous) { struct isp_buffer *buf = NULL; if (continuous && video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) omap3isp_video_queue_discard_done(video->queue); if (!list_empty(&video->dmaqueue)) { buf = list_first_entry(&video->dmaqueue, struct isp_buffer, buffer.irqlist); video->ops->queue(video, buf); video->dmaqueue_flags |= ISP_VIDEO_DMAQUEUE_QUEUED; } else { if (continuous) video->dmaqueue_flags |= ISP_VIDEO_DMAQUEUE_UNDERRUN; } } /* ----------------------------------------------------------------------------- * V4L2 ioctls */ static int isp_video_querycap(struct file *file, void *fh, struct v4l2_capability *cap) { struct isp_video *video = video_drvdata(file); strlcpy(cap->driver, ISP_VIDEO_DRIVER_NAME, sizeof(cap->driver)); strlcpy(cap->card, video->video.name, sizeof(cap->card)); strlcpy(cap->bus_info, "media", sizeof(cap->bus_info)); if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING; else cap->capabilities = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING; return 0; } static int isp_video_get_format(struct file *file, void *fh, struct v4l2_format *format) { struct isp_video_fh *vfh = to_isp_video_fh(fh); struct isp_video *video = video_drvdata(file); if (format->type != video->type) return -EINVAL; mutex_lock(&video->mutex); *format = vfh->format; mutex_unlock(&video->mutex); return 0; } static int isp_video_set_format(struct file *file, void *fh, struct v4l2_format *format) { struct isp_video_fh *vfh = to_isp_video_fh(fh); struct isp_video *video = video_drvdata(file); struct v4l2_mbus_framefmt fmt; if (format->type != video->type) return -EINVAL; mutex_lock(&video->mutex); /* Fill the bytesperline and sizeimage fields by converting to media bus * format and back to pixel format. */ isp_video_pix_to_mbus(&format->fmt.pix, &fmt); isp_video_mbus_to_pix(video, &fmt, &format->fmt.pix); vfh->format = *format; mutex_unlock(&video->mutex); return 0; } static int isp_video_try_format(struct file *file, void *fh, struct v4l2_format *format) { struct isp_video *video = video_drvdata(file); struct v4l2_subdev_format fmt; struct v4l2_subdev *subdev; u32 pad; int ret; if (format->type != video->type) return -EINVAL; subdev = isp_video_remote_subdev(video, &pad); if (subdev == NULL) return -EINVAL; isp_video_pix_to_mbus(&format->fmt.pix, &fmt.format); fmt.pad = pad; fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE; ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt); if (ret) return ret == -ENOIOCTLCMD ? -EINVAL : ret; isp_video_mbus_to_pix(video, &fmt.format, &format->fmt.pix); return 0; } static int isp_video_cropcap(struct file *file, void *fh, struct v4l2_cropcap *cropcap) { struct isp_video *video = video_drvdata(file); struct v4l2_subdev *subdev; int ret; subdev = isp_video_remote_subdev(video, NULL); if (subdev == NULL) return -EINVAL; mutex_lock(&video->mutex); ret = v4l2_subdev_call(subdev, video, cropcap, cropcap); mutex_unlock(&video->mutex); return ret == -ENOIOCTLCMD ? -EINVAL : ret; } static int isp_video_get_crop(struct file *file, void *fh, struct v4l2_crop *crop) { struct isp_video *video = video_drvdata(file); struct v4l2_subdev_format format; struct v4l2_subdev *subdev; u32 pad; int ret; subdev = isp_video_remote_subdev(video, &pad); if (subdev == NULL) return -EINVAL; /* Try the get crop operation first and fallback to get format if not * implemented. */ ret = v4l2_subdev_call(subdev, video, g_crop, crop); if (ret != -ENOIOCTLCMD) return ret; format.pad = pad; format.which = V4L2_SUBDEV_FORMAT_ACTIVE; ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &format); if (ret < 0) return ret == -ENOIOCTLCMD ? -EINVAL : ret; crop->c.left = 0; crop->c.top = 0; crop->c.width = format.format.width; crop->c.height = format.format.height; return 0; } static int isp_video_set_crop(struct file *file, void *fh, struct v4l2_crop *crop) { struct isp_video *video = video_drvdata(file); struct v4l2_subdev *subdev; int ret; subdev = isp_video_remote_subdev(video, NULL); if (subdev == NULL) return -EINVAL; mutex_lock(&video->mutex); ret = v4l2_subdev_call(subdev, video, s_crop, crop); mutex_unlock(&video->mutex); return ret == -ENOIOCTLCMD ? -EINVAL : ret; } static int isp_video_get_param(struct file *file, void *fh, struct v4l2_streamparm *a) { struct isp_video_fh *vfh = to_isp_video_fh(fh); struct isp_video *video = video_drvdata(file); if (video->type != V4L2_BUF_TYPE_VIDEO_OUTPUT || video->type != a->type) return -EINVAL; memset(a, 0, sizeof(*a)); a->type = V4L2_BUF_TYPE_VIDEO_OUTPUT; a->parm.output.capability = V4L2_CAP_TIMEPERFRAME; a->parm.output.timeperframe = vfh->timeperframe; return 0; } static int isp_video_set_param(struct file *file, void *fh, struct v4l2_streamparm *a) { struct isp_video_fh *vfh = to_isp_video_fh(fh); struct isp_video *video = video_drvdata(file); if (video->type != V4L2_BUF_TYPE_VIDEO_OUTPUT || video->type != a->type) return -EINVAL; if (a->parm.output.timeperframe.denominator == 0) a->parm.output.timeperframe.denominator = 1; vfh->timeperframe = a->parm.output.timeperframe; return 0; } static int isp_video_reqbufs(struct file *file, void *fh, struct v4l2_requestbuffers *rb) { struct isp_video_fh *vfh = to_isp_video_fh(fh); return omap3isp_video_queue_reqbufs(&vfh->queue, rb); } static int isp_video_querybuf(struct file *file, void *fh, struct v4l2_buffer *b) { struct isp_video_fh *vfh = to_isp_video_fh(fh); return omap3isp_video_queue_querybuf(&vfh->queue, b); } static int isp_video_qbuf(struct file *file, void *fh, struct v4l2_buffer *b) { struct isp_video_fh *vfh = to_isp_video_fh(fh); return omap3isp_video_queue_qbuf(&vfh->queue, b); } static int isp_video_dqbuf(struct file *file, void *fh, struct v4l2_buffer *b) { struct isp_video_fh *vfh = to_isp_video_fh(fh); return omap3isp_video_queue_dqbuf(&vfh->queue, b, file->f_flags & O_NONBLOCK); } /* * Stream management * * Every ISP pipeline has a single input and a single output. The input can be * either a sensor or a video node. The output is always a video node. * * As every pipeline has an output video node, the ISP video objects at the * pipeline output stores the pipeline state. It tracks the streaming state of * both the input and output, as well as the availability of buffers. * * In sensor-to-memory mode, frames are always available at the pipeline input. * Starting the sensor usually requires I2C transfers and must be done in * interruptible context. The pipeline is started and stopped synchronously * to the stream on/off commands. All modules in the pipeline will get their * subdev set stream handler called. The module at the end of the pipeline must * delay starting the hardware until buffers are available at its output. * * In memory-to-memory mode, starting/stopping the stream requires * synchronization between the input and output. ISP modules can't be stopped * in the middle of a frame, and at least some of the modules seem to become * busy as soon as they're started, even if they don't receive a frame start * event. For that reason frames need to be processed in single-shot mode. The * driver needs to wait until a frame is completely processed and written to * memory before restarting the pipeline for the next frame. Pipelined * processing might be possible but requires more testing. * * Stream start must be delayed until buffers are available at both the input * and output. The pipeline must be started in the videobuf queue callback with * the buffers queue spinlock held. The modules subdev set stream operation must * not sleep. */ static int isp_video_streamon(struct file *file, void *fh, enum v4l2_buf_type type) { struct isp_video_fh *vfh = to_isp_video_fh(fh); struct isp_video *video = video_drvdata(file); enum isp_pipeline_state state; struct isp_pipeline *pipe; struct isp_video *far_end; unsigned long flags; int ret; if (type != video->type) return -EINVAL; mutex_lock(&video->stream_lock); if (video->streaming) { mutex_unlock(&video->stream_lock); return -EBUSY; } /* Start streaming on the pipeline. No link touching an entity in the * pipeline can be activated or deactivated once streaming is started. */ pipe = video->video.entity.pipe ? to_isp_pipeline(&video->video.entity) : &video->pipe; media_entity_pipeline_start(&video->video.entity, &pipe->pipe); /* Verify that the currently configured format matches the output of * the connected subdev. */ ret = isp_video_check_format(video, vfh); if (ret < 0) goto error; video->bpl_padding = ret; video->bpl_value = vfh->format.fmt.pix.bytesperline; /* Find the ISP video node connected at the far end of the pipeline and * update the pipeline. */ far_end = isp_video_far_end(video); if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) { state = ISP_PIPELINE_STREAM_OUTPUT | ISP_PIPELINE_IDLE_OUTPUT; pipe->input = far_end; pipe->output = video; } else { if (far_end == NULL) { ret = -EPIPE; goto error; } state = ISP_PIPELINE_STREAM_INPUT | ISP_PIPELINE_IDLE_INPUT; pipe->input = video; pipe->output = far_end; } if (video->isp->pdata->set_constraints) video->isp->pdata->set_constraints(video->isp, true); pipe->l3_ick = clk_get_rate(video->isp->clock[ISP_CLK_L3_ICK]); /* Validate the pipeline and update its state. */ ret = isp_video_validate_pipeline(pipe); if (ret < 0) goto error; pipe->error = false; spin_lock_irqsave(&pipe->lock, flags); pipe->state &= ~ISP_PIPELINE_STREAM; pipe->state |= state; spin_unlock_irqrestore(&pipe->lock, flags); /* Set the maximum time per frame as the value requested by userspace. * This is a soft limit that can be overridden if the hardware doesn't * support the request limit. */ if (video->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) pipe->max_timeperframe = vfh->timeperframe; video->queue = &vfh->queue; INIT_LIST_HEAD(&video->dmaqueue); atomic_set(&pipe->frame_number, -1); ret = omap3isp_video_queue_streamon(&vfh->queue); if (ret < 0) goto error; /* In sensor-to-memory mode, the stream can be started synchronously * to the stream on command. In memory-to-memory mode, it will be * started when buffers are queued on both the input and output. */ if (pipe->input == NULL) { ret = omap3isp_pipeline_set_stream(pipe, ISP_PIPELINE_STREAM_CONTINUOUS); if (ret < 0) goto error; spin_lock_irqsave(&video->queue->irqlock, flags); if (list_empty(&video->dmaqueue)) video->dmaqueue_flags |= ISP_VIDEO_DMAQUEUE_UNDERRUN; spin_unlock_irqrestore(&video->queue->irqlock, flags); } error: if (ret < 0) { omap3isp_video_queue_streamoff(&vfh->queue); if (video->isp->pdata->set_constraints) video->isp->pdata->set_constraints(video->isp, false); media_entity_pipeline_stop(&video->video.entity); /* The DMA queue must be emptied here, otherwise CCDC interrupts * that will get triggered the next time the CCDC is powered up * will try to access buffers that might have been freed but * still present in the DMA queue. This can easily get triggered * if the above omap3isp_pipeline_set_stream() call fails on a * system with a free-running sensor. */ INIT_LIST_HEAD(&video->dmaqueue); video->queue = NULL; } if (!ret) video->streaming = 1; mutex_unlock(&video->stream_lock); return ret; } static int isp_video_streamoff(struct file *file, void *fh, enum v4l2_buf_type type) { struct isp_video_fh *vfh = to_isp_video_fh(fh); struct isp_video *video = video_drvdata(file); struct isp_pipeline *pipe = to_isp_pipeline(&video->video.entity); enum isp_pipeline_state state; unsigned int streaming; unsigned long flags; if (type != video->type) return -EINVAL; mutex_lock(&video->stream_lock); /* Make sure we're not streaming yet. */ mutex_lock(&vfh->queue.lock); streaming = vfh->queue.streaming; mutex_unlock(&vfh->queue.lock); if (!streaming) goto done; /* Update the pipeline state. */ if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) state = ISP_PIPELINE_STREAM_OUTPUT | ISP_PIPELINE_QUEUE_OUTPUT; else state = ISP_PIPELINE_STREAM_INPUT | ISP_PIPELINE_QUEUE_INPUT; spin_lock_irqsave(&pipe->lock, flags); pipe->state &= ~state; spin_unlock_irqrestore(&pipe->lock, flags); /* Stop the stream. */ omap3isp_pipeline_set_stream(pipe, ISP_PIPELINE_STREAM_STOPPED); omap3isp_video_queue_streamoff(&vfh->queue); video->queue = NULL; video->streaming = 0; if (video->isp->pdata->set_constraints) video->isp->pdata->set_constraints(video->isp, false); media_entity_pipeline_stop(&video->video.entity); done: mutex_unlock(&video->stream_lock); return 0; } static int isp_video_enum_input(struct file *file, void *fh, struct v4l2_input *input) { if (input->index > 0) return -EINVAL; strlcpy(input->name, "camera", sizeof(input->name)); input->type = V4L2_INPUT_TYPE_CAMERA; return 0; } static int isp_video_g_input(struct file *file, void *fh, unsigned int *input) { *input = 0; return 0; } static int isp_video_s_input(struct file *file, void *fh, unsigned int input) { return input == 0 ? 0 : -EINVAL; } static const struct v4l2_ioctl_ops isp_video_ioctl_ops = { .vidioc_querycap = isp_video_querycap, .vidioc_g_fmt_vid_cap = isp_video_get_format, .vidioc_s_fmt_vid_cap = isp_video_set_format, .vidioc_try_fmt_vid_cap = isp_video_try_format, .vidioc_g_fmt_vid_out = isp_video_get_format, .vidioc_s_fmt_vid_out = isp_video_set_format, .vidioc_try_fmt_vid_out = isp_video_try_format, .vidioc_cropcap = isp_video_cropcap, .vidioc_g_crop = isp_video_get_crop, .vidioc_s_crop = isp_video_set_crop, .vidioc_g_parm = isp_video_get_param, .vidioc_s_parm = isp_video_set_param, .vidioc_reqbufs = isp_video_reqbufs, .vidioc_querybuf = isp_video_querybuf, .vidioc_qbuf = isp_video_qbuf, .vidioc_dqbuf = isp_video_dqbuf, .vidioc_streamon = isp_video_streamon, .vidioc_streamoff = isp_video_streamoff, .vidioc_enum_input = isp_video_enum_input, .vidioc_g_input = isp_video_g_input, .vidioc_s_input = isp_video_s_input, }; /* ----------------------------------------------------------------------------- * V4L2 file operations */ static int isp_video_open(struct file *file) { struct isp_video *video = video_drvdata(file); struct isp_video_fh *handle; int ret = 0; handle = kzalloc(sizeof(*handle), GFP_KERNEL); if (handle == NULL) return -ENOMEM; v4l2_fh_init(&handle->vfh, &video->video); v4l2_fh_add(&handle->vfh); /* If this is the first user, initialise the pipeline. */ if (omap3isp_get(video->isp) == NULL) { ret = -EBUSY; goto done; } ret = omap3isp_pipeline_pm_use(&video->video.entity, 1); if (ret < 0) { omap3isp_put(video->isp); goto done; } omap3isp_video_queue_init(&handle->queue, video->type, &isp_video_queue_ops, video->isp->dev, sizeof(struct isp_buffer)); memset(&handle->format, 0, sizeof(handle->format)); handle->format.type = video->type; handle->timeperframe.denominator = 1; handle->video = video; file->private_data = &handle->vfh; done: if (ret < 0) { v4l2_fh_del(&handle->vfh); kfree(handle); } return ret; } static int isp_video_release(struct file *file) { struct isp_video *video = video_drvdata(file); struct v4l2_fh *vfh = file->private_data; struct isp_video_fh *handle = to_isp_video_fh(vfh); /* Disable streaming and free the buffers queue resources. */ isp_video_streamoff(file, vfh, video->type); mutex_lock(&handle->queue.lock); omap3isp_video_queue_cleanup(&handle->queue); mutex_unlock(&handle->queue.lock); omap3isp_pipeline_pm_use(&video->video.entity, 0); /* Release the file handle. */ v4l2_fh_del(vfh); kfree(handle); file->private_data = NULL; omap3isp_put(video->isp); return 0; } static unsigned int isp_video_poll(struct file *file, poll_table *wait) { struct isp_video_fh *vfh = to_isp_video_fh(file->private_data); struct isp_video_queue *queue = &vfh->queue; return omap3isp_video_queue_poll(queue, file, wait); } static int isp_video_mmap(struct file *file, struct vm_area_struct *vma) { struct isp_video_fh *vfh = to_isp_video_fh(file->private_data); return omap3isp_video_queue_mmap(&vfh->queue, vma); } static struct v4l2_file_operations isp_video_fops = { .owner = THIS_MODULE, .unlocked_ioctl = video_ioctl2, .open = isp_video_open, .release = isp_video_release, .poll = isp_video_poll, .mmap = isp_video_mmap, }; /* ----------------------------------------------------------------------------- * ISP video core */ static const struct isp_video_operations isp_video_dummy_ops = { }; int omap3isp_video_init(struct isp_video *video, const char *name) { const char *direction; int ret; switch (video->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: direction = "output"; video->pad.flags = MEDIA_PAD_FL_SINK; break; case V4L2_BUF_TYPE_VIDEO_OUTPUT: direction = "input"; video->pad.flags = MEDIA_PAD_FL_SOURCE; break; default: return -EINVAL; } ret = media_entity_init(&video->video.entity, 1, &video->pad, 0); if (ret < 0) return ret; mutex_init(&video->mutex); atomic_set(&video->active, 0); spin_lock_init(&video->pipe.lock); mutex_init(&video->stream_lock); /* Initialize the video device. */ if (video->ops == NULL) video->ops = &isp_video_dummy_ops; video->video.fops = &isp_video_fops; snprintf(video->video.name, sizeof(video->video.name), "OMAP3 ISP %s %s", name, direction); video->video.vfl_type = VFL_TYPE_GRABBER; video->video.release = video_device_release_empty; video->video.ioctl_ops = &isp_video_ioctl_ops; video->pipe.stream_state = ISP_PIPELINE_STREAM_STOPPED; video_set_drvdata(&video->video, video); return 0; } void omap3isp_video_cleanup(struct isp_video *video) { media_entity_cleanup(&video->video.entity); mutex_destroy(&video->stream_lock); mutex_destroy(&video->mutex); } int omap3isp_video_register(struct isp_video *video, struct v4l2_device *vdev) { int ret; video->video.v4l2_dev = vdev; ret = video_register_device(&video->video, VFL_TYPE_GRABBER, -1); if (ret < 0) printk(KERN_ERR "%s: could not register video device (%d)\n", __func__, ret); return ret; } void omap3isp_video_unregister(struct isp_video *video) { if (video_is_registered(&video->video)) video_unregister_device(&video->video); }
gpl-2.0
CyanideL/android_kernel_samsung_klte
drivers/power/z2_battery.c
4898
8017
/* * Battery measurement code for Zipit Z2 * * Copyright (C) 2009 Peter Edwards <sweetlilmre@gmail.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/gpio.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/power_supply.h> #include <linux/slab.h> #include <linux/z2_battery.h> #define Z2_DEFAULT_NAME "Z2" struct z2_charger { struct z2_battery_info *info; int bat_status; struct i2c_client *client; struct power_supply batt_ps; struct mutex work_lock; struct work_struct bat_work; }; static unsigned long z2_read_bat(struct z2_charger *charger) { int data; data = i2c_smbus_read_byte_data(charger->client, charger->info->batt_I2C_reg); if (data < 0) return 0; return data * charger->info->batt_mult / charger->info->batt_div; } static int z2_batt_get_property(struct power_supply *batt_ps, enum power_supply_property psp, union power_supply_propval *val) { struct z2_charger *charger = container_of(batt_ps, struct z2_charger, batt_ps); struct z2_battery_info *info = charger->info; switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = charger->bat_status; break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = info->batt_tech; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: if (info->batt_I2C_reg >= 0) val->intval = z2_read_bat(charger); else return -EINVAL; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: if (info->max_voltage >= 0) val->intval = info->max_voltage; else return -EINVAL; break; case POWER_SUPPLY_PROP_VOLTAGE_MIN: if (info->min_voltage >= 0) val->intval = info->min_voltage; else return -EINVAL; break; case POWER_SUPPLY_PROP_PRESENT: val->intval = 1; break; default: return -EINVAL; } return 0; } static void z2_batt_ext_power_changed(struct power_supply *batt_ps) { struct z2_charger *charger = container_of(batt_ps, struct z2_charger, batt_ps); schedule_work(&charger->bat_work); } static void z2_batt_update(struct z2_charger *charger) { int old_status = charger->bat_status; struct z2_battery_info *info; info = charger->info; mutex_lock(&charger->work_lock); charger->bat_status = (info->charge_gpio >= 0) ? (gpio_get_value(info->charge_gpio) ? POWER_SUPPLY_STATUS_CHARGING : POWER_SUPPLY_STATUS_DISCHARGING) : POWER_SUPPLY_STATUS_UNKNOWN; if (old_status != charger->bat_status) { pr_debug("%s: %i -> %i\n", charger->batt_ps.name, old_status, charger->bat_status); power_supply_changed(&charger->batt_ps); } mutex_unlock(&charger->work_lock); } static void z2_batt_work(struct work_struct *work) { struct z2_charger *charger; charger = container_of(work, struct z2_charger, bat_work); z2_batt_update(charger); } static irqreturn_t z2_charge_switch_irq(int irq, void *devid) { struct z2_charger *charger = devid; schedule_work(&charger->bat_work); return IRQ_HANDLED; } static int z2_batt_ps_init(struct z2_charger *charger, int props) { int i = 0; enum power_supply_property *prop; struct z2_battery_info *info = charger->info; if (info->charge_gpio >= 0) props++; /* POWER_SUPPLY_PROP_STATUS */ if (info->batt_tech >= 0) props++; /* POWER_SUPPLY_PROP_TECHNOLOGY */ if (info->batt_I2C_reg >= 0) props++; /* POWER_SUPPLY_PROP_VOLTAGE_NOW */ if (info->max_voltage >= 0) props++; /* POWER_SUPPLY_PROP_VOLTAGE_MAX */ if (info->min_voltage >= 0) props++; /* POWER_SUPPLY_PROP_VOLTAGE_MIN */ prop = kzalloc(props * sizeof(*prop), GFP_KERNEL); if (!prop) return -ENOMEM; prop[i++] = POWER_SUPPLY_PROP_PRESENT; if (info->charge_gpio >= 0) prop[i++] = POWER_SUPPLY_PROP_STATUS; if (info->batt_tech >= 0) prop[i++] = POWER_SUPPLY_PROP_TECHNOLOGY; if (info->batt_I2C_reg >= 0) prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_NOW; if (info->max_voltage >= 0) prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_MAX; if (info->min_voltage >= 0) prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_MIN; if (!info->batt_name) { dev_info(&charger->client->dev, "Please consider setting proper battery " "name in platform definition file, falling " "back to name \" Z2_DEFAULT_NAME \"\n"); charger->batt_ps.name = Z2_DEFAULT_NAME; } else charger->batt_ps.name = info->batt_name; charger->batt_ps.properties = prop; charger->batt_ps.num_properties = props; charger->batt_ps.type = POWER_SUPPLY_TYPE_BATTERY; charger->batt_ps.get_property = z2_batt_get_property; charger->batt_ps.external_power_changed = z2_batt_ext_power_changed; charger->batt_ps.use_for_apm = 1; return 0; } static int __devinit z2_batt_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret = 0; int props = 1; /* POWER_SUPPLY_PROP_PRESENT */ struct z2_charger *charger; struct z2_battery_info *info = client->dev.platform_data; if (info == NULL) { dev_err(&client->dev, "Please set platform device platform_data" " to a valid z2_battery_info pointer!\n"); return -EINVAL; } charger = kzalloc(sizeof(*charger), GFP_KERNEL); if (charger == NULL) return -ENOMEM; charger->bat_status = POWER_SUPPLY_STATUS_UNKNOWN; charger->info = info; charger->client = client; i2c_set_clientdata(client, charger); mutex_init(&charger->work_lock); if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) { ret = gpio_request(info->charge_gpio, "BATT CHRG"); if (ret) goto err; ret = gpio_direction_input(info->charge_gpio); if (ret) goto err2; irq_set_irq_type(gpio_to_irq(info->charge_gpio), IRQ_TYPE_EDGE_BOTH); ret = request_irq(gpio_to_irq(info->charge_gpio), z2_charge_switch_irq, 0, "AC Detect", charger); if (ret) goto err3; } ret = z2_batt_ps_init(charger, props); if (ret) goto err3; INIT_WORK(&charger->bat_work, z2_batt_work); ret = power_supply_register(&client->dev, &charger->batt_ps); if (ret) goto err4; schedule_work(&charger->bat_work); return 0; err4: kfree(charger->batt_ps.properties); err3: if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) free_irq(gpio_to_irq(info->charge_gpio), charger); err2: if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) gpio_free(info->charge_gpio); err: kfree(charger); return ret; } static int __devexit z2_batt_remove(struct i2c_client *client) { struct z2_charger *charger = i2c_get_clientdata(client); struct z2_battery_info *info = charger->info; cancel_work_sync(&charger->bat_work); power_supply_unregister(&charger->batt_ps); kfree(charger->batt_ps.properties); if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) { free_irq(gpio_to_irq(info->charge_gpio), charger); gpio_free(info->charge_gpio); } kfree(charger); return 0; } #ifdef CONFIG_PM static int z2_batt_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct z2_charger *charger = i2c_get_clientdata(client); flush_work_sync(&charger->bat_work); return 0; } static int z2_batt_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct z2_charger *charger = i2c_get_clientdata(client); schedule_work(&charger->bat_work); return 0; } static const struct dev_pm_ops z2_battery_pm_ops = { .suspend = z2_batt_suspend, .resume = z2_batt_resume, }; #define Z2_BATTERY_PM_OPS (&z2_battery_pm_ops) #else #define Z2_BATTERY_PM_OPS (NULL) #endif static const struct i2c_device_id z2_batt_id[] = { { "aer915", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, z2_batt_id); static struct i2c_driver z2_batt_driver = { .driver = { .name = "z2-battery", .owner = THIS_MODULE, .pm = Z2_BATTERY_PM_OPS }, .probe = z2_batt_probe, .remove = __devexit_p(z2_batt_remove), .id_table = z2_batt_id, }; module_i2c_driver(z2_batt_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Peter Edwards <sweetlilmre@gmail.com>"); MODULE_DESCRIPTION("Zipit Z2 battery driver");
gpl-2.0
zombah/android_kernel_nokia_msm8610
drivers/xen/xen-pciback/conf_space_header.c
6434
8786
/* * PCI Backend - Handles the virtual fields in the configuration space headers. * * Author: Ryan Wilson <hap9@epoch.ncsc.mil> */ #include <linux/kernel.h> #include <linux/pci.h> #include "pciback.h" #include "conf_space.h" struct pci_bar_info { u32 val; u32 len_val; int which; }; #define is_enable_cmd(value) ((value)&(PCI_COMMAND_MEMORY|PCI_COMMAND_IO)) #define is_master_cmd(value) ((value)&PCI_COMMAND_MASTER) static int command_read(struct pci_dev *dev, int offset, u16 *value, void *data) { int i; int ret; ret = xen_pcibk_read_config_word(dev, offset, value, data); if (!pci_is_enabled(dev)) return ret; for (i = 0; i < PCI_ROM_RESOURCE; i++) { if (dev->resource[i].flags & IORESOURCE_IO) *value |= PCI_COMMAND_IO; if (dev->resource[i].flags & IORESOURCE_MEM) *value |= PCI_COMMAND_MEMORY; } return ret; } static int command_write(struct pci_dev *dev, int offset, u16 value, void *data) { struct xen_pcibk_dev_data *dev_data; int err; dev_data = pci_get_drvdata(dev); if (!pci_is_enabled(dev) && is_enable_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: enable\n", pci_name(dev)); err = pci_enable_device(dev); if (err) return err; if (dev_data) dev_data->enable_intx = 1; } else if (pci_is_enabled(dev) && !is_enable_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: disable\n", pci_name(dev)); pci_disable_device(dev); if (dev_data) dev_data->enable_intx = 0; } if (!dev->is_busmaster && is_master_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: set bus master\n", pci_name(dev)); pci_set_master(dev); } if (value & PCI_COMMAND_INVALIDATE) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: enable memory-write-invalidate\n", pci_name(dev)); err = pci_set_mwi(dev); if (err) { printk(KERN_WARNING DRV_NAME ": %s: cannot enable " "memory-write-invalidate (%d)\n", pci_name(dev), err); value &= ~PCI_COMMAND_INVALIDATE; } } return pci_write_config_word(dev, offset, value); } static int rom_write(struct pci_dev *dev, int offset, u32 value, void *data) { struct pci_bar_info *bar = data; if (unlikely(!bar)) { printk(KERN_WARNING DRV_NAME ": driver data not found for %s\n", pci_name(dev)); return XEN_PCI_ERR_op_failed; } /* A write to obtain the length must happen as a 32-bit write. * This does not (yet) support writing individual bytes */ if (value == ~PCI_ROM_ADDRESS_ENABLE) bar->which = 1; else { u32 tmpval; pci_read_config_dword(dev, offset, &tmpval); if (tmpval != bar->val && value == bar->val) { /* Allow restoration of bar value. */ pci_write_config_dword(dev, offset, bar->val); } bar->which = 0; } /* Do we need to support enabling/disabling the rom address here? */ return 0; } /* For the BARs, only allow writes which write ~0 or * the correct resource information * (Needed for when the driver probes the resource usage) */ static int bar_write(struct pci_dev *dev, int offset, u32 value, void *data) { struct pci_bar_info *bar = data; if (unlikely(!bar)) { printk(KERN_WARNING DRV_NAME ": driver data not found for %s\n", pci_name(dev)); return XEN_PCI_ERR_op_failed; } /* A write to obtain the length must happen as a 32-bit write. * This does not (yet) support writing individual bytes */ if (value == ~0) bar->which = 1; else { u32 tmpval; pci_read_config_dword(dev, offset, &tmpval); if (tmpval != bar->val && value == bar->val) { /* Allow restoration of bar value. */ pci_write_config_dword(dev, offset, bar->val); } bar->which = 0; } return 0; } static int bar_read(struct pci_dev *dev, int offset, u32 * value, void *data) { struct pci_bar_info *bar = data; if (unlikely(!bar)) { printk(KERN_WARNING DRV_NAME ": driver data not found for %s\n", pci_name(dev)); return XEN_PCI_ERR_op_failed; } *value = bar->which ? bar->len_val : bar->val; return 0; } static inline void read_dev_bar(struct pci_dev *dev, struct pci_bar_info *bar_info, int offset, u32 len_mask) { int pos; struct resource *res = dev->resource; if (offset == PCI_ROM_ADDRESS || offset == PCI_ROM_ADDRESS1) pos = PCI_ROM_RESOURCE; else { pos = (offset - PCI_BASE_ADDRESS_0) / 4; if (pos && ((res[pos - 1].flags & (PCI_BASE_ADDRESS_SPACE | PCI_BASE_ADDRESS_MEM_TYPE_MASK)) == (PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64))) { bar_info->val = res[pos - 1].start >> 32; bar_info->len_val = res[pos - 1].end >> 32; return; } } bar_info->val = res[pos].start | (res[pos].flags & PCI_REGION_FLAG_MASK); bar_info->len_val = resource_size(&res[pos]); } static void *bar_init(struct pci_dev *dev, int offset) { struct pci_bar_info *bar = kmalloc(sizeof(*bar), GFP_KERNEL); if (!bar) return ERR_PTR(-ENOMEM); read_dev_bar(dev, bar, offset, ~0); bar->which = 0; return bar; } static void *rom_init(struct pci_dev *dev, int offset) { struct pci_bar_info *bar = kmalloc(sizeof(*bar), GFP_KERNEL); if (!bar) return ERR_PTR(-ENOMEM); read_dev_bar(dev, bar, offset, ~PCI_ROM_ADDRESS_ENABLE); bar->which = 0; return bar; } static void bar_reset(struct pci_dev *dev, int offset, void *data) { struct pci_bar_info *bar = data; bar->which = 0; } static void bar_release(struct pci_dev *dev, int offset, void *data) { kfree(data); } static int xen_pcibk_read_vendor(struct pci_dev *dev, int offset, u16 *value, void *data) { *value = dev->vendor; return 0; } static int xen_pcibk_read_device(struct pci_dev *dev, int offset, u16 *value, void *data) { *value = dev->device; return 0; } static int interrupt_read(struct pci_dev *dev, int offset, u8 * value, void *data) { *value = (u8) dev->irq; return 0; } static int bist_write(struct pci_dev *dev, int offset, u8 value, void *data) { u8 cur_value; int err; err = pci_read_config_byte(dev, offset, &cur_value); if (err) goto out; if ((cur_value & ~PCI_BIST_START) == (value & ~PCI_BIST_START) || value == PCI_BIST_START) err = pci_write_config_byte(dev, offset, value); out: return err; } static const struct config_field header_common[] = { { .offset = PCI_VENDOR_ID, .size = 2, .u.w.read = xen_pcibk_read_vendor, }, { .offset = PCI_DEVICE_ID, .size = 2, .u.w.read = xen_pcibk_read_device, }, { .offset = PCI_COMMAND, .size = 2, .u.w.read = command_read, .u.w.write = command_write, }, { .offset = PCI_INTERRUPT_LINE, .size = 1, .u.b.read = interrupt_read, }, { .offset = PCI_INTERRUPT_PIN, .size = 1, .u.b.read = xen_pcibk_read_config_byte, }, { /* Any side effects of letting driver domain control cache line? */ .offset = PCI_CACHE_LINE_SIZE, .size = 1, .u.b.read = xen_pcibk_read_config_byte, .u.b.write = xen_pcibk_write_config_byte, }, { .offset = PCI_LATENCY_TIMER, .size = 1, .u.b.read = xen_pcibk_read_config_byte, }, { .offset = PCI_BIST, .size = 1, .u.b.read = xen_pcibk_read_config_byte, .u.b.write = bist_write, }, {} }; #define CFG_FIELD_BAR(reg_offset) \ { \ .offset = reg_offset, \ .size = 4, \ .init = bar_init, \ .reset = bar_reset, \ .release = bar_release, \ .u.dw.read = bar_read, \ .u.dw.write = bar_write, \ } #define CFG_FIELD_ROM(reg_offset) \ { \ .offset = reg_offset, \ .size = 4, \ .init = rom_init, \ .reset = bar_reset, \ .release = bar_release, \ .u.dw.read = bar_read, \ .u.dw.write = rom_write, \ } static const struct config_field header_0[] = { CFG_FIELD_BAR(PCI_BASE_ADDRESS_0), CFG_FIELD_BAR(PCI_BASE_ADDRESS_1), CFG_FIELD_BAR(PCI_BASE_ADDRESS_2), CFG_FIELD_BAR(PCI_BASE_ADDRESS_3), CFG_FIELD_BAR(PCI_BASE_ADDRESS_4), CFG_FIELD_BAR(PCI_BASE_ADDRESS_5), CFG_FIELD_ROM(PCI_ROM_ADDRESS), {} }; static const struct config_field header_1[] = { CFG_FIELD_BAR(PCI_BASE_ADDRESS_0), CFG_FIELD_BAR(PCI_BASE_ADDRESS_1), CFG_FIELD_ROM(PCI_ROM_ADDRESS1), {} }; int xen_pcibk_config_header_add_fields(struct pci_dev *dev) { int err; err = xen_pcibk_config_add_fields(dev, header_common); if (err) goto out; switch (dev->hdr_type) { case PCI_HEADER_TYPE_NORMAL: err = xen_pcibk_config_add_fields(dev, header_0); break; case PCI_HEADER_TYPE_BRIDGE: err = xen_pcibk_config_add_fields(dev, header_1); break; default: err = -EINVAL; printk(KERN_ERR DRV_NAME ": %s: Unsupported header type %d!\n", pci_name(dev), dev->hdr_type); break; } out: return err; }
gpl-2.0
genesi/linux-testing
arch/arm/mach-at91/board-eb01.c
7714
1470
/* * arch/arm/mach-at91/board-eb01.c * * (C) Copyright 2007, Greg Ungerer <gerg@snapgear.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/irq.h> #include <asm/mach-types.h> #include <mach/hardware.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/board.h> #include "generic.h" static void __init at91eb01_init_irq(void) { at91x40_init_interrupts(NULL); } static void __init at91eb01_init_early(void) { at91x40_initialize(40000000); } MACHINE_START(AT91EB01, "Atmel AT91 EB01") /* Maintainer: Greg Ungerer <gerg@snapgear.com> */ .timer = &at91x40_timer, .init_early = at91eb01_init_early, .init_irq = at91eb01_init_irq, MACHINE_END
gpl-2.0
Flemmard/akh8960_cm
drivers/clocksource/cyclone.c
7714
2954
#include <linux/clocksource.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/timex.h> #include <linux/init.h> #include <asm/pgtable.h> #include <asm/io.h> #include <asm/mach_timer.h> #define CYCLONE_CBAR_ADDR 0xFEB00CD0 /* base address ptr */ #define CYCLONE_PMCC_OFFSET 0x51A0 /* offset to control register */ #define CYCLONE_MPCS_OFFSET 0x51A8 /* offset to select register */ #define CYCLONE_MPMC_OFFSET 0x51D0 /* offset to count register */ #define CYCLONE_TIMER_FREQ 99780000 /* 100Mhz, but not really */ #define CYCLONE_TIMER_MASK CLOCKSOURCE_MASK(32) /* 32 bit mask */ int use_cyclone = 0; static void __iomem *cyclone_ptr; static cycle_t read_cyclone(struct clocksource *cs) { return (cycle_t)readl(cyclone_ptr); } static struct clocksource clocksource_cyclone = { .name = "cyclone", .rating = 250, .read = read_cyclone, .mask = CYCLONE_TIMER_MASK, .flags = CLOCK_SOURCE_IS_CONTINUOUS, }; static int __init init_cyclone_clocksource(void) { unsigned long base; /* saved value from CBAR */ unsigned long offset; u32 __iomem* volatile cyclone_timer; /* Cyclone MPMC0 register */ u32 __iomem* reg; int i; /* make sure we're on a summit box: */ if (!use_cyclone) return -ENODEV; printk(KERN_INFO "Summit chipset: Starting Cyclone Counter.\n"); /* find base address: */ offset = CYCLONE_CBAR_ADDR; reg = ioremap_nocache(offset, sizeof(reg)); if (!reg) { printk(KERN_ERR "Summit chipset: Could not find valid CBAR register.\n"); return -ENODEV; } /* even on 64bit systems, this is only 32bits: */ base = readl(reg); iounmap(reg); if (!base) { printk(KERN_ERR "Summit chipset: Could not find valid CBAR value.\n"); return -ENODEV; } /* setup PMCC: */ offset = base + CYCLONE_PMCC_OFFSET; reg = ioremap_nocache(offset, sizeof(reg)); if (!reg) { printk(KERN_ERR "Summit chipset: Could not find valid PMCC register.\n"); return -ENODEV; } writel(0x00000001,reg); iounmap(reg); /* setup MPCS: */ offset = base + CYCLONE_MPCS_OFFSET; reg = ioremap_nocache(offset, sizeof(reg)); if (!reg) { printk(KERN_ERR "Summit chipset: Could not find valid MPCS register.\n"); return -ENODEV; } writel(0x00000001,reg); iounmap(reg); /* map in cyclone_timer: */ offset = base + CYCLONE_MPMC_OFFSET; cyclone_timer = ioremap_nocache(offset, sizeof(u64)); if (!cyclone_timer) { printk(KERN_ERR "Summit chipset: Could not find valid MPMC register.\n"); return -ENODEV; } /* quick test to make sure its ticking: */ for (i = 0; i < 3; i++){ u32 old = readl(cyclone_timer); int stall = 100; while (stall--) barrier(); if (readl(cyclone_timer) == old) { printk(KERN_ERR "Summit chipset: Counter not counting! DISABLED\n"); iounmap(cyclone_timer); cyclone_timer = NULL; return -ENODEV; } } cyclone_ptr = cyclone_timer; return clocksource_register_hz(&clocksource_cyclone, CYCLONE_TIMER_FREQ); } arch_initcall(init_cyclone_clocksource);
gpl-2.0
piccolo-dev/android_kernel_bq_piccolo
net/irda/irda_device.c
7714
8204
/********************************************************************* * * Filename: irda_device.c * Version: 0.9 * Description: Utility functions used by the device drivers * Status: Experimental. * Author: Dag Brattli <dagb@cs.uit.no> * Created at: Sat Oct 9 09:22:27 1999 * Modified at: Sun Jan 23 17:41:24 2000 * Modified by: Dag Brattli <dagb@cs.uit.no> * * Copyright (c) 1999-2000 Dag Brattli, All Rights Reserved. * Copyright (c) 2000-2001 Jean Tourrilhes <jt@hpl.hp.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ********************************************************************/ #include <linux/string.h> #include <linux/proc_fs.h> #include <linux/skbuff.h> #include <linux/capability.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_arp.h> #include <linux/netdevice.h> #include <linux/init.h> #include <linux/tty.h> #include <linux/kmod.h> #include <linux/spinlock.h> #include <linux/slab.h> #include <linux/export.h> #include <asm/ioctls.h> #include <asm/uaccess.h> #include <asm/dma.h> #include <asm/io.h> #include <net/irda/irda_device.h> #include <net/irda/irlap.h> #include <net/irda/timer.h> #include <net/irda/wrapper.h> static void __irda_task_delete(struct irda_task *task); static hashbin_t *dongles = NULL; static hashbin_t *tasks = NULL; static void irda_task_timer_expired(void *data); int __init irda_device_init( void) { dongles = hashbin_new(HB_NOLOCK); if (dongles == NULL) { IRDA_WARNING("IrDA: Can't allocate dongles hashbin!\n"); return -ENOMEM; } spin_lock_init(&dongles->hb_spinlock); tasks = hashbin_new(HB_LOCK); if (tasks == NULL) { IRDA_WARNING("IrDA: Can't allocate tasks hashbin!\n"); hashbin_delete(dongles, NULL); return -ENOMEM; } /* We no longer initialise the driver ourselves here, we let * the system do it for us... - Jean II */ return 0; } static void leftover_dongle(void *arg) { struct dongle_reg *reg = arg; IRDA_WARNING("IrDA: Dongle type %x not unregistered\n", reg->type); } void irda_device_cleanup(void) { IRDA_DEBUG(4, "%s()\n", __func__); hashbin_delete(tasks, (FREE_FUNC) __irda_task_delete); hashbin_delete(dongles, leftover_dongle); } /* * Function irda_device_set_media_busy (self, status) * * Called when we have detected that another station is transmitting * in contention mode. */ void irda_device_set_media_busy(struct net_device *dev, int status) { struct irlap_cb *self; IRDA_DEBUG(4, "%s(%s)\n", __func__, status ? "TRUE" : "FALSE"); self = (struct irlap_cb *) dev->atalk_ptr; /* Some drivers may enable the receive interrupt before calling * irlap_open(), or they may disable the receive interrupt * after calling irlap_close(). * The IrDA stack is protected from this in irlap_driver_rcv(). * However, the driver calls directly the wrapper, that calls * us directly. Make sure we protect ourselves. * Jean II */ if (!self || self->magic != LAP_MAGIC) return; if (status) { self->media_busy = TRUE; if (status == SMALL) irlap_start_mbusy_timer(self, SMALLBUSY_TIMEOUT); else irlap_start_mbusy_timer(self, MEDIABUSY_TIMEOUT); IRDA_DEBUG( 4, "Media busy!\n"); } else { self->media_busy = FALSE; irlap_stop_mbusy_timer(self); } } EXPORT_SYMBOL(irda_device_set_media_busy); /* * Function irda_device_is_receiving (dev) * * Check if the device driver is currently receiving data * */ int irda_device_is_receiving(struct net_device *dev) { struct if_irda_req req; int ret; IRDA_DEBUG(2, "%s()\n", __func__); if (!dev->netdev_ops->ndo_do_ioctl) { IRDA_ERROR("%s: do_ioctl not impl. by device driver\n", __func__); return -1; } ret = (dev->netdev_ops->ndo_do_ioctl)(dev, (struct ifreq *) &req, SIOCGRECEIVING); if (ret < 0) return ret; return req.ifr_receiving; } static void __irda_task_delete(struct irda_task *task) { del_timer(&task->timer); kfree(task); } static void irda_task_delete(struct irda_task *task) { /* Unregister task */ hashbin_remove(tasks, (long) task, NULL); __irda_task_delete(task); } /* * Function irda_task_kick (task) * * Tries to execute a task possible multiple times until the task is either * finished, or askes for a timeout. When a task is finished, we do post * processing, and notify the parent task, that is waiting for this task * to complete. */ static int irda_task_kick(struct irda_task *task) { int finished = TRUE; int count = 0; int timeout; IRDA_DEBUG(2, "%s()\n", __func__); IRDA_ASSERT(task != NULL, return -1;); IRDA_ASSERT(task->magic == IRDA_TASK_MAGIC, return -1;); /* Execute task until it's finished, or askes for a timeout */ do { timeout = task->function(task); if (count++ > 100) { IRDA_ERROR("%s: error in task handler!\n", __func__); irda_task_delete(task); return TRUE; } } while ((timeout == 0) && (task->state != IRDA_TASK_DONE)); if (timeout < 0) { IRDA_ERROR("%s: Error executing task!\n", __func__); irda_task_delete(task); return TRUE; } /* Check if we are finished */ if (task->state == IRDA_TASK_DONE) { del_timer(&task->timer); /* Do post processing */ if (task->finished) task->finished(task); /* Notify parent */ if (task->parent) { /* Check if parent is waiting for us to complete */ if (task->parent->state == IRDA_TASK_CHILD_WAIT) { task->parent->state = IRDA_TASK_CHILD_DONE; /* Stop timer now that we are here */ del_timer(&task->parent->timer); /* Kick parent task */ irda_task_kick(task->parent); } } irda_task_delete(task); } else if (timeout > 0) { irda_start_timer(&task->timer, timeout, (void *) task, irda_task_timer_expired); finished = FALSE; } else { IRDA_DEBUG(0, "%s(), not finished, and no timeout!\n", __func__); finished = FALSE; } return finished; } /* * Function irda_task_timer_expired (data) * * Task time has expired. We now try to execute task (again), and restart * the timer if the task has not finished yet */ static void irda_task_timer_expired(void *data) { struct irda_task *task; IRDA_DEBUG(2, "%s()\n", __func__); task = data; irda_task_kick(task); } /* * Function irda_device_setup (dev) * * This function should be used by low level device drivers in a similar way * as ether_setup() is used by normal network device drivers */ static void irda_device_setup(struct net_device *dev) { dev->hard_header_len = 0; dev->addr_len = LAP_ALEN; dev->type = ARPHRD_IRDA; dev->tx_queue_len = 8; /* Window size + 1 s-frame */ memset(dev->broadcast, 0xff, LAP_ALEN); dev->mtu = 2048; dev->flags = IFF_NOARP; } /* * Funciton alloc_irdadev * Allocates and sets up an IRDA device in a manner similar to * alloc_etherdev. */ struct net_device *alloc_irdadev(int sizeof_priv) { return alloc_netdev(sizeof_priv, "irda%d", irda_device_setup); } EXPORT_SYMBOL(alloc_irdadev); #ifdef CONFIG_ISA_DMA_API /* * Function setup_dma (idev, buffer, count, mode) * * Setup the DMA channel. Commonly used by LPC FIR drivers * */ void irda_setup_dma(int channel, dma_addr_t buffer, int count, int mode) { unsigned long flags; flags = claim_dma_lock(); disable_dma(channel); clear_dma_ff(channel); set_dma_mode(channel, mode); set_dma_addr(channel, buffer); set_dma_count(channel, count); enable_dma(channel); release_dma_lock(flags); } EXPORT_SYMBOL(irda_setup_dma); #endif
gpl-2.0
Kuzma30/NT34K
arch/arm/mach-imx/mx31lilly-db.c
7714
5404
/* * LILLY-1131 development board support * * Copyright (c) 2009 Daniel Mack <daniel@caiaq.de> * * based on code for other MX31 boards, * * Copyright 2005-2007 Freescale Semiconductor * Copyright (c) 2009 Alberto Panizzo <maramaopercheseimorto@gmail.com> * Copyright (C) 2009 Valentin Longchamp, EPFL Mobots group * * This program is free software; you can redistribute it and/or modify * it under the terms of the 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/kernel.h> #include <linux/types.h> #include <linux/init.h> #include <linux/gpio.h> #include <linux/platform_device.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/hardware.h> #include <mach/common.h> #include <mach/iomux-mx3.h> #include <mach/board-mx31lilly.h> #include "devices-imx31.h" /* * This file contains board-specific initialization routines for the * LILLY-1131 development board. If you design an own baseboard for the * module, use this file as base for support code. */ static unsigned int lilly_db_board_pins[] __initdata = { MX31_PIN_CTS1__CTS1, MX31_PIN_RTS1__RTS1, MX31_PIN_TXD1__TXD1, MX31_PIN_RXD1__RXD1, MX31_PIN_CTS2__CTS2, MX31_PIN_RTS2__RTS2, MX31_PIN_TXD2__TXD2, MX31_PIN_RXD2__RXD2, MX31_PIN_CSPI3_MOSI__RXD3, MX31_PIN_CSPI3_MISO__TXD3, MX31_PIN_CSPI3_SCLK__RTS3, MX31_PIN_CSPI3_SPI_RDY__CTS3, MX31_PIN_SD1_DATA3__SD1_DATA3, MX31_PIN_SD1_DATA2__SD1_DATA2, MX31_PIN_SD1_DATA1__SD1_DATA1, MX31_PIN_SD1_DATA0__SD1_DATA0, MX31_PIN_SD1_CLK__SD1_CLK, MX31_PIN_SD1_CMD__SD1_CMD, MX31_PIN_LD0__LD0, MX31_PIN_LD1__LD1, MX31_PIN_LD2__LD2, MX31_PIN_LD3__LD3, MX31_PIN_LD4__LD4, MX31_PIN_LD5__LD5, MX31_PIN_LD6__LD6, MX31_PIN_LD7__LD7, MX31_PIN_LD8__LD8, MX31_PIN_LD9__LD9, MX31_PIN_LD10__LD10, MX31_PIN_LD11__LD11, MX31_PIN_LD12__LD12, MX31_PIN_LD13__LD13, MX31_PIN_LD14__LD14, MX31_PIN_LD15__LD15, MX31_PIN_LD16__LD16, MX31_PIN_LD17__LD17, MX31_PIN_VSYNC3__VSYNC3, MX31_PIN_HSYNC__HSYNC, MX31_PIN_FPSHIFT__FPSHIFT, MX31_PIN_DRDY0__DRDY0, MX31_PIN_CONTRAST__CONTRAST, }; /* UART */ static const struct imxuart_platform_data uart_pdata __initconst = { .flags = IMXUART_HAVE_RTSCTS, }; /* MMC support */ static int mxc_mmc1_get_ro(struct device *dev) { return gpio_get_value(IOMUX_TO_GPIO(MX31_PIN_LCS0)); } static int gpio_det, gpio_wp; #define MMC_PAD_CFG (PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST | PAD_CTL_HYS_CMOS | \ PAD_CTL_ODE_CMOS | PAD_CTL_100K_PU) static int mxc_mmc1_init(struct device *dev, irq_handler_t detect_irq, void *data) { int ret; gpio_det = IOMUX_TO_GPIO(MX31_PIN_GPIO1_1); gpio_wp = IOMUX_TO_GPIO(MX31_PIN_LCS0); mxc_iomux_set_pad(MX31_PIN_SD1_DATA0, MMC_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_SD1_DATA1, MMC_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_SD1_DATA2, MMC_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_SD1_DATA3, MMC_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_SD1_CLK, MMC_PAD_CFG); mxc_iomux_set_pad(MX31_PIN_SD1_CMD, MMC_PAD_CFG); ret = gpio_request(gpio_det, "MMC detect"); if (ret) return ret; ret = gpio_request(gpio_wp, "MMC w/p"); if (ret) goto exit_free_det; gpio_direction_input(gpio_det); gpio_direction_input(gpio_wp); ret = request_irq(IOMUX_TO_IRQ(MX31_PIN_GPIO1_1), detect_irq, IRQF_DISABLED | IRQF_TRIGGER_FALLING, "MMC detect", data); if (ret) goto exit_free_wp; return 0; exit_free_wp: gpio_free(gpio_wp); exit_free_det: gpio_free(gpio_det); return ret; } static void mxc_mmc1_exit(struct device *dev, void *data) { gpio_free(gpio_det); gpio_free(gpio_wp); free_irq(IOMUX_TO_IRQ(MX31_PIN_GPIO1_1), data); } static const struct imxmmc_platform_data mmc_pdata __initconst = { .get_ro = mxc_mmc1_get_ro, .init = mxc_mmc1_init, .exit = mxc_mmc1_exit, }; /* Framebuffer support */ static const struct ipu_platform_data ipu_data __initconst = { .irq_base = MXC_IPU_IRQ_START, }; static const struct fb_videomode fb_modedb = { /* 640x480 TFT panel (IPS-056T) */ .name = "CRT-VGA", .refresh = 64, .xres = 640, .yres = 480, .pixclock = 30000, .left_margin = 200, .right_margin = 2, .upper_margin = 2, .lower_margin = 2, .hsync_len = 3, .vsync_len = 1, .sync = FB_SYNC_VERT_HIGH_ACT | FB_SYNC_OE_ACT_HIGH, .vmode = FB_VMODE_NONINTERLACED, .flag = 0, }; static struct mx3fb_platform_data fb_pdata __initdata = { .name = "CRT-VGA", .mode = &fb_modedb, .num_modes = 1, }; #define LCD_VCC_EN_GPIO (7) static void __init mx31lilly_init_fb(void) { if (gpio_request(LCD_VCC_EN_GPIO, "LCD enable") != 0) { printk(KERN_WARNING "unable to request LCD_VCC_EN pin.\n"); return; } imx31_add_ipu_core(&ipu_data); imx31_add_mx3_sdc_fb(&fb_pdata); gpio_direction_output(LCD_VCC_EN_GPIO, 1); } void __init mx31lilly_db_init(void) { mxc_iomux_setup_multiple_pins(lilly_db_board_pins, ARRAY_SIZE(lilly_db_board_pins), "development board pins"); imx31_add_imx_uart0(&uart_pdata); imx31_add_imx_uart1(&uart_pdata); imx31_add_imx_uart2(&uart_pdata); imx31_add_mxc_mmc(0, &mmc_pdata); mx31lilly_init_fb(); }
gpl-2.0
Megatron007/Megabyte_kernel_victara
net/dccp/qpolicy.c
13090
3431
/* * net/dccp/qpolicy.c * * Policy-based packet dequeueing interface for DCCP. * * Copyright (c) 2008 Tomasz Grobelny <tomasz@grobelny.oswiecenia.net> * * 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. */ #include "dccp.h" /* * Simple Dequeueing Policy: * If tx_qlen is different from 0, enqueue up to tx_qlen elements. */ static void qpolicy_simple_push(struct sock *sk, struct sk_buff *skb) { skb_queue_tail(&sk->sk_write_queue, skb); } static bool qpolicy_simple_full(struct sock *sk) { return dccp_sk(sk)->dccps_tx_qlen && sk->sk_write_queue.qlen >= dccp_sk(sk)->dccps_tx_qlen; } static struct sk_buff *qpolicy_simple_top(struct sock *sk) { return skb_peek(&sk->sk_write_queue); } /* * Priority-based Dequeueing Policy: * If tx_qlen is different from 0 and the queue has reached its upper bound * of tx_qlen elements, replace older packets lowest-priority-first. */ static struct sk_buff *qpolicy_prio_best_skb(struct sock *sk) { struct sk_buff *skb, *best = NULL; skb_queue_walk(&sk->sk_write_queue, skb) if (best == NULL || skb->priority > best->priority) best = skb; return best; } static struct sk_buff *qpolicy_prio_worst_skb(struct sock *sk) { struct sk_buff *skb, *worst = NULL; skb_queue_walk(&sk->sk_write_queue, skb) if (worst == NULL || skb->priority < worst->priority) worst = skb; return worst; } static bool qpolicy_prio_full(struct sock *sk) { if (qpolicy_simple_full(sk)) dccp_qpolicy_drop(sk, qpolicy_prio_worst_skb(sk)); return false; } /** * struct dccp_qpolicy_operations - TX Packet Dequeueing Interface * @push: add a new @skb to the write queue * @full: indicates that no more packets will be admitted * @top: peeks at whatever the queueing policy defines as its `top' */ static struct dccp_qpolicy_operations { void (*push) (struct sock *sk, struct sk_buff *skb); bool (*full) (struct sock *sk); struct sk_buff* (*top) (struct sock *sk); __be32 params; } qpol_table[DCCPQ_POLICY_MAX] = { [DCCPQ_POLICY_SIMPLE] = { .push = qpolicy_simple_push, .full = qpolicy_simple_full, .top = qpolicy_simple_top, .params = 0, }, [DCCPQ_POLICY_PRIO] = { .push = qpolicy_simple_push, .full = qpolicy_prio_full, .top = qpolicy_prio_best_skb, .params = DCCP_SCM_PRIORITY, }, }; /* * Externally visible interface */ void dccp_qpolicy_push(struct sock *sk, struct sk_buff *skb) { qpol_table[dccp_sk(sk)->dccps_qpolicy].push(sk, skb); } bool dccp_qpolicy_full(struct sock *sk) { return qpol_table[dccp_sk(sk)->dccps_qpolicy].full(sk); } void dccp_qpolicy_drop(struct sock *sk, struct sk_buff *skb) { if (skb != NULL) { skb_unlink(skb, &sk->sk_write_queue); kfree_skb(skb); } } struct sk_buff *dccp_qpolicy_top(struct sock *sk) { return qpol_table[dccp_sk(sk)->dccps_qpolicy].top(sk); } struct sk_buff *dccp_qpolicy_pop(struct sock *sk) { struct sk_buff *skb = dccp_qpolicy_top(sk); if (skb != NULL) { /* Clear any skb fields that we used internally */ skb->priority = 0; skb_unlink(skb, &sk->sk_write_queue); } return skb; } bool dccp_qpolicy_param_ok(struct sock *sk, __be32 param) { /* check if exactly one bit is set */ if (!param || (param & (param - 1))) return false; return (qpol_table[dccp_sk(sk)->dccps_qpolicy].params & param) == param; }
gpl-2.0
pathletboy/rt-thread
bsp/asm9260t/platform/rt_low_level_init.c
35
1073
/* * File : rt_low_level_init.c * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the 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. * * Change Logs: * Date Author Notes * 2015-04-14 ArdaFu first version * 2015-04-27 ArdaFu Port bsp from at91sam9260 to asm9260t */ void rt_low_level_init(void) { }
gpl-2.0
SaberMod/GCC_SaberMod
libgfortran/generated/pow_c16_i16.c
35
1979
/* Support routines for the intrinsic power (**) operator. Copyright (C) 2004-2014 Free Software Foundation, Inc. Contributed by Paul Brook This file is part of the GNU Fortran 95 runtime library (libgfortran). Libgfortran is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Libgfortran is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ #include "libgfortran.h" /* Use Binary Method to calculate the powi. This is not an optimal but a simple and reasonable arithmetic. See section 4.6.3, "Evaluation of Powers" of Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art of Computer Programming", 3rd Edition, 1998. */ #if defined (HAVE_GFC_COMPLEX_16) && defined (HAVE_GFC_INTEGER_16) GFC_COMPLEX_16 pow_c16_i16 (GFC_COMPLEX_16 a, GFC_INTEGER_16 b); export_proto(pow_c16_i16); GFC_COMPLEX_16 pow_c16_i16 (GFC_COMPLEX_16 a, GFC_INTEGER_16 b) { GFC_COMPLEX_16 pow, x; GFC_INTEGER_16 n; GFC_UINTEGER_16 u; n = b; x = a; pow = 1; if (n != 0) { if (n < 0) { u = -n; x = pow / x; } else { u = n; } for (;;) { if (u & 1) pow *= x; u >>= 1; if (u) x *= x; else break; } } return pow; } #endif
gpl-2.0
AdiPat/android_kernel_tegra_n1
arch/arm/mach-tegra/board-whistler.c
35
15695
/* * arch/arm/mach-tegra/board-whistler.c * * Copyright (c) 2010 - 2011, NVIDIA 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/ctype.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/serial_8250.h> #include <linux/i2c.h> #include <linux/synaptics_i2c_rmi.h> #include <linux/dma-mapping.h> #include <linux/delay.h> #include <linux/i2c-tegra.h> #include <linux/gpio.h> #include <linux/gpio_scrollwheel.h> #include <linux/input.h> #include <linux/platform_data/tegra_usb.h> #include <linux/mfd/max8907c.h> #include <linux/memblock.h> #include <linux/tegra_uart.h> #include <mach/clk.h> #include <mach/iomap.h> #include <mach/irqs.h> #include <mach/pinmux.h> #include <mach/iomap.h> #include <mach/io.h> #include <mach/i2s.h> #include <mach/tegra_asoc_pdata.h> #include <sound/tlv320aic326x.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <mach/usb_phy.h> #include "board.h" #include "clock.h" #include "board-whistler.h" #include "devices.h" #include "gpio-names.h" #include "fuse.h" #include "pm.h" #include "board-whistler-baseband.h" #define SZ_3M (SZ_1M + SZ_2M) #define SZ_152M (SZ_128M + SZ_16M + SZ_8M) #define USB1_VBUS_GPIO TCA6416_GPIO_BASE static struct plat_serial8250_port debug_uartb_platform_data[] = { { .membase = IO_ADDRESS(TEGRA_UARTB_BASE), .mapbase = TEGRA_UARTB_BASE, .irq = INT_UARTB, .flags = UPF_BOOT_AUTOCONF | UPF_FIXED_TYPE, .type = PORT_TEGRA, .iotype = UPIO_MEM, .regshift = 2, .uartclk = 216000000, }, { .flags = 0, } }; static struct platform_device debug_uartb = { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev = { .platform_data = debug_uartb_platform_data, }, }; static struct plat_serial8250_port debug_uarta_platform_data[] = { { .membase = IO_ADDRESS(TEGRA_UARTA_BASE), .mapbase = TEGRA_UARTA_BASE, .irq = INT_UARTA, .flags = UPF_BOOT_AUTOCONF | UPF_FIXED_TYPE, .type = PORT_TEGRA, .iotype = UPIO_MEM, .regshift = 2, .uartclk = 216000000, }, { .flags = 0, } }; static struct platform_device debug_uarta = { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev = { .platform_data = debug_uarta_platform_data, }, }; static struct platform_device *whistler_uart_devices[] __initdata = { &tegra_uarta_device, &tegra_uartb_device, &tegra_uartc_device, }; struct uart_clk_parent uart_parent_clk[] = { [0] = {.name = "pll_p"}, [1] = {.name = "pll_m"}, [2] = {.name = "clk_m"}, }; static struct tegra_uart_platform_data whistler_uart_pdata; static void __init uart_debug_init(void) { unsigned long rate; struct clk *debug_uart_clk; struct clk *c; int modem_id = tegra_get_modem_id(); if (modem_id == 0x1) { /* UARTB is the debug port. */ pr_info("Selecting UARTB as the debug console\n"); whistler_uart_devices[1] = &debug_uartb; debug_uart_port_base = debug_uartb_platform_data[0].mapbase; debug_uart_clk = clk_get_sys("serial8250.0", "uartb"); /* Clock enable for the debug channel */ if (!IS_ERR_OR_NULL(debug_uart_clk)) { rate = debug_uartb_platform_data[0].uartclk; pr_info("The debug console clock name is %s\n", debug_uart_clk->name); c = tegra_get_clock_by_name("pll_p"); if (IS_ERR_OR_NULL(c)) pr_err("Not getting the parent clock pll_p\n"); else clk_set_parent(debug_uart_clk, c); clk_enable(debug_uart_clk); clk_set_rate(debug_uart_clk, rate); } else { pr_err("Not getting the clock %s for debug console\n", debug_uart_clk->name); } } else { /* UARTA is the debug port. */ pr_info("Selecting UARTA as the debug console\n"); whistler_uart_devices[0] = &debug_uarta; debug_uart_port_base = debug_uarta_platform_data[0].mapbase; debug_uart_clk = clk_get_sys("serial8250.0", "uarta"); /* Clock enable for the debug channel */ if (!IS_ERR_OR_NULL(debug_uart_clk)) { rate = debug_uarta_platform_data[0].uartclk; pr_info("The debug console clock name is %s\n", debug_uart_clk->name); c = tegra_get_clock_by_name("pll_p"); if (IS_ERR_OR_NULL(c)) pr_err("Not getting the parent clock pll_p\n"); else clk_set_parent(debug_uart_clk, c); clk_enable(debug_uart_clk); clk_set_rate(debug_uart_clk, rate); } else { pr_err("Not getting the clock %s for debug console\n", debug_uart_clk->name); } } } static void __init whistler_uart_init(void) { int i; struct clk *c; for (i = 0; i < ARRAY_SIZE(uart_parent_clk); ++i) { c = tegra_get_clock_by_name(uart_parent_clk[i].name); if (IS_ERR_OR_NULL(c)) { pr_err("Not able to get the clock for %s\n", uart_parent_clk[i].name); continue; } uart_parent_clk[i].parent_clk = c; uart_parent_clk[i].fixed_clk_rate = clk_get_rate(c); } whistler_uart_pdata.parent_clk_list = uart_parent_clk; whistler_uart_pdata.parent_clk_count = ARRAY_SIZE(uart_parent_clk); tegra_uarta_device.dev.platform_data = &whistler_uart_pdata; tegra_uartb_device.dev.platform_data = &whistler_uart_pdata; tegra_uartc_device.dev.platform_data = &whistler_uart_pdata; if (!is_tegra_debug_uartport_hs()) uart_debug_init(); platform_add_devices(whistler_uart_devices, ARRAY_SIZE(whistler_uart_devices)); } static struct resource whistler_bcm4329_rfkill_resources[] = { { .name = "bcm4329_nshutdown_gpio", .start = TEGRA_GPIO_PU0, .end = TEGRA_GPIO_PU0, .flags = IORESOURCE_IO, }, }; static struct platform_device whistler_bcm4329_rfkill_device = { .name = "bcm4329_rfkill", .id = -1, .num_resources = ARRAY_SIZE(whistler_bcm4329_rfkill_resources), .resource = whistler_bcm4329_rfkill_resources, }; static struct resource whistler_bluesleep_resources[] = { [0] = { .name = "gpio_host_wake", .start = TEGRA_GPIO_PU6, .end = TEGRA_GPIO_PU6, .flags = IORESOURCE_IO, }, [1] = { .name = "gpio_ext_wake", .start = TEGRA_GPIO_PU1, .end = TEGRA_GPIO_PU1, .flags = IORESOURCE_IO, }, [2] = { .name = "host_wake", .start = TEGRA_GPIO_TO_IRQ(TEGRA_GPIO_PU6), .end = TEGRA_GPIO_TO_IRQ(TEGRA_GPIO_PU6), .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE, }, }; static struct platform_device whistler_bluesleep_device = { .name = "bluesleep", .id = -1, .num_resources = ARRAY_SIZE(whistler_bluesleep_resources), .resource = whistler_bluesleep_resources, }; static void __init whistler_setup_bluesleep(void) { platform_device_register(&whistler_bluesleep_device); tegra_gpio_enable(TEGRA_GPIO_PU6); tegra_gpio_enable(TEGRA_GPIO_PU1); return; } static struct tegra_utmip_config utmi_phy_config[] = { [0] = { .hssync_start_delay = 9, .idle_wait_delay = 17, .elastic_limit = 16, .term_range_adj = 6, .xcvr_setup = 15, .xcvr_lsfslew = 2, .xcvr_lsrslew = 2, }, [1] = { .hssync_start_delay = 9, .idle_wait_delay = 17, .elastic_limit = 16, .term_range_adj = 6, .xcvr_setup = 8, .xcvr_lsfslew = 2, .xcvr_lsrslew = 2, }, }; static struct tegra_ulpi_config ulpi_phy_config = { .reset_gpio = TEGRA_GPIO_PG2, .clk = "cdev2", }; static __initdata struct tegra_clk_init_table whistler_clk_init_table[] = { /* name parent rate enabled */ { "pwm", "clk_32k", 32768, false}, { "kbc", "clk_32k", 32768, true}, { "sdmmc2", "pll_p", 25000000, false}, { "i2s1", "pll_a_out0", 0, false}, { "i2s2", "pll_a_out0", 0, false}, { "spdif_out", "pll_a_out0", 0, false}, { NULL, NULL, 0, 0}, }; static struct tegra_i2c_platform_data whistler_i2c1_platform_data = { .adapter_nr = 0, .bus_count = 1, .bus_clk_rate = { 400000, 0 }, .scl_gpio = {TEGRA_GPIO_PC4, 0}, .sda_gpio = {TEGRA_GPIO_PC5, 0}, .arb_recovery = arb_lost_recovery, .slave_addr = 0xFC, }; static const struct tegra_pingroup_config i2c2_ddc = { .pingroup = TEGRA_PINGROUP_DDC, .func = TEGRA_MUX_I2C2, }; static const struct tegra_pingroup_config i2c2_gen2 = { .pingroup = TEGRA_PINGROUP_PTA, .func = TEGRA_MUX_I2C2, }; static struct tegra_i2c_platform_data whistler_i2c2_platform_data = { .adapter_nr = 1, .bus_count = 2, .bus_clk_rate = { 10000, 100000 }, .bus_mux = { &i2c2_ddc, &i2c2_gen2 }, .bus_mux_len = { 1, 1 }, .scl_gpio = {0, TEGRA_GPIO_PT5}, .sda_gpio = {0, TEGRA_GPIO_PT6}, .arb_recovery = arb_lost_recovery, .slave_addr = 0xFC, }; static struct tegra_i2c_platform_data whistler_i2c3_platform_data = { .adapter_nr = 3, .bus_count = 1, .bus_clk_rate = { 400000, 0 }, .scl_gpio = {TEGRA_GPIO_PBB2, 0}, .sda_gpio = {TEGRA_GPIO_PBB3, 0}, .arb_recovery = arb_lost_recovery, .slave_addr = 0xFC, }; static struct tegra_i2c_platform_data whistler_dvc_platform_data = { .adapter_nr = 4, .bus_count = 1, .bus_clk_rate = { 400000, 0 }, .is_dvc = true, .scl_gpio = {TEGRA_GPIO_PZ6, 0}, .sda_gpio = {TEGRA_GPIO_PZ7, 0}, .arb_recovery = arb_lost_recovery, }; static struct aic326x_pdata whistler_aic3262_pdata = { /* debounce time */ .debounce_time_ms = 512, }; static struct i2c_board_info __initdata wm8753_board_info[] = { { I2C_BOARD_INFO("wm8753", 0x1a), .irq = TEGRA_GPIO_TO_IRQ(TEGRA_GPIO_HP_DET), }, { I2C_BOARD_INFO("aic3262-codec", 0x18), .platform_data = &whistler_aic3262_pdata, .irq = TEGRA_GPIO_TO_IRQ(TEGRA_GPIO_HP_DET), }, }; static void whistler_i2c_init(void) { tegra_i2c_device1.dev.platform_data = &whistler_i2c1_platform_data; tegra_i2c_device2.dev.platform_data = &whistler_i2c2_platform_data; tegra_i2c_device3.dev.platform_data = &whistler_i2c3_platform_data; tegra_i2c_device4.dev.platform_data = &whistler_dvc_platform_data; platform_device_register(&tegra_i2c_device4); platform_device_register(&tegra_i2c_device3); platform_device_register(&tegra_i2c_device2); platform_device_register(&tegra_i2c_device1); i2c_register_board_info(4, wm8753_board_info, ARRAY_SIZE(wm8753_board_info)); } #define GPIO_SCROLL(_pinaction, _gpio, _desc) \ { \ .pinaction = GPIO_SCROLLWHEEL_PIN_##_pinaction, \ .gpio = TEGRA_GPIO_##_gpio, \ .desc = _desc, \ .active_low = 1, \ .debounce_interval = 2, \ } static struct gpio_scrollwheel_button scroll_keys[] = { [0] = GPIO_SCROLL(ONOFF, PR3, "sw_onoff"), [1] = GPIO_SCROLL(PRESS, PQ5, "sw_press"), [2] = GPIO_SCROLL(ROT1, PQ3, "sw_rot1"), [3] = GPIO_SCROLL(ROT2, PQ4, "sw_rot2"), }; static struct gpio_scrollwheel_platform_data whistler_scroll_platform_data = { .buttons = scroll_keys, .nbuttons = ARRAY_SIZE(scroll_keys), }; static struct platform_device whistler_scroll_device = { .name = "alps-gpio-scrollwheel", .id = 0, .dev = { .platform_data = &whistler_scroll_platform_data, }, }; static struct platform_device tegra_camera = { .name = "tegra_camera", .id = -1, }; static struct tegra_asoc_platform_data whistler_audio_pdata = { .gpio_spkr_en = -1, .gpio_hp_det = TEGRA_GPIO_HP_DET, .gpio_hp_mute = -1, .gpio_int_mic_en = -1, .gpio_ext_mic_en = -1, .debounce_time_hp = 200, }; static struct platform_device whistler_audio_aic326x_device = { .name = "tegra-snd-aic326x", .id = 0, .dev = { .platform_data = &whistler_audio_pdata, }, }; static struct platform_device whistler_audio_wm8753_device = { .name = "tegra-snd-wm8753", .id = 0, .dev = { .platform_data = &whistler_audio_pdata, }, }; static struct platform_device *whistler_devices[] __initdata = { &tegra_pmu_device, &tegra_udc_device, &tegra_gart_device, &tegra_aes_device, &tegra_wdt_device, &tegra_avp_device, &whistler_scroll_device, &tegra_camera, &tegra_i2s_device1, &tegra_i2s_device2, &tegra_spdif_device, &tegra_das_device, &spdif_dit_device, &bluetooth_dit_device, &baseband_dit_device, &whistler_bcm4329_rfkill_device, &tegra_pcm_device, &whistler_audio_aic326x_device, &whistler_audio_wm8753_device, }; static struct synaptics_i2c_rmi_platform_data synaptics_pdata = { .flags = SYNAPTICS_FLIP_X | SYNAPTICS_FLIP_Y | SYNAPTICS_SWAP_XY, .irqflags = IRQF_TRIGGER_LOW, }; static const struct i2c_board_info whistler_i2c_touch_info[] = { { I2C_BOARD_INFO("synaptics-rmi-ts", 0x20), .irq = TEGRA_GPIO_TO_IRQ(TEGRA_GPIO_PC6), .platform_data = &synaptics_pdata, }, }; static int __init whistler_touch_init(void) { tegra_gpio_enable(TEGRA_GPIO_PC6); i2c_register_board_info(0, whistler_i2c_touch_info, 1); return 0; } static int __init whistler_scroll_init(void) { int i; for (i = 0; i < ARRAY_SIZE(scroll_keys); i++) tegra_gpio_enable(scroll_keys[i].gpio); return 0; } static struct usb_phy_plat_data tegra_usb_phy_pdata[] = { [0] = { .instance = 0, .vbus_irq = MAX8907C_INT_BASE + MAX8907C_IRQ_VCHG_DC_R, .vbus_gpio = USB1_VBUS_GPIO, }, [1] = { .instance = 1, .vbus_gpio = -1, }, [2] = { .instance = 2, .vbus_gpio = -1, }, }; static struct tegra_ehci_platform_data tegra_ehci_pdata[] = { [0] = { .phy_config = &utmi_phy_config[0], .operating_mode = TEGRA_USB_HOST, .power_down_on_bus_suspend = 1, .default_enable = false, }, [1] = { .phy_config = &ulpi_phy_config, .operating_mode = TEGRA_USB_HOST, .power_down_on_bus_suspend = 1, .default_enable = false, }, [2] = { .phy_config = &utmi_phy_config[1], .operating_mode = TEGRA_USB_HOST, .power_down_on_bus_suspend = 1, .default_enable = false, }, }; static struct tegra_otg_platform_data tegra_otg_pdata = { .ehci_device = &tegra_ehci1_device, .ehci_pdata = &tegra_ehci_pdata[0], }; static int __init whistler_gps_init(void) { tegra_gpio_enable(TEGRA_GPIO_PU4); return 0; } static void whistler_usb_init(void) { tegra_usb_phy_init(tegra_usb_phy_pdata, ARRAY_SIZE(tegra_usb_phy_pdata)); tegra_otg_device.dev.platform_data = &tegra_otg_pdata; platform_device_register(&tegra_otg_device); } static void __init tegra_whistler_init(void) { int modem_id = tegra_get_modem_id(); tegra_clk_init_from_table(whistler_clk_init_table); whistler_pinmux_init(); whistler_i2c_init(); whistler_uart_init(); platform_add_devices(whistler_devices, ARRAY_SIZE(whistler_devices)); tegra_ram_console_debug_init(); whistler_sdhci_init(); whistler_regulator_init(); whistler_panel_init(); whistler_sensors_init(); whistler_touch_init(); whistler_kbc_init(); whistler_gps_init(); whistler_usb_init(); whistler_scroll_init(); whistler_emc_init(); if (modem_id == 0x1) whistler_baseband_init(); whistler_setup_bluesleep(); tegra_release_bootloader_fb(); } int __init tegra_whistler_protected_aperture_init(void) { tegra_protected_aperture_init(tegra_grhost_aperture); return 0; } void __init tegra_whistler_reserve(void) { if (memblock_reserve(0x0, 4096) < 0) pr_warn("Cannot reserve first 4K of memory for safety\n"); tegra_reserve(SZ_152M, SZ_3M, SZ_1M); tegra_ram_console_debug_reserve(SZ_1M); } MACHINE_START(WHISTLER, "whistler") .boot_params = 0x00000100, .map_io = tegra_map_common_io, .reserve = tegra_whistler_reserve, .init_early = tegra_init_early, .init_irq = tegra_init_irq, .timer = &tegra_timer, .init_machine = tegra_whistler_init, MACHINE_END
gpl-2.0
danonbrown/trltetmo-kernel
drivers/platform/msm/ipa/ipa_rm_peers_list.c
291
5860
/* 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/slab.h> #include "ipa_i.h" #include "ipa_rm_i.h" #include "ipa_rm_resource.h" /** * ipa_rm_peers_list_get_resource_index() - resource name to index * of this resource in corresponding peers list * @resource_name: [in] resource name * * Returns: resource index mapping, IPA_RM_INDEX_INVALID * in case provided resource name isn't contained in enum * ipa_rm_resource_name. * */ static int ipa_rm_peers_list_get_resource_index( enum ipa_rm_resource_name resource_name) { int resource_index = IPA_RM_INDEX_INVALID; if (IPA_RM_RESORCE_IS_PROD(resource_name)) resource_index = ipa_rm_prod_index(resource_name); else if (IPA_RM_RESORCE_IS_CONS(resource_name)) { resource_index = ipa_rm_cons_index(resource_name); if (resource_index != IPA_RM_INDEX_INVALID) resource_index = resource_index - IPA_RM_RESOURCE_PROD_MAX; } return resource_index; } static bool ipa_rm_peers_list_check_index(int index, struct ipa_rm_peers_list *peers_list) { return !(index > peers_list->max_peers || index < 0); } /** * ipa_rm_peers_list_create() - creates the peers list * * @max_peers: maximum number of peers in new list * @peers_list: [out] newly created peers list * * Returns: 0 in case of SUCCESS, negative otherwise */ int ipa_rm_peers_list_create(int max_peers, struct ipa_rm_peers_list **peers_list) { int result; *peers_list = kzalloc(sizeof(**peers_list), GFP_KERNEL); if (!*peers_list) { IPA_RM_ERR("no mem\n"); result = -ENOMEM; goto bail; } (*peers_list)->max_peers = max_peers; (*peers_list)->peers = kzalloc((*peers_list)->max_peers * sizeof(struct ipa_rm_resource *), GFP_KERNEL); if (!((*peers_list)->peers)) { IPA_RM_ERR("no mem\n"); result = -ENOMEM; goto list_alloc_fail; } return 0; list_alloc_fail: kfree(*peers_list); bail: return result; } /** * ipa_rm_peers_list_delete() - deletes the peers list * * @peers_list: peers list * */ void ipa_rm_peers_list_delete(struct ipa_rm_peers_list *peers_list) { if (peers_list) { kfree(peers_list->peers); kfree(peers_list); } } /** * ipa_rm_peers_list_remove_peer() - removes peer from the list * * @peers_list: peers list * @resource_name: name of the resource to remove * */ void ipa_rm_peers_list_remove_peer( struct ipa_rm_peers_list *peers_list, enum ipa_rm_resource_name resource_name) { if (!peers_list) return; peers_list->peers[ipa_rm_peers_list_get_resource_index( resource_name)] = NULL; peers_list->peers_count--; } /** * ipa_rm_peers_list_add_peer() - adds peer to the list * * @peers_list: peers list * @resource: resource to add * */ void ipa_rm_peers_list_add_peer( struct ipa_rm_peers_list *peers_list, struct ipa_rm_resource *resource) { if (!peers_list || !resource) return; peers_list->peers[ipa_rm_peers_list_get_resource_index( resource->name)] = resource; peers_list->peers_count++; } /** * ipa_rm_peers_list_is_empty() - checks * if resource peers list is empty * * @peers_list: peers list * * Returns: true if the list is empty, false otherwise */ bool ipa_rm_peers_list_is_empty(struct ipa_rm_peers_list *peers_list) { bool result = true; if (!peers_list) goto bail; if (peers_list->peers_count > 0) result = false; bail: return result; } /** * ipa_rm_peers_list_has_last_peer() - checks * if resource peers list has exactly one peer * * @peers_list: peers list * * Returns: true if the list has exactly one peer, false otherwise */ bool ipa_rm_peers_list_has_last_peer( struct ipa_rm_peers_list *peers_list) { bool result = false; if (!peers_list) goto bail; if (peers_list->peers_count == 1) result = true; bail: return result; } /** * ipa_rm_peers_list_check_dependency() - check dependency * between 2 peer lists * @resource_peers: first peers list * @resource_name: first peers list resource name * @depends_on_peers: second peers list * @depends_on_name: second peers list resource name * * Returns: true if there is dependency, false otherwise * */ bool ipa_rm_peers_list_check_dependency( struct ipa_rm_peers_list *resource_peers, enum ipa_rm_resource_name resource_name, struct ipa_rm_peers_list *depends_on_peers, enum ipa_rm_resource_name depends_on_name) { bool result = false; if (!resource_peers || !depends_on_peers) return result; if (resource_peers->peers[ipa_rm_peers_list_get_resource_index( depends_on_name)] != NULL) result = true; if (depends_on_peers->peers[ipa_rm_peers_list_get_resource_index( resource_name)] != NULL) result = true; return result; } /** * ipa_rm_peers_list_get_resource() - get resource by * resource index * @resource_index: resource index * @resource_peers: peers list * * Returns: the resource if found, NULL otherwise */ struct ipa_rm_resource *ipa_rm_peers_list_get_resource(int resource_index, struct ipa_rm_peers_list *resource_peers) { struct ipa_rm_resource *result = NULL; if (!ipa_rm_peers_list_check_index(resource_index, resource_peers)) goto bail; result = resource_peers->peers[resource_index]; bail: return result; } /** * ipa_rm_peers_list_get_size() - get peers list sise * * @peers_list: peers list * * Returns: the size of the peers list */ int ipa_rm_peers_list_get_size(struct ipa_rm_peers_list *peers_list) { return peers_list->max_peers; }
gpl-2.0
GtrCraft/Optimus_Lux
crypto/seed.c
2339
17789
/* * Cryptographic API. * * SEED Cipher Algorithm. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Documentation of SEED can be found in RFC 4269. * Copyright (C) 2007 Korea Information Security Agency (KISA). */ #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/crypto.h> #include <asm/byteorder.h> #define SEED_NUM_KCONSTANTS 16 #define SEED_KEY_SIZE 16 #define SEED_BLOCK_SIZE 16 #define SEED_KEYSCHED_LEN 32 /* * #define byte(x, nr) ((unsigned char)((x) >> (nr*8))) */ static inline u8 byte(const u32 x, const unsigned n) { return x >> (n << 3); } struct seed_ctx { u32 keysched[SEED_KEYSCHED_LEN]; }; static const u32 SS0[256] = { 0x2989a1a8, 0x05858184, 0x16c6d2d4, 0x13c3d3d0, 0x14445054, 0x1d0d111c, 0x2c8ca0ac, 0x25052124, 0x1d4d515c, 0x03434340, 0x18081018, 0x1e0e121c, 0x11415150, 0x3cccf0fc, 0x0acac2c8, 0x23436360, 0x28082028, 0x04444044, 0x20002020, 0x1d8d919c, 0x20c0e0e0, 0x22c2e2e0, 0x08c8c0c8, 0x17071314, 0x2585a1a4, 0x0f8f838c, 0x03030300, 0x3b4b7378, 0x3b8bb3b8, 0x13031310, 0x12c2d2d0, 0x2ecee2ec, 0x30407070, 0x0c8c808c, 0x3f0f333c, 0x2888a0a8, 0x32023230, 0x1dcdd1dc, 0x36c6f2f4, 0x34447074, 0x2ccce0ec, 0x15859194, 0x0b0b0308, 0x17475354, 0x1c4c505c, 0x1b4b5358, 0x3d8db1bc, 0x01010100, 0x24042024, 0x1c0c101c, 0x33437370, 0x18889098, 0x10001010, 0x0cccc0cc, 0x32c2f2f0, 0x19c9d1d8, 0x2c0c202c, 0x27c7e3e4, 0x32427270, 0x03838380, 0x1b8b9398, 0x11c1d1d0, 0x06868284, 0x09c9c1c8, 0x20406060, 0x10405050, 0x2383a3a0, 0x2bcbe3e8, 0x0d0d010c, 0x3686b2b4, 0x1e8e929c, 0x0f4f434c, 0x3787b3b4, 0x1a4a5258, 0x06c6c2c4, 0x38487078, 0x2686a2a4, 0x12021210, 0x2f8fa3ac, 0x15c5d1d4, 0x21416160, 0x03c3c3c0, 0x3484b0b4, 0x01414140, 0x12425250, 0x3d4d717c, 0x0d8d818c, 0x08080008, 0x1f0f131c, 0x19899198, 0x00000000, 0x19091118, 0x04040004, 0x13435350, 0x37c7f3f4, 0x21c1e1e0, 0x3dcdf1fc, 0x36467274, 0x2f0f232c, 0x27072324, 0x3080b0b0, 0x0b8b8388, 0x0e0e020c, 0x2b8ba3a8, 0x2282a2a0, 0x2e4e626c, 0x13839390, 0x0d4d414c, 0x29496168, 0x3c4c707c, 0x09090108, 0x0a0a0208, 0x3f8fb3bc, 0x2fcfe3ec, 0x33c3f3f0, 0x05c5c1c4, 0x07878384, 0x14041014, 0x3ecef2fc, 0x24446064, 0x1eced2dc, 0x2e0e222c, 0x0b4b4348, 0x1a0a1218, 0x06060204, 0x21012120, 0x2b4b6368, 0x26466264, 0x02020200, 0x35c5f1f4, 0x12829290, 0x0a8a8288, 0x0c0c000c, 0x3383b3b0, 0x3e4e727c, 0x10c0d0d0, 0x3a4a7278, 0x07474344, 0x16869294, 0x25c5e1e4, 0x26062224, 0x00808080, 0x2d8da1ac, 0x1fcfd3dc, 0x2181a1a0, 0x30003030, 0x37073334, 0x2e8ea2ac, 0x36063234, 0x15051114, 0x22022220, 0x38083038, 0x34c4f0f4, 0x2787a3a4, 0x05454144, 0x0c4c404c, 0x01818180, 0x29c9e1e8, 0x04848084, 0x17879394, 0x35053134, 0x0bcbc3c8, 0x0ecec2cc, 0x3c0c303c, 0x31417170, 0x11011110, 0x07c7c3c4, 0x09898188, 0x35457174, 0x3bcbf3f8, 0x1acad2d8, 0x38c8f0f8, 0x14849094, 0x19495158, 0x02828280, 0x04c4c0c4, 0x3fcff3fc, 0x09494148, 0x39093138, 0x27476364, 0x00c0c0c0, 0x0fcfc3cc, 0x17c7d3d4, 0x3888b0b8, 0x0f0f030c, 0x0e8e828c, 0x02424240, 0x23032320, 0x11819190, 0x2c4c606c, 0x1bcbd3d8, 0x2484a0a4, 0x34043034, 0x31c1f1f0, 0x08484048, 0x02c2c2c0, 0x2f4f636c, 0x3d0d313c, 0x2d0d212c, 0x00404040, 0x3e8eb2bc, 0x3e0e323c, 0x3c8cb0bc, 0x01c1c1c0, 0x2a8aa2a8, 0x3a8ab2b8, 0x0e4e424c, 0x15455154, 0x3b0b3338, 0x1cccd0dc, 0x28486068, 0x3f4f737c, 0x1c8c909c, 0x18c8d0d8, 0x0a4a4248, 0x16465254, 0x37477374, 0x2080a0a0, 0x2dcde1ec, 0x06464244, 0x3585b1b4, 0x2b0b2328, 0x25456164, 0x3acaf2f8, 0x23c3e3e0, 0x3989b1b8, 0x3181b1b0, 0x1f8f939c, 0x1e4e525c, 0x39c9f1f8, 0x26c6e2e4, 0x3282b2b0, 0x31013130, 0x2acae2e8, 0x2d4d616c, 0x1f4f535c, 0x24c4e0e4, 0x30c0f0f0, 0x0dcdc1cc, 0x08888088, 0x16061214, 0x3a0a3238, 0x18485058, 0x14c4d0d4, 0x22426260, 0x29092128, 0x07070304, 0x33033330, 0x28c8e0e8, 0x1b0b1318, 0x05050104, 0x39497178, 0x10809090, 0x2a4a6268, 0x2a0a2228, 0x1a8a9298, }; static const u32 SS1[256] = { 0x38380830, 0xe828c8e0, 0x2c2d0d21, 0xa42686a2, 0xcc0fcfc3, 0xdc1eced2, 0xb03383b3, 0xb83888b0, 0xac2f8fa3, 0x60204060, 0x54154551, 0xc407c7c3, 0x44044440, 0x6c2f4f63, 0x682b4b63, 0x581b4b53, 0xc003c3c3, 0x60224262, 0x30330333, 0xb43585b1, 0x28290921, 0xa02080a0, 0xe022c2e2, 0xa42787a3, 0xd013c3d3, 0x90118191, 0x10110111, 0x04060602, 0x1c1c0c10, 0xbc3c8cb0, 0x34360632, 0x480b4b43, 0xec2fcfe3, 0x88088880, 0x6c2c4c60, 0xa82888a0, 0x14170713, 0xc404c4c0, 0x14160612, 0xf434c4f0, 0xc002c2c2, 0x44054541, 0xe021c1e1, 0xd416c6d2, 0x3c3f0f33, 0x3c3d0d31, 0x8c0e8e82, 0x98188890, 0x28280820, 0x4c0e4e42, 0xf436c6f2, 0x3c3e0e32, 0xa42585a1, 0xf839c9f1, 0x0c0d0d01, 0xdc1fcfd3, 0xd818c8d0, 0x282b0b23, 0x64264662, 0x783a4a72, 0x24270723, 0x2c2f0f23, 0xf031c1f1, 0x70324272, 0x40024242, 0xd414c4d0, 0x40014141, 0xc000c0c0, 0x70334373, 0x64274763, 0xac2c8ca0, 0x880b8b83, 0xf437c7f3, 0xac2d8da1, 0x80008080, 0x1c1f0f13, 0xc80acac2, 0x2c2c0c20, 0xa82a8aa2, 0x34340430, 0xd012c2d2, 0x080b0b03, 0xec2ecee2, 0xe829c9e1, 0x5c1d4d51, 0x94148490, 0x18180810, 0xf838c8f0, 0x54174753, 0xac2e8ea2, 0x08080800, 0xc405c5c1, 0x10130313, 0xcc0dcdc1, 0x84068682, 0xb83989b1, 0xfc3fcff3, 0x7c3d4d71, 0xc001c1c1, 0x30310131, 0xf435c5f1, 0x880a8a82, 0x682a4a62, 0xb03181b1, 0xd011c1d1, 0x20200020, 0xd417c7d3, 0x00020202, 0x20220222, 0x04040400, 0x68284860, 0x70314171, 0x04070703, 0xd81bcbd3, 0x9c1d8d91, 0x98198991, 0x60214161, 0xbc3e8eb2, 0xe426c6e2, 0x58194951, 0xdc1dcdd1, 0x50114151, 0x90108090, 0xdc1cccd0, 0x981a8a92, 0xa02383a3, 0xa82b8ba3, 0xd010c0d0, 0x80018181, 0x0c0f0f03, 0x44074743, 0x181a0a12, 0xe023c3e3, 0xec2ccce0, 0x8c0d8d81, 0xbc3f8fb3, 0x94168692, 0x783b4b73, 0x5c1c4c50, 0xa02282a2, 0xa02181a1, 0x60234363, 0x20230323, 0x4c0d4d41, 0xc808c8c0, 0x9c1e8e92, 0x9c1c8c90, 0x383a0a32, 0x0c0c0c00, 0x2c2e0e22, 0xb83a8ab2, 0x6c2e4e62, 0x9c1f8f93, 0x581a4a52, 0xf032c2f2, 0x90128292, 0xf033c3f3, 0x48094941, 0x78384870, 0xcc0cccc0, 0x14150511, 0xf83bcbf3, 0x70304070, 0x74354571, 0x7c3f4f73, 0x34350531, 0x10100010, 0x00030303, 0x64244460, 0x6c2d4d61, 0xc406c6c2, 0x74344470, 0xd415c5d1, 0xb43484b0, 0xe82acae2, 0x08090901, 0x74364672, 0x18190911, 0xfc3ecef2, 0x40004040, 0x10120212, 0xe020c0e0, 0xbc3d8db1, 0x04050501, 0xf83acaf2, 0x00010101, 0xf030c0f0, 0x282a0a22, 0x5c1e4e52, 0xa82989a1, 0x54164652, 0x40034343, 0x84058581, 0x14140410, 0x88098981, 0x981b8b93, 0xb03080b0, 0xe425c5e1, 0x48084840, 0x78394971, 0x94178793, 0xfc3cccf0, 0x1c1e0e12, 0x80028282, 0x20210121, 0x8c0c8c80, 0x181b0b13, 0x5c1f4f53, 0x74374773, 0x54144450, 0xb03282b2, 0x1c1d0d11, 0x24250521, 0x4c0f4f43, 0x00000000, 0x44064642, 0xec2dcde1, 0x58184850, 0x50124252, 0xe82bcbe3, 0x7c3e4e72, 0xd81acad2, 0xc809c9c1, 0xfc3dcdf1, 0x30300030, 0x94158591, 0x64254561, 0x3c3c0c30, 0xb43686b2, 0xe424c4e0, 0xb83b8bb3, 0x7c3c4c70, 0x0c0e0e02, 0x50104050, 0x38390931, 0x24260622, 0x30320232, 0x84048480, 0x68294961, 0x90138393, 0x34370733, 0xe427c7e3, 0x24240420, 0xa42484a0, 0xc80bcbc3, 0x50134353, 0x080a0a02, 0x84078783, 0xd819c9d1, 0x4c0c4c40, 0x80038383, 0x8c0f8f83, 0xcc0ecec2, 0x383b0b33, 0x480a4a42, 0xb43787b3, }; static const u32 SS2[256] = { 0xa1a82989, 0x81840585, 0xd2d416c6, 0xd3d013c3, 0x50541444, 0x111c1d0d, 0xa0ac2c8c, 0x21242505, 0x515c1d4d, 0x43400343, 0x10181808, 0x121c1e0e, 0x51501141, 0xf0fc3ccc, 0xc2c80aca, 0x63602343, 0x20282808, 0x40440444, 0x20202000, 0x919c1d8d, 0xe0e020c0, 0xe2e022c2, 0xc0c808c8, 0x13141707, 0xa1a42585, 0x838c0f8f, 0x03000303, 0x73783b4b, 0xb3b83b8b, 0x13101303, 0xd2d012c2, 0xe2ec2ece, 0x70703040, 0x808c0c8c, 0x333c3f0f, 0xa0a82888, 0x32303202, 0xd1dc1dcd, 0xf2f436c6, 0x70743444, 0xe0ec2ccc, 0x91941585, 0x03080b0b, 0x53541747, 0x505c1c4c, 0x53581b4b, 0xb1bc3d8d, 0x01000101, 0x20242404, 0x101c1c0c, 0x73703343, 0x90981888, 0x10101000, 0xc0cc0ccc, 0xf2f032c2, 0xd1d819c9, 0x202c2c0c, 0xe3e427c7, 0x72703242, 0x83800383, 0x93981b8b, 0xd1d011c1, 0x82840686, 0xc1c809c9, 0x60602040, 0x50501040, 0xa3a02383, 0xe3e82bcb, 0x010c0d0d, 0xb2b43686, 0x929c1e8e, 0x434c0f4f, 0xb3b43787, 0x52581a4a, 0xc2c406c6, 0x70783848, 0xa2a42686, 0x12101202, 0xa3ac2f8f, 0xd1d415c5, 0x61602141, 0xc3c003c3, 0xb0b43484, 0x41400141, 0x52501242, 0x717c3d4d, 0x818c0d8d, 0x00080808, 0x131c1f0f, 0x91981989, 0x00000000, 0x11181909, 0x00040404, 0x53501343, 0xf3f437c7, 0xe1e021c1, 0xf1fc3dcd, 0x72743646, 0x232c2f0f, 0x23242707, 0xb0b03080, 0x83880b8b, 0x020c0e0e, 0xa3a82b8b, 0xa2a02282, 0x626c2e4e, 0x93901383, 0x414c0d4d, 0x61682949, 0x707c3c4c, 0x01080909, 0x02080a0a, 0xb3bc3f8f, 0xe3ec2fcf, 0xf3f033c3, 0xc1c405c5, 0x83840787, 0x10141404, 0xf2fc3ece, 0x60642444, 0xd2dc1ece, 0x222c2e0e, 0x43480b4b, 0x12181a0a, 0x02040606, 0x21202101, 0x63682b4b, 0x62642646, 0x02000202, 0xf1f435c5, 0x92901282, 0x82880a8a, 0x000c0c0c, 0xb3b03383, 0x727c3e4e, 0xd0d010c0, 0x72783a4a, 0x43440747, 0x92941686, 0xe1e425c5, 0x22242606, 0x80800080, 0xa1ac2d8d, 0xd3dc1fcf, 0xa1a02181, 0x30303000, 0x33343707, 0xa2ac2e8e, 0x32343606, 0x11141505, 0x22202202, 0x30383808, 0xf0f434c4, 0xa3a42787, 0x41440545, 0x404c0c4c, 0x81800181, 0xe1e829c9, 0x80840484, 0x93941787, 0x31343505, 0xc3c80bcb, 0xc2cc0ece, 0x303c3c0c, 0x71703141, 0x11101101, 0xc3c407c7, 0x81880989, 0x71743545, 0xf3f83bcb, 0xd2d81aca, 0xf0f838c8, 0x90941484, 0x51581949, 0x82800282, 0xc0c404c4, 0xf3fc3fcf, 0x41480949, 0x31383909, 0x63642747, 0xc0c000c0, 0xc3cc0fcf, 0xd3d417c7, 0xb0b83888, 0x030c0f0f, 0x828c0e8e, 0x42400242, 0x23202303, 0x91901181, 0x606c2c4c, 0xd3d81bcb, 0xa0a42484, 0x30343404, 0xf1f031c1, 0x40480848, 0xc2c002c2, 0x636c2f4f, 0x313c3d0d, 0x212c2d0d, 0x40400040, 0xb2bc3e8e, 0x323c3e0e, 0xb0bc3c8c, 0xc1c001c1, 0xa2a82a8a, 0xb2b83a8a, 0x424c0e4e, 0x51541545, 0x33383b0b, 0xd0dc1ccc, 0x60682848, 0x737c3f4f, 0x909c1c8c, 0xd0d818c8, 0x42480a4a, 0x52541646, 0x73743747, 0xa0a02080, 0xe1ec2dcd, 0x42440646, 0xb1b43585, 0x23282b0b, 0x61642545, 0xf2f83aca, 0xe3e023c3, 0xb1b83989, 0xb1b03181, 0x939c1f8f, 0x525c1e4e, 0xf1f839c9, 0xe2e426c6, 0xb2b03282, 0x31303101, 0xe2e82aca, 0x616c2d4d, 0x535c1f4f, 0xe0e424c4, 0xf0f030c0, 0xc1cc0dcd, 0x80880888, 0x12141606, 0x32383a0a, 0x50581848, 0xd0d414c4, 0x62602242, 0x21282909, 0x03040707, 0x33303303, 0xe0e828c8, 0x13181b0b, 0x01040505, 0x71783949, 0x90901080, 0x62682a4a, 0x22282a0a, 0x92981a8a, }; static const u32 SS3[256] = { 0x08303838, 0xc8e0e828, 0x0d212c2d, 0x86a2a426, 0xcfc3cc0f, 0xced2dc1e, 0x83b3b033, 0x88b0b838, 0x8fa3ac2f, 0x40606020, 0x45515415, 0xc7c3c407, 0x44404404, 0x4f636c2f, 0x4b63682b, 0x4b53581b, 0xc3c3c003, 0x42626022, 0x03333033, 0x85b1b435, 0x09212829, 0x80a0a020, 0xc2e2e022, 0x87a3a427, 0xc3d3d013, 0x81919011, 0x01111011, 0x06020406, 0x0c101c1c, 0x8cb0bc3c, 0x06323436, 0x4b43480b, 0xcfe3ec2f, 0x88808808, 0x4c606c2c, 0x88a0a828, 0x07131417, 0xc4c0c404, 0x06121416, 0xc4f0f434, 0xc2c2c002, 0x45414405, 0xc1e1e021, 0xc6d2d416, 0x0f333c3f, 0x0d313c3d, 0x8e828c0e, 0x88909818, 0x08202828, 0x4e424c0e, 0xc6f2f436, 0x0e323c3e, 0x85a1a425, 0xc9f1f839, 0x0d010c0d, 0xcfd3dc1f, 0xc8d0d818, 0x0b23282b, 0x46626426, 0x4a72783a, 0x07232427, 0x0f232c2f, 0xc1f1f031, 0x42727032, 0x42424002, 0xc4d0d414, 0x41414001, 0xc0c0c000, 0x43737033, 0x47636427, 0x8ca0ac2c, 0x8b83880b, 0xc7f3f437, 0x8da1ac2d, 0x80808000, 0x0f131c1f, 0xcac2c80a, 0x0c202c2c, 0x8aa2a82a, 0x04303434, 0xc2d2d012, 0x0b03080b, 0xcee2ec2e, 0xc9e1e829, 0x4d515c1d, 0x84909414, 0x08101818, 0xc8f0f838, 0x47535417, 0x8ea2ac2e, 0x08000808, 0xc5c1c405, 0x03131013, 0xcdc1cc0d, 0x86828406, 0x89b1b839, 0xcff3fc3f, 0x4d717c3d, 0xc1c1c001, 0x01313031, 0xc5f1f435, 0x8a82880a, 0x4a62682a, 0x81b1b031, 0xc1d1d011, 0x00202020, 0xc7d3d417, 0x02020002, 0x02222022, 0x04000404, 0x48606828, 0x41717031, 0x07030407, 0xcbd3d81b, 0x8d919c1d, 0x89919819, 0x41616021, 0x8eb2bc3e, 0xc6e2e426, 0x49515819, 0xcdd1dc1d, 0x41515011, 0x80909010, 0xccd0dc1c, 0x8a92981a, 0x83a3a023, 0x8ba3a82b, 0xc0d0d010, 0x81818001, 0x0f030c0f, 0x47434407, 0x0a12181a, 0xc3e3e023, 0xcce0ec2c, 0x8d818c0d, 0x8fb3bc3f, 0x86929416, 0x4b73783b, 0x4c505c1c, 0x82a2a022, 0x81a1a021, 0x43636023, 0x03232023, 0x4d414c0d, 0xc8c0c808, 0x8e929c1e, 0x8c909c1c, 0x0a32383a, 0x0c000c0c, 0x0e222c2e, 0x8ab2b83a, 0x4e626c2e, 0x8f939c1f, 0x4a52581a, 0xc2f2f032, 0x82929012, 0xc3f3f033, 0x49414809, 0x48707838, 0xccc0cc0c, 0x05111415, 0xcbf3f83b, 0x40707030, 0x45717435, 0x4f737c3f, 0x05313435, 0x00101010, 0x03030003, 0x44606424, 0x4d616c2d, 0xc6c2c406, 0x44707434, 0xc5d1d415, 0x84b0b434, 0xcae2e82a, 0x09010809, 0x46727436, 0x09111819, 0xcef2fc3e, 0x40404000, 0x02121012, 0xc0e0e020, 0x8db1bc3d, 0x05010405, 0xcaf2f83a, 0x01010001, 0xc0f0f030, 0x0a22282a, 0x4e525c1e, 0x89a1a829, 0x46525416, 0x43434003, 0x85818405, 0x04101414, 0x89818809, 0x8b93981b, 0x80b0b030, 0xc5e1e425, 0x48404808, 0x49717839, 0x87939417, 0xccf0fc3c, 0x0e121c1e, 0x82828002, 0x01212021, 0x8c808c0c, 0x0b13181b, 0x4f535c1f, 0x47737437, 0x44505414, 0x82b2b032, 0x0d111c1d, 0x05212425, 0x4f434c0f, 0x00000000, 0x46424406, 0xcde1ec2d, 0x48505818, 0x42525012, 0xcbe3e82b, 0x4e727c3e, 0xcad2d81a, 0xc9c1c809, 0xcdf1fc3d, 0x00303030, 0x85919415, 0x45616425, 0x0c303c3c, 0x86b2b436, 0xc4e0e424, 0x8bb3b83b, 0x4c707c3c, 0x0e020c0e, 0x40505010, 0x09313839, 0x06222426, 0x02323032, 0x84808404, 0x49616829, 0x83939013, 0x07333437, 0xc7e3e427, 0x04202424, 0x84a0a424, 0xcbc3c80b, 0x43535013, 0x0a02080a, 0x87838407, 0xc9d1d819, 0x4c404c0c, 0x83838003, 0x8f838c0f, 0xcec2cc0e, 0x0b33383b, 0x4a42480a, 0x87b3b437, }; static const u32 KC[SEED_NUM_KCONSTANTS] = { 0x9e3779b9, 0x3c6ef373, 0x78dde6e6, 0xf1bbcdcc, 0xe3779b99, 0xc6ef3733, 0x8dde6e67, 0x1bbcdccf, 0x3779b99e, 0x6ef3733c, 0xdde6e678, 0xbbcdccf1, 0x779b99e3, 0xef3733c6, 0xde6e678d, 0xbcdccf1b, }; #define OP(X1, X2, X3, X4, rbase) \ t0 = X3 ^ ks[rbase]; \ t1 = X4 ^ ks[rbase+1]; \ t1 ^= t0; \ t1 = SS0[byte(t1, 0)] ^ SS1[byte(t1, 1)] ^ \ SS2[byte(t1, 2)] ^ SS3[byte(t1, 3)]; \ t0 += t1; \ t0 = SS0[byte(t0, 0)] ^ SS1[byte(t0, 1)] ^ \ SS2[byte(t0, 2)] ^ SS3[byte(t0, 3)]; \ t1 += t0; \ t1 = SS0[byte(t1, 0)] ^ SS1[byte(t1, 1)] ^ \ SS2[byte(t1, 2)] ^ SS3[byte(t1, 3)]; \ t0 += t1; \ X1 ^= t0; \ X2 ^= t1; static int seed_set_key(struct crypto_tfm *tfm, const u8 *in_key, unsigned int key_len) { struct seed_ctx *ctx = crypto_tfm_ctx(tfm); u32 *keyout = ctx->keysched; const __be32 *key = (const __be32 *)in_key; u32 i, t0, t1, x1, x2, x3, x4; x1 = be32_to_cpu(key[0]); x2 = be32_to_cpu(key[1]); x3 = be32_to_cpu(key[2]); x4 = be32_to_cpu(key[3]); for (i = 0; i < SEED_NUM_KCONSTANTS; i++) { t0 = x1 + x3 - KC[i]; t1 = x2 + KC[i] - x4; *(keyout++) = SS0[byte(t0, 0)] ^ SS1[byte(t0, 1)] ^ SS2[byte(t0, 2)] ^ SS3[byte(t0, 3)]; *(keyout++) = SS0[byte(t1, 0)] ^ SS1[byte(t1, 1)] ^ SS2[byte(t1, 2)] ^ SS3[byte(t1, 3)]; if (i % 2 == 0) { t0 = x1; x1 = (x1 >> 8) ^ (x2 << 24); x2 = (x2 >> 8) ^ (t0 << 24); } else { t0 = x3; x3 = (x3 << 8) ^ (x4 >> 24); x4 = (x4 << 8) ^ (t0 >> 24); } } return 0; } /* encrypt a block of text */ static void seed_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in) { const struct seed_ctx *ctx = crypto_tfm_ctx(tfm); const __be32 *src = (const __be32 *)in; __be32 *dst = (__be32 *)out; u32 x1, x2, x3, x4, t0, t1; const u32 *ks = ctx->keysched; x1 = be32_to_cpu(src[0]); x2 = be32_to_cpu(src[1]); x3 = be32_to_cpu(src[2]); x4 = be32_to_cpu(src[3]); OP(x1, x2, x3, x4, 0); OP(x3, x4, x1, x2, 2); OP(x1, x2, x3, x4, 4); OP(x3, x4, x1, x2, 6); OP(x1, x2, x3, x4, 8); OP(x3, x4, x1, x2, 10); OP(x1, x2, x3, x4, 12); OP(x3, x4, x1, x2, 14); OP(x1, x2, x3, x4, 16); OP(x3, x4, x1, x2, 18); OP(x1, x2, x3, x4, 20); OP(x3, x4, x1, x2, 22); OP(x1, x2, x3, x4, 24); OP(x3, x4, x1, x2, 26); OP(x1, x2, x3, x4, 28); OP(x3, x4, x1, x2, 30); dst[0] = cpu_to_be32(x3); dst[1] = cpu_to_be32(x4); dst[2] = cpu_to_be32(x1); dst[3] = cpu_to_be32(x2); } /* decrypt a block of text */ static void seed_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in) { const struct seed_ctx *ctx = crypto_tfm_ctx(tfm); const __be32 *src = (const __be32 *)in; __be32 *dst = (__be32 *)out; u32 x1, x2, x3, x4, t0, t1; const u32 *ks = ctx->keysched; x1 = be32_to_cpu(src[0]); x2 = be32_to_cpu(src[1]); x3 = be32_to_cpu(src[2]); x4 = be32_to_cpu(src[3]); OP(x1, x2, x3, x4, 30); OP(x3, x4, x1, x2, 28); OP(x1, x2, x3, x4, 26); OP(x3, x4, x1, x2, 24); OP(x1, x2, x3, x4, 22); OP(x3, x4, x1, x2, 20); OP(x1, x2, x3, x4, 18); OP(x3, x4, x1, x2, 16); OP(x1, x2, x3, x4, 14); OP(x3, x4, x1, x2, 12); OP(x1, x2, x3, x4, 10); OP(x3, x4, x1, x2, 8); OP(x1, x2, x3, x4, 6); OP(x3, x4, x1, x2, 4); OP(x1, x2, x3, x4, 2); OP(x3, x4, x1, x2, 0); dst[0] = cpu_to_be32(x3); dst[1] = cpu_to_be32(x4); dst[2] = cpu_to_be32(x1); dst[3] = cpu_to_be32(x2); } static struct crypto_alg seed_alg = { .cra_name = "seed", .cra_driver_name = "seed-generic", .cra_priority = 100, .cra_flags = CRYPTO_ALG_TYPE_CIPHER, .cra_blocksize = SEED_BLOCK_SIZE, .cra_ctxsize = sizeof(struct seed_ctx), .cra_alignmask = 3, .cra_module = THIS_MODULE, .cra_u = { .cipher = { .cia_min_keysize = SEED_KEY_SIZE, .cia_max_keysize = SEED_KEY_SIZE, .cia_setkey = seed_set_key, .cia_encrypt = seed_encrypt, .cia_decrypt = seed_decrypt } } }; static int __init seed_init(void) { return crypto_register_alg(&seed_alg); } static void __exit seed_fini(void) { crypto_unregister_alg(&seed_alg); } module_init(seed_init); module_exit(seed_fini); MODULE_DESCRIPTION("SEED Cipher Algorithm"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Hye-Shik Chang <perky@FreeBSD.org>, Kim Hyun <hkim@kisa.or.kr>");
gpl-2.0
hanss70/n7100-Nadia-kernel-kk
drivers/net/ibm_newemac/phy.c
4387
12755
/* * drivers/net/ibm_newemac/phy.c * * Driver for PowerPC 4xx on-chip ethernet controller, PHY support. * Borrowed from sungem_phy.c, though I only kept the generic MII * driver for now. * * This file should be shared with other drivers or eventually * merged as the "low level" part of miilib * * Copyright 2007 Benjamin Herrenschmidt, IBM Corp. * <benh@kernel.crashing.org> * * Based on the arch/ppc version of the driver: * * (c) 2003, Benjamin Herrenscmidt (benh@kernel.crashing.org) * (c) 2004-2005, Eugene Surovegin <ebs@ebshome.net> * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/netdevice.h> #include <linux/mii.h> #include <linux/ethtool.h> #include <linux/delay.h> #include "emac.h" #include "phy.h" static inline int phy_read(struct mii_phy *phy, int reg) { return phy->mdio_read(phy->dev, phy->address, reg); } static inline void phy_write(struct mii_phy *phy, int reg, int val) { phy->mdio_write(phy->dev, phy->address, reg, val); } static inline int gpcs_phy_read(struct mii_phy *phy, int reg) { return phy->mdio_read(phy->dev, phy->gpcs_address, reg); } static inline void gpcs_phy_write(struct mii_phy *phy, int reg, int val) { phy->mdio_write(phy->dev, phy->gpcs_address, reg, val); } int emac_mii_reset_phy(struct mii_phy *phy) { int val; int limit = 10000; val = phy_read(phy, MII_BMCR); val &= ~(BMCR_ISOLATE | BMCR_ANENABLE); val |= BMCR_RESET; phy_write(phy, MII_BMCR, val); udelay(300); while (--limit) { val = phy_read(phy, MII_BMCR); if (val >= 0 && (val & BMCR_RESET) == 0) break; udelay(10); } if ((val & BMCR_ISOLATE) && limit > 0) phy_write(phy, MII_BMCR, val & ~BMCR_ISOLATE); return limit <= 0; } int emac_mii_reset_gpcs(struct mii_phy *phy) { int val; int limit = 10000; val = gpcs_phy_read(phy, MII_BMCR); val &= ~(BMCR_ISOLATE | BMCR_ANENABLE); val |= BMCR_RESET; gpcs_phy_write(phy, MII_BMCR, val); udelay(300); while (--limit) { val = gpcs_phy_read(phy, MII_BMCR); if (val >= 0 && (val & BMCR_RESET) == 0) break; udelay(10); } if ((val & BMCR_ISOLATE) && limit > 0) gpcs_phy_write(phy, MII_BMCR, val & ~BMCR_ISOLATE); if (limit > 0 && phy->mode == PHY_MODE_SGMII) { /* Configure GPCS interface to recommended setting for SGMII */ gpcs_phy_write(phy, 0x04, 0x8120); /* AsymPause, FDX */ gpcs_phy_write(phy, 0x07, 0x2801); /* msg_pg, toggle */ gpcs_phy_write(phy, 0x00, 0x0140); /* 1Gbps, FDX */ } return limit <= 0; } static int genmii_setup_aneg(struct mii_phy *phy, u32 advertise) { int ctl, adv; phy->autoneg = AUTONEG_ENABLE; phy->speed = SPEED_10; phy->duplex = DUPLEX_HALF; phy->pause = phy->asym_pause = 0; phy->advertising = advertise; ctl = phy_read(phy, MII_BMCR); if (ctl < 0) return ctl; ctl &= ~(BMCR_FULLDPLX | BMCR_SPEED100 | BMCR_SPEED1000 | BMCR_ANENABLE); /* First clear the PHY */ phy_write(phy, MII_BMCR, ctl); /* Setup standard advertise */ adv = phy_read(phy, MII_ADVERTISE); if (adv < 0) return adv; adv &= ~(ADVERTISE_ALL | ADVERTISE_100BASE4 | ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM); if (advertise & ADVERTISED_10baseT_Half) adv |= ADVERTISE_10HALF; if (advertise & ADVERTISED_10baseT_Full) adv |= ADVERTISE_10FULL; if (advertise & ADVERTISED_100baseT_Half) adv |= ADVERTISE_100HALF; if (advertise & ADVERTISED_100baseT_Full) adv |= ADVERTISE_100FULL; if (advertise & ADVERTISED_Pause) adv |= ADVERTISE_PAUSE_CAP; if (advertise & ADVERTISED_Asym_Pause) adv |= ADVERTISE_PAUSE_ASYM; phy_write(phy, MII_ADVERTISE, adv); if (phy->features & (SUPPORTED_1000baseT_Full | SUPPORTED_1000baseT_Half)) { adv = phy_read(phy, MII_CTRL1000); if (adv < 0) return adv; adv &= ~(ADVERTISE_1000FULL | ADVERTISE_1000HALF); if (advertise & ADVERTISED_1000baseT_Full) adv |= ADVERTISE_1000FULL; if (advertise & ADVERTISED_1000baseT_Half) adv |= ADVERTISE_1000HALF; phy_write(phy, MII_CTRL1000, adv); } /* Start/Restart aneg */ ctl = phy_read(phy, MII_BMCR); ctl |= (BMCR_ANENABLE | BMCR_ANRESTART); phy_write(phy, MII_BMCR, ctl); return 0; } static int genmii_setup_forced(struct mii_phy *phy, int speed, int fd) { int ctl; phy->autoneg = AUTONEG_DISABLE; phy->speed = speed; phy->duplex = fd; phy->pause = phy->asym_pause = 0; ctl = phy_read(phy, MII_BMCR); if (ctl < 0) return ctl; ctl &= ~(BMCR_FULLDPLX | BMCR_SPEED100 | BMCR_SPEED1000 | BMCR_ANENABLE); /* First clear the PHY */ phy_write(phy, MII_BMCR, ctl | BMCR_RESET); /* Select speed & duplex */ switch (speed) { case SPEED_10: break; case SPEED_100: ctl |= BMCR_SPEED100; break; case SPEED_1000: ctl |= BMCR_SPEED1000; break; default: return -EINVAL; } if (fd == DUPLEX_FULL) ctl |= BMCR_FULLDPLX; phy_write(phy, MII_BMCR, ctl); return 0; } static int genmii_poll_link(struct mii_phy *phy) { int status; /* Clear latched value with dummy read */ phy_read(phy, MII_BMSR); status = phy_read(phy, MII_BMSR); if (status < 0 || (status & BMSR_LSTATUS) == 0) return 0; if (phy->autoneg == AUTONEG_ENABLE && !(status & BMSR_ANEGCOMPLETE)) return 0; return 1; } static int genmii_read_link(struct mii_phy *phy) { if (phy->autoneg == AUTONEG_ENABLE) { int glpa = 0; int lpa = phy_read(phy, MII_LPA) & phy_read(phy, MII_ADVERTISE); if (lpa < 0) return lpa; if (phy->features & (SUPPORTED_1000baseT_Full | SUPPORTED_1000baseT_Half)) { int adv = phy_read(phy, MII_CTRL1000); glpa = phy_read(phy, MII_STAT1000); if (glpa < 0 || adv < 0) return adv; glpa &= adv << 2; } phy->speed = SPEED_10; phy->duplex = DUPLEX_HALF; phy->pause = phy->asym_pause = 0; if (glpa & (LPA_1000FULL | LPA_1000HALF)) { phy->speed = SPEED_1000; if (glpa & LPA_1000FULL) phy->duplex = DUPLEX_FULL; } else if (lpa & (LPA_100FULL | LPA_100HALF)) { phy->speed = SPEED_100; if (lpa & LPA_100FULL) phy->duplex = DUPLEX_FULL; } else if (lpa & LPA_10FULL) phy->duplex = DUPLEX_FULL; if (phy->duplex == DUPLEX_FULL) { phy->pause = lpa & LPA_PAUSE_CAP ? 1 : 0; phy->asym_pause = lpa & LPA_PAUSE_ASYM ? 1 : 0; } } else { int bmcr = phy_read(phy, MII_BMCR); if (bmcr < 0) return bmcr; if (bmcr & BMCR_FULLDPLX) phy->duplex = DUPLEX_FULL; else phy->duplex = DUPLEX_HALF; if (bmcr & BMCR_SPEED1000) phy->speed = SPEED_1000; else if (bmcr & BMCR_SPEED100) phy->speed = SPEED_100; else phy->speed = SPEED_10; phy->pause = phy->asym_pause = 0; } return 0; } /* Generic implementation for most 10/100/1000 PHYs */ static struct mii_phy_ops generic_phy_ops = { .setup_aneg = genmii_setup_aneg, .setup_forced = genmii_setup_forced, .poll_link = genmii_poll_link, .read_link = genmii_read_link }; static struct mii_phy_def genmii_phy_def = { .phy_id = 0x00000000, .phy_id_mask = 0x00000000, .name = "Generic MII", .ops = &generic_phy_ops }; /* CIS8201 */ #define MII_CIS8201_10BTCSR 0x16 #define TENBTCSR_ECHO_DISABLE 0x2000 #define MII_CIS8201_EPCR 0x17 #define EPCR_MODE_MASK 0x3000 #define EPCR_GMII_MODE 0x0000 #define EPCR_RGMII_MODE 0x1000 #define EPCR_TBI_MODE 0x2000 #define EPCR_RTBI_MODE 0x3000 #define MII_CIS8201_ACSR 0x1c #define ACSR_PIN_PRIO_SELECT 0x0004 static int cis8201_init(struct mii_phy *phy) { int epcr; epcr = phy_read(phy, MII_CIS8201_EPCR); if (epcr < 0) return epcr; epcr &= ~EPCR_MODE_MASK; switch (phy->mode) { case PHY_MODE_TBI: epcr |= EPCR_TBI_MODE; break; case PHY_MODE_RTBI: epcr |= EPCR_RTBI_MODE; break; case PHY_MODE_GMII: epcr |= EPCR_GMII_MODE; break; case PHY_MODE_RGMII: default: epcr |= EPCR_RGMII_MODE; } phy_write(phy, MII_CIS8201_EPCR, epcr); /* MII regs override strap pins */ phy_write(phy, MII_CIS8201_ACSR, phy_read(phy, MII_CIS8201_ACSR) | ACSR_PIN_PRIO_SELECT); /* Disable TX_EN -> CRS echo mode, otherwise 10/HDX doesn't work */ phy_write(phy, MII_CIS8201_10BTCSR, phy_read(phy, MII_CIS8201_10BTCSR) | TENBTCSR_ECHO_DISABLE); return 0; } static struct mii_phy_ops cis8201_phy_ops = { .init = cis8201_init, .setup_aneg = genmii_setup_aneg, .setup_forced = genmii_setup_forced, .poll_link = genmii_poll_link, .read_link = genmii_read_link }; static struct mii_phy_def cis8201_phy_def = { .phy_id = 0x000fc410, .phy_id_mask = 0x000ffff0, .name = "CIS8201 Gigabit Ethernet", .ops = &cis8201_phy_ops }; static struct mii_phy_def bcm5248_phy_def = { .phy_id = 0x0143bc00, .phy_id_mask = 0x0ffffff0, .name = "BCM5248 10/100 SMII Ethernet", .ops = &generic_phy_ops }; static int m88e1111_init(struct mii_phy *phy) { pr_debug("%s: Marvell 88E1111 Ethernet\n", __func__); phy_write(phy, 0x14, 0x0ce3); phy_write(phy, 0x18, 0x4101); phy_write(phy, 0x09, 0x0e00); phy_write(phy, 0x04, 0x01e1); phy_write(phy, 0x00, 0x9140); phy_write(phy, 0x00, 0x1140); return 0; } static int m88e1112_init(struct mii_phy *phy) { /* * Marvell 88E1112 PHY needs to have the SGMII MAC * interace (page 2) properly configured to * communicate with the 460EX/GT GPCS interface. */ u16 reg_short; pr_debug("%s: Marvell 88E1112 Ethernet\n", __func__); /* Set access to Page 2 */ phy_write(phy, 0x16, 0x0002); phy_write(phy, 0x00, 0x0040); /* 1Gbps */ reg_short = (u16)(phy_read(phy, 0x1a)); reg_short |= 0x8000; /* bypass Auto-Negotiation */ phy_write(phy, 0x1a, reg_short); emac_mii_reset_phy(phy); /* reset MAC interface */ /* Reset access to Page 0 */ phy_write(phy, 0x16, 0x0000); return 0; } static int et1011c_init(struct mii_phy *phy) { u16 reg_short; reg_short = (u16)(phy_read(phy, 0x16)); reg_short &= ~(0x7); reg_short |= 0x6; /* RGMII Trace Delay*/ phy_write(phy, 0x16, reg_short); reg_short = (u16)(phy_read(phy, 0x17)); reg_short &= ~(0x40); phy_write(phy, 0x17, reg_short); phy_write(phy, 0x1c, 0x74f0); return 0; } static struct mii_phy_ops et1011c_phy_ops = { .init = et1011c_init, .setup_aneg = genmii_setup_aneg, .setup_forced = genmii_setup_forced, .poll_link = genmii_poll_link, .read_link = genmii_read_link }; static struct mii_phy_def et1011c_phy_def = { .phy_id = 0x0282f000, .phy_id_mask = 0x0fffff00, .name = "ET1011C Gigabit Ethernet", .ops = &et1011c_phy_ops }; static struct mii_phy_ops m88e1111_phy_ops = { .init = m88e1111_init, .setup_aneg = genmii_setup_aneg, .setup_forced = genmii_setup_forced, .poll_link = genmii_poll_link, .read_link = genmii_read_link }; static struct mii_phy_def m88e1111_phy_def = { .phy_id = 0x01410CC0, .phy_id_mask = 0x0ffffff0, .name = "Marvell 88E1111 Ethernet", .ops = &m88e1111_phy_ops, }; static struct mii_phy_ops m88e1112_phy_ops = { .init = m88e1112_init, .setup_aneg = genmii_setup_aneg, .setup_forced = genmii_setup_forced, .poll_link = genmii_poll_link, .read_link = genmii_read_link }; static struct mii_phy_def m88e1112_phy_def = { .phy_id = 0x01410C90, .phy_id_mask = 0x0ffffff0, .name = "Marvell 88E1112 Ethernet", .ops = &m88e1112_phy_ops, }; static struct mii_phy_def *mii_phy_table[] = { &et1011c_phy_def, &cis8201_phy_def, &bcm5248_phy_def, &m88e1111_phy_def, &m88e1112_phy_def, &genmii_phy_def, NULL }; int emac_mii_phy_probe(struct mii_phy *phy, int address) { struct mii_phy_def *def; int i; u32 id; phy->autoneg = AUTONEG_DISABLE; phy->advertising = 0; phy->address = address; phy->speed = SPEED_10; phy->duplex = DUPLEX_HALF; phy->pause = phy->asym_pause = 0; /* Take PHY out of isolate mode and reset it. */ if (emac_mii_reset_phy(phy)) return -ENODEV; /* Read ID and find matching entry */ id = (phy_read(phy, MII_PHYSID1) << 16) | phy_read(phy, MII_PHYSID2); for (i = 0; (def = mii_phy_table[i]) != NULL; i++) if ((id & def->phy_id_mask) == def->phy_id) break; /* Should never be NULL (we have a generic entry), but... */ if (!def) return -ENODEV; phy->def = def; /* Determine PHY features if needed */ phy->features = def->features; if (!phy->features) { u16 bmsr = phy_read(phy, MII_BMSR); if (bmsr & BMSR_ANEGCAPABLE) phy->features |= SUPPORTED_Autoneg; if (bmsr & BMSR_10HALF) phy->features |= SUPPORTED_10baseT_Half; if (bmsr & BMSR_10FULL) phy->features |= SUPPORTED_10baseT_Full; if (bmsr & BMSR_100HALF) phy->features |= SUPPORTED_100baseT_Half; if (bmsr & BMSR_100FULL) phy->features |= SUPPORTED_100baseT_Full; if (bmsr & BMSR_ESTATEN) { u16 esr = phy_read(phy, MII_ESTATUS); if (esr & ESTATUS_1000_TFULL) phy->features |= SUPPORTED_1000baseT_Full; if (esr & ESTATUS_1000_THALF) phy->features |= SUPPORTED_1000baseT_Half; } phy->features |= SUPPORTED_MII; } /* Setup default advertising */ phy->advertising = phy->features; return 0; } MODULE_LICENSE("GPL");
gpl-2.0
KCFTech/Linux_3_2_0-26_Kernel
arch/cris/arch-v32/kernel/smp.c
4643
8333
#include <linux/types.h> #include <asm/delay.h> #include <irq.h> #include <hwregs/intr_vect.h> #include <hwregs/intr_vect_defs.h> #include <asm/tlbflush.h> #include <asm/mmu_context.h> #include <hwregs/asm/mmu_defs_asm.h> #include <hwregs/supp_reg.h> #include <linux/atomic.h> #include <linux/err.h> #include <linux/init.h> #include <linux/timex.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/cpumask.h> #include <linux/interrupt.h> #include <linux/module.h> #define IPI_SCHEDULE 1 #define IPI_CALL 2 #define IPI_FLUSH_TLB 4 #define IPI_BOOT 8 #define FLUSH_ALL (void*)0xffffffff /* Vector of locks used for various atomic operations */ spinlock_t cris_atomic_locks[] = { [0 ... LOCK_COUNT - 1] = __SPIN_LOCK_UNLOCKED(cris_atomic_locks) }; /* CPU masks */ cpumask_t phys_cpu_present_map = CPU_MASK_NONE; EXPORT_SYMBOL(phys_cpu_present_map); /* Variables used during SMP boot */ volatile int cpu_now_booting = 0; volatile struct thread_info *smp_init_current_idle_thread; /* Variables used during IPI */ static DEFINE_SPINLOCK(call_lock); static DEFINE_SPINLOCK(tlbstate_lock); struct call_data_struct { void (*func) (void *info); void *info; int wait; }; static struct call_data_struct * call_data; static struct mm_struct* flush_mm; static struct vm_area_struct* flush_vma; static unsigned long flush_addr; /* Mode registers */ static unsigned long irq_regs[NR_CPUS] = { regi_irq, regi_irq2 }; static irqreturn_t crisv32_ipi_interrupt(int irq, void *dev_id); static int send_ipi(int vector, int wait, cpumask_t cpu_mask); static struct irqaction irq_ipi = { .handler = crisv32_ipi_interrupt, .flags = IRQF_DISABLED, .name = "ipi", }; extern void cris_mmu_init(void); extern void cris_timer_init(void); /* SMP initialization */ void __init smp_prepare_cpus(unsigned int max_cpus) { int i; /* From now on we can expect IPIs so set them up */ setup_irq(IPI_INTR_VECT, &irq_ipi); /* Mark all possible CPUs as present */ for (i = 0; i < max_cpus; i++) cpumask_set_cpu(i, &phys_cpu_present_map); } void __devinit smp_prepare_boot_cpu(void) { /* PGD pointer has moved after per_cpu initialization so * update the MMU. */ pgd_t **pgd; pgd = (pgd_t**)&per_cpu(current_pgd, smp_processor_id()); SUPP_BANK_SEL(1); SUPP_REG_WR(RW_MM_TLB_PGD, pgd); SUPP_BANK_SEL(2); SUPP_REG_WR(RW_MM_TLB_PGD, pgd); set_cpu_online(0, true); cpumask_set_cpu(0, &phys_cpu_present_map); set_cpu_possible(0, true); } void __init smp_cpus_done(unsigned int max_cpus) { } /* Bring one cpu online.*/ static int __init smp_boot_one_cpu(int cpuid) { unsigned timeout; struct task_struct *idle; cpumask_t cpu_mask; cpumask_clear(&cpu_mask); idle = fork_idle(cpuid); if (IS_ERR(idle)) panic("SMP: fork failed for CPU:%d", cpuid); task_thread_info(idle)->cpu = cpuid; /* Information to the CPU that is about to boot */ smp_init_current_idle_thread = task_thread_info(idle); cpu_now_booting = cpuid; /* Kick it */ set_cpu_online(cpuid, true); cpumask_set_cpu(cpuid, &cpu_mask); send_ipi(IPI_BOOT, 0, cpu_mask); set_cpu_online(cpuid, false); /* Wait for CPU to come online */ for (timeout = 0; timeout < 10000; timeout++) { if(cpu_online(cpuid)) { cpu_now_booting = 0; smp_init_current_idle_thread = NULL; return 0; /* CPU online */ } udelay(100); barrier(); } put_task_struct(idle); idle = NULL; printk(KERN_CRIT "SMP: CPU:%d is stuck.\n", cpuid); return -1; } /* Secondary CPUs starts using C here. Here we need to setup CPU * specific stuff such as the local timer and the MMU. */ void __init smp_callin(void) { extern void cpu_idle(void); int cpu = cpu_now_booting; reg_intr_vect_rw_mask vect_mask = {0}; /* Initialise the idle task for this CPU */ atomic_inc(&init_mm.mm_count); current->active_mm = &init_mm; /* Set up MMU */ cris_mmu_init(); __flush_tlb_all(); /* Setup local timer. */ cris_timer_init(); /* Enable IRQ and idle */ REG_WR(intr_vect, irq_regs[cpu], rw_mask, vect_mask); crisv32_unmask_irq(IPI_INTR_VECT); crisv32_unmask_irq(TIMER0_INTR_VECT); preempt_disable(); notify_cpu_starting(cpu); local_irq_enable(); set_cpu_online(cpu, true); cpu_idle(); } /* Stop execution on this CPU.*/ void stop_this_cpu(void* dummy) { local_irq_disable(); asm volatile("halt"); } /* Other calls */ void smp_send_stop(void) { smp_call_function(stop_this_cpu, NULL, 0); } int setup_profiling_timer(unsigned int multiplier) { return -EINVAL; } /* cache_decay_ticks is used by the scheduler to decide if a process * is "hot" on one CPU. A higher value means a higher penalty to move * a process to another CPU. Our cache is rather small so we report * 1 tick. */ unsigned long cache_decay_ticks = 1; int __cpuinit __cpu_up(unsigned int cpu) { smp_boot_one_cpu(cpu); return cpu_online(cpu) ? 0 : -ENOSYS; } void smp_send_reschedule(int cpu) { cpumask_t cpu_mask; cpumask_clear(&cpu_mask); cpumask_set_cpu(cpu, &cpu_mask); send_ipi(IPI_SCHEDULE, 0, cpu_mask); } /* TLB flushing * * Flush needs to be done on the local CPU and on any other CPU that * may have the same mapping. The mm->cpu_vm_mask is used to keep track * of which CPUs that a specific process has been executed on. */ void flush_tlb_common(struct mm_struct* mm, struct vm_area_struct* vma, unsigned long addr) { unsigned long flags; cpumask_t cpu_mask; spin_lock_irqsave(&tlbstate_lock, flags); cpu_mask = (mm == FLUSH_ALL ? cpu_all_mask : *mm_cpumask(mm)); cpumask_clear_cpu(smp_processor_id(), &cpu_mask); flush_mm = mm; flush_vma = vma; flush_addr = addr; send_ipi(IPI_FLUSH_TLB, 1, cpu_mask); spin_unlock_irqrestore(&tlbstate_lock, flags); } void flush_tlb_all(void) { __flush_tlb_all(); flush_tlb_common(FLUSH_ALL, FLUSH_ALL, 0); } void flush_tlb_mm(struct mm_struct *mm) { __flush_tlb_mm(mm); flush_tlb_common(mm, FLUSH_ALL, 0); /* No more mappings in other CPUs */ cpumask_clear(mm_cpumask(mm)); cpumask_set_cpu(smp_processor_id(), mm_cpumask(mm)); } void flush_tlb_page(struct vm_area_struct *vma, unsigned long addr) { __flush_tlb_page(vma, addr); flush_tlb_common(vma->vm_mm, vma, addr); } /* Inter processor interrupts * * The IPIs are used for: * * Force a schedule on a CPU * * FLush TLB on other CPUs * * Call a function on other CPUs */ int send_ipi(int vector, int wait, cpumask_t cpu_mask) { int i = 0; reg_intr_vect_rw_ipi ipi = REG_RD(intr_vect, irq_regs[i], rw_ipi); int ret = 0; /* Calculate CPUs to send to. */ cpumask_and(&cpu_mask, &cpu_mask, cpu_online_mask); /* Send the IPI. */ for_each_cpu(i, &cpu_mask) { ipi.vector |= vector; REG_WR(intr_vect, irq_regs[i], rw_ipi, ipi); } /* Wait for IPI to finish on other CPUS */ if (wait) { for_each_cpu(i, &cpu_mask) { int j; for (j = 0 ; j < 1000; j++) { ipi = REG_RD(intr_vect, irq_regs[i], rw_ipi); if (!ipi.vector) break; udelay(100); } /* Timeout? */ if (ipi.vector) { printk("SMP call timeout from %d to %d\n", smp_processor_id(), i); ret = -ETIMEDOUT; dump_stack(); } } } return ret; } /* * You must not call this function with disabled interrupts or from a * hardware interrupt handler or from a bottom half handler. */ int smp_call_function(void (*func)(void *info), void *info, int wait) { cpumask_t cpu_mask; struct call_data_struct data; int ret; cpumask_setall(&cpu_mask); cpumask_clear_cpu(smp_processor_id(), &cpu_mask); WARN_ON(irqs_disabled()); data.func = func; data.info = info; data.wait = wait; spin_lock(&call_lock); call_data = &data; ret = send_ipi(IPI_CALL, wait, cpu_mask); spin_unlock(&call_lock); return ret; } irqreturn_t crisv32_ipi_interrupt(int irq, void *dev_id) { void (*func) (void *info) = call_data->func; void *info = call_data->info; reg_intr_vect_rw_ipi ipi; ipi = REG_RD(intr_vect, irq_regs[smp_processor_id()], rw_ipi); if (ipi.vector & IPI_SCHEDULE) { scheduler_ipi(); } if (ipi.vector & IPI_CALL) { func(info); } if (ipi.vector & IPI_FLUSH_TLB) { if (flush_mm == FLUSH_ALL) __flush_tlb_all(); else if (flush_vma == FLUSH_ALL) __flush_tlb_mm(flush_mm); else __flush_tlb_page(flush_vma, flush_addr); } ipi.vector = 0; REG_WR(intr_vect, irq_regs[smp_processor_id()], rw_ipi, ipi); return IRQ_HANDLED; }
gpl-2.0
byzvulture/android_kernel_nubia_nx507j
drivers/media/video/em28xx/em28xx-audio.c
4899
19483
/* * Empiatech em28x1 audio extension * * Copyright (C) 2006 Markus Rechberger <mrechberger@gmail.com> * * Copyright (C) 2007-2011 Mauro Carvalho Chehab <mchehab@redhat.com> * - Port to work with the in-kernel driver * - Cleanups, fixes, alsa-controls, etc. * * This driver is based on my previous au600 usb pstn audio driver * and inherits all the copyrights * * This program is free software; you can redistribute it and/or modify * it under the terms of the 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/kernel.h> #include <linux/usb.h> #include <linux/init.h> #include <linux/sound.h> #include <linux/spinlock.h> #include <linux/soundcard.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/info.h> #include <sound/initval.h> #include <sound/control.h> #include <sound/tlv.h> #include <media/v4l2-common.h> #include "em28xx.h" static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "activates debug info"); #define dprintk(fmt, arg...) do { \ if (debug) \ printk(KERN_INFO "em28xx-audio %s: " fmt, \ __func__, ##arg); \ } while (0) static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; static int em28xx_deinit_isoc_audio(struct em28xx *dev) { int i; dprintk("Stopping isoc\n"); for (i = 0; i < EM28XX_AUDIO_BUFS; i++) { if (!irqs_disabled()) usb_kill_urb(dev->adev.urb[i]); else usb_unlink_urb(dev->adev.urb[i]); usb_free_urb(dev->adev.urb[i]); dev->adev.urb[i] = NULL; kfree(dev->adev.transfer_buffer[i]); dev->adev.transfer_buffer[i] = NULL; } return 0; } static void em28xx_audio_isocirq(struct urb *urb) { struct em28xx *dev = urb->context; int i; unsigned int oldptr; int period_elapsed = 0; int status; unsigned char *cp; unsigned int stride; struct snd_pcm_substream *substream; struct snd_pcm_runtime *runtime; switch (urb->status) { case 0: /* success */ case -ETIMEDOUT: /* NAK */ break; case -ECONNRESET: /* kill */ case -ENOENT: case -ESHUTDOWN: return; default: /* error */ dprintk("urb completition error %d.\n", urb->status); break; } if (atomic_read(&dev->stream_started) == 0) return; if (dev->adev.capture_pcm_substream) { substream = dev->adev.capture_pcm_substream; runtime = substream->runtime; stride = runtime->frame_bits >> 3; for (i = 0; i < urb->number_of_packets; i++) { int length = urb->iso_frame_desc[i].actual_length / stride; cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset; if (!length) continue; oldptr = dev->adev.hwptr_done_capture; if (oldptr + length >= runtime->buffer_size) { unsigned int cnt = runtime->buffer_size - oldptr; memcpy(runtime->dma_area + oldptr * stride, cp, cnt * stride); memcpy(runtime->dma_area, cp + cnt * stride, length * stride - cnt * stride); } else { memcpy(runtime->dma_area + oldptr * stride, cp, length * stride); } snd_pcm_stream_lock(substream); dev->adev.hwptr_done_capture += length; if (dev->adev.hwptr_done_capture >= runtime->buffer_size) dev->adev.hwptr_done_capture -= runtime->buffer_size; dev->adev.capture_transfer_done += length; if (dev->adev.capture_transfer_done >= runtime->period_size) { dev->adev.capture_transfer_done -= runtime->period_size; period_elapsed = 1; } snd_pcm_stream_unlock(substream); } if (period_elapsed) snd_pcm_period_elapsed(substream); } urb->status = 0; status = usb_submit_urb(urb, GFP_ATOMIC); if (status < 0) { em28xx_errdev("resubmit of audio urb failed (error=%i)\n", status); } return; } static int em28xx_init_audio_isoc(struct em28xx *dev) { int i, errCode; const int sb_size = EM28XX_NUM_AUDIO_PACKETS * EM28XX_AUDIO_MAX_PACKET_SIZE; dprintk("Starting isoc transfers\n"); for (i = 0; i < EM28XX_AUDIO_BUFS; i++) { struct urb *urb; int j, k; dev->adev.transfer_buffer[i] = kmalloc(sb_size, GFP_ATOMIC); if (!dev->adev.transfer_buffer[i]) return -ENOMEM; memset(dev->adev.transfer_buffer[i], 0x80, sb_size); urb = usb_alloc_urb(EM28XX_NUM_AUDIO_PACKETS, GFP_ATOMIC); if (!urb) { em28xx_errdev("usb_alloc_urb failed!\n"); for (j = 0; j < i; j++) { usb_free_urb(dev->adev.urb[j]); kfree(dev->adev.transfer_buffer[j]); } return -ENOMEM; } urb->dev = dev->udev; urb->context = dev; urb->pipe = usb_rcvisocpipe(dev->udev, EM28XX_EP_AUDIO); urb->transfer_flags = URB_ISO_ASAP; urb->transfer_buffer = dev->adev.transfer_buffer[i]; urb->interval = 1; urb->complete = em28xx_audio_isocirq; urb->number_of_packets = EM28XX_NUM_AUDIO_PACKETS; urb->transfer_buffer_length = sb_size; for (j = k = 0; j < EM28XX_NUM_AUDIO_PACKETS; j++, k += EM28XX_AUDIO_MAX_PACKET_SIZE) { urb->iso_frame_desc[j].offset = k; urb->iso_frame_desc[j].length = EM28XX_AUDIO_MAX_PACKET_SIZE; } dev->adev.urb[i] = urb; } for (i = 0; i < EM28XX_AUDIO_BUFS; i++) { errCode = usb_submit_urb(dev->adev.urb[i], GFP_ATOMIC); if (errCode) { em28xx_errdev("submit of audio urb failed\n"); em28xx_deinit_isoc_audio(dev); atomic_set(&dev->stream_started, 0); return errCode; } } return 0; } static int snd_pcm_alloc_vmalloc_buffer(struct snd_pcm_substream *subs, size_t size) { struct snd_pcm_runtime *runtime = subs->runtime; dprintk("Allocating vbuffer\n"); if (runtime->dma_area) { if (runtime->dma_bytes > size) return 0; vfree(runtime->dma_area); } runtime->dma_area = vmalloc(size); if (!runtime->dma_area) return -ENOMEM; runtime->dma_bytes = size; return 0; } static struct snd_pcm_hardware snd_em28xx_hw_capture = { .info = SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BATCH | SNDRV_PCM_INFO_MMAP_VALID, .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_KNOT, .rate_min = 48000, .rate_max = 48000, .channels_min = 2, .channels_max = 2, .buffer_bytes_max = 62720 * 8, /* just about the value in usbaudio.c */ .period_bytes_min = 64, /* 12544/2, */ .period_bytes_max = 12544, .periods_min = 2, .periods_max = 98, /* 12544, */ }; static int snd_em28xx_capture_open(struct snd_pcm_substream *substream) { struct em28xx *dev = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; int ret = 0; dprintk("opening device and trying to acquire exclusive lock\n"); if (!dev) { em28xx_err("BUG: em28xx can't find device struct." " Can't proceed with open\n"); return -ENODEV; } runtime->hw = snd_em28xx_hw_capture; if ((dev->alt == 0 || dev->audio_ifnum) && dev->adev.users == 0) { if (dev->audio_ifnum) dev->alt = 1; else dev->alt = 7; dprintk("changing alternate number on interface %d to %d\n", dev->audio_ifnum, dev->alt); usb_set_interface(dev->udev, dev->audio_ifnum, dev->alt); /* Sets volume, mute, etc */ dev->mute = 0; mutex_lock(&dev->lock); ret = em28xx_audio_analog_set(dev); if (ret < 0) goto err; dev->adev.users++; mutex_unlock(&dev->lock); } snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); dev->adev.capture_pcm_substream = substream; runtime->private_data = dev; return 0; err: mutex_unlock(&dev->lock); em28xx_err("Error while configuring em28xx mixer\n"); return ret; } static int snd_em28xx_pcm_close(struct snd_pcm_substream *substream) { struct em28xx *dev = snd_pcm_substream_chip(substream); dprintk("closing device\n"); dev->mute = 1; mutex_lock(&dev->lock); dev->adev.users--; if (atomic_read(&dev->stream_started) > 0) { atomic_set(&dev->stream_started, 0); schedule_work(&dev->wq_trigger); } em28xx_audio_analog_set(dev); if (substream->runtime->dma_area) { dprintk("freeing\n"); vfree(substream->runtime->dma_area); substream->runtime->dma_area = NULL; } mutex_unlock(&dev->lock); return 0; } static int snd_em28xx_hw_capture_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { unsigned int channels, rate, format; int ret; dprintk("Setting capture parameters\n"); ret = snd_pcm_alloc_vmalloc_buffer(substream, params_buffer_bytes(hw_params)); if (ret < 0) return ret; format = params_format(hw_params); rate = params_rate(hw_params); channels = params_channels(hw_params); /* TODO: set up em28xx audio chip to deliver the correct audio format, current default is 48000hz multiplexed => 96000hz mono which shouldn't matter since analogue TV only supports mono */ return 0; } static int snd_em28xx_hw_capture_free(struct snd_pcm_substream *substream) { struct em28xx *dev = snd_pcm_substream_chip(substream); dprintk("Stop capture, if needed\n"); if (atomic_read(&dev->stream_started) > 0) { atomic_set(&dev->stream_started, 0); schedule_work(&dev->wq_trigger); } return 0; } static int snd_em28xx_prepare(struct snd_pcm_substream *substream) { struct em28xx *dev = snd_pcm_substream_chip(substream); dev->adev.hwptr_done_capture = 0; dev->adev.capture_transfer_done = 0; return 0; } static void audio_trigger(struct work_struct *work) { struct em28xx *dev = container_of(work, struct em28xx, wq_trigger); if (atomic_read(&dev->stream_started)) { dprintk("starting capture"); em28xx_init_audio_isoc(dev); } else { dprintk("stopping capture"); em28xx_deinit_isoc_audio(dev); } } static int snd_em28xx_capture_trigger(struct snd_pcm_substream *substream, int cmd) { struct em28xx *dev = snd_pcm_substream_chip(substream); int retval = 0; switch (cmd) { case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: /* fall through */ case SNDRV_PCM_TRIGGER_RESUME: /* fall through */ case SNDRV_PCM_TRIGGER_START: atomic_set(&dev->stream_started, 1); break; case SNDRV_PCM_TRIGGER_PAUSE_PUSH: /* fall through */ case SNDRV_PCM_TRIGGER_SUSPEND: /* fall through */ case SNDRV_PCM_TRIGGER_STOP: atomic_set(&dev->stream_started, 0); break; default: retval = -EINVAL; } schedule_work(&dev->wq_trigger); return retval; } static snd_pcm_uframes_t snd_em28xx_capture_pointer(struct snd_pcm_substream *substream) { unsigned long flags; struct em28xx *dev; snd_pcm_uframes_t hwptr_done; dev = snd_pcm_substream_chip(substream); spin_lock_irqsave(&dev->adev.slock, flags); hwptr_done = dev->adev.hwptr_done_capture; spin_unlock_irqrestore(&dev->adev.slock, flags); return hwptr_done; } static struct page *snd_pcm_get_vmalloc_page(struct snd_pcm_substream *subs, unsigned long offset) { void *pageptr = subs->runtime->dma_area + offset; return vmalloc_to_page(pageptr); } /* * AC97 volume control support */ static int em28xx_vol_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *info) { info->type = SNDRV_CTL_ELEM_TYPE_INTEGER; info->count = 2; info->value.integer.min = 0; info->value.integer.max = 0x1f; return 0; } static int em28xx_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { struct em28xx *dev = snd_kcontrol_chip(kcontrol); u16 val = (0x1f - (value->value.integer.value[0] & 0x1f)) | (0x1f - (value->value.integer.value[1] & 0x1f)) << 8; int rc; mutex_lock(&dev->lock); rc = em28xx_read_ac97(dev, kcontrol->private_value); if (rc < 0) goto err; val |= rc & 0x8000; /* Preserve the mute flag */ rc = em28xx_write_ac97(dev, kcontrol->private_value, val); if (rc < 0) goto err; dprintk("%sleft vol %d, right vol %d (0x%04x) to ac97 volume control 0x%04x\n", (val & 0x8000) ? "muted " : "", 0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f), val, (int)kcontrol->private_value); err: mutex_unlock(&dev->lock); return rc; } static int em28xx_vol_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { struct em28xx *dev = snd_kcontrol_chip(kcontrol); int val; mutex_lock(&dev->lock); val = em28xx_read_ac97(dev, kcontrol->private_value); mutex_unlock(&dev->lock); if (val < 0) return val; dprintk("%sleft vol %d, right vol %d (0x%04x) from ac97 volume control 0x%04x\n", (val & 0x8000) ? "muted " : "", 0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f), val, (int)kcontrol->private_value); value->value.integer.value[0] = 0x1f - (val & 0x1f); value->value.integer.value[1] = 0x1f - ((val << 8) & 0x1f); return 0; } static int em28xx_vol_put_mute(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { struct em28xx *dev = snd_kcontrol_chip(kcontrol); u16 val = value->value.integer.value[0]; int rc; mutex_lock(&dev->lock); rc = em28xx_read_ac97(dev, kcontrol->private_value); if (rc < 0) goto err; if (val) rc &= 0x1f1f; else rc |= 0x8000; rc = em28xx_write_ac97(dev, kcontrol->private_value, rc); if (rc < 0) goto err; dprintk("%sleft vol %d, right vol %d (0x%04x) to ac97 volume control 0x%04x\n", (val & 0x8000) ? "muted " : "", 0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f), val, (int)kcontrol->private_value); err: mutex_unlock(&dev->lock); return rc; } static int em28xx_vol_get_mute(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value) { struct em28xx *dev = snd_kcontrol_chip(kcontrol); int val; mutex_lock(&dev->lock); val = em28xx_read_ac97(dev, kcontrol->private_value); mutex_unlock(&dev->lock); if (val < 0) return val; if (val & 0x8000) value->value.integer.value[0] = 0; else value->value.integer.value[0] = 1; dprintk("%sleft vol %d, right vol %d (0x%04x) from ac97 volume control 0x%04x\n", (val & 0x8000) ? "muted " : "", 0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f), val, (int)kcontrol->private_value); return 0; } static const DECLARE_TLV_DB_SCALE(em28xx_db_scale, -3450, 150, 0); static int em28xx_cvol_new(struct snd_card *card, struct em28xx *dev, char *name, int id) { int err; char ctl_name[44]; struct snd_kcontrol *kctl; struct snd_kcontrol_new tmp; memset (&tmp, 0, sizeof(tmp)); tmp.iface = SNDRV_CTL_ELEM_IFACE_MIXER, tmp.private_value = id, tmp.name = ctl_name, /* Add Mute Control */ sprintf(ctl_name, "%s Switch", name); tmp.get = em28xx_vol_get_mute; tmp.put = em28xx_vol_put_mute; tmp.info = snd_ctl_boolean_mono_info; kctl = snd_ctl_new1(&tmp, dev); err = snd_ctl_add(card, kctl); if (err < 0) return err; dprintk("Added control %s for ac97 volume control 0x%04x\n", ctl_name, id); memset (&tmp, 0, sizeof(tmp)); tmp.iface = SNDRV_CTL_ELEM_IFACE_MIXER, tmp.private_value = id, tmp.name = ctl_name, /* Add Volume Control */ sprintf(ctl_name, "%s Volume", name); tmp.get = em28xx_vol_get; tmp.put = em28xx_vol_put; tmp.info = em28xx_vol_info; tmp.tlv.p = em28xx_db_scale, kctl = snd_ctl_new1(&tmp, dev); err = snd_ctl_add(card, kctl); if (err < 0) return err; dprintk("Added control %s for ac97 volume control 0x%04x\n", ctl_name, id); return 0; } /* * register/unregister code and data */ static struct snd_pcm_ops snd_em28xx_pcm_capture = { .open = snd_em28xx_capture_open, .close = snd_em28xx_pcm_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_em28xx_hw_capture_params, .hw_free = snd_em28xx_hw_capture_free, .prepare = snd_em28xx_prepare, .trigger = snd_em28xx_capture_trigger, .pointer = snd_em28xx_capture_pointer, .page = snd_pcm_get_vmalloc_page, }; static int em28xx_audio_init(struct em28xx *dev) { struct em28xx_audio *adev = &dev->adev; struct snd_pcm *pcm; struct snd_card *card; static int devnr; int err; if (!dev->has_alsa_audio || dev->audio_ifnum < 0) { /* This device does not support the extension (in this case the device is expecting the snd-usb-audio module or doesn't have analog audio support at all) */ return 0; } printk(KERN_INFO "em28xx-audio.c: probing for em28xx Audio Vendor Class\n"); printk(KERN_INFO "em28xx-audio.c: Copyright (C) 2006 Markus " "Rechberger\n"); printk(KERN_INFO "em28xx-audio.c: Copyright (C) 2007-2011 Mauro Carvalho Chehab\n"); err = snd_card_create(index[devnr], "Em28xx Audio", THIS_MODULE, 0, &card); if (err < 0) return err; spin_lock_init(&adev->slock); err = snd_pcm_new(card, "Em28xx Audio", 0, 0, 1, &pcm); if (err < 0) { snd_card_free(card); return err; } snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_em28xx_pcm_capture); pcm->info_flags = 0; pcm->private_data = dev; strcpy(pcm->name, "Empia 28xx Capture"); snd_card_set_dev(card, &dev->udev->dev); strcpy(card->driver, "Em28xx-Audio"); strcpy(card->shortname, "Em28xx Audio"); strcpy(card->longname, "Empia Em28xx Audio"); INIT_WORK(&dev->wq_trigger, audio_trigger); if (dev->audio_mode.ac97 != EM28XX_NO_AC97) { em28xx_cvol_new(card, dev, "Video", AC97_VIDEO_VOL); em28xx_cvol_new(card, dev, "Line In", AC97_LINEIN_VOL); em28xx_cvol_new(card, dev, "Phone", AC97_PHONE_VOL); em28xx_cvol_new(card, dev, "Microphone", AC97_PHONE_VOL); em28xx_cvol_new(card, dev, "CD", AC97_CD_VOL); em28xx_cvol_new(card, dev, "AUX", AC97_AUX_VOL); em28xx_cvol_new(card, dev, "PCM", AC97_PCM_OUT_VOL); em28xx_cvol_new(card, dev, "Master", AC97_MASTER_VOL); em28xx_cvol_new(card, dev, "Line", AC97_LINE_LEVEL_VOL); em28xx_cvol_new(card, dev, "Mono", AC97_MASTER_MONO_VOL); em28xx_cvol_new(card, dev, "LFE", AC97_LFE_MASTER_VOL); em28xx_cvol_new(card, dev, "Surround", AC97_SURR_MASTER_VOL); } err = snd_card_register(card); if (err < 0) { snd_card_free(card); return err; } adev->sndcard = card; adev->udev = dev->udev; return 0; } static int em28xx_audio_fini(struct em28xx *dev) { if (dev == NULL) return 0; if (dev->has_alsa_audio != 1) { /* This device does not support the extension (in this case the device is expecting the snd-usb-audio module or doesn't have analog audio support at all) */ return 0; } if (dev->adev.sndcard) { snd_card_free(dev->adev.sndcard); dev->adev.sndcard = NULL; } return 0; } static struct em28xx_ops audio_ops = { .id = EM28XX_AUDIO, .name = "Em28xx Audio Extension", .init = em28xx_audio_init, .fini = em28xx_audio_fini, }; static int __init em28xx_alsa_register(void) { return em28xx_register_extension(&audio_ops); } static void __exit em28xx_alsa_unregister(void) { em28xx_unregister_extension(&audio_ops); } MODULE_LICENSE("GPL"); MODULE_AUTHOR("Markus Rechberger <mrechberger@gmail.com>"); MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>"); MODULE_DESCRIPTION("Em28xx Audio driver"); module_init(em28xx_alsa_register); module_exit(em28xx_alsa_unregister);
gpl-2.0
V4MSHI/zte_racer_2.6.32
arch/mips/sibyte/sb1250/bus_watcher.c
4899
7864
/* * Copyright (C) 2002,2003 Broadcom 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. */ /* * The Bus Watcher monitors internal bus transactions and maintains * counts of transactions with error status, logging details and * causing one of several interrupts. This driver provides a handler * for those interrupts which aggregates the counts (to avoid * saturating the 8-bit counters) and provides a presence in * /proc/bus_watcher if PROC_FS is on. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/interrupt.h> #include <linux/sched.h> #include <linux/proc_fs.h> #include <asm/system.h> #include <asm/io.h> #include <asm/sibyte/sb1250.h> #include <asm/sibyte/sb1250_regs.h> #include <asm/sibyte/sb1250_int.h> #include <asm/sibyte/sb1250_scd.h> struct bw_stats_struct { uint64_t status; uint32_t l2_err; uint32_t memio_err; int status_printed; unsigned long l2_cor_d; unsigned long l2_bad_d; unsigned long l2_cor_t; unsigned long l2_bad_t; unsigned long mem_cor_d; unsigned long mem_bad_d; unsigned long bus_error; } bw_stats; static void print_summary(uint32_t status, uint32_t l2_err, uint32_t memio_err) { printk("Bus watcher error counters: %08x %08x\n", l2_err, memio_err); printk("\nLast recorded signature:\n"); printk("Request %02x from %d, answered by %d with Dcode %d\n", (unsigned int)(G_SCD_BERR_TID(status) & 0x3f), (int)(G_SCD_BERR_TID(status) >> 6), (int)G_SCD_BERR_RID(status), (int)G_SCD_BERR_DCODE(status)); } /* * check_bus_watcher is exported for use in situations where we want * to see the most recent status of the bus watcher, which might have * already been destructively read out of the registers. * * notes: this is currently used by the cache error handler * should provide locking against the interrupt handler */ void check_bus_watcher(void) { u32 status, l2_err, memio_err; #ifdef CONFIG_SB1_PASS_1_WORKAROUNDS /* Destructive read, clears register and interrupt */ status = csr_in32(IOADDR(A_SCD_BUS_ERR_STATUS)); #else /* Use non-destructive register */ status = csr_in32(IOADDR(A_SCD_BUS_ERR_STATUS_DEBUG)); #endif if (!(status & 0x7fffffff)) { printk("Using last values reaped by bus watcher driver\n"); status = bw_stats.status; l2_err = bw_stats.l2_err; memio_err = bw_stats.memio_err; } else { l2_err = csr_in32(IOADDR(A_BUS_L2_ERRORS)); memio_err = csr_in32(IOADDR(A_BUS_MEM_IO_ERRORS)); } if (status & ~(1UL << 31)) print_summary(status, l2_err, memio_err); else printk("Bus watcher indicates no error\n"); } static int bw_print_buffer(char *page, struct bw_stats_struct *stats) { int len; len = sprintf(page, "SiByte Bus Watcher statistics\n"); len += sprintf(page+len, "-----------------------------\n"); len += sprintf(page+len, "L2-d-cor %8ld\nL2-d-bad %8ld\n", stats->l2_cor_d, stats->l2_bad_d); len += sprintf(page+len, "L2-t-cor %8ld\nL2-t-bad %8ld\n", stats->l2_cor_t, stats->l2_bad_t); len += sprintf(page+len, "MC-d-cor %8ld\nMC-d-bad %8ld\n", stats->mem_cor_d, stats->mem_bad_d); len += sprintf(page+len, "IO-err %8ld\n", stats->bus_error); len += sprintf(page+len, "\nLast recorded signature:\n"); len += sprintf(page+len, "Request %02x from %d, answered by %d with Dcode %d\n", (unsigned int)(G_SCD_BERR_TID(stats->status) & 0x3f), (int)(G_SCD_BERR_TID(stats->status) >> 6), (int)G_SCD_BERR_RID(stats->status), (int)G_SCD_BERR_DCODE(stats->status)); /* XXXKW indicate multiple errors between printings, or stats collection (or both)? */ if (stats->status & M_SCD_BERR_MULTERRS) len += sprintf(page+len, "Multiple errors observed since last check.\n"); if (stats->status_printed) { len += sprintf(page+len, "(no change since last printing)\n"); } else { stats->status_printed = 1; } return len; } #ifdef CONFIG_PROC_FS /* For simplicity, I want to assume a single read is required each time */ static int bw_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data) { int len; if (off == 0) { len = bw_print_buffer(page, data); *start = page; } else { len = 0; *eof = 1; } return len; } static void create_proc_decoder(struct bw_stats_struct *stats) { struct proc_dir_entry *ent; ent = create_proc_read_entry("bus_watcher", S_IWUSR | S_IRUGO, NULL, bw_read_proc, stats); if (!ent) { printk(KERN_INFO "Unable to initialize bus_watcher /proc entry\n"); return; } } #endif /* CONFIG_PROC_FS */ /* * sibyte_bw_int - handle bus watcher interrupts and accumulate counts * * notes: possible re-entry due to multiple sources * should check/indicate saturation */ static irqreturn_t sibyte_bw_int(int irq, void *data) { struct bw_stats_struct *stats = data; unsigned long cntr; #ifdef CONFIG_SIBYTE_BW_TRACE int i; #endif #ifndef CONFIG_PROC_FS char bw_buf[1024]; #endif #ifdef CONFIG_SIBYTE_BW_TRACE csr_out32(M_SCD_TRACE_CFG_FREEZE, IOADDR(A_SCD_TRACE_CFG)); csr_out32(M_SCD_TRACE_CFG_START_READ, IOADDR(A_SCD_TRACE_CFG)); for (i=0; i<256*6; i++) printk("%016llx\n", (long long)__raw_readq(IOADDR(A_SCD_TRACE_READ))); csr_out32(M_SCD_TRACE_CFG_RESET, IOADDR(A_SCD_TRACE_CFG)); csr_out32(M_SCD_TRACE_CFG_START, IOADDR(A_SCD_TRACE_CFG)); #endif /* Destructive read, clears register and interrupt */ stats->status = csr_in32(IOADDR(A_SCD_BUS_ERR_STATUS)); stats->status_printed = 0; stats->l2_err = cntr = csr_in32(IOADDR(A_BUS_L2_ERRORS)); stats->l2_cor_d += G_SCD_L2ECC_CORR_D(cntr); stats->l2_bad_d += G_SCD_L2ECC_BAD_D(cntr); stats->l2_cor_t += G_SCD_L2ECC_CORR_T(cntr); stats->l2_bad_t += G_SCD_L2ECC_BAD_T(cntr); csr_out32(0, IOADDR(A_BUS_L2_ERRORS)); stats->memio_err = cntr = csr_in32(IOADDR(A_BUS_MEM_IO_ERRORS)); stats->mem_cor_d += G_SCD_MEM_ECC_CORR(cntr); stats->mem_bad_d += G_SCD_MEM_ECC_BAD(cntr); stats->bus_error += G_SCD_MEM_BUSERR(cntr); csr_out32(0, IOADDR(A_BUS_MEM_IO_ERRORS)); #ifndef CONFIG_PROC_FS bw_print_buffer(bw_buf, stats); printk(bw_buf); #endif return IRQ_HANDLED; } int __init sibyte_bus_watcher(void) { memset(&bw_stats, 0, sizeof(struct bw_stats_struct)); bw_stats.status_printed = 1; if (request_irq(K_INT_BAD_ECC, sibyte_bw_int, 0, "Bus watcher", &bw_stats)) { printk("Failed to register bus watcher BAD_ECC irq\n"); return -1; } if (request_irq(K_INT_COR_ECC, sibyte_bw_int, 0, "Bus watcher", &bw_stats)) { free_irq(K_INT_BAD_ECC, &bw_stats); printk("Failed to register bus watcher COR_ECC irq\n"); return -1; } if (request_irq(K_INT_IO_BUS, sibyte_bw_int, 0, "Bus watcher", &bw_stats)) { free_irq(K_INT_BAD_ECC, &bw_stats); free_irq(K_INT_COR_ECC, &bw_stats); printk("Failed to register bus watcher IO_BUS irq\n"); return -1; } #ifdef CONFIG_PROC_FS create_proc_decoder(&bw_stats); #endif #ifdef CONFIG_SIBYTE_BW_TRACE csr_out32((M_SCD_TRSEQ_ASAMPLE | M_SCD_TRSEQ_DSAMPLE | K_SCD_TRSEQ_TRIGGER_ALL), IOADDR(A_SCD_TRACE_SEQUENCE_0)); csr_out32(M_SCD_TRACE_CFG_RESET, IOADDR(A_SCD_TRACE_CFG)); csr_out32(M_SCD_TRACE_CFG_START, IOADDR(A_SCD_TRACE_CFG)); #endif return 0; } __initcall(sibyte_bus_watcher);
gpl-2.0
oppo-source/Find7-5.0-kernel-source
net/rfkill/input.c
5155
9048
/* * Input layer to RF Kill interface connector * * Copyright (c) 2007 Dmitry Torokhov * Copyright 2009 Johannes Berg <johannes@sipsolutions.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. * * If you ever run into a situation in which you have a SW_ type rfkill * input device, then you can revive code that was removed in the patch * "rfkill-input: remove unused code". */ #include <linux/input.h> #include <linux/slab.h> #include <linux/moduleparam.h> #include <linux/workqueue.h> #include <linux/init.h> #include <linux/rfkill.h> #include <linux/sched.h> #include "rfkill.h" enum rfkill_input_master_mode { RFKILL_INPUT_MASTER_UNLOCK = 0, RFKILL_INPUT_MASTER_RESTORE = 1, RFKILL_INPUT_MASTER_UNBLOCKALL = 2, NUM_RFKILL_INPUT_MASTER_MODES }; /* Delay (in ms) between consecutive switch ops */ #define RFKILL_OPS_DELAY 200 static enum rfkill_input_master_mode rfkill_master_switch_mode = RFKILL_INPUT_MASTER_UNBLOCKALL; module_param_named(master_switch_mode, rfkill_master_switch_mode, uint, 0); MODULE_PARM_DESC(master_switch_mode, "SW_RFKILL_ALL ON should: 0=do nothing (only unlock); 1=restore; 2=unblock all"); static spinlock_t rfkill_op_lock; static bool rfkill_op_pending; static unsigned long rfkill_sw_pending[BITS_TO_LONGS(NUM_RFKILL_TYPES)]; static unsigned long rfkill_sw_state[BITS_TO_LONGS(NUM_RFKILL_TYPES)]; enum rfkill_sched_op { RFKILL_GLOBAL_OP_EPO = 0, RFKILL_GLOBAL_OP_RESTORE, RFKILL_GLOBAL_OP_UNLOCK, RFKILL_GLOBAL_OP_UNBLOCK, }; static enum rfkill_sched_op rfkill_master_switch_op; static enum rfkill_sched_op rfkill_op; static void __rfkill_handle_global_op(enum rfkill_sched_op op) { unsigned int i; switch (op) { case RFKILL_GLOBAL_OP_EPO: rfkill_epo(); break; case RFKILL_GLOBAL_OP_RESTORE: rfkill_restore_states(); break; case RFKILL_GLOBAL_OP_UNLOCK: rfkill_remove_epo_lock(); break; case RFKILL_GLOBAL_OP_UNBLOCK: rfkill_remove_epo_lock(); for (i = 0; i < NUM_RFKILL_TYPES; i++) rfkill_switch_all(i, false); break; default: /* memory corruption or bug, fail safely */ rfkill_epo(); WARN(1, "Unknown requested operation %d! " "rfkill Emergency Power Off activated\n", op); } } static void __rfkill_handle_normal_op(const enum rfkill_type type, const bool complement) { bool blocked; blocked = rfkill_get_global_sw_state(type); if (complement) blocked = !blocked; rfkill_switch_all(type, blocked); } static void rfkill_op_handler(struct work_struct *work) { unsigned int i; bool c; spin_lock_irq(&rfkill_op_lock); do { if (rfkill_op_pending) { enum rfkill_sched_op op = rfkill_op; rfkill_op_pending = false; memset(rfkill_sw_pending, 0, sizeof(rfkill_sw_pending)); spin_unlock_irq(&rfkill_op_lock); __rfkill_handle_global_op(op); spin_lock_irq(&rfkill_op_lock); /* * handle global ops first -- during unlocked period * we might have gotten a new global op. */ if (rfkill_op_pending) continue; } if (rfkill_is_epo_lock_active()) continue; for (i = 0; i < NUM_RFKILL_TYPES; i++) { if (__test_and_clear_bit(i, rfkill_sw_pending)) { c = __test_and_clear_bit(i, rfkill_sw_state); spin_unlock_irq(&rfkill_op_lock); __rfkill_handle_normal_op(i, c); spin_lock_irq(&rfkill_op_lock); } } } while (rfkill_op_pending); spin_unlock_irq(&rfkill_op_lock); } static DECLARE_DELAYED_WORK(rfkill_op_work, rfkill_op_handler); static unsigned long rfkill_last_scheduled; static unsigned long rfkill_ratelimit(const unsigned long last) { const unsigned long delay = msecs_to_jiffies(RFKILL_OPS_DELAY); return time_after(jiffies, last + delay) ? 0 : delay; } static void rfkill_schedule_ratelimited(void) { if (delayed_work_pending(&rfkill_op_work)) return; schedule_delayed_work(&rfkill_op_work, rfkill_ratelimit(rfkill_last_scheduled)); rfkill_last_scheduled = jiffies; } static void rfkill_schedule_global_op(enum rfkill_sched_op op) { unsigned long flags; spin_lock_irqsave(&rfkill_op_lock, flags); rfkill_op = op; rfkill_op_pending = true; if (op == RFKILL_GLOBAL_OP_EPO && !rfkill_is_epo_lock_active()) { /* bypass the limiter for EPO */ cancel_delayed_work(&rfkill_op_work); schedule_delayed_work(&rfkill_op_work, 0); rfkill_last_scheduled = jiffies; } else rfkill_schedule_ratelimited(); spin_unlock_irqrestore(&rfkill_op_lock, flags); } static void rfkill_schedule_toggle(enum rfkill_type type) { unsigned long flags; if (rfkill_is_epo_lock_active()) return; spin_lock_irqsave(&rfkill_op_lock, flags); if (!rfkill_op_pending) { __set_bit(type, rfkill_sw_pending); __change_bit(type, rfkill_sw_state); rfkill_schedule_ratelimited(); } spin_unlock_irqrestore(&rfkill_op_lock, flags); } static void rfkill_schedule_evsw_rfkillall(int state) { if (state) rfkill_schedule_global_op(rfkill_master_switch_op); else rfkill_schedule_global_op(RFKILL_GLOBAL_OP_EPO); } static void rfkill_event(struct input_handle *handle, unsigned int type, unsigned int code, int data) { if (type == EV_KEY && data == 1) { switch (code) { case KEY_WLAN: rfkill_schedule_toggle(RFKILL_TYPE_WLAN); break; case KEY_BLUETOOTH: rfkill_schedule_toggle(RFKILL_TYPE_BLUETOOTH); break; case KEY_UWB: rfkill_schedule_toggle(RFKILL_TYPE_UWB); break; case KEY_WIMAX: rfkill_schedule_toggle(RFKILL_TYPE_WIMAX); break; case KEY_RFKILL: rfkill_schedule_toggle(RFKILL_TYPE_ALL); break; } } else if (type == EV_SW && code == SW_RFKILL_ALL) rfkill_schedule_evsw_rfkillall(data); } static int rfkill_connect(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id) { struct input_handle *handle; int error; handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL); if (!handle) return -ENOMEM; handle->dev = dev; handle->handler = handler; handle->name = "rfkill"; /* causes rfkill_start() to be called */ error = input_register_handle(handle); if (error) goto err_free_handle; error = input_open_device(handle); if (error) goto err_unregister_handle; return 0; err_unregister_handle: input_unregister_handle(handle); err_free_handle: kfree(handle); return error; } static void rfkill_start(struct input_handle *handle) { /* * Take event_lock to guard against configuration changes, we * should be able to deal with concurrency with rfkill_event() * just fine (which event_lock will also avoid). */ spin_lock_irq(&handle->dev->event_lock); if (test_bit(EV_SW, handle->dev->evbit) && test_bit(SW_RFKILL_ALL, handle->dev->swbit)) rfkill_schedule_evsw_rfkillall(test_bit(SW_RFKILL_ALL, handle->dev->sw)); spin_unlock_irq(&handle->dev->event_lock); } static void rfkill_disconnect(struct input_handle *handle) { input_close_device(handle); input_unregister_handle(handle); kfree(handle); } static const struct input_device_id rfkill_ids[] = { { .flags = INPUT_DEVICE_ID_MATCH_EVBIT | INPUT_DEVICE_ID_MATCH_KEYBIT, .evbit = { BIT_MASK(EV_KEY) }, .keybit = { [BIT_WORD(KEY_WLAN)] = BIT_MASK(KEY_WLAN) }, }, { .flags = INPUT_DEVICE_ID_MATCH_EVBIT | INPUT_DEVICE_ID_MATCH_KEYBIT, .evbit = { BIT_MASK(EV_KEY) }, .keybit = { [BIT_WORD(KEY_BLUETOOTH)] = BIT_MASK(KEY_BLUETOOTH) }, }, { .flags = INPUT_DEVICE_ID_MATCH_EVBIT | INPUT_DEVICE_ID_MATCH_KEYBIT, .evbit = { BIT_MASK(EV_KEY) }, .keybit = { [BIT_WORD(KEY_UWB)] = BIT_MASK(KEY_UWB) }, }, { .flags = INPUT_DEVICE_ID_MATCH_EVBIT | INPUT_DEVICE_ID_MATCH_KEYBIT, .evbit = { BIT_MASK(EV_KEY) }, .keybit = { [BIT_WORD(KEY_WIMAX)] = BIT_MASK(KEY_WIMAX) }, }, { .flags = INPUT_DEVICE_ID_MATCH_EVBIT | INPUT_DEVICE_ID_MATCH_KEYBIT, .evbit = { BIT_MASK(EV_KEY) }, .keybit = { [BIT_WORD(KEY_RFKILL)] = BIT_MASK(KEY_RFKILL) }, }, { .flags = INPUT_DEVICE_ID_MATCH_EVBIT | INPUT_DEVICE_ID_MATCH_SWBIT, .evbit = { BIT(EV_SW) }, .swbit = { [BIT_WORD(SW_RFKILL_ALL)] = BIT_MASK(SW_RFKILL_ALL) }, }, { } }; static struct input_handler rfkill_handler = { .name = "rfkill", .event = rfkill_event, .connect = rfkill_connect, .start = rfkill_start, .disconnect = rfkill_disconnect, .id_table = rfkill_ids, }; int __init rfkill_handler_init(void) { switch (rfkill_master_switch_mode) { case RFKILL_INPUT_MASTER_UNBLOCKALL: rfkill_master_switch_op = RFKILL_GLOBAL_OP_UNBLOCK; break; case RFKILL_INPUT_MASTER_RESTORE: rfkill_master_switch_op = RFKILL_GLOBAL_OP_RESTORE; break; case RFKILL_INPUT_MASTER_UNLOCK: rfkill_master_switch_op = RFKILL_GLOBAL_OP_UNLOCK; break; default: return -EINVAL; } spin_lock_init(&rfkill_op_lock); /* Avoid delay at first schedule */ rfkill_last_scheduled = jiffies - msecs_to_jiffies(RFKILL_OPS_DELAY) - 1; return input_register_handler(&rfkill_handler); } void __exit rfkill_handler_exit(void) { input_unregister_handler(&rfkill_handler); cancel_delayed_work_sync(&rfkill_op_work); }
gpl-2.0
weevergh/android_kernel_lenovo_kiton
sound/soc/samsung/s3c-i2s-v2.c
5411
18057
/* sound/soc/samsung/s3c-i2c-v2.c * * ALSA Soc Audio Layer - I2S core for newer Samsung SoCs. * * Copyright (c) 2006 Wolfson Microelectronics PLC. * Graeme Gregory graeme.gregory@wolfsonmicro.com * linux@wolfsonmicro.com * * Copyright (c) 2008, 2007, 2004-2005 Simtec Electronics * http://armlinux.simtec.co.uk/ * Ben Dooks <ben@simtec.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. */ #include <linux/module.h> #include <linux/delay.h> #include <linux/clk.h> #include <linux/io.h> #include <sound/soc.h> #include <sound/pcm_params.h> #include <mach/dma.h> #include "regs-i2s-v2.h" #include "s3c-i2s-v2.h" #include "dma.h" #undef S3C_IIS_V2_SUPPORTED #if defined(CONFIG_CPU_S3C2412) || defined(CONFIG_CPU_S3C2413) \ || defined(CONFIG_CPU_S5PV210) #define S3C_IIS_V2_SUPPORTED #endif #ifdef CONFIG_PLAT_S3C64XX #define S3C_IIS_V2_SUPPORTED #endif #ifndef S3C_IIS_V2_SUPPORTED #error Unsupported CPU model #endif #define S3C2412_I2S_DEBUG_CON 0 static inline struct s3c_i2sv2_info *to_info(struct snd_soc_dai *cpu_dai) { return snd_soc_dai_get_drvdata(cpu_dai); } #define bit_set(v, b) (((v) & (b)) ? 1 : 0) #if S3C2412_I2S_DEBUG_CON static void dbg_showcon(const char *fn, u32 con) { printk(KERN_DEBUG "%s: LRI=%d, TXFEMPT=%d, RXFEMPT=%d, TXFFULL=%d, RXFFULL=%d\n", fn, bit_set(con, S3C2412_IISCON_LRINDEX), bit_set(con, S3C2412_IISCON_TXFIFO_EMPTY), bit_set(con, S3C2412_IISCON_RXFIFO_EMPTY), bit_set(con, S3C2412_IISCON_TXFIFO_FULL), bit_set(con, S3C2412_IISCON_RXFIFO_FULL)); printk(KERN_DEBUG "%s: PAUSE: TXDMA=%d, RXDMA=%d, TXCH=%d, RXCH=%d\n", fn, bit_set(con, S3C2412_IISCON_TXDMA_PAUSE), bit_set(con, S3C2412_IISCON_RXDMA_PAUSE), bit_set(con, S3C2412_IISCON_TXCH_PAUSE), bit_set(con, S3C2412_IISCON_RXCH_PAUSE)); printk(KERN_DEBUG "%s: ACTIVE: TXDMA=%d, RXDMA=%d, IIS=%d\n", fn, bit_set(con, S3C2412_IISCON_TXDMA_ACTIVE), bit_set(con, S3C2412_IISCON_RXDMA_ACTIVE), bit_set(con, S3C2412_IISCON_IIS_ACTIVE)); } #else static inline void dbg_showcon(const char *fn, u32 con) { } #endif /* Turn on or off the transmission path. */ static void s3c2412_snd_txctrl(struct s3c_i2sv2_info *i2s, int on) { void __iomem *regs = i2s->regs; u32 fic, con, mod; pr_debug("%s(%d)\n", __func__, on); fic = readl(regs + S3C2412_IISFIC); con = readl(regs + S3C2412_IISCON); mod = readl(regs + S3C2412_IISMOD); pr_debug("%s: IIS: CON=%x MOD=%x FIC=%x\n", __func__, con, mod, fic); if (on) { con |= S3C2412_IISCON_TXDMA_ACTIVE | S3C2412_IISCON_IIS_ACTIVE; con &= ~S3C2412_IISCON_TXDMA_PAUSE; con &= ~S3C2412_IISCON_TXCH_PAUSE; switch (mod & S3C2412_IISMOD_MODE_MASK) { case S3C2412_IISMOD_MODE_TXONLY: case S3C2412_IISMOD_MODE_TXRX: /* do nothing, we are in the right mode */ break; case S3C2412_IISMOD_MODE_RXONLY: mod &= ~S3C2412_IISMOD_MODE_MASK; mod |= S3C2412_IISMOD_MODE_TXRX; break; default: dev_err(i2s->dev, "TXEN: Invalid MODE %x in IISMOD\n", mod & S3C2412_IISMOD_MODE_MASK); break; } writel(con, regs + S3C2412_IISCON); writel(mod, regs + S3C2412_IISMOD); } else { /* Note, we do not have any indication that the FIFO problems * tha the S3C2410/2440 had apply here, so we should be able * to disable the DMA and TX without resetting the FIFOS. */ con |= S3C2412_IISCON_TXDMA_PAUSE; con |= S3C2412_IISCON_TXCH_PAUSE; con &= ~S3C2412_IISCON_TXDMA_ACTIVE; switch (mod & S3C2412_IISMOD_MODE_MASK) { case S3C2412_IISMOD_MODE_TXRX: mod &= ~S3C2412_IISMOD_MODE_MASK; mod |= S3C2412_IISMOD_MODE_RXONLY; break; case S3C2412_IISMOD_MODE_TXONLY: mod &= ~S3C2412_IISMOD_MODE_MASK; con &= ~S3C2412_IISCON_IIS_ACTIVE; break; default: dev_err(i2s->dev, "TXDIS: Invalid MODE %x in IISMOD\n", mod & S3C2412_IISMOD_MODE_MASK); break; } writel(mod, regs + S3C2412_IISMOD); writel(con, regs + S3C2412_IISCON); } fic = readl(regs + S3C2412_IISFIC); dbg_showcon(__func__, con); pr_debug("%s: IIS: CON=%x MOD=%x FIC=%x\n", __func__, con, mod, fic); } static void s3c2412_snd_rxctrl(struct s3c_i2sv2_info *i2s, int on) { void __iomem *regs = i2s->regs; u32 fic, con, mod; pr_debug("%s(%d)\n", __func__, on); fic = readl(regs + S3C2412_IISFIC); con = readl(regs + S3C2412_IISCON); mod = readl(regs + S3C2412_IISMOD); pr_debug("%s: IIS: CON=%x MOD=%x FIC=%x\n", __func__, con, mod, fic); if (on) { con |= S3C2412_IISCON_RXDMA_ACTIVE | S3C2412_IISCON_IIS_ACTIVE; con &= ~S3C2412_IISCON_RXDMA_PAUSE; con &= ~S3C2412_IISCON_RXCH_PAUSE; switch (mod & S3C2412_IISMOD_MODE_MASK) { case S3C2412_IISMOD_MODE_TXRX: case S3C2412_IISMOD_MODE_RXONLY: /* do nothing, we are in the right mode */ break; case S3C2412_IISMOD_MODE_TXONLY: mod &= ~S3C2412_IISMOD_MODE_MASK; mod |= S3C2412_IISMOD_MODE_TXRX; break; default: dev_err(i2s->dev, "RXEN: Invalid MODE %x in IISMOD\n", mod & S3C2412_IISMOD_MODE_MASK); } writel(mod, regs + S3C2412_IISMOD); writel(con, regs + S3C2412_IISCON); } else { /* See txctrl notes on FIFOs. */ con &= ~S3C2412_IISCON_RXDMA_ACTIVE; con |= S3C2412_IISCON_RXDMA_PAUSE; con |= S3C2412_IISCON_RXCH_PAUSE; switch (mod & S3C2412_IISMOD_MODE_MASK) { case S3C2412_IISMOD_MODE_RXONLY: con &= ~S3C2412_IISCON_IIS_ACTIVE; mod &= ~S3C2412_IISMOD_MODE_MASK; break; case S3C2412_IISMOD_MODE_TXRX: mod &= ~S3C2412_IISMOD_MODE_MASK; mod |= S3C2412_IISMOD_MODE_TXONLY; break; default: dev_err(i2s->dev, "RXDIS: Invalid MODE %x in IISMOD\n", mod & S3C2412_IISMOD_MODE_MASK); } writel(con, regs + S3C2412_IISCON); writel(mod, regs + S3C2412_IISMOD); } fic = readl(regs + S3C2412_IISFIC); pr_debug("%s: IIS: CON=%x MOD=%x FIC=%x\n", __func__, con, mod, fic); } #define msecs_to_loops(t) (loops_per_jiffy / 1000 * HZ * t) /* * Wait for the LR signal to allow synchronisation to the L/R clock * from the codec. May only be needed for slave mode. */ static int s3c2412_snd_lrsync(struct s3c_i2sv2_info *i2s) { u32 iiscon; unsigned long loops = msecs_to_loops(5); pr_debug("Entered %s\n", __func__); while (--loops) { iiscon = readl(i2s->regs + S3C2412_IISCON); if (iiscon & S3C2412_IISCON_LRINDEX) break; cpu_relax(); } if (!loops) { printk(KERN_ERR "%s: timeout\n", __func__); return -ETIMEDOUT; } return 0; } /* * Set S3C2412 I2S DAI format */ static int s3c2412_i2s_set_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt) { struct s3c_i2sv2_info *i2s = to_info(cpu_dai); u32 iismod; pr_debug("Entered %s\n", __func__); iismod = readl(i2s->regs + S3C2412_IISMOD); pr_debug("hw_params r: IISMOD: %x \n", iismod); switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBM_CFM: i2s->master = 0; iismod |= S3C2412_IISMOD_SLAVE; break; case SND_SOC_DAIFMT_CBS_CFS: i2s->master = 1; iismod &= ~S3C2412_IISMOD_SLAVE; break; default: pr_err("unknwon master/slave format\n"); return -EINVAL; } iismod &= ~S3C2412_IISMOD_SDF_MASK; switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_RIGHT_J: iismod |= S3C2412_IISMOD_LR_RLOW; iismod |= S3C2412_IISMOD_SDF_MSB; break; case SND_SOC_DAIFMT_LEFT_J: iismod |= S3C2412_IISMOD_LR_RLOW; iismod |= S3C2412_IISMOD_SDF_LSB; break; case SND_SOC_DAIFMT_I2S: iismod &= ~S3C2412_IISMOD_LR_RLOW; iismod |= S3C2412_IISMOD_SDF_IIS; break; default: pr_err("Unknown data format\n"); return -EINVAL; } writel(iismod, i2s->regs + S3C2412_IISMOD); pr_debug("hw_params w: IISMOD: %x \n", iismod); return 0; } static int s3c_i2sv2_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct s3c_i2sv2_info *i2s = to_info(dai); struct s3c_dma_params *dma_data; u32 iismod; pr_debug("Entered %s\n", __func__); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) dma_data = i2s->dma_playback; else dma_data = i2s->dma_capture; snd_soc_dai_set_dma_data(dai, substream, dma_data); /* Working copies of register */ iismod = readl(i2s->regs + S3C2412_IISMOD); pr_debug("%s: r: IISMOD: %x\n", __func__, iismod); iismod &= ~S3C64XX_IISMOD_BLC_MASK; /* Sample size */ switch (params_format(params)) { case SNDRV_PCM_FORMAT_S8: iismod |= S3C64XX_IISMOD_BLC_8BIT; break; case SNDRV_PCM_FORMAT_S16_LE: break; case SNDRV_PCM_FORMAT_S24_LE: iismod |= S3C64XX_IISMOD_BLC_24BIT; break; } writel(iismod, i2s->regs + S3C2412_IISMOD); pr_debug("%s: w: IISMOD: %x\n", __func__, iismod); return 0; } static int s3c_i2sv2_set_sysclk(struct snd_soc_dai *cpu_dai, int clk_id, unsigned int freq, int dir) { struct s3c_i2sv2_info *i2s = to_info(cpu_dai); u32 iismod = readl(i2s->regs + S3C2412_IISMOD); pr_debug("Entered %s\n", __func__); pr_debug("%s r: IISMOD: %x\n", __func__, iismod); switch (clk_id) { case S3C_I2SV2_CLKSRC_PCLK: iismod &= ~S3C2412_IISMOD_IMS_SYSMUX; break; case S3C_I2SV2_CLKSRC_AUDIOBUS: iismod |= S3C2412_IISMOD_IMS_SYSMUX; break; case S3C_I2SV2_CLKSRC_CDCLK: /* Error if controller doesn't have the CDCLKCON bit */ if (!(i2s->feature & S3C_FEATURE_CDCLKCON)) return -EINVAL; switch (dir) { case SND_SOC_CLOCK_IN: iismod |= S3C64XX_IISMOD_CDCLKCON; break; case SND_SOC_CLOCK_OUT: iismod &= ~S3C64XX_IISMOD_CDCLKCON; break; default: return -EINVAL; } break; default: return -EINVAL; } writel(iismod, i2s->regs + S3C2412_IISMOD); pr_debug("%s w: IISMOD: %x\n", __func__, iismod); return 0; } static int s3c2412_i2s_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct s3c_i2sv2_info *i2s = to_info(rtd->cpu_dai); int capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE); unsigned long irqs; int ret = 0; struct s3c_dma_params *dma_data = snd_soc_dai_get_dma_data(rtd->cpu_dai, substream); pr_debug("Entered %s\n", __func__); switch (cmd) { case SNDRV_PCM_TRIGGER_START: /* On start, ensure that the FIFOs are cleared and reset. */ writel(capture ? S3C2412_IISFIC_RXFLUSH : S3C2412_IISFIC_TXFLUSH, i2s->regs + S3C2412_IISFIC); /* clear again, just in case */ writel(0x0, i2s->regs + S3C2412_IISFIC); case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: if (!i2s->master) { ret = s3c2412_snd_lrsync(i2s); if (ret) goto exit_err; } local_irq_save(irqs); if (capture) s3c2412_snd_rxctrl(i2s, 1); else s3c2412_snd_txctrl(i2s, 1); local_irq_restore(irqs); /* * Load the next buffer to DMA to meet the reqirement * of the auto reload mechanism of S3C24XX. * This call won't bother S3C64XX. */ s3c2410_dma_ctrl(dma_data->channel, S3C2410_DMAOP_STARTED); break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: local_irq_save(irqs); if (capture) s3c2412_snd_rxctrl(i2s, 0); else s3c2412_snd_txctrl(i2s, 0); local_irq_restore(irqs); break; default: ret = -EINVAL; break; } exit_err: return ret; } /* * Set S3C2412 Clock dividers */ static int s3c2412_i2s_set_clkdiv(struct snd_soc_dai *cpu_dai, int div_id, int div) { struct s3c_i2sv2_info *i2s = to_info(cpu_dai); u32 reg; pr_debug("%s(%p, %d, %d)\n", __func__, cpu_dai, div_id, div); switch (div_id) { case S3C_I2SV2_DIV_BCLK: switch (div) { case 16: div = S3C2412_IISMOD_BCLK_16FS; break; case 32: div = S3C2412_IISMOD_BCLK_32FS; break; case 24: div = S3C2412_IISMOD_BCLK_24FS; break; case 48: div = S3C2412_IISMOD_BCLK_48FS; break; default: return -EINVAL; } reg = readl(i2s->regs + S3C2412_IISMOD); reg &= ~S3C2412_IISMOD_BCLK_MASK; writel(reg | div, i2s->regs + S3C2412_IISMOD); pr_debug("%s: MOD=%08x\n", __func__, readl(i2s->regs + S3C2412_IISMOD)); break; case S3C_I2SV2_DIV_RCLK: switch (div) { case 256: div = S3C2412_IISMOD_RCLK_256FS; break; case 384: div = S3C2412_IISMOD_RCLK_384FS; break; case 512: div = S3C2412_IISMOD_RCLK_512FS; break; case 768: div = S3C2412_IISMOD_RCLK_768FS; break; default: return -EINVAL; } reg = readl(i2s->regs + S3C2412_IISMOD); reg &= ~S3C2412_IISMOD_RCLK_MASK; writel(reg | div, i2s->regs + S3C2412_IISMOD); pr_debug("%s: MOD=%08x\n", __func__, readl(i2s->regs + S3C2412_IISMOD)); break; case S3C_I2SV2_DIV_PRESCALER: if (div >= 0) { writel((div << 8) | S3C2412_IISPSR_PSREN, i2s->regs + S3C2412_IISPSR); } else { writel(0x0, i2s->regs + S3C2412_IISPSR); } pr_debug("%s: PSR=%08x\n", __func__, readl(i2s->regs + S3C2412_IISPSR)); break; default: return -EINVAL; } return 0; } static snd_pcm_sframes_t s3c2412_i2s_delay(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct s3c_i2sv2_info *i2s = to_info(dai); u32 reg = readl(i2s->regs + S3C2412_IISFIC); snd_pcm_sframes_t delay; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) delay = S3C2412_IISFIC_TXCOUNT(reg); else delay = S3C2412_IISFIC_RXCOUNT(reg); return delay; } struct clk *s3c_i2sv2_get_clock(struct snd_soc_dai *cpu_dai) { struct s3c_i2sv2_info *i2s = to_info(cpu_dai); u32 iismod = readl(i2s->regs + S3C2412_IISMOD); if (iismod & S3C2412_IISMOD_IMS_SYSMUX) return i2s->iis_cclk; else return i2s->iis_pclk; } EXPORT_SYMBOL_GPL(s3c_i2sv2_get_clock); /* default table of all avaialable root fs divisors */ static unsigned int iis_fs_tab[] = { 256, 512, 384, 768 }; int s3c_i2sv2_iis_calc_rate(struct s3c_i2sv2_rate_calc *info, unsigned int *fstab, unsigned int rate, struct clk *clk) { unsigned long clkrate = clk_get_rate(clk); unsigned int div; unsigned int fsclk; unsigned int actual; unsigned int fs; unsigned int fsdiv; signed int deviation = 0; unsigned int best_fs = 0; unsigned int best_div = 0; unsigned int best_rate = 0; unsigned int best_deviation = INT_MAX; pr_debug("Input clock rate %ldHz\n", clkrate); if (fstab == NULL) fstab = iis_fs_tab; for (fs = 0; fs < ARRAY_SIZE(iis_fs_tab); fs++) { fsdiv = iis_fs_tab[fs]; fsclk = clkrate / fsdiv; div = fsclk / rate; if ((fsclk % rate) > (rate / 2)) div++; if (div <= 1) continue; actual = clkrate / (fsdiv * div); deviation = actual - rate; printk(KERN_DEBUG "%ufs: div %u => result %u, deviation %d\n", fsdiv, div, actual, deviation); deviation = abs(deviation); if (deviation < best_deviation) { best_fs = fsdiv; best_div = div; best_rate = actual; best_deviation = deviation; } if (deviation == 0) break; } printk(KERN_DEBUG "best: fs=%u, div=%u, rate=%u\n", best_fs, best_div, best_rate); info->fs_div = best_fs; info->clk_div = best_div; return 0; } EXPORT_SYMBOL_GPL(s3c_i2sv2_iis_calc_rate); int s3c_i2sv2_probe(struct snd_soc_dai *dai, struct s3c_i2sv2_info *i2s, unsigned long base) { struct device *dev = dai->dev; unsigned int iismod; i2s->dev = dev; /* record our i2s structure for later use in the callbacks */ snd_soc_dai_set_drvdata(dai, i2s); i2s->regs = ioremap(base, 0x100); if (i2s->regs == NULL) { dev_err(dev, "cannot ioremap registers\n"); return -ENXIO; } i2s->iis_pclk = clk_get(dev, "iis"); if (IS_ERR(i2s->iis_pclk)) { dev_err(dev, "failed to get iis_clock\n"); iounmap(i2s->regs); return -ENOENT; } clk_enable(i2s->iis_pclk); /* Mark ourselves as in TXRX mode so we can run through our cleanup * process without warnings. */ iismod = readl(i2s->regs + S3C2412_IISMOD); iismod |= S3C2412_IISMOD_MODE_TXRX; writel(iismod, i2s->regs + S3C2412_IISMOD); s3c2412_snd_txctrl(i2s, 0); s3c2412_snd_rxctrl(i2s, 0); return 0; } EXPORT_SYMBOL_GPL(s3c_i2sv2_probe); #ifdef CONFIG_PM static int s3c2412_i2s_suspend(struct snd_soc_dai *dai) { struct s3c_i2sv2_info *i2s = to_info(dai); u32 iismod; if (dai->active) { i2s->suspend_iismod = readl(i2s->regs + S3C2412_IISMOD); i2s->suspend_iiscon = readl(i2s->regs + S3C2412_IISCON); i2s->suspend_iispsr = readl(i2s->regs + S3C2412_IISPSR); /* some basic suspend checks */ iismod = readl(i2s->regs + S3C2412_IISMOD); if (iismod & S3C2412_IISCON_RXDMA_ACTIVE) pr_warning("%s: RXDMA active?\n", __func__); if (iismod & S3C2412_IISCON_TXDMA_ACTIVE) pr_warning("%s: TXDMA active?\n", __func__); if (iismod & S3C2412_IISCON_IIS_ACTIVE) pr_warning("%s: IIS active\n", __func__); } return 0; } static int s3c2412_i2s_resume(struct snd_soc_dai *dai) { struct s3c_i2sv2_info *i2s = to_info(dai); pr_info("dai_active %d, IISMOD %08x, IISCON %08x\n", dai->active, i2s->suspend_iismod, i2s->suspend_iiscon); if (dai->active) { writel(i2s->suspend_iiscon, i2s->regs + S3C2412_IISCON); writel(i2s->suspend_iismod, i2s->regs + S3C2412_IISMOD); writel(i2s->suspend_iispsr, i2s->regs + S3C2412_IISPSR); writel(S3C2412_IISFIC_RXFLUSH | S3C2412_IISFIC_TXFLUSH, i2s->regs + S3C2412_IISFIC); ndelay(250); writel(0x0, i2s->regs + S3C2412_IISFIC); } return 0; } #else #define s3c2412_i2s_suspend NULL #define s3c2412_i2s_resume NULL #endif int s3c_i2sv2_register_dai(struct device *dev, int id, struct snd_soc_dai_driver *drv) { struct snd_soc_dai_ops *ops = drv->ops; ops->trigger = s3c2412_i2s_trigger; if (!ops->hw_params) ops->hw_params = s3c_i2sv2_hw_params; ops->set_fmt = s3c2412_i2s_set_fmt; ops->set_clkdiv = s3c2412_i2s_set_clkdiv; ops->set_sysclk = s3c_i2sv2_set_sysclk; /* Allow overriding by (for example) IISv4 */ if (!ops->delay) ops->delay = s3c2412_i2s_delay; drv->suspend = s3c2412_i2s_suspend; drv->resume = s3c2412_i2s_resume; return snd_soc_register_dai(dev, drv); } EXPORT_SYMBOL_GPL(s3c_i2sv2_register_dai); MODULE_LICENSE("GPL");
gpl-2.0
TEAM-RAZOR-DEVICES/kernel_cyanogen_msm8916
drivers/misc/ds1682.c
7715
7013
/* * Dallas Semiconductor DS1682 Elapsed Time Recorder device driver * * Written by: Grant Likely <grant.likely@secretlab.ca> * * Copyright (C) 2007 Secret Lab Technologies Ltd. * * 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. */ /* * The DS1682 elapsed timer recorder is a simple device that implements * one elapsed time counter, one event counter, an alarm signal and 10 * bytes of general purpose EEPROM. * * This driver provides access to the DS1682 counters and user data via * the sysfs. The following attributes are added to the device node: * elapsed_time (u32): Total elapsed event time in ms resolution * alarm_time (u32): When elapsed time exceeds the value in alarm_time, * then the alarm pin is asserted. * event_count (u16): number of times the event pin has gone low. * eeprom (u8[10]): general purpose EEPROM * * Counter registers and user data are both read/write unless the device * has been write protected. This driver does not support turning off write * protection. Once write protection is turned on, it is impossible to * turn it off again, so I have left the feature out of this driver to avoid * accidental enabling, but it is trivial to add write protect support. * */ #include <linux/module.h> #include <linux/init.h> #include <linux/i2c.h> #include <linux/string.h> #include <linux/list.h> #include <linux/sysfs.h> #include <linux/ctype.h> #include <linux/hwmon-sysfs.h> /* Device registers */ #define DS1682_REG_CONFIG 0x00 #define DS1682_REG_ALARM 0x01 #define DS1682_REG_ELAPSED 0x05 #define DS1682_REG_EVT_CNTR 0x09 #define DS1682_REG_EEPROM 0x0b #define DS1682_REG_RESET 0x1d #define DS1682_REG_WRITE_DISABLE 0x1e #define DS1682_REG_WRITE_MEM_DISABLE 0x1f #define DS1682_EEPROM_SIZE 10 /* * Generic counter attributes */ static ssize_t ds1682_show(struct device *dev, struct device_attribute *attr, char *buf) { struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr); struct i2c_client *client = to_i2c_client(dev); __le32 val = 0; int rc; dev_dbg(dev, "ds1682_show() called on %s\n", attr->attr.name); /* Read the register */ rc = i2c_smbus_read_i2c_block_data(client, sattr->index, sattr->nr, (u8 *) & val); if (rc < 0) return -EIO; /* Special case: the 32 bit regs are time values with 1/4s * resolution, scale them up to milliseconds */ if (sattr->nr == 4) return sprintf(buf, "%llu\n", ((unsigned long long)le32_to_cpu(val)) * 250); /* Format the output string and return # of bytes */ return sprintf(buf, "%li\n", (long)le32_to_cpu(val)); } static ssize_t ds1682_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr); struct i2c_client *client = to_i2c_client(dev); char *endp; u64 val; __le32 val_le; int rc; dev_dbg(dev, "ds1682_store() called on %s\n", attr->attr.name); /* Decode input */ val = simple_strtoull(buf, &endp, 0); if (buf == endp) { dev_dbg(dev, "input string not a number\n"); return -EINVAL; } /* Special case: the 32 bit regs are time values with 1/4s * resolution, scale input down to quarter-seconds */ if (sattr->nr == 4) do_div(val, 250); /* write out the value */ val_le = cpu_to_le32(val); rc = i2c_smbus_write_i2c_block_data(client, sattr->index, sattr->nr, (u8 *) & val_le); if (rc < 0) { dev_err(dev, "register write failed; reg=0x%x, size=%i\n", sattr->index, sattr->nr); return -EIO; } return count; } /* * Simple register attributes */ static SENSOR_DEVICE_ATTR_2(elapsed_time, S_IRUGO | S_IWUSR, ds1682_show, ds1682_store, 4, DS1682_REG_ELAPSED); static SENSOR_DEVICE_ATTR_2(alarm_time, S_IRUGO | S_IWUSR, ds1682_show, ds1682_store, 4, DS1682_REG_ALARM); static SENSOR_DEVICE_ATTR_2(event_count, S_IRUGO | S_IWUSR, ds1682_show, ds1682_store, 2, DS1682_REG_EVT_CNTR); static const struct attribute_group ds1682_group = { .attrs = (struct attribute *[]) { &sensor_dev_attr_elapsed_time.dev_attr.attr, &sensor_dev_attr_alarm_time.dev_attr.attr, &sensor_dev_attr_event_count.dev_attr.attr, NULL, }, }; /* * User data attribute */ static ssize_t ds1682_eeprom_read(struct file *filp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct i2c_client *client = kobj_to_i2c_client(kobj); int rc; dev_dbg(&client->dev, "ds1682_eeprom_read(p=%p, off=%lli, c=%zi)\n", buf, off, count); if (off >= DS1682_EEPROM_SIZE) return 0; if (off + count > DS1682_EEPROM_SIZE) count = DS1682_EEPROM_SIZE - off; rc = i2c_smbus_read_i2c_block_data(client, DS1682_REG_EEPROM + off, count, buf); if (rc < 0) return -EIO; return count; } static ssize_t ds1682_eeprom_write(struct file *filp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct i2c_client *client = kobj_to_i2c_client(kobj); dev_dbg(&client->dev, "ds1682_eeprom_write(p=%p, off=%lli, c=%zi)\n", buf, off, count); if (off >= DS1682_EEPROM_SIZE) return -ENOSPC; if (off + count > DS1682_EEPROM_SIZE) count = DS1682_EEPROM_SIZE - off; /* Write out to the device */ if (i2c_smbus_write_i2c_block_data(client, DS1682_REG_EEPROM + off, count, buf) < 0) return -EIO; return count; } static struct bin_attribute ds1682_eeprom_attr = { .attr = { .name = "eeprom", .mode = S_IRUGO | S_IWUSR, }, .size = DS1682_EEPROM_SIZE, .read = ds1682_eeprom_read, .write = ds1682_eeprom_write, }; /* * Called when a ds1682 device is matched with this driver */ static int ds1682_probe(struct i2c_client *client, const struct i2c_device_id *id) { int rc; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_I2C_BLOCK)) { dev_err(&client->dev, "i2c bus does not support the ds1682\n"); rc = -ENODEV; goto exit; } rc = sysfs_create_group(&client->dev.kobj, &ds1682_group); if (rc) goto exit; rc = sysfs_create_bin_file(&client->dev.kobj, &ds1682_eeprom_attr); if (rc) goto exit_bin_attr; return 0; exit_bin_attr: sysfs_remove_group(&client->dev.kobj, &ds1682_group); exit: return rc; } static int ds1682_remove(struct i2c_client *client) { sysfs_remove_bin_file(&client->dev.kobj, &ds1682_eeprom_attr); sysfs_remove_group(&client->dev.kobj, &ds1682_group); return 0; } static const struct i2c_device_id ds1682_id[] = { { "ds1682", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, ds1682_id); static struct i2c_driver ds1682_driver = { .driver = { .name = "ds1682", }, .probe = ds1682_probe, .remove = ds1682_remove, .id_table = ds1682_id, }; module_i2c_driver(ds1682_driver); MODULE_AUTHOR("Grant Likely <grant.likely@secretlab.ca>"); MODULE_DESCRIPTION("DS1682 Elapsed Time Indicator driver"); MODULE_LICENSE("GPL");
gpl-2.0
cornus/linux-samsung
drivers/staging/tidspbridge/dynload/getsection.c
11299
12358
/* * getsection.c * * DSP-BIOS Bridge driver support functions for TI OMAP processors. * * Copyright (C) 2005-2006 Texas Instruments, Inc. * * This package 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 PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <dspbridge/getsection.h> #include "header.h" /* * Error strings */ static const char readstrm[] = { "Error reading %s from input stream" }; static const char seek[] = { "Set file position to %d failed" }; static const char isiz[] = { "Bad image packet size %d" }; static const char err_checksum[] = { "Checksum failed on %s" }; static const char err_reloc[] = { "dload_get_section unable to read" "sections containing relocation entries" }; #if BITS_PER_AU > BITS_PER_BYTE static const char err_alloc[] = { "Syms->dload_allocate( %d ) failed" }; static const char stbl[] = { "Bad string table offset " FMT_UI32 }; #endif /************************************************************** */ /********************* SUPPORT FUNCTIONS ********************** */ /************************************************************** */ #if BITS_PER_AU > BITS_PER_BYTE /************************************************************************** * Procedure unpack_sec_name * * Parameters: * dlthis Handle from dload_module_open for this module * soffset Byte offset into the string table * dst Place to store the expanded string * * Effect: * Stores a string from the string table into the destination, expanding * it in the process. Returns a pointer just past the end of the stored * string on success, or NULL on failure. * ************************************************************************ */ static char *unpack_sec_name(struct dload_state *dlthis, u32 soffset, char *dst) { u8 tmp, *src; if (soffset >= dlthis->dfile_hdr.df_scn_name_size) { dload_error(dlthis, stbl, soffset); return NULL; } src = (u8 *) dlthis->str_head + (soffset >> (LOG_BITS_PER_AU - LOG_BITS_PER_BYTE)); if (soffset & 1) *dst++ = *src++; /* only 1 character in first word */ do { tmp = *src++; *dst = (tmp >> BITS_PER_BYTE) if (!(*dst++)) break; } while ((*dst++ = tmp & BYTE_MASK)); return dst; } /************************************************************************** * Procedure expand_sec_names * * Parameters: * dlthis Handle from dload_module_open for this module * * Effect: * Allocates a buffer, unpacks and copies strings from string table into it. * Stores a pointer to the buffer into a state variable. ************************************************************************* */ static void expand_sec_names(struct dload_state *dlthis) { char *xstrings, *curr, *next; u32 xsize; u16 sec; struct ldr_section_info *shp; /* assume worst-case size requirement */ xsize = dlthis->dfile_hdr.df_max_str_len * dlthis->dfile_hdr.df_no_scns; xstrings = (char *)dlthis->mysym->dload_allocate(dlthis->mysym, xsize); if (xstrings == NULL) { dload_error(dlthis, err_alloc, xsize); return; } dlthis->xstrings = xstrings; /* For each sec, copy and expand its name */ curr = xstrings; for (sec = 0; sec < dlthis->dfile_hdr.df_no_scns; sec++) { shp = (struct ldr_section_info *)&dlthis->sect_hdrs[sec]; next = unpack_sec_name(dlthis, *(u32 *) &shp->name, curr); if (next == NULL) break; /* error */ shp->name = curr; curr = next; } } #endif /************************************************************** */ /********************* EXPORTED FUNCTIONS ********************* */ /************************************************************** */ /************************************************************************** * Procedure dload_module_open * * Parameters: * module The input stream that supplies the module image * syms Host-side malloc/free and error reporting functions. * Other methods are unused. * * Effect: * Reads header information from a dynamic loader module using the specified * stream object, and returns a handle for the module information. This * handle may be used in subsequent query calls to obtain information * contained in the module. * * Returns: * NULL if an error is encountered, otherwise a module handle for use * in subsequent operations. ************************************************************************* */ void *dload_module_open(struct dynamic_loader_stream *module, struct dynamic_loader_sym *syms) { struct dload_state *dlthis; /* internal state for this call */ unsigned *dp, sz; u32 sec_start; #if BITS_PER_AU <= BITS_PER_BYTE u16 sec; #endif /* Check that mandatory arguments are present */ if (!module || !syms) { if (syms != NULL) dload_syms_error(syms, "Required parameter is NULL"); return NULL; } dlthis = (struct dload_state *) syms->dload_allocate(syms, sizeof(struct dload_state)); if (!dlthis) { /* not enough storage */ dload_syms_error(syms, "Can't allocate module info"); return NULL; } /* clear our internal state */ dp = (unsigned *)dlthis; for (sz = sizeof(struct dload_state) / sizeof(unsigned); sz > 0; sz -= 1) *dp++ = 0; dlthis->strm = module; dlthis->mysym = syms; /* read in the doff image and store in our state variable */ dload_headers(dlthis); if (!dlthis->dload_errcount) dload_strings(dlthis, true); /* skip ahead past the unread portion of the string table */ sec_start = sizeof(struct doff_filehdr_t) + sizeof(struct doff_verify_rec_t) + BYTE_TO_HOST(DOFF_ALIGN(dlthis->dfile_hdr.df_strtab_size)); if (dlthis->strm->set_file_posn(dlthis->strm, sec_start) != 0) { dload_error(dlthis, seek, sec_start); return NULL; } if (!dlthis->dload_errcount) dload_sections(dlthis); if (dlthis->dload_errcount) { dload_module_close(dlthis); /* errors, blow off our state */ dlthis = NULL; return NULL; } #if BITS_PER_AU > BITS_PER_BYTE /* Expand all section names from the string table into the */ /* state variable, and convert section names from a relative */ /* string table offset to a pointers to the expanded string. */ expand_sec_names(dlthis); #else /* Convert section names from a relative string table offset */ /* to a pointer into the string table. */ for (sec = 0; sec < dlthis->dfile_hdr.df_no_scns; sec++) { struct ldr_section_info *shp = (struct ldr_section_info *)&dlthis->sect_hdrs[sec]; shp->name = dlthis->str_head + *(u32 *) &shp->name; } #endif return dlthis; } /*************************************************************************** * Procedure dload_get_section_info * * Parameters: * minfo Handle from dload_module_open for this module * section_name Pointer to the string name of the section desired * section_info Address of a section info structure pointer to be * initialized * * Effect: * Finds the specified section in the module information, and initializes * the provided struct ldr_section_info pointer. * * Returns: * true for success, false for section not found ************************************************************************* */ int dload_get_section_info(void *minfo, const char *section_name, const struct ldr_section_info **const section_info) { struct dload_state *dlthis; struct ldr_section_info *shp; u16 sec; dlthis = (struct dload_state *)minfo; if (!dlthis) return false; for (sec = 0; sec < dlthis->dfile_hdr.df_no_scns; sec++) { shp = (struct ldr_section_info *)&dlthis->sect_hdrs[sec]; if (strcmp(section_name, shp->name) == 0) { *section_info = shp; return true; } } return false; } #define IPH_SIZE (sizeof(struct image_packet_t) - sizeof(u32)) /************************************************************************** * Procedure dload_get_section * * Parameters: * minfo Handle from dload_module_open for this module * section_info Pointer to a section info structure for the desired * section * section_data Buffer to contain the section initialized data * * Effect: * Copies the initialized data for the specified section into the * supplied buffer. * * Returns: * true for success, false for section not found ************************************************************************* */ int dload_get_section(void *minfo, const struct ldr_section_info *section_info, void *section_data) { struct dload_state *dlthis; u32 pos; struct doff_scnhdr_t *sptr = NULL; s32 nip; struct image_packet_t ipacket; s32 ipsize; u32 checks; s8 *dest = (s8 *) section_data; dlthis = (struct dload_state *)minfo; if (!dlthis) return false; sptr = (struct doff_scnhdr_t *)section_info; if (sptr == NULL) return false; /* skip ahead to the start of the first packet */ pos = BYTE_TO_HOST(DOFF_ALIGN((u32) sptr->ds_first_pkt_offset)); if (dlthis->strm->set_file_posn(dlthis->strm, pos) != 0) { dload_error(dlthis, seek, pos); return false; } nip = sptr->ds_nipacks; while ((nip -= 1) >= 0) { /* for each packet */ /* get the fixed header bits */ if (dlthis->strm->read_buffer(dlthis->strm, &ipacket, IPH_SIZE) != IPH_SIZE) { dload_error(dlthis, readstrm, "image packet"); return false; } /* reorder the header if need be */ if (dlthis->reorder_map) dload_reorder(&ipacket, IPH_SIZE, dlthis->reorder_map); /* Now read the packet image bits. Note: round the size up to * the next multiple of 4 bytes; this is what checksum * routines want. */ ipsize = BYTE_TO_HOST(DOFF_ALIGN(ipacket.packet_size)); if (ipsize > BYTE_TO_HOST(IMAGE_PACKET_SIZE)) { dload_error(dlthis, isiz, ipsize); return false; } if (dlthis->strm->read_buffer (dlthis->strm, dest, ipsize) != ipsize) { dload_error(dlthis, readstrm, "image packet"); return false; } /* reorder the bytes if need be */ #if !defined(_BIG_ENDIAN) || (TARGET_AU_BITS > 16) if (dlthis->reorder_map) dload_reorder(dest, ipsize, dlthis->reorder_map); checks = dload_checksum(dest, ipsize); #else if (dlthis->dfile_hdr.df_byte_reshuffle != TARGET_ORDER(REORDER_MAP(BYTE_RESHUFFLE_VALUE))) { /* put image bytes in big-endian order, not PC order */ dload_reorder(dest, ipsize, TARGET_ORDER(dlthis-> dfile_hdr.df_byte_reshuffle)); } #if TARGET_AU_BITS > 8 checks = dload_reverse_checksum16(dest, ipsize); #else checks = dload_reverse_checksum(dest, ipsize); #endif #endif checks += dload_checksum(&ipacket, IPH_SIZE); /* NYI: unable to handle relocation entries here. Reloc * entries referring to fields that span the packet boundaries * may result in packets of sizes that are not multiple of * 4 bytes. Our checksum implementation works on 32-bit words * only. */ if (ipacket.num_relocs != 0) { dload_error(dlthis, err_reloc, ipsize); return false; } if (~checks) { dload_error(dlthis, err_checksum, "image packet"); return false; } /*Advance destination ptr by the size of the just-read packet */ dest += ipsize; } return true; } /*************************************************************************** * Procedure dload_module_close * * Parameters: * minfo Handle from dload_module_open for this module * * Effect: * Releases any storage associated with the module handle. On return, * the module handle is invalid. * * Returns: * Zero for success. On error, the number of errors detected is returned. * Individual errors are reported using syms->error_report(), where syms was * an argument to dload_module_open ************************************************************************* */ void dload_module_close(void *minfo) { struct dload_state *dlthis; dlthis = (struct dload_state *)minfo; if (!dlthis) return; if (dlthis->str_head) dlthis->mysym->dload_deallocate(dlthis->mysym, dlthis->str_head); if (dlthis->sect_hdrs) dlthis->mysym->dload_deallocate(dlthis->mysym, dlthis->sect_hdrs); #if BITS_PER_AU > BITS_PER_BYTE if (dlthis->xstrings) dlthis->mysym->dload_deallocate(dlthis->mysym, dlthis->xstrings); #endif dlthis->mysym->dload_deallocate(dlthis->mysym, dlthis); }
gpl-2.0
DARKCHYLDX101/GCC-UBER
libgomp/target.c
36
2997
/* Copyright (C) 2013-2014 Free Software Foundation, Inc. Contributed by Jakub Jelinek <jakub@redhat.com>. This file is part of the GNU OpenMP Library (libgomp). Libgomp is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ /* This file handles the maintainence of threads in response to team creation and termination. */ #include "libgomp.h" #include <limits.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> attribute_hidden int gomp_get_num_devices (void) { return 0; } /* Called when encountering a target directive. If DEVICE is -1, it means use device-var ICV. If it is -2 (or any other value larger than last available hw device, use host fallback. FN is address of host code, OPENMP_TARGET contains value of the __OPENMP_TARGET__ symbol in the shared library or binary that invokes GOMP_target. HOSTADDRS, SIZES and KINDS are arrays with MAPNUM entries, with addresses of the host objects, sizes of the host objects (resp. for pointer kind pointer bias and assumed sizeof (void *) size) and kinds. */ void GOMP_target (int device, void (*fn) (void *), const void *openmp_target, size_t mapnum, void **hostaddrs, size_t *sizes, unsigned char *kinds) { /* Host fallback. */ struct gomp_thread old_thr, *thr = gomp_thread (); old_thr = *thr; memset (thr, '\0', sizeof (*thr)); if (gomp_places_list) { thr->place = old_thr.place; thr->ts.place_partition_len = gomp_places_list_len; } fn (hostaddrs); gomp_free_thread (thr); *thr = old_thr; } void GOMP_target_data (int device, const void *openmp_target, size_t mapnum, void **hostaddrs, size_t *sizes, unsigned char *kinds) { } void GOMP_target_end_data (void) { } void GOMP_target_update (int device, const void *openmp_target, size_t mapnum, void **hostaddrs, size_t *sizes, unsigned char *kinds) { } void GOMP_teams (unsigned int num_teams, unsigned int thread_limit) { if (thread_limit) { struct gomp_task_icv *icv = gomp_icv (true); icv->thread_limit_var = thread_limit > INT_MAX ? UINT_MAX : thread_limit; } (void) num_teams; }
gpl-2.0
davidmueller13/L900_3.9_Experiment
drivers/net/can/mcp251x.c
36
32749
/* * CAN bus driver for Microchip 251x CAN Controller with SPI Interface * * MCP2510 support and bug fixes by Christian Pellegrin * <chripell@evolware.org> * * Copyright 2009 Christian Pellegrin EVOL S.r.l. * * Copyright 2007 Raymarine UK, Ltd. All Rights Reserved. * Written under contract by: * Chris Elston, Katalix Systems, Ltd. * * Based on Microchip MCP251x CAN controller driver written by * David Vrabel, Copyright 2006 Arcom Control Systems Ltd. * * Based on CAN bus driver for the CCAN controller written by * - Sascha Hauer, Marc Kleine-Budde, Pengutronix * - Simon Kallweit, intefo AG * Copyright 2007 * * This program is free software; you can redistribute it and/or modify * it under the terms of the 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * * Your platform definition file should specify something like: * * static struct mcp251x_platform_data mcp251x_info = { * .oscillator_frequency = 8000000, * .board_specific_setup = &mcp251x_setup, * .power_enable = mcp251x_power_enable, * .transceiver_enable = NULL, * }; * * static struct spi_board_info spi_board_info[] = { * { * .modalias = "mcp2510", * // or "mcp2515" depending on your controller * .platform_data = &mcp251x_info, * .irq = IRQ_EINT13, * .max_speed_hz = 2*1000*1000, * .chip_select = 2, * }, * }; * * Please see mcp251x.h for a description of the fields in * struct mcp251x_platform_data. * */ #include <linux/can/core.h> #include <linux/can/dev.h> #include <linux/can/led.h> #include <linux/can/platform/mcp251x.h> #include <linux/completion.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/dma-mapping.h> #include <linux/freezer.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/netdevice.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/uaccess.h> /* SPI interface instruction set */ #define INSTRUCTION_WRITE 0x02 #define INSTRUCTION_READ 0x03 #define INSTRUCTION_BIT_MODIFY 0x05 #define INSTRUCTION_LOAD_TXB(n) (0x40 + 2 * (n)) #define INSTRUCTION_READ_RXB(n) (((n) == 0) ? 0x90 : 0x94) #define INSTRUCTION_RESET 0xC0 #define RTS_TXB0 0x01 #define RTS_TXB1 0x02 #define RTS_TXB2 0x04 #define INSTRUCTION_RTS(n) (0x80 | ((n) & 0x07)) /* MPC251x registers */ #define CANSTAT 0x0e #define CANCTRL 0x0f # define CANCTRL_REQOP_MASK 0xe0 # define CANCTRL_REQOP_CONF 0x80 # define CANCTRL_REQOP_LISTEN_ONLY 0x60 # define CANCTRL_REQOP_LOOPBACK 0x40 # define CANCTRL_REQOP_SLEEP 0x20 # define CANCTRL_REQOP_NORMAL 0x00 # define CANCTRL_OSM 0x08 # define CANCTRL_ABAT 0x10 #define TEC 0x1c #define REC 0x1d #define CNF1 0x2a # define CNF1_SJW_SHIFT 6 #define CNF2 0x29 # define CNF2_BTLMODE 0x80 # define CNF2_SAM 0x40 # define CNF2_PS1_SHIFT 3 #define CNF3 0x28 # define CNF3_SOF 0x08 # define CNF3_WAKFIL 0x04 # define CNF3_PHSEG2_MASK 0x07 #define CANINTE 0x2b # define CANINTE_MERRE 0x80 # define CANINTE_WAKIE 0x40 # define CANINTE_ERRIE 0x20 # define CANINTE_TX2IE 0x10 # define CANINTE_TX1IE 0x08 # define CANINTE_TX0IE 0x04 # define CANINTE_RX1IE 0x02 # define CANINTE_RX0IE 0x01 #define CANINTF 0x2c # define CANINTF_MERRF 0x80 # define CANINTF_WAKIF 0x40 # define CANINTF_ERRIF 0x20 # define CANINTF_TX2IF 0x10 # define CANINTF_TX1IF 0x08 # define CANINTF_TX0IF 0x04 # define CANINTF_RX1IF 0x02 # define CANINTF_RX0IF 0x01 # define CANINTF_RX (CANINTF_RX0IF | CANINTF_RX1IF) # define CANINTF_TX (CANINTF_TX2IF | CANINTF_TX1IF | CANINTF_TX0IF) # define CANINTF_ERR (CANINTF_ERRIF) #define EFLG 0x2d # define EFLG_EWARN 0x01 # define EFLG_RXWAR 0x02 # define EFLG_TXWAR 0x04 # define EFLG_RXEP 0x08 # define EFLG_TXEP 0x10 # define EFLG_TXBO 0x20 # define EFLG_RX0OVR 0x40 # define EFLG_RX1OVR 0x80 #define TXBCTRL(n) (((n) * 0x10) + 0x30 + TXBCTRL_OFF) # define TXBCTRL_ABTF 0x40 # define TXBCTRL_MLOA 0x20 # define TXBCTRL_TXERR 0x10 # define TXBCTRL_TXREQ 0x08 #define TXBSIDH(n) (((n) * 0x10) + 0x30 + TXBSIDH_OFF) # define SIDH_SHIFT 3 #define TXBSIDL(n) (((n) * 0x10) + 0x30 + TXBSIDL_OFF) # define SIDL_SID_MASK 7 # define SIDL_SID_SHIFT 5 # define SIDL_EXIDE_SHIFT 3 # define SIDL_EID_SHIFT 16 # define SIDL_EID_MASK 3 #define TXBEID8(n) (((n) * 0x10) + 0x30 + TXBEID8_OFF) #define TXBEID0(n) (((n) * 0x10) + 0x30 + TXBEID0_OFF) #define TXBDLC(n) (((n) * 0x10) + 0x30 + TXBDLC_OFF) # define DLC_RTR_SHIFT 6 #define TXBCTRL_OFF 0 #define TXBSIDH_OFF 1 #define TXBSIDL_OFF 2 #define TXBEID8_OFF 3 #define TXBEID0_OFF 4 #define TXBDLC_OFF 5 #define TXBDAT_OFF 6 #define RXBCTRL(n) (((n) * 0x10) + 0x60 + RXBCTRL_OFF) # define RXBCTRL_BUKT 0x04 # define RXBCTRL_RXM0 0x20 # define RXBCTRL_RXM1 0x40 #define RXBSIDH(n) (((n) * 0x10) + 0x60 + RXBSIDH_OFF) # define RXBSIDH_SHIFT 3 #define RXBSIDL(n) (((n) * 0x10) + 0x60 + RXBSIDL_OFF) # define RXBSIDL_IDE 0x08 # define RXBSIDL_SRR 0x10 # define RXBSIDL_EID 3 # define RXBSIDL_SHIFT 5 #define RXBEID8(n) (((n) * 0x10) + 0x60 + RXBEID8_OFF) #define RXBEID0(n) (((n) * 0x10) + 0x60 + RXBEID0_OFF) #define RXBDLC(n) (((n) * 0x10) + 0x60 + RXBDLC_OFF) # define RXBDLC_LEN_MASK 0x0f # define RXBDLC_RTR 0x40 #define RXBCTRL_OFF 0 #define RXBSIDH_OFF 1 #define RXBSIDL_OFF 2 #define RXBEID8_OFF 3 #define RXBEID0_OFF 4 #define RXBDLC_OFF 5 #define RXBDAT_OFF 6 #define RXFSIDH(n) ((n) * 4) #define RXFSIDL(n) ((n) * 4 + 1) #define RXFEID8(n) ((n) * 4 + 2) #define RXFEID0(n) ((n) * 4 + 3) #define RXMSIDH(n) ((n) * 4 + 0x20) #define RXMSIDL(n) ((n) * 4 + 0x21) #define RXMEID8(n) ((n) * 4 + 0x22) #define RXMEID0(n) ((n) * 4 + 0x23) #define GET_BYTE(val, byte) \ (((val) >> ((byte) * 8)) & 0xff) #define SET_BYTE(val, byte) \ (((val) & 0xff) << ((byte) * 8)) /* * Buffer size required for the largest SPI transfer (i.e., reading a * frame) */ #define CAN_FRAME_MAX_DATA_LEN 8 #define SPI_TRANSFER_BUF_LEN (6 + CAN_FRAME_MAX_DATA_LEN) #define CAN_FRAME_MAX_BITS 128 #define TX_ECHO_SKB_MAX 1 #define DEVICE_NAME "mcp251x" static int mcp251x_enable_dma; /* Enable SPI DMA. Default: 0 (Off) */ module_param(mcp251x_enable_dma, int, S_IRUGO); MODULE_PARM_DESC(mcp251x_enable_dma, "Enable SPI DMA. Default: 0 (Off)"); static const struct can_bittiming_const mcp251x_bittiming_const = { .name = DEVICE_NAME, .tseg1_min = 3, .tseg1_max = 16, .tseg2_min = 2, .tseg2_max = 8, .sjw_max = 4, .brp_min = 1, .brp_max = 64, .brp_inc = 1, }; enum mcp251x_model { CAN_MCP251X_MCP2510 = 0x2510, CAN_MCP251X_MCP2515 = 0x2515, }; struct mcp251x_priv { struct can_priv can; struct net_device *net; struct spi_device *spi; enum mcp251x_model model; struct mutex mcp_lock; /* SPI device lock */ u8 *spi_tx_buf; u8 *spi_rx_buf; dma_addr_t spi_tx_dma; dma_addr_t spi_rx_dma; struct sk_buff *tx_skb; int tx_len; struct workqueue_struct *wq; struct work_struct tx_work; struct work_struct restart_work; int force_quit; int after_suspend; #define AFTER_SUSPEND_UP 1 #define AFTER_SUSPEND_DOWN 2 #define AFTER_SUSPEND_POWER 4 #define AFTER_SUSPEND_RESTART 8 int restart_tx; }; #define MCP251X_IS(_model) \ static inline int mcp251x_is_##_model(struct spi_device *spi) \ { \ struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); \ return priv->model == CAN_MCP251X_MCP##_model; \ } MCP251X_IS(2510); MCP251X_IS(2515); static void mcp251x_clean(struct net_device *net) { struct mcp251x_priv *priv = netdev_priv(net); if (priv->tx_skb || priv->tx_len) net->stats.tx_errors++; if (priv->tx_skb) dev_kfree_skb(priv->tx_skb); if (priv->tx_len) can_free_echo_skb(priv->net, 0); priv->tx_skb = NULL; priv->tx_len = 0; } /* * Note about handling of error return of mcp251x_spi_trans: accessing * registers via SPI is not really different conceptually than using * normal I/O assembler instructions, although it's much more * complicated from a practical POV. So it's not advisable to always * check the return value of this function. Imagine that every * read{b,l}, write{b,l} and friends would be bracketed in "if ( < 0) * error();", it would be a great mess (well there are some situation * when exception handling C++ like could be useful after all). So we * just check that transfers are OK at the beginning of our * conversation with the chip and to avoid doing really nasty things * (like injecting bogus packets in the network stack). */ static int mcp251x_spi_trans(struct spi_device *spi, int len) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); struct spi_transfer t = { .tx_buf = priv->spi_tx_buf, .rx_buf = priv->spi_rx_buf, .len = len, .cs_change = 0, }; struct spi_message m; int ret; spi_message_init(&m); if (mcp251x_enable_dma) { t.tx_dma = priv->spi_tx_dma; t.rx_dma = priv->spi_rx_dma; m.is_dma_mapped = 1; } spi_message_add_tail(&t, &m); ret = spi_sync(spi, &m); if (ret) dev_err(&spi->dev, "spi transfer failed: ret = %d\n", ret); return ret; } static u8 mcp251x_read_reg(struct spi_device *spi, uint8_t reg) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); u8 val = 0; priv->spi_tx_buf[0] = INSTRUCTION_READ; priv->spi_tx_buf[1] = reg; mcp251x_spi_trans(spi, 3); val = priv->spi_rx_buf[2]; return val; } static void mcp251x_read_2regs(struct spi_device *spi, uint8_t reg, uint8_t *v1, uint8_t *v2) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); priv->spi_tx_buf[0] = INSTRUCTION_READ; priv->spi_tx_buf[1] = reg; mcp251x_spi_trans(spi, 4); *v1 = priv->spi_rx_buf[2]; *v2 = priv->spi_rx_buf[3]; } static void mcp251x_write_reg(struct spi_device *spi, u8 reg, uint8_t val) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); priv->spi_tx_buf[0] = INSTRUCTION_WRITE; priv->spi_tx_buf[1] = reg; priv->spi_tx_buf[2] = val; mcp251x_spi_trans(spi, 3); } static void mcp251x_write_bits(struct spi_device *spi, u8 reg, u8 mask, uint8_t val) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); priv->spi_tx_buf[0] = INSTRUCTION_BIT_MODIFY; priv->spi_tx_buf[1] = reg; priv->spi_tx_buf[2] = mask; priv->spi_tx_buf[3] = val; mcp251x_spi_trans(spi, 4); } static void mcp251x_hw_tx_frame(struct spi_device *spi, u8 *buf, int len, int tx_buf_idx) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); if (mcp251x_is_2510(spi)) { int i; for (i = 1; i < TXBDAT_OFF + len; i++) mcp251x_write_reg(spi, TXBCTRL(tx_buf_idx) + i, buf[i]); } else { memcpy(priv->spi_tx_buf, buf, TXBDAT_OFF + len); mcp251x_spi_trans(spi, TXBDAT_OFF + len); } } static void mcp251x_hw_tx(struct spi_device *spi, struct can_frame *frame, int tx_buf_idx) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); u32 sid, eid, exide, rtr; u8 buf[SPI_TRANSFER_BUF_LEN]; exide = (frame->can_id & CAN_EFF_FLAG) ? 1 : 0; /* Extended ID Enable */ if (exide) sid = (frame->can_id & CAN_EFF_MASK) >> 18; else sid = frame->can_id & CAN_SFF_MASK; /* Standard ID */ eid = frame->can_id & CAN_EFF_MASK; /* Extended ID */ rtr = (frame->can_id & CAN_RTR_FLAG) ? 1 : 0; /* Remote transmission */ buf[TXBCTRL_OFF] = INSTRUCTION_LOAD_TXB(tx_buf_idx); buf[TXBSIDH_OFF] = sid >> SIDH_SHIFT; buf[TXBSIDL_OFF] = ((sid & SIDL_SID_MASK) << SIDL_SID_SHIFT) | (exide << SIDL_EXIDE_SHIFT) | ((eid >> SIDL_EID_SHIFT) & SIDL_EID_MASK); buf[TXBEID8_OFF] = GET_BYTE(eid, 1); buf[TXBEID0_OFF] = GET_BYTE(eid, 0); buf[TXBDLC_OFF] = (rtr << DLC_RTR_SHIFT) | frame->can_dlc; memcpy(buf + TXBDAT_OFF, frame->data, frame->can_dlc); mcp251x_hw_tx_frame(spi, buf, frame->can_dlc, tx_buf_idx); /* use INSTRUCTION_RTS, to avoid "repeated frame problem" */ priv->spi_tx_buf[0] = INSTRUCTION_RTS(1 << tx_buf_idx); mcp251x_spi_trans(priv->spi, 1); } static void mcp251x_hw_rx_frame(struct spi_device *spi, u8 *buf, int buf_idx) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); if (mcp251x_is_2510(spi)) { int i, len; for (i = 1; i < RXBDAT_OFF; i++) buf[i] = mcp251x_read_reg(spi, RXBCTRL(buf_idx) + i); len = get_can_dlc(buf[RXBDLC_OFF] & RXBDLC_LEN_MASK); for (; i < (RXBDAT_OFF + len); i++) buf[i] = mcp251x_read_reg(spi, RXBCTRL(buf_idx) + i); } else { priv->spi_tx_buf[RXBCTRL_OFF] = INSTRUCTION_READ_RXB(buf_idx); mcp251x_spi_trans(spi, SPI_TRANSFER_BUF_LEN); memcpy(buf, priv->spi_rx_buf, SPI_TRANSFER_BUF_LEN); } } static void mcp251x_hw_rx(struct spi_device *spi, int buf_idx) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); struct sk_buff *skb; struct can_frame *frame; u8 buf[SPI_TRANSFER_BUF_LEN]; skb = alloc_can_skb(priv->net, &frame); if (!skb) { dev_err(&spi->dev, "cannot allocate RX skb\n"); priv->net->stats.rx_dropped++; return; } mcp251x_hw_rx_frame(spi, buf, buf_idx); if (buf[RXBSIDL_OFF] & RXBSIDL_IDE) { /* Extended ID format */ frame->can_id = CAN_EFF_FLAG; frame->can_id |= /* Extended ID part */ SET_BYTE(buf[RXBSIDL_OFF] & RXBSIDL_EID, 2) | SET_BYTE(buf[RXBEID8_OFF], 1) | SET_BYTE(buf[RXBEID0_OFF], 0) | /* Standard ID part */ (((buf[RXBSIDH_OFF] << RXBSIDH_SHIFT) | (buf[RXBSIDL_OFF] >> RXBSIDL_SHIFT)) << 18); /* Remote transmission request */ if (buf[RXBDLC_OFF] & RXBDLC_RTR) frame->can_id |= CAN_RTR_FLAG; } else { /* Standard ID format */ frame->can_id = (buf[RXBSIDH_OFF] << RXBSIDH_SHIFT) | (buf[RXBSIDL_OFF] >> RXBSIDL_SHIFT); if (buf[RXBSIDL_OFF] & RXBSIDL_SRR) frame->can_id |= CAN_RTR_FLAG; } /* Data length */ frame->can_dlc = get_can_dlc(buf[RXBDLC_OFF] & RXBDLC_LEN_MASK); memcpy(frame->data, buf + RXBDAT_OFF, frame->can_dlc); priv->net->stats.rx_packets++; priv->net->stats.rx_bytes += frame->can_dlc; can_led_event(priv->net, CAN_LED_EVENT_RX); netif_rx_ni(skb); } static void mcp251x_hw_sleep(struct spi_device *spi) { mcp251x_write_reg(spi, CANCTRL, CANCTRL_REQOP_SLEEP); } static netdev_tx_t mcp251x_hard_start_xmit(struct sk_buff *skb, struct net_device *net) { struct mcp251x_priv *priv = netdev_priv(net); struct spi_device *spi = priv->spi; if (priv->tx_skb || priv->tx_len) { dev_warn(&spi->dev, "hard_xmit called while tx busy\n"); return NETDEV_TX_BUSY; } if (can_dropped_invalid_skb(net, skb)) return NETDEV_TX_OK; netif_stop_queue(net); priv->tx_skb = skb; queue_work(priv->wq, &priv->tx_work); return NETDEV_TX_OK; } static int mcp251x_do_set_mode(struct net_device *net, enum can_mode mode) { struct mcp251x_priv *priv = netdev_priv(net); switch (mode) { case CAN_MODE_START: mcp251x_clean(net); /* We have to delay work since SPI I/O may sleep */ priv->can.state = CAN_STATE_ERROR_ACTIVE; priv->restart_tx = 1; if (priv->can.restart_ms == 0) priv->after_suspend = AFTER_SUSPEND_RESTART; queue_work(priv->wq, &priv->restart_work); break; default: return -EOPNOTSUPP; } return 0; } static int mcp251x_set_normal_mode(struct spi_device *spi) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); unsigned long timeout; /* Enable interrupts */ mcp251x_write_reg(spi, CANINTE, CANINTE_ERRIE | CANINTE_TX2IE | CANINTE_TX1IE | CANINTE_TX0IE | CANINTE_RX1IE | CANINTE_RX0IE); if (priv->can.ctrlmode & CAN_CTRLMODE_LOOPBACK) { /* Put device into loopback mode */ mcp251x_write_reg(spi, CANCTRL, CANCTRL_REQOP_LOOPBACK); } else if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) { /* Put device into listen-only mode */ mcp251x_write_reg(spi, CANCTRL, CANCTRL_REQOP_LISTEN_ONLY); } else { /* Put device into normal mode */ mcp251x_write_reg(spi, CANCTRL, CANCTRL_REQOP_NORMAL); /* Wait for the device to enter normal mode */ timeout = jiffies + HZ; while (mcp251x_read_reg(spi, CANSTAT) & CANCTRL_REQOP_MASK) { schedule(); if (time_after(jiffies, timeout)) { dev_err(&spi->dev, "MCP251x didn't" " enter in normal mode\n"); return -EBUSY; } } } priv->can.state = CAN_STATE_ERROR_ACTIVE; return 0; } static int mcp251x_do_set_bittiming(struct net_device *net) { struct mcp251x_priv *priv = netdev_priv(net); struct can_bittiming *bt = &priv->can.bittiming; struct spi_device *spi = priv->spi; mcp251x_write_reg(spi, CNF1, ((bt->sjw - 1) << CNF1_SJW_SHIFT) | (bt->brp - 1)); mcp251x_write_reg(spi, CNF2, CNF2_BTLMODE | (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES ? CNF2_SAM : 0) | ((bt->phase_seg1 - 1) << CNF2_PS1_SHIFT) | (bt->prop_seg - 1)); mcp251x_write_bits(spi, CNF3, CNF3_PHSEG2_MASK, (bt->phase_seg2 - 1)); dev_info(&spi->dev, "CNF: 0x%02x 0x%02x 0x%02x\n", mcp251x_read_reg(spi, CNF1), mcp251x_read_reg(spi, CNF2), mcp251x_read_reg(spi, CNF3)); return 0; } static int mcp251x_setup(struct net_device *net, struct mcp251x_priv *priv, struct spi_device *spi) { mcp251x_do_set_bittiming(net); mcp251x_write_reg(spi, RXBCTRL(0), RXBCTRL_BUKT | RXBCTRL_RXM0 | RXBCTRL_RXM1); mcp251x_write_reg(spi, RXBCTRL(1), RXBCTRL_RXM0 | RXBCTRL_RXM1); return 0; } static int mcp251x_hw_reset(struct spi_device *spi) { struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); int ret; unsigned long timeout; priv->spi_tx_buf[0] = INSTRUCTION_RESET; ret = spi_write(spi, priv->spi_tx_buf, 1); if (ret) { dev_err(&spi->dev, "reset failed: ret = %d\n", ret); return -EIO; } /* Wait for reset to finish */ timeout = jiffies + HZ; mdelay(10); while ((mcp251x_read_reg(spi, CANSTAT) & CANCTRL_REQOP_MASK) != CANCTRL_REQOP_CONF) { schedule(); if (time_after(jiffies, timeout)) { dev_err(&spi->dev, "MCP251x didn't" " enter in conf mode after reset\n"); return -EBUSY; } } return 0; } static int mcp251x_hw_probe(struct spi_device *spi) { int st1, st2; mcp251x_hw_reset(spi); /* * Please note that these are "magic values" based on after * reset defaults taken from data sheet which allows us to see * if we really have a chip on the bus (we avoid common all * zeroes or all ones situations) */ st1 = mcp251x_read_reg(spi, CANSTAT) & 0xEE; st2 = mcp251x_read_reg(spi, CANCTRL) & 0x17; dev_dbg(&spi->dev, "CANSTAT 0x%02x CANCTRL 0x%02x\n", st1, st2); /* Check for power up default values */ return (st1 == 0x80 && st2 == 0x07) ? 1 : 0; } static void mcp251x_open_clean(struct net_device *net) { struct mcp251x_priv *priv = netdev_priv(net); struct spi_device *spi = priv->spi; struct mcp251x_platform_data *pdata = spi->dev.platform_data; free_irq(spi->irq, priv); mcp251x_hw_sleep(spi); if (pdata->transceiver_enable) pdata->transceiver_enable(0); close_candev(net); } static int mcp251x_stop(struct net_device *net) { struct mcp251x_priv *priv = netdev_priv(net); struct spi_device *spi = priv->spi; struct mcp251x_platform_data *pdata = spi->dev.platform_data; close_candev(net); priv->force_quit = 1; free_irq(spi->irq, priv); destroy_workqueue(priv->wq); priv->wq = NULL; mutex_lock(&priv->mcp_lock); /* Disable and clear pending interrupts */ mcp251x_write_reg(spi, CANINTE, 0x00); mcp251x_write_reg(spi, CANINTF, 0x00); mcp251x_write_reg(spi, TXBCTRL(0), 0); mcp251x_clean(net); mcp251x_hw_sleep(spi); if (pdata->transceiver_enable) pdata->transceiver_enable(0); priv->can.state = CAN_STATE_STOPPED; mutex_unlock(&priv->mcp_lock); can_led_event(net, CAN_LED_EVENT_STOP); return 0; } static void mcp251x_error_skb(struct net_device *net, int can_id, int data1) { struct sk_buff *skb; struct can_frame *frame; skb = alloc_can_err_skb(net, &frame); if (skb) { frame->can_id |= can_id; frame->data[1] = data1; netif_rx_ni(skb); } else { netdev_err(net, "cannot allocate error skb\n"); } } static void mcp251x_tx_work_handler(struct work_struct *ws) { struct mcp251x_priv *priv = container_of(ws, struct mcp251x_priv, tx_work); struct spi_device *spi = priv->spi; struct net_device *net = priv->net; struct can_frame *frame; mutex_lock(&priv->mcp_lock); if (priv->tx_skb) { if (priv->can.state == CAN_STATE_BUS_OFF) { mcp251x_clean(net); } else { frame = (struct can_frame *)priv->tx_skb->data; if (frame->can_dlc > CAN_FRAME_MAX_DATA_LEN) frame->can_dlc = CAN_FRAME_MAX_DATA_LEN; mcp251x_hw_tx(spi, frame, 0); priv->tx_len = 1 + frame->can_dlc; can_put_echo_skb(priv->tx_skb, net, 0); priv->tx_skb = NULL; } } mutex_unlock(&priv->mcp_lock); } static void mcp251x_restart_work_handler(struct work_struct *ws) { struct mcp251x_priv *priv = container_of(ws, struct mcp251x_priv, restart_work); struct spi_device *spi = priv->spi; struct net_device *net = priv->net; mutex_lock(&priv->mcp_lock); if (priv->after_suspend) { mdelay(10); mcp251x_hw_reset(spi); mcp251x_setup(net, priv, spi); if (priv->after_suspend & AFTER_SUSPEND_RESTART) { mcp251x_set_normal_mode(spi); } else if (priv->after_suspend & AFTER_SUSPEND_UP) { netif_device_attach(net); mcp251x_clean(net); mcp251x_set_normal_mode(spi); netif_wake_queue(net); } else { mcp251x_hw_sleep(spi); } priv->after_suspend = 0; priv->force_quit = 0; } if (priv->restart_tx) { priv->restart_tx = 0; mcp251x_write_reg(spi, TXBCTRL(0), 0); mcp251x_clean(net); netif_wake_queue(net); mcp251x_error_skb(net, CAN_ERR_RESTARTED, 0); } mutex_unlock(&priv->mcp_lock); } static irqreturn_t mcp251x_can_ist(int irq, void *dev_id) { struct mcp251x_priv *priv = dev_id; struct spi_device *spi = priv->spi; struct net_device *net = priv->net; mutex_lock(&priv->mcp_lock); while (!priv->force_quit) { enum can_state new_state; u8 intf, eflag; u8 clear_intf = 0; int can_id = 0, data1 = 0; mcp251x_read_2regs(spi, CANINTF, &intf, &eflag); /* mask out flags we don't care about */ intf &= CANINTF_RX | CANINTF_TX | CANINTF_ERR; /* receive buffer 0 */ if (intf & CANINTF_RX0IF) { mcp251x_hw_rx(spi, 0); /* * Free one buffer ASAP * (The MCP2515 does this automatically.) */ if (mcp251x_is_2510(spi)) mcp251x_write_bits(spi, CANINTF, CANINTF_RX0IF, 0x00); } /* receive buffer 1 */ if (intf & CANINTF_RX1IF) { mcp251x_hw_rx(spi, 1); /* the MCP2515 does this automatically */ if (mcp251x_is_2510(spi)) clear_intf |= CANINTF_RX1IF; } /* any error or tx interrupt we need to clear? */ if (intf & (CANINTF_ERR | CANINTF_TX)) clear_intf |= intf & (CANINTF_ERR | CANINTF_TX); if (clear_intf) mcp251x_write_bits(spi, CANINTF, clear_intf, 0x00); if (eflag) mcp251x_write_bits(spi, EFLG, eflag, 0x00); /* Update can state */ if (eflag & EFLG_TXBO) { new_state = CAN_STATE_BUS_OFF; can_id |= CAN_ERR_BUSOFF; } else if (eflag & EFLG_TXEP) { new_state = CAN_STATE_ERROR_PASSIVE; can_id |= CAN_ERR_CRTL; data1 |= CAN_ERR_CRTL_TX_PASSIVE; } else if (eflag & EFLG_RXEP) { new_state = CAN_STATE_ERROR_PASSIVE; can_id |= CAN_ERR_CRTL; data1 |= CAN_ERR_CRTL_RX_PASSIVE; } else if (eflag & EFLG_TXWAR) { new_state = CAN_STATE_ERROR_WARNING; can_id |= CAN_ERR_CRTL; data1 |= CAN_ERR_CRTL_TX_WARNING; } else if (eflag & EFLG_RXWAR) { new_state = CAN_STATE_ERROR_WARNING; can_id |= CAN_ERR_CRTL; data1 |= CAN_ERR_CRTL_RX_WARNING; } else { new_state = CAN_STATE_ERROR_ACTIVE; } /* Update can state statistics */ switch (priv->can.state) { case CAN_STATE_ERROR_ACTIVE: if (new_state >= CAN_STATE_ERROR_WARNING && new_state <= CAN_STATE_BUS_OFF) priv->can.can_stats.error_warning++; case CAN_STATE_ERROR_WARNING: /* fallthrough */ if (new_state >= CAN_STATE_ERROR_PASSIVE && new_state <= CAN_STATE_BUS_OFF) priv->can.can_stats.error_passive++; break; default: break; } priv->can.state = new_state; if (intf & CANINTF_ERRIF) { /* Handle overflow counters */ if (eflag & (EFLG_RX0OVR | EFLG_RX1OVR)) { if (eflag & EFLG_RX0OVR) { net->stats.rx_over_errors++; net->stats.rx_errors++; } if (eflag & EFLG_RX1OVR) { net->stats.rx_over_errors++; net->stats.rx_errors++; } can_id |= CAN_ERR_CRTL; data1 |= CAN_ERR_CRTL_RX_OVERFLOW; } mcp251x_error_skb(net, can_id, data1); } if (priv->can.state == CAN_STATE_BUS_OFF) { if (priv->can.restart_ms == 0) { priv->force_quit = 1; can_bus_off(net); mcp251x_hw_sleep(spi); break; } } if (intf == 0) break; if (intf & CANINTF_TX) { net->stats.tx_packets++; net->stats.tx_bytes += priv->tx_len - 1; can_led_event(net, CAN_LED_EVENT_TX); if (priv->tx_len) { can_get_echo_skb(net, 0); priv->tx_len = 0; } netif_wake_queue(net); } } mutex_unlock(&priv->mcp_lock); return IRQ_HANDLED; } static int mcp251x_open(struct net_device *net) { struct mcp251x_priv *priv = netdev_priv(net); struct spi_device *spi = priv->spi; struct mcp251x_platform_data *pdata = spi->dev.platform_data; int ret; ret = open_candev(net); if (ret) { dev_err(&spi->dev, "unable to set initial baudrate!\n"); return ret; } mutex_lock(&priv->mcp_lock); if (pdata->transceiver_enable) pdata->transceiver_enable(1); priv->force_quit = 0; priv->tx_skb = NULL; priv->tx_len = 0; ret = request_threaded_irq(spi->irq, NULL, mcp251x_can_ist, pdata->irq_flags ? pdata->irq_flags : IRQF_TRIGGER_FALLING, DEVICE_NAME, priv); if (ret) { dev_err(&spi->dev, "failed to acquire irq %d\n", spi->irq); if (pdata->transceiver_enable) pdata->transceiver_enable(0); close_candev(net); goto open_unlock; } priv->wq = create_freezable_workqueue("mcp251x_wq"); INIT_WORK(&priv->tx_work, mcp251x_tx_work_handler); INIT_WORK(&priv->restart_work, mcp251x_restart_work_handler); ret = mcp251x_hw_reset(spi); if (ret) { mcp251x_open_clean(net); goto open_unlock; } ret = mcp251x_setup(net, priv, spi); if (ret) { mcp251x_open_clean(net); goto open_unlock; } ret = mcp251x_set_normal_mode(spi); if (ret) { mcp251x_open_clean(net); goto open_unlock; } can_led_event(net, CAN_LED_EVENT_OPEN); netif_wake_queue(net); open_unlock: mutex_unlock(&priv->mcp_lock); return ret; } static const struct net_device_ops mcp251x_netdev_ops = { .ndo_open = mcp251x_open, .ndo_stop = mcp251x_stop, .ndo_start_xmit = mcp251x_hard_start_xmit, }; static int mcp251x_can_probe(struct spi_device *spi) { struct net_device *net; struct mcp251x_priv *priv; struct mcp251x_platform_data *pdata = spi->dev.platform_data; int ret = -ENODEV; if (!pdata) /* Platform data is required for osc freq */ goto error_out; /* Allocate can/net device */ net = alloc_candev(sizeof(struct mcp251x_priv), TX_ECHO_SKB_MAX); if (!net) { ret = -ENOMEM; goto error_alloc; } net->netdev_ops = &mcp251x_netdev_ops; net->flags |= IFF_ECHO; priv = netdev_priv(net); priv->can.bittiming_const = &mcp251x_bittiming_const; priv->can.do_set_mode = mcp251x_do_set_mode; priv->can.clock.freq = pdata->oscillator_frequency / 2; priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES | CAN_CTRLMODE_LOOPBACK | CAN_CTRLMODE_LISTENONLY; priv->model = spi_get_device_id(spi)->driver_data; priv->net = net; dev_set_drvdata(&spi->dev, priv); priv->spi = spi; mutex_init(&priv->mcp_lock); /* If requested, allocate DMA buffers */ if (mcp251x_enable_dma) { spi->dev.coherent_dma_mask = ~0; /* * Minimum coherent DMA allocation is PAGE_SIZE, so allocate * that much and share it between Tx and Rx DMA buffers. */ priv->spi_tx_buf = dma_alloc_coherent(&spi->dev, PAGE_SIZE, &priv->spi_tx_dma, GFP_DMA); if (priv->spi_tx_buf) { priv->spi_rx_buf = (priv->spi_tx_buf + (PAGE_SIZE / 2)); priv->spi_rx_dma = (dma_addr_t)(priv->spi_tx_dma + (PAGE_SIZE / 2)); } else { /* Fall back to non-DMA */ mcp251x_enable_dma = 0; } } /* Allocate non-DMA buffers */ if (!mcp251x_enable_dma) { priv->spi_tx_buf = kmalloc(SPI_TRANSFER_BUF_LEN, GFP_KERNEL); if (!priv->spi_tx_buf) { ret = -ENOMEM; goto error_tx_buf; } priv->spi_rx_buf = kmalloc(SPI_TRANSFER_BUF_LEN, GFP_KERNEL); if (!priv->spi_rx_buf) { ret = -ENOMEM; goto error_rx_buf; } } if (pdata->power_enable) pdata->power_enable(1); /* Call out to platform specific setup */ if (pdata->board_specific_setup) pdata->board_specific_setup(spi); SET_NETDEV_DEV(net, &spi->dev); /* Configure the SPI bus */ spi->mode = SPI_MODE_0; spi->bits_per_word = 8; spi_setup(spi); /* Here is OK to not lock the MCP, no one knows about it yet */ if (!mcp251x_hw_probe(spi)) { dev_info(&spi->dev, "Probe failed\n"); goto error_probe; } mcp251x_hw_sleep(spi); if (pdata->transceiver_enable) pdata->transceiver_enable(0); ret = register_candev(net); if (ret) goto error_probe; devm_can_led_init(net); dev_info(&spi->dev, "probed\n"); return ret; error_probe: if (!mcp251x_enable_dma) kfree(priv->spi_rx_buf); error_rx_buf: if (!mcp251x_enable_dma) kfree(priv->spi_tx_buf); error_tx_buf: free_candev(net); if (mcp251x_enable_dma) dma_free_coherent(&spi->dev, PAGE_SIZE, priv->spi_tx_buf, priv->spi_tx_dma); error_alloc: if (pdata->power_enable) pdata->power_enable(0); dev_err(&spi->dev, "probe failed\n"); error_out: return ret; } static int mcp251x_can_remove(struct spi_device *spi) { struct mcp251x_platform_data *pdata = spi->dev.platform_data; struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); struct net_device *net = priv->net; unregister_candev(net); free_candev(net); if (mcp251x_enable_dma) { dma_free_coherent(&spi->dev, PAGE_SIZE, priv->spi_tx_buf, priv->spi_tx_dma); } else { kfree(priv->spi_tx_buf); kfree(priv->spi_rx_buf); } if (pdata->power_enable) pdata->power_enable(0); return 0; } #ifdef CONFIG_PM static int mcp251x_can_suspend(struct spi_device *spi, pm_message_t state) { struct mcp251x_platform_data *pdata = spi->dev.platform_data; struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); struct net_device *net = priv->net; priv->force_quit = 1; disable_irq(spi->irq); /* * Note: at this point neither IST nor workqueues are running. * open/stop cannot be called anyway so locking is not needed */ if (netif_running(net)) { netif_device_detach(net); mcp251x_hw_sleep(spi); if (pdata->transceiver_enable) pdata->transceiver_enable(0); priv->after_suspend = AFTER_SUSPEND_UP; } else { priv->after_suspend = AFTER_SUSPEND_DOWN; } if (pdata->power_enable) { pdata->power_enable(0); priv->after_suspend |= AFTER_SUSPEND_POWER; } return 0; } static int mcp251x_can_resume(struct spi_device *spi) { struct mcp251x_platform_data *pdata = spi->dev.platform_data; struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); if (priv->after_suspend & AFTER_SUSPEND_POWER) { pdata->power_enable(1); queue_work(priv->wq, &priv->restart_work); } else { if (priv->after_suspend & AFTER_SUSPEND_UP) { if (pdata->transceiver_enable) pdata->transceiver_enable(1); queue_work(priv->wq, &priv->restart_work); } else { priv->after_suspend = 0; } } priv->force_quit = 0; enable_irq(spi->irq); return 0; } #else #define mcp251x_can_suspend NULL #define mcp251x_can_resume NULL #endif static const struct spi_device_id mcp251x_id_table[] = { { "mcp2510", CAN_MCP251X_MCP2510 }, { "mcp2515", CAN_MCP251X_MCP2515 }, { }, }; MODULE_DEVICE_TABLE(spi, mcp251x_id_table); static struct spi_driver mcp251x_can_driver = { .driver = { .name = DEVICE_NAME, .bus = &spi_bus_type, .owner = THIS_MODULE, }, .id_table = mcp251x_id_table, .probe = mcp251x_can_probe, .remove = mcp251x_can_remove, .suspend = mcp251x_can_suspend, .resume = mcp251x_can_resume, }; static int __init mcp251x_can_init(void) { return spi_register_driver(&mcp251x_can_driver); } static void __exit mcp251x_can_exit(void) { spi_unregister_driver(&mcp251x_can_driver); } module_init(mcp251x_can_init); module_exit(mcp251x_can_exit); MODULE_AUTHOR("Chris Elston <celston@katalix.com>, " "Christian Pellegrin <chripell@evolware.org>"); MODULE_DESCRIPTION("Microchip 251x CAN driver"); MODULE_LICENSE("GPL v2");
gpl-2.0
P-Kito/TrinityCore
src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp
36
3849
/* * Copyright (C) 2008-2016 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 "blackwing_lair.h" enum Say { SAY_AGGRO = 0, SAY_LEASH = 1 }; enum Spells { SPELL_CLEAVE = 26350, SPELL_BLASTWAVE = 23331, SPELL_MORTALSTRIKE = 24573, SPELL_KNOCKBACK = 25778 }; enum Events { EVENT_CLEAVE = 1, EVENT_BLASTWAVE = 2, EVENT_MORTALSTRIKE = 3, EVENT_KNOCKBACK = 4, EVENT_CHECK = 5 }; class boss_broodlord : public CreatureScript { public: boss_broodlord() : CreatureScript("boss_broodlord") { } struct boss_broodlordAI : public BossAI { boss_broodlordAI(Creature* creature) : BossAI(creature, DATA_BROODLORD_LASHLAYER) { } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); Talk(SAY_AGGRO); events.ScheduleEvent(EVENT_CLEAVE, 8000); events.ScheduleEvent(EVENT_BLASTWAVE, 12000); events.ScheduleEvent(EVENT_MORTALSTRIKE, 20000); events.ScheduleEvent(EVENT_KNOCKBACK, 30000); events.ScheduleEvent(EVENT_CHECK, 1000); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_CLEAVE: DoCastVictim(SPELL_CLEAVE); events.ScheduleEvent(EVENT_CLEAVE, 7000); break; case EVENT_BLASTWAVE: DoCastVictim(SPELL_BLASTWAVE); events.ScheduleEvent(EVENT_BLASTWAVE, urand(8000, 16000)); break; case EVENT_MORTALSTRIKE: DoCastVictim(SPELL_MORTALSTRIKE); events.ScheduleEvent(EVENT_MORTALSTRIKE, urand(25000, 35000)); break; case EVENT_KNOCKBACK: DoCastVictim(SPELL_KNOCKBACK); if (DoGetThreat(me->GetVictim())) DoModifyThreatPercent(me->GetVictim(), -50); events.ScheduleEvent(EVENT_KNOCKBACK, urand(15000, 30000)); break; case EVENT_CHECK: if (me->GetDistance(me->GetHomePosition()) > 150.0f) { Talk(SAY_LEASH); EnterEvadeMode(); } events.ScheduleEvent(EVENT_CHECK, 1000); break; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetInstanceAI<boss_broodlordAI>(creature); } }; void AddSC_boss_broodlord() { new boss_broodlord(); }
gpl-2.0
shaqfu786/android_kernel_lge_omap4-common
drivers/usb/gadget/f_acm.c
36
23333
/* * f_acm.c -- USB CDC serial (ACM) function driver * * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com) * Copyright (C) 2008 by David Brownell * Copyright (C) 2008 by Nokia Corporation * Copyright (C) 2009 by Samsung Electronics * Author: Michal Nazarewicz (m.nazarewicz@samsung.com) * * This software is distributed under the terms of the GNU General * Public License ("GPL") as published by the Free Software Foundation, * either version 2 of that License or (at your option) any later version. */ /* #define VERBOSE_DEBUG */ #include <linux/slab.h> #include <linux/kernel.h> #include <linux/device.h> #include "u_serial.h" #include "gadget_chips.h" /* * This CDC ACM function support just wraps control functions and * notifications around the generic serial-over-usb code. * * Because CDC ACM is standardized by the USB-IF, many host operating * systems have drivers for it. Accordingly, ACM is the preferred * interop solution for serial-port type connections. The control * models are often not necessary, and in any case don't do much in * this bare-bones implementation. * * Note that even MS-Windows has some support for ACM. However, that * support is somewhat broken because when you use ACM in a composite * device, having multiple interfaces confuses the poor OS. It doesn't * seem to understand CDC Union descriptors. The new "association" * descriptors (roughly equivalent to CDC Unions) may sometimes help. */ struct acm_ep_descs { struct usb_endpoint_descriptor *in; struct usb_endpoint_descriptor *out; struct usb_endpoint_descriptor *notify; }; struct f_acm { struct gserial port; u8 ctrl_id, data_id; u8 port_num; u8 pending; /* lock is mostly for pending and notify_req ... they get accessed * by callbacks both from tty (open/close/break) under its spinlock, * and notify_req.complete() which can't use that lock. */ spinlock_t lock; struct acm_ep_descs fs; struct acm_ep_descs hs; struct usb_ep *notify; struct usb_endpoint_descriptor *notify_desc; struct usb_request *notify_req; struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */ /* SetControlLineState request -- CDC 1.1 section 6.2.14 (INPUT) */ u16 port_handshake_bits; #define ACM_CTRL_RTS (1 << 1) /* unused with full duplex */ #define ACM_CTRL_DTR (1 << 0) /* host is ready for data r/w */ /* SerialState notification -- CDC 1.1 section 6.3.5 (OUTPUT) */ u16 serial_state; #define ACM_CTRL_OVERRUN (1 << 6) #define ACM_CTRL_PARITY (1 << 5) #define ACM_CTRL_FRAMING (1 << 4) #define ACM_CTRL_RI (1 << 3) #define ACM_CTRL_BRK (1 << 2) #define ACM_CTRL_DSR (1 << 1) #define ACM_CTRL_DCD (1 << 0) }; static inline struct f_acm *func_to_acm(struct usb_function *f) { return container_of(f, struct f_acm, port.func); } static inline struct f_acm *port_to_acm(struct gserial *p) { return container_of(p, struct f_acm, port); } /*-------------------------------------------------------------------------*/ /* notification endpoint uses smallish and infrequent fixed-size messages */ /* LGE_SJIT_S 10/21/2011 [mohamed.khadri@lge.com] LG Gadget driver */ #define GS_LOG2_NOTIFY_INTERVAL 5 /* 1 << 5 == 32 msec */ #if defined(CONFIG_LGE_ANDROID_USB) /* LGE host Drvier Notify Size Fix */ #define GS_NOTIFY_MAXPACKET 16 /* notification + 2 bytes */ #else #define GS_NOTIFY_MAXPACKET 10 /* notification + 2 bytes */ #endif /* LGE_SJIT_E 10/21/2011 [mohamed.khadri@lge.com] LG Gadget driver */ /* interface and class descriptors: */ static struct usb_interface_assoc_descriptor acm_iad_descriptor = { .bLength = sizeof acm_iad_descriptor, .bDescriptorType = USB_DT_INTERFACE_ASSOCIATION, /* .bFirstInterface = DYNAMIC, */ .bInterfaceCount = 2, // control + data .bFunctionClass = USB_CLASS_COMM, .bFunctionSubClass = USB_CDC_SUBCLASS_ACM, .bFunctionProtocol = USB_CDC_ACM_PROTO_AT_V25TER, /* .iFunction = DYNAMIC */ }; static struct usb_interface_descriptor acm_control_interface_desc = { .bLength = USB_DT_INTERFACE_SIZE, .bDescriptorType = USB_DT_INTERFACE, /* .bInterfaceNumber = DYNAMIC */ .bNumEndpoints = 1, .bInterfaceClass = USB_CLASS_COMM, .bInterfaceSubClass = USB_CDC_SUBCLASS_ACM, .bInterfaceProtocol = USB_CDC_ACM_PROTO_AT_V25TER, /* .iInterface = DYNAMIC */ }; static struct usb_interface_descriptor acm_data_interface_desc = { .bLength = USB_DT_INTERFACE_SIZE, .bDescriptorType = USB_DT_INTERFACE, /* .bInterfaceNumber = DYNAMIC */ .bNumEndpoints = 2, .bInterfaceClass = USB_CLASS_CDC_DATA, .bInterfaceSubClass = 0, .bInterfaceProtocol = 0, /* .iInterface = DYNAMIC */ }; static struct usb_cdc_header_desc acm_header_desc = { .bLength = sizeof(acm_header_desc), .bDescriptorType = USB_DT_CS_INTERFACE, .bDescriptorSubType = USB_CDC_HEADER_TYPE, .bcdCDC = cpu_to_le16(0x0110), }; static struct usb_cdc_call_mgmt_descriptor acm_call_mgmt_descriptor = { .bLength = sizeof(acm_call_mgmt_descriptor), .bDescriptorType = USB_DT_CS_INTERFACE, .bDescriptorSubType = USB_CDC_CALL_MANAGEMENT_TYPE, .bmCapabilities = 0, /* .bDataInterface = DYNAMIC */ }; static struct usb_cdc_acm_descriptor acm_descriptor = { .bLength = sizeof(acm_descriptor), .bDescriptorType = USB_DT_CS_INTERFACE, .bDescriptorSubType = USB_CDC_ACM_TYPE, .bmCapabilities = USB_CDC_CAP_LINE, }; static struct usb_cdc_union_desc acm_union_desc = { .bLength = sizeof(acm_union_desc), .bDescriptorType = USB_DT_CS_INTERFACE, .bDescriptorSubType = USB_CDC_UNION_TYPE, /* .bMasterInterface0 = DYNAMIC */ /* .bSlaveInterface0 = DYNAMIC */ }; /* full speed support: */ static struct usb_endpoint_descriptor acm_fs_notify_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_INT, .wMaxPacketSize = cpu_to_le16(GS_NOTIFY_MAXPACKET), .bInterval = 1 << GS_LOG2_NOTIFY_INTERVAL, }; static struct usb_endpoint_descriptor acm_fs_in_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_BULK, }; static struct usb_endpoint_descriptor acm_fs_out_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_OUT, .bmAttributes = USB_ENDPOINT_XFER_BULK, }; static struct usb_descriptor_header *acm_fs_function[] = { (struct usb_descriptor_header *) &acm_iad_descriptor, (struct usb_descriptor_header *) &acm_control_interface_desc, (struct usb_descriptor_header *) &acm_header_desc, (struct usb_descriptor_header *) &acm_call_mgmt_descriptor, (struct usb_descriptor_header *) &acm_descriptor, (struct usb_descriptor_header *) &acm_union_desc, (struct usb_descriptor_header *) &acm_fs_notify_desc, (struct usb_descriptor_header *) &acm_data_interface_desc, (struct usb_descriptor_header *) &acm_fs_in_desc, (struct usb_descriptor_header *) &acm_fs_out_desc, NULL, }; /* high speed support: */ static struct usb_endpoint_descriptor acm_hs_notify_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_INT, .wMaxPacketSize = cpu_to_le16(GS_NOTIFY_MAXPACKET), .bInterval = GS_LOG2_NOTIFY_INTERVAL+4, }; static struct usb_endpoint_descriptor acm_hs_in_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = cpu_to_le16(512), }; static struct usb_endpoint_descriptor acm_hs_out_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = cpu_to_le16(512), }; static struct usb_descriptor_header *acm_hs_function[] = { (struct usb_descriptor_header *) &acm_iad_descriptor, (struct usb_descriptor_header *) &acm_control_interface_desc, (struct usb_descriptor_header *) &acm_header_desc, (struct usb_descriptor_header *) &acm_call_mgmt_descriptor, (struct usb_descriptor_header *) &acm_descriptor, (struct usb_descriptor_header *) &acm_union_desc, (struct usb_descriptor_header *) &acm_hs_notify_desc, (struct usb_descriptor_header *) &acm_data_interface_desc, (struct usb_descriptor_header *) &acm_hs_in_desc, (struct usb_descriptor_header *) &acm_hs_out_desc, NULL, }; /* string descriptors: */ #define ACM_CTRL_IDX 0 #define ACM_DATA_IDX 1 #define ACM_IAD_IDX 2 /* static strings, in UTF-8 */ static struct usb_string acm_string_defs[] = { [ACM_CTRL_IDX].s = "CDC Abstract Control Model (ACM)", [ACM_DATA_IDX].s = "CDC ACM Data", [ACM_IAD_IDX ].s = "CDC Serial", { /* ZEROES END LIST */ }, }; static struct usb_gadget_strings acm_string_table = { .language = 0x0409, /* en-us */ .strings = acm_string_defs, }; static struct usb_gadget_strings *acm_strings[] = { &acm_string_table, NULL, }; /*-------------------------------------------------------------------------*/ /* ACM control ... data handling is delegated to tty library code. * The main task of this function is to activate and deactivate * that code based on device state; track parameters like line * speed, handshake state, and so on; and issue notifications. */ static void acm_complete_set_line_coding(struct usb_ep *ep, struct usb_request *req) { struct f_acm *acm = ep->driver_data; struct usb_composite_dev *cdev = acm->port.func.config->cdev; if (req->status != 0) { DBG(cdev, "acm ttyGS%d completion, err %d\n", acm->port_num, req->status); return; } /* normal completion */ if (req->actual != sizeof(acm->port_line_coding)) { DBG(cdev, "acm ttyGS%d short resp, len %d\n", acm->port_num, req->actual); usb_ep_set_halt(ep); } else { struct usb_cdc_line_coding *value = req->buf; /* REVISIT: we currently just remember this data. * If we change that, (a) validate it first, then * (b) update whatever hardware needs updating, * (c) worry about locking. This is information on * the order of 9600-8-N-1 ... most of which means * nothing unless we control a real RS232 line. */ acm->port_line_coding = *value; } } static int acm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl) { struct f_acm *acm = func_to_acm(f); struct usb_composite_dev *cdev = f->config->cdev; struct usb_request *req = cdev->req; int value = -EOPNOTSUPP; u16 w_index = le16_to_cpu(ctrl->wIndex); u16 w_value = le16_to_cpu(ctrl->wValue); u16 w_length = le16_to_cpu(ctrl->wLength); /* composite driver infrastructure handles everything except * CDC class messages; interface activation uses set_alt(). * * Note CDC spec table 4 lists the ACM request profile. It requires * encapsulated command support ... we don't handle any, and respond * to them by stalling. Options include get/set/clear comm features * (not that useful) and SEND_BREAK. */ switch ((ctrl->bRequestType << 8) | ctrl->bRequest) { /* SET_LINE_CODING ... just read and save what the host sends */ case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8) | USB_CDC_REQ_SET_LINE_CODING: if (w_length != sizeof(struct usb_cdc_line_coding) || w_index != acm->ctrl_id) goto invalid; value = w_length; cdev->gadget->ep0->driver_data = acm; req->complete = acm_complete_set_line_coding; break; /* GET_LINE_CODING ... return what host sent, or initial value */ case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8) | USB_CDC_REQ_GET_LINE_CODING: if (w_index != acm->ctrl_id) goto invalid; value = min_t(unsigned, w_length, sizeof(struct usb_cdc_line_coding)); memcpy(req->buf, &acm->port_line_coding, value); break; /* SET_CONTROL_LINE_STATE ... save what the host sent */ case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8) | USB_CDC_REQ_SET_CONTROL_LINE_STATE: if (w_index != acm->ctrl_id) goto invalid; value = 0; /* FIXME we should not allow data to flow until the * host sets the ACM_CTRL_DTR bit; and when it clears * that bit, we should return to that no-flow state. */ acm->port_handshake_bits = w_value; break; default: invalid: VDBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n", ctrl->bRequestType, ctrl->bRequest, w_value, w_index, w_length); } /* respond with data transfer or status phase? */ if (value >= 0) { DBG(cdev, "acm ttyGS%d req%02x.%02x v%04x i%04x l%d\n", acm->port_num, ctrl->bRequestType, ctrl->bRequest, w_value, w_index, w_length); req->zero = 0; req->length = value; value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC); if (value < 0) ERROR(cdev, "acm response on ttyGS%d, err %d\n", acm->port_num, value); } /* device either stalls (value < 0) or reports success */ return value; } static int acm_set_alt(struct usb_function *f, unsigned intf, unsigned alt) { struct f_acm *acm = func_to_acm(f); struct usb_composite_dev *cdev = f->config->cdev; /* we know alt == 0, so this is an activation or a reset */ if (intf == acm->ctrl_id) { if (acm->notify->driver_data) { VDBG(cdev, "reset acm control interface %d\n", intf); usb_ep_disable(acm->notify); } else { VDBG(cdev, "init acm ctrl interface %d\n", intf); } acm->notify_desc = ep_choose(cdev->gadget, acm->hs.notify, acm->fs.notify); usb_ep_enable(acm->notify, acm->notify_desc); acm->notify->driver_data = acm; } else if (intf == acm->data_id) { if (acm->port.in->driver_data) { DBG(cdev, "reset acm ttyGS%d\n", acm->port_num); gserial_disconnect(&acm->port); } else { DBG(cdev, "activate acm ttyGS%d\n", acm->port_num); } acm->port.in_desc = ep_choose(cdev->gadget, acm->hs.in, acm->fs.in); acm->port.out_desc = ep_choose(cdev->gadget, acm->hs.out, acm->fs.out); gserial_connect(&acm->port, acm->port_num); } else return -EINVAL; return 0; } static void acm_disable(struct usb_function *f) { struct f_acm *acm = func_to_acm(f); struct usb_composite_dev *cdev = f->config->cdev; DBG(cdev, "acm ttyGS%d deactivated\n", acm->port_num); gserial_disconnect(&acm->port); usb_ep_disable(acm->notify); acm->notify->driver_data = NULL; } /*-------------------------------------------------------------------------*/ /** * acm_cdc_notify - issue CDC notification to host * @acm: wraps host to be notified * @type: notification type * @value: Refer to cdc specs, wValue field. * @data: data to be sent * @length: size of data * Context: irqs blocked, acm->lock held, acm_notify_req non-null * * Returns zero on success or a negative errno. * * See section 6.3.5 of the CDC 1.1 specification for information * about the only notification we issue: SerialState change. */ static int acm_cdc_notify(struct f_acm *acm, u8 type, u16 value, void *data, unsigned length) { struct usb_ep *ep = acm->notify; struct usb_request *req; struct usb_cdc_notification *notify; const unsigned len = sizeof(*notify) + length; void *buf; int status; req = acm->notify_req; acm->notify_req = NULL; acm->pending = false; req->length = len; notify = req->buf; buf = notify + 1; notify->bmRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE; notify->bNotificationType = type; notify->wValue = cpu_to_le16(value); notify->wIndex = cpu_to_le16(acm->ctrl_id); notify->wLength = cpu_to_le16(length); memcpy(buf, data, length); /* ep_queue() can complete immediately if it fills the fifo... */ spin_unlock(&acm->lock); status = usb_ep_queue(ep, req, GFP_ATOMIC); spin_lock(&acm->lock); if (status < 0) { ERROR(acm->port.func.config->cdev, "acm ttyGS%d can't notify serial state, %d\n", acm->port_num, status); acm->notify_req = req; } return status; } static int acm_notify_serial_state(struct f_acm *acm) { struct usb_composite_dev *cdev = acm->port.func.config->cdev; int status; spin_lock(&acm->lock); if (acm->notify_req) { DBG(cdev, "acm ttyGS%d serial state %04x\n", acm->port_num, acm->serial_state); status = acm_cdc_notify(acm, USB_CDC_NOTIFY_SERIAL_STATE, 0, &acm->serial_state, sizeof(acm->serial_state)); } else { acm->pending = true; status = 0; } spin_unlock(&acm->lock); return status; } static void acm_cdc_notify_complete(struct usb_ep *ep, struct usb_request *req) { struct f_acm *acm = req->context; u8 doit = false; /* on this call path we do NOT hold the port spinlock, * which is why ACM needs its own spinlock */ spin_lock(&acm->lock); if (req->status != -ESHUTDOWN) doit = acm->pending; acm->notify_req = req; spin_unlock(&acm->lock); if (doit) acm_notify_serial_state(acm); } /* connect == the TTY link is open */ static void acm_connect(struct gserial *port) { struct f_acm *acm = port_to_acm(port); acm->serial_state |= ACM_CTRL_DSR | ACM_CTRL_DCD; acm_notify_serial_state(acm); } static void acm_disconnect(struct gserial *port) { struct f_acm *acm = port_to_acm(port); acm->serial_state &= ~(ACM_CTRL_DSR | ACM_CTRL_DCD); acm_notify_serial_state(acm); } static int acm_send_break(struct gserial *port, int duration) { struct f_acm *acm = port_to_acm(port); u16 state; state = acm->serial_state; state &= ~ACM_CTRL_BRK; if (duration) state |= ACM_CTRL_BRK; acm->serial_state = state; return acm_notify_serial_state(acm); } /*-------------------------------------------------------------------------*/ /* ACM function driver setup/binding */ static int acm_bind(struct usb_configuration *c, struct usb_function *f) { struct usb_composite_dev *cdev = c->cdev; struct f_acm *acm = func_to_acm(f); int status; struct usb_ep *ep; /* allocate instance-specific interface IDs, and patch descriptors */ status = usb_interface_id(c, f); if (status < 0) goto fail; acm->ctrl_id = status; acm_iad_descriptor.bFirstInterface = status; acm_control_interface_desc.bInterfaceNumber = status; acm_union_desc .bMasterInterface0 = status; status = usb_interface_id(c, f); if (status < 0) goto fail; acm->data_id = status; acm_data_interface_desc.bInterfaceNumber = status; acm_union_desc.bSlaveInterface0 = status; acm_call_mgmt_descriptor.bDataInterface = status; status = -ENODEV; /* allocate instance-specific endpoints */ ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_in_desc); if (!ep) goto fail; acm->port.in = ep; ep->driver_data = cdev; /* claim */ ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_out_desc); if (!ep) goto fail; acm->port.out = ep; ep->driver_data = cdev; /* claim */ ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_notify_desc); if (!ep) goto fail; acm->notify = ep; ep->driver_data = cdev; /* claim */ /* allocate notification */ acm->notify_req = gs_alloc_req(ep, sizeof(struct usb_cdc_notification) + 2, GFP_KERNEL); if (!acm->notify_req) goto fail; acm->notify_req->complete = acm_cdc_notify_complete; acm->notify_req->context = acm; /* copy descriptors, and track endpoint copies */ f->descriptors = usb_copy_descriptors(acm_fs_function); if (!f->descriptors) goto fail; acm->fs.in = usb_find_endpoint(acm_fs_function, f->descriptors, &acm_fs_in_desc); acm->fs.out = usb_find_endpoint(acm_fs_function, f->descriptors, &acm_fs_out_desc); acm->fs.notify = usb_find_endpoint(acm_fs_function, f->descriptors, &acm_fs_notify_desc); /* support all relevant hardware speeds... we expect that when * hardware is dual speed, all bulk-capable endpoints work at * both speeds */ if (gadget_is_dualspeed(c->cdev->gadget)) { acm_hs_in_desc.bEndpointAddress = acm_fs_in_desc.bEndpointAddress; acm_hs_out_desc.bEndpointAddress = acm_fs_out_desc.bEndpointAddress; acm_hs_notify_desc.bEndpointAddress = acm_fs_notify_desc.bEndpointAddress; /* copy descriptors, and track endpoint copies */ f->hs_descriptors = usb_copy_descriptors(acm_hs_function); acm->hs.in = usb_find_endpoint(acm_hs_function, f->hs_descriptors, &acm_hs_in_desc); acm->hs.out = usb_find_endpoint(acm_hs_function, f->hs_descriptors, &acm_hs_out_desc); acm->hs.notify = usb_find_endpoint(acm_hs_function, f->hs_descriptors, &acm_hs_notify_desc); } DBG(cdev, "acm ttyGS%d: %s speed IN/%s OUT/%s NOTIFY/%s\n", acm->port_num, gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full", acm->port.in->name, acm->port.out->name, acm->notify->name); return 0; fail: if (acm->notify_req) gs_free_req(acm->notify, acm->notify_req); /* we might as well release our claims on endpoints */ if (acm->notify) acm->notify->driver_data = NULL; if (acm->port.out) acm->port.out->driver_data = NULL; if (acm->port.in) acm->port.in->driver_data = NULL; ERROR(cdev, "%s/%p: can't bind, err %d\n", f->name, f, status); return status; } static void acm_unbind(struct usb_configuration *c, struct usb_function *f) { struct f_acm *acm = func_to_acm(f); if (gadget_is_dualspeed(c->cdev->gadget)) usb_free_descriptors(f->hs_descriptors); usb_free_descriptors(f->descriptors); gs_free_req(acm->notify, acm->notify_req); kfree(acm->port.func.name); kfree(acm); } /* Some controllers can't support CDC ACM ... */ static inline bool can_support_cdc(struct usb_configuration *c) { /* everything else is *probably* fine ... */ return true; } /** * acm_bind_config - add a CDC ACM function to a configuration * @c: the configuration to support the CDC ACM instance * @port_num: /dev/ttyGS* port this interface will use * Context: single threaded during gadget setup * * Returns zero on success, else negative errno. * * Caller must have called @gserial_setup() with enough ports to * handle all the ones it binds. Caller is also responsible * for calling @gserial_cleanup() before module unload. */ int acm_bind_config(struct usb_configuration *c, u8 port_num) { struct f_acm *acm; int status; if (!can_support_cdc(c)) return -EINVAL; /* REVISIT might want instance-specific strings to help * distinguish instances ... */ /* maybe allocate device-global string IDs, and patch descriptors */ if (acm_string_defs[ACM_CTRL_IDX].id == 0) { status = usb_string_id(c->cdev); if (status < 0) return status; acm_string_defs[ACM_CTRL_IDX].id = status; acm_control_interface_desc.iInterface = status; status = usb_string_id(c->cdev); if (status < 0) return status; acm_string_defs[ACM_DATA_IDX].id = status; acm_data_interface_desc.iInterface = status; status = usb_string_id(c->cdev); if (status < 0) return status; acm_string_defs[ACM_IAD_IDX].id = status; acm_iad_descriptor.iFunction = status; } /* allocate and initialize one new instance */ acm = kzalloc(sizeof *acm, GFP_KERNEL); if (!acm) return -ENOMEM; spin_lock_init(&acm->lock); acm->port_num = port_num; acm->port.connect = acm_connect; acm->port.disconnect = acm_disconnect; acm->port.send_break = acm_send_break; acm->port.func.name = kasprintf(GFP_KERNEL, "acm%u", port_num); if (!acm->port.func.name) { kfree(acm); return -ENOMEM; } acm->port.func.strings = acm_strings; /* descriptors are per-instance copies */ acm->port.func.bind = acm_bind; acm->port.func.unbind = acm_unbind; acm->port.func.set_alt = acm_set_alt; acm->port.func.setup = acm_setup; acm->port.func.disable = acm_disable; status = usb_add_function(c, &acm->port.func); if (status) kfree(acm); return status; }
gpl-2.0
WatchBeam/obs-studio
libobs/graphics/libnsgif/libnsgif.c
36
46524
/* * Copyright 2003 James Bursa <bursa@users.sourceforge.net> * Copyright 2004 John Tytgat <John.Tytgat@aaug.net> * Copyright 2004 Richard Wilson <richard.wilson@netsurf-browser.org> * Copyright 2008 Sean Fox <dyntryx@gmail.com> * * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/ * Licenced under the MIT License, * http://www.opensource.org/licenses/mit-license.php */ //#include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <stdio.h> #include "libnsgif.h" #ifdef NDEBUG # define LOG(x) ((void) 0) #else # define LOG(x) do { fprintf(stderr, x), fputc('\n', stderr); } while (0) #endif /* NDEBUG */ /* READING GIF FILES ================= The functions provided by this file allow for efficient progressive GIF decoding. Whilst the initialisation does not ensure that there is sufficient image data to complete the entire frame, it does ensure that the information provided is valid. Any subsequent attempts to decode an initialised GIF are guaranteed to succeed, and any bytes of the image not present are assumed to be totally transparent. To begin decoding a GIF, the 'gif' structure must be initialised with the 'gif_data' and 'buffer_size' set to their initial values. The 'buffer_position' should initially be 0, and will be internally updated as the decoding commences. The caller should then repeatedly call gif_initialise() with the structure until the function returns 1, or no more data is avaliable. Once the initialisation has begun, the decoder completes the variables 'frame_count' and 'frame_count_partial'. The former being the total number of frames that have been successfully initialised, and the latter being the number of frames that a partial amount of data is available for. This assists the caller in managing the animation whilst decoding is continuing. To decode a frame, the caller must use gif_decode_frame() which updates the current 'frame_image' to reflect the desired frame. The required 'disposal_method' is also updated to reflect how the frame should be plotted. The caller must not assume that the current 'frame_image' will be valid between calls if initialisation is still occuring, and should either always request that the frame is decoded (no processing will occur if the 'decoded_frame' has not been invalidated by initialisation) or perform the check itself. It should be noted that gif_finalise() should always be called, even if no frames were initialised. Additionally, it is the responsibility of the caller to free 'gif_data'. [rjw] - Fri 2nd April 2004 */ /* TO-DO LIST ================= + Plain text and comment extensions could be implemented if there is any interest in doing so. */ /* Maximum colour table size */ #define GIF_MAX_COLOURS 256 /* Internal flag that the colour table needs to be processed */ #define GIF_PROCESS_COLOURS 0xaa000000 /* Internal flag that a frame is invalid/unprocessed */ #define GIF_INVALID_FRAME -1 /* Transparent colour */ #define GIF_TRANSPARENT_COLOUR 0x00 /* GIF Flags */ #define GIF_FRAME_COMBINE 1 #define GIF_FRAME_CLEAR 2 #define GIF_FRAME_RESTORE 3 #define GIF_FRAME_QUIRKS_RESTORE 4 #define GIF_IMAGE_SEPARATOR 0x2c #define GIF_INTERLACE_MASK 0x40 #define GIF_COLOUR_TABLE_MASK 0x80 #define GIF_COLOUR_TABLE_SIZE_MASK 0x07 #define GIF_EXTENSION_INTRODUCER 0x21 #define GIF_EXTENSION_GRAPHIC_CONTROL 0xf9 #define GIF_DISPOSAL_MASK 0x1c #define GIF_TRANSPARENCY_MASK 0x01 #define GIF_EXTENSION_COMMENT 0xfe #define GIF_EXTENSION_PLAIN_TEXT 0x01 #define GIF_EXTENSION_APPLICATION 0xff #define GIF_BLOCK_TERMINATOR 0x00 #define GIF_TRAILER 0x3b /* Internal GIF routines */ static gif_result gif_initialise_sprite(gif_animation *gif, unsigned int width, unsigned int height); static gif_result gif_initialise_frame(gif_animation *gif); static gif_result gif_initialise_frame_extensions(gif_animation *gif, const int frame); static gif_result gif_skip_frame_extensions(gif_animation *gif); static unsigned int gif_interlaced_line(int height, int y); /* Internal LZW routines */ static void gif_init_LZW(gif_animation *gif); static bool gif_next_LZW(gif_animation *gif); static int gif_next_code(gif_animation *gif, int code_size); static const int maskTbl[16] = {0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff}; /** Initialises necessary gif_animation members. */ void gif_create(gif_animation *gif, gif_bitmap_callback_vt *bitmap_callbacks) { memset(gif, 0, sizeof(gif_animation)); gif->bitmap_callbacks = *bitmap_callbacks; gif->decoded_frame = GIF_INVALID_FRAME; } /** Initialises any workspace held by the animation and attempts to decode any information that hasn't already been decoded. If an error occurs, all previously decoded frames are retained. @return GIF_FRAME_DATA_ERROR for GIF frame data error GIF_INSUFFICIENT_FRAME_DATA for insufficient data to process any more frames GIF_INSUFFICIENT_MEMORY for memory error GIF_DATA_ERROR for GIF error GIF_INSUFFICIENT_DATA for insufficient data to do anything GIF_OK for successful decoding GIF_WORKING for successful decoding if more frames are expected */ gif_result gif_initialise(gif_animation *gif, size_t size, unsigned char *data) { unsigned char *gif_data; unsigned int index; gif_result return_value; /* The GIF format is thoroughly documented; a full description * can be found at http://www.w3.org/Graphics/GIF/spec-gif89a.txt */ /* Initialize values */ gif->buffer_size = (unsigned int)size; gif->gif_data = data; /* Check for sufficient data to be a GIF (6-byte header + 7-byte logical screen descriptor) */ if (gif->buffer_size < 13) return GIF_INSUFFICIENT_DATA; /* Get our current processing position */ gif_data = gif->gif_data + gif->buffer_position; /* See if we should initialise the GIF */ if (gif->buffer_position == 0) { /* We want everything to be NULL before we start so we've no chance of freeing bad pointers (paranoia) */ gif->frame_image = NULL; gif->frames = NULL; gif->local_colour_table = NULL; gif->global_colour_table = NULL; /* The caller may have been lazy and not reset any values */ gif->frame_count = 0; gif->frame_count_partial = 0; gif->decoded_frame = GIF_INVALID_FRAME; /* 6-byte GIF file header is: * * +0 3CHARS Signature ('GIF') * +3 3CHARS Version ('87a' or '89a') */ if (strncmp((const char *) gif_data, "GIF", 3) != 0) return GIF_DATA_ERROR; gif_data += 3; /* Ensure GIF reports version 87a or 89a */ /* if ((strncmp(gif_data, "87a", 3) != 0) && (strncmp(gif_data, "89a", 3) != 0)) LOG(("Unknown GIF format - proceeding anyway")); */ gif_data += 3; /* 7-byte Logical Screen Descriptor is: * * +0 SHORT Logical Screen Width * +2 SHORT Logical Screen Height * +4 CHAR __Packed Fields__ * 1BIT Global Colour Table Flag * 3BITS Colour Resolution * 1BIT Sort Flag * 3BITS Size of Global Colour Table * +5 CHAR Background Colour Index * +6 CHAR Pixel Aspect Ratio */ gif->width = gif_data[0] | (gif_data[1] << 8); gif->height = gif_data[2] | (gif_data[3] << 8); gif->global_colours = (gif_data[4] & GIF_COLOUR_TABLE_MASK); gif->colour_table_size = (2 << (gif_data[4] & GIF_COLOUR_TABLE_SIZE_MASK)); gif->background_index = gif_data[5]; gif->aspect_ratio = gif_data[6]; gif->loop_count = 1; gif_data += 7; /* Some broken GIFs report the size as the screen size they were created in. As such, we detect for the common cases and set the sizes as 0 if they are found which results in the GIF being the maximum size of the frames. */ if (((gif->width == 640) && (gif->height == 480)) || ((gif->width == 640) && (gif->height == 512)) || ((gif->width == 800) && (gif->height == 600)) || ((gif->width == 1024) && (gif->height == 768)) || ((gif->width == 1280) && (gif->height == 1024)) || ((gif->width == 1600) && (gif->height == 1200)) || ((gif->width == 0) || (gif->height == 0)) || ((gif->width > 2048) || (gif->height > 2048))) { gif->width = 1; gif->height = 1; } /* Allocate some data irrespective of whether we've got any colour tables. We always get the maximum size in case a GIF is lying to us. It's far better to give the wrong colours than to trample over some memory somewhere. */ gif->global_colour_table = (unsigned int *)calloc(GIF_MAX_COLOURS, sizeof(int)); gif->local_colour_table = (unsigned int *)calloc(GIF_MAX_COLOURS, sizeof(int)); if ((gif->global_colour_table == NULL) || (gif->local_colour_table == NULL)) { gif_finalise(gif); return GIF_INSUFFICIENT_MEMORY; } /* Set the first colour to a value that will never occur in reality so we know if we've processed it */ gif->global_colour_table[0] = GIF_PROCESS_COLOURS; /* Check if the GIF has no frame data (13-byte header + 1-byte termination block) * Although generally useless, the GIF specification does not expressly prohibit this */ if (gif->buffer_size == 14) { if (gif_data[0] == GIF_TRAILER) return GIF_OK; else return GIF_INSUFFICIENT_DATA; } /* Initialise enough workspace for 4 frames initially */ if ((gif->frames = (gif_frame *)malloc(sizeof(gif_frame))) == NULL) { gif_finalise(gif); return GIF_INSUFFICIENT_MEMORY; } gif->frame_holders = 1; /* Initialise the sprite header */ assert(gif->bitmap_callbacks.bitmap_create); if ((gif->frame_image = gif->bitmap_callbacks.bitmap_create(gif->width, gif->height)) == NULL) { gif_finalise(gif); return GIF_INSUFFICIENT_MEMORY; } /* Remember we've done this now */ gif->buffer_position = (unsigned int)(gif_data - gif->gif_data); } /* Do the colour map if we haven't already. As the top byte is always 0xff or 0x00 depending on the transparency we know if it's been filled in. */ if (gif->global_colour_table[0] == GIF_PROCESS_COLOURS) { /* Check for a global colour map signified by bit 7 */ if (gif->global_colours) { if (gif->buffer_size < (gif->colour_table_size * 3 + 12)) { return GIF_INSUFFICIENT_DATA; } for (index = 0; index < gif->colour_table_size; index++) { /* Gif colour map contents are r,g,b. * * We want to pack them bytewise into the * colour table, such that the red component * is in byte 0 and the alpha component is in * byte 3. */ unsigned char *entry = (unsigned char *) &gif-> global_colour_table[index]; entry[0] = gif_data[0]; /* r */ entry[1] = gif_data[1]; /* g */ entry[2] = gif_data[2]; /* b */ entry[3] = 0xff; /* a */ gif_data += 3; } gif->buffer_position = (unsigned int)(gif_data - gif->gif_data); } else { /* Create a default colour table with the first two colours as black and white */ unsigned int *entry = gif->global_colour_table; entry[0] = 0x00000000; /* Force Alpha channel to opaque */ ((unsigned char *) entry)[3] = 0xff; entry[1] = 0xffffffff; } } /* Repeatedly try to initialise frames */ while ((return_value = gif_initialise_frame(gif)) == GIF_WORKING); /* If there was a memory error tell the caller */ if ((return_value == GIF_INSUFFICIENT_MEMORY) || (return_value == GIF_DATA_ERROR)) return return_value; /* If we didn't have some frames then a GIF_INSUFFICIENT_DATA becomes a GIF_INSUFFICIENT_FRAME_DATA */ if ((return_value == GIF_INSUFFICIENT_DATA) && (gif->frame_count_partial > 0)) return GIF_INSUFFICIENT_FRAME_DATA; /* Return how many we got */ return return_value; } /** Updates the sprite memory size @return GIF_INSUFFICIENT_MEMORY for a memory error GIF_OK for success */ static gif_result gif_initialise_sprite(gif_animation *gif, unsigned int width, unsigned int height) { unsigned int max_width; unsigned int max_height; struct bitmap *buffer; /* Check if we've changed */ if ((width <= gif->width) && (height <= gif->height)) return GIF_OK; /* Get our maximum values */ max_width = (width > gif->width) ? width : gif->width; max_height = (height > gif->height) ? height : gif->height; /* Allocate some more memory */ assert(gif->bitmap_callbacks.bitmap_create); if ((buffer = gif->bitmap_callbacks.bitmap_create(max_width, max_height)) == NULL) return GIF_INSUFFICIENT_MEMORY; assert(gif->bitmap_callbacks.bitmap_destroy); gif->bitmap_callbacks.bitmap_destroy(gif->frame_image); gif->frame_image = buffer; gif->width = max_width; gif->height = max_height; /* Invalidate our currently decoded image */ gif->decoded_frame = GIF_INVALID_FRAME; return GIF_OK; } /** Attempts to initialise the next frame @return GIF_INSUFFICIENT_DATA for insufficient data to do anything GIF_FRAME_DATA_ERROR for GIF frame data error GIF_INSUFFICIENT_MEMORY for insufficient memory to process GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame GIF_DATA_ERROR for GIF error (invalid frame header) GIF_OK for successful decoding GIF_WORKING for successful decoding if more frames are expected */ static gif_result gif_initialise_frame(gif_animation *gif) { int frame; gif_frame *temp_buf; unsigned char *gif_data, *gif_end; int gif_bytes; unsigned int flags = 0; unsigned int width, height, offset_x, offset_y; unsigned int block_size, colour_table_size; bool first_image = true; gif_result return_value; /* Get the frame to decode and our data position */ frame = gif->frame_count; /* Get our buffer position etc. */ gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position); gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size); gif_bytes = (unsigned int)(gif_end - gif_data); /* Check if we've finished */ if ((gif_bytes > 0) && (gif_data[0] == GIF_TRAILER)) return GIF_OK; /* Check if we have enough data * The shortest block of data is a 4-byte comment extension + 1-byte block terminator + 1-byte gif trailer */ if (gif_bytes < 6) return GIF_INSUFFICIENT_DATA; /* We could theoretically get some junk data that gives us millions of frames, so we ensure that we don't have a silly number */ if (frame > 4096) return GIF_FRAME_DATA_ERROR; /* Get some memory to store our pointers in etc. */ if ((int)gif->frame_holders <= frame) { /* Allocate more memory */ if ((temp_buf = (gif_frame *)realloc(gif->frames, (frame + 1) * sizeof(gif_frame))) == NULL) return GIF_INSUFFICIENT_MEMORY; gif->frames = temp_buf; gif->frame_holders = frame + 1; } /* Store our frame pointer. We would do it when allocating except we start off with one frame allocated so we can always use realloc. */ gif->frames[frame].frame_pointer = gif->buffer_position; gif->frames[frame].display = false; gif->frames[frame].virgin = true; gif->frames[frame].disposal_method = 0; gif->frames[frame].transparency = false; gif->frames[frame].frame_delay = 100; gif->frames[frame].redraw_required = false; /* Invalidate any previous decoding we have of this frame */ if (gif->decoded_frame == frame) gif->decoded_frame = GIF_INVALID_FRAME; /* We pretend to initialise the frames, but really we just skip over all the data contained within. This is all basically a cut down version of gif_decode_frame that doesn't have any of the LZW bits in it. */ /* Initialise any extensions */ gif->buffer_position = (unsigned int)(gif_data - gif->gif_data); if ((return_value = gif_initialise_frame_extensions(gif, frame)) != GIF_OK) return return_value; gif_data = (gif->gif_data + gif->buffer_position); gif_bytes = (unsigned int)(gif_end - gif_data); /* Check if we've finished */ if ((gif_bytes = (unsigned int)(gif_end - gif_data)) < 1) return GIF_INSUFFICIENT_FRAME_DATA; else if (gif_data[0] == GIF_TRAILER) { gif->buffer_position = (unsigned int)(gif_data - gif->gif_data); gif->frame_count = frame + 1; return GIF_OK; } /* If we're not done, there should be an image descriptor */ if (gif_data[0] != GIF_IMAGE_SEPARATOR) return GIF_FRAME_DATA_ERROR; /* Do some simple boundary checking */ offset_x = gif_data[1] | (gif_data[2] << 8); offset_y = gif_data[3] | (gif_data[4] << 8); width = gif_data[5] | (gif_data[6] << 8); height = gif_data[7] | (gif_data[8] << 8); /* Set up the redraw characteristics. We have to check for extending the area due to multi-image frames. */ if (!first_image) { if (gif->frames[frame].redraw_x > offset_x) { gif->frames[frame].redraw_width += (gif->frames[frame].redraw_x - offset_x); gif->frames[frame].redraw_x = offset_x; } if (gif->frames[frame].redraw_y > offset_y) { gif->frames[frame].redraw_height += (gif->frames[frame].redraw_y - offset_y); gif->frames[frame].redraw_y = offset_y; } if ((offset_x + width) > (gif->frames[frame].redraw_x + gif->frames[frame].redraw_width)) gif->frames[frame].redraw_width = (offset_x + width) - gif->frames[frame].redraw_x; if ((offset_y + height) > (gif->frames[frame].redraw_y + gif->frames[frame].redraw_height)) gif->frames[frame].redraw_height = (offset_y + height) - gif->frames[frame].redraw_y; } else { first_image = false; gif->frames[frame].redraw_x = offset_x; gif->frames[frame].redraw_y = offset_y; gif->frames[frame].redraw_width = width; gif->frames[frame].redraw_height = height; } /* if we are clearing the background then we need to redraw enough to cover the previous frame too */ gif->frames[frame].redraw_required = ((gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) || (gif->frames[frame].disposal_method == GIF_FRAME_RESTORE)); /* Boundary checking - shouldn't ever happen except with junk data */ if (gif_initialise_sprite(gif, (offset_x + width), (offset_y + height))) return GIF_INSUFFICIENT_MEMORY; /* Decode the flags */ flags = gif_data[9]; colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK); /* Move our data onwards and remember we've got a bit of this frame */ gif_data += 10; gif_bytes = (unsigned int)(gif_end - gif_data); gif->frame_count_partial = frame + 1; /* Skip the local colour table */ if (flags & GIF_COLOUR_TABLE_MASK) { gif_data += 3 * colour_table_size; if ((gif_bytes = (unsigned int)(gif_end - gif_data)) < 0) return GIF_INSUFFICIENT_FRAME_DATA; } /* Ensure we have a correct code size */ if (gif_data[0] > GIF_MAX_LZW) return GIF_DATA_ERROR; /* Move our pointer to the actual image data */ gif_data++; if (--gif_bytes < 0) return GIF_INSUFFICIENT_FRAME_DATA; /* Repeatedly skip blocks until we get a zero block or run out of data * These blocks of image data are processed later by gif_decode_frame() */ block_size = 0; while (block_size != 1) { block_size = gif_data[0] + 1; /* Check if the frame data runs off the end of the file */ if ((int)(gif_bytes - block_size) < 0) { /* Try to recover by signaling the end of the gif. * Once we get garbage data, there is no logical * way to determine where the next frame is. * It's probably better to partially load the gif * than not at all. */ if (gif_bytes >= 2) { gif_data[0] = 0; gif_data[1] = GIF_TRAILER; gif_bytes = 1; ++gif_data; break; } else return GIF_INSUFFICIENT_FRAME_DATA; } else { gif_bytes -= block_size; gif_data += block_size; } } /* Add the frame and set the display flag */ gif->buffer_position = (unsigned int)(gif_data - gif->gif_data); gif->frame_count = frame + 1; gif->frames[frame].display = true; /* Check if we've finished */ if (gif_bytes < 1) return GIF_INSUFFICIENT_FRAME_DATA; else if (gif_data[0] == GIF_TRAILER) return GIF_OK; return GIF_WORKING; } /** Attempts to initialise the frame's extensions @return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame GIF_OK for successful initialisation */ static gif_result gif_initialise_frame_extensions(gif_animation *gif, const int frame) { unsigned char *gif_data, *gif_end; int gif_bytes; unsigned int block_size; /* Get our buffer position etc. */ gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position); gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size); /* Initialise the extensions */ while (gif_data[0] == GIF_EXTENSION_INTRODUCER) { ++gif_data; gif_bytes = (unsigned int)(gif_end - gif_data); /* Switch on extension label */ switch(gif_data[0]) { /* 6-byte Graphic Control Extension is: * * +0 CHAR Graphic Control Label * +1 CHAR Block Size * +2 CHAR __Packed Fields__ * 3BITS Reserved * 3BITS Disposal Method * 1BIT User Input Flag * 1BIT Transparent Color Flag * +3 SHORT Delay Time * +5 CHAR Transparent Color Index */ case GIF_EXTENSION_GRAPHIC_CONTROL: if (gif_bytes < 6) return GIF_INSUFFICIENT_FRAME_DATA; gif->frames[frame].frame_delay = gif_data[3] | (gif_data[4] << 8); if (gif_data[2] & GIF_TRANSPARENCY_MASK) { gif->frames[frame].transparency = true; gif->frames[frame].transparency_index = gif_data[5]; } gif->frames[frame].disposal_method = ((gif_data[2] & GIF_DISPOSAL_MASK) >> 2); /* I have encountered documentation and GIFs in the wild that use * 0x04 to restore the previous frame, rather than the officially * documented 0x03. I believe some (older?) software may even actually * export this way. We handle this as a type of "quirks" mode. */ if (gif->frames[frame].disposal_method == GIF_FRAME_QUIRKS_RESTORE) gif->frames[frame].disposal_method = GIF_FRAME_RESTORE; gif_data += (2 + gif_data[1]); break; /* 14-byte+ Application Extension is: * * +0 CHAR Application Extension Label * +1 CHAR Block Size * +2 8CHARS Application Identifier * +10 3CHARS Appl. Authentication Code * +13 1-256 Application Data (Data sub-blocks) */ case GIF_EXTENSION_APPLICATION: if (gif_bytes < 17) return GIF_INSUFFICIENT_FRAME_DATA; if ((gif_data[1] == 0x0b) && (strncmp((const char *) gif_data + 2, "NETSCAPE2.0", 11) == 0) && (gif_data[13] == 0x03) && (gif_data[14] == 0x01)) { gif->loop_count = gif_data[15] | (gif_data[16] << 8); } gif_data += (2 + gif_data[1]); break; /* Move the pointer to the first data sub-block * Skip 1 byte for the extension label */ case GIF_EXTENSION_COMMENT: ++gif_data; break; /* Move the pointer to the first data sub-block * Skip 2 bytes for the extension label and size fields * Skip the extension size itself */ default: gif_data += (2 + gif_data[1]); } /* Repeatedly skip blocks until we get a zero block or run out of data * This data is ignored by this gif decoder */ gif_bytes = (unsigned int)(gif_end - gif_data); block_size = 0; while (gif_data[0] != GIF_BLOCK_TERMINATOR) { block_size = gif_data[0] + 1; if ((gif_bytes -= block_size) < 0) return GIF_INSUFFICIENT_FRAME_DATA; gif_data += block_size; } ++gif_data; } /* Set buffer position and return */ gif->buffer_position = (unsigned int)(gif_data - gif->gif_data); return GIF_OK; } /** Decodes a GIF frame. @return GIF_FRAME_DATA_ERROR for GIF frame data error GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame GIF_DATA_ERROR for GIF error (invalid frame header) GIF_INSUFFICIENT_DATA for insufficient data to do anything GIF_INSUFFICIENT_MEMORY for insufficient memory to process GIF_OK for successful decoding If a frame does not contain any image data, GIF_OK is returned and gif->current_error is set to GIF_FRAME_NO_DISPLAY */ gif_result gif_decode_frame(gif_animation *gif, unsigned int frame) { unsigned int index = 0; unsigned char *gif_data, *gif_end; int gif_bytes; unsigned int width, height, offset_x, offset_y; unsigned int flags, colour_table_size, interlace; unsigned int *colour_table; unsigned int *frame_data = 0; // Set to 0 for no warnings unsigned int *frame_scanline; unsigned int save_buffer_position; gif_result return_value = GIF_OK; unsigned int x, y, decode_y, burst_bytes; int last_undisposed_frame = (frame - 1); register unsigned char colour; /* Ensure we have a frame to decode */ if (frame >= gif->frame_count_partial) return GIF_INSUFFICIENT_DATA; /* Ensure this frame is supposed to be decoded */ if (gif->frames[frame].display == false) { gif->current_error = GIF_FRAME_NO_DISPLAY; return GIF_OK; } if ((!gif->clear_image) && ((int)frame == gif->decoded_frame)) return GIF_OK; /* Get the start of our frame data and the end of the GIF data */ gif_data = gif->gif_data + gif->frames[frame].frame_pointer; gif_end = gif->gif_data + gif->buffer_size; gif_bytes = (unsigned int)(gif_end - gif_data); /* Check if we have enough data * The shortest block of data is a 10-byte image descriptor + 1-byte gif trailer */ if (gif_bytes < 12) return GIF_INSUFFICIENT_FRAME_DATA; /* Save the buffer position */ save_buffer_position = gif->buffer_position; gif->buffer_position = (unsigned int)(gif_data - gif->gif_data); /* Skip any extensions because we all ready processed them */ if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) goto gif_decode_frame_exit; gif_data = (gif->gif_data + gif->buffer_position); gif_bytes = (unsigned int)(gif_end - gif_data); /* Ensure we have enough data for the 10-byte image descriptor + 1-byte gif trailer */ if (gif_bytes < 12) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } /* 10-byte Image Descriptor is: * * +0 CHAR Image Separator (0x2c) * +1 SHORT Image Left Position * +3 SHORT Image Top Position * +5 SHORT Width * +7 SHORT Height * +9 CHAR __Packed Fields__ * 1BIT Local Colour Table Flag * 1BIT Interlace Flag * 1BIT Sort Flag * 2BITS Reserved * 3BITS Size of Local Colour Table */ if (gif_data[0] != GIF_IMAGE_SEPARATOR) { return_value = GIF_DATA_ERROR; goto gif_decode_frame_exit; } offset_x = gif_data[1] | (gif_data[2] << 8); offset_y = gif_data[3] | (gif_data[4] << 8); width = gif_data[5] | (gif_data[6] << 8); height = gif_data[7] | (gif_data[8] << 8); /* Boundary checking - shouldn't ever happen except unless the data has been modified since initialisation. */ if ((offset_x + width > gif->width) || (offset_y + height > gif->height)) { return_value = GIF_DATA_ERROR; goto gif_decode_frame_exit; } /* Decode the flags */ flags = gif_data[9]; colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK); interlace = flags & GIF_INTERLACE_MASK; /* Move our pointer to the colour table or image data (if no colour table is given) */ gif_data += 10; gif_bytes = (unsigned int)(gif_end - gif_data); /* Set up the colour table */ if (flags & GIF_COLOUR_TABLE_MASK) { if (gif_bytes < (int)(3 * colour_table_size)) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } colour_table = gif->local_colour_table; if (!gif->clear_image) { for (index = 0; index < colour_table_size; index++) { /* Gif colour map contents are r,g,b. * * We want to pack them bytewise into the * colour table, such that the red component * is in byte 0 and the alpha component is in * byte 3. */ unsigned char *entry = (unsigned char *) &colour_table[index]; entry[0] = gif_data[0]; /* r */ entry[1] = gif_data[1]; /* g */ entry[2] = gif_data[2]; /* b */ entry[3] = 0xff; /* a */ gif_data += 3; } } else { gif_data += 3 * colour_table_size; } gif_bytes = (unsigned int)(gif_end - gif_data); } else { colour_table = gif->global_colour_table; } /* Check if we've finished */ if (gif_bytes < 1) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; } else if (gif_data[0] == GIF_TRAILER) { return_value = GIF_OK; goto gif_decode_frame_exit; } /* Get the frame data */ assert(gif->bitmap_callbacks.bitmap_get_buffer); frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); if (!frame_data) return GIF_INSUFFICIENT_MEMORY; /* If we are clearing the image we just clear, if not decode */ if (!gif->clear_image) { /* Ensure we have enough data for a 1-byte LZW code size + 1-byte gif trailer */ if (gif_bytes < 2) { return_value = GIF_INSUFFICIENT_FRAME_DATA; goto gif_decode_frame_exit; /* If we only have a 1-byte LZW code size + 1-byte gif trailer, we're finished */ } else if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) { return_value = GIF_OK; goto gif_decode_frame_exit; } /* If the previous frame's disposal method requires we restore the background * colour or this is the first frame, clear the frame data */ if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) { memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int)); gif->decoded_frame = frame; /* The line below would fill the image with its background color, but because GIFs support * transparency we likely wouldn't want to do that. */ /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */ } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) { gif->clear_image = true; if ((return_value = gif_decode_frame(gif, (frame - 1))) != GIF_OK) goto gif_decode_frame_exit; gif->clear_image = false; /* If the previous frame's disposal method requires we restore the previous * image, find the last image set to "do not dispose" and get that frame data */ } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) { while ((last_undisposed_frame != -1) && (gif->frames[last_undisposed_frame--].disposal_method == GIF_FRAME_RESTORE)) { } /* If we don't find one, clear the frame data */ if (last_undisposed_frame == -1) { /* see notes above on transparency vs. background color */ memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int)); } else { if ((return_value = gif_decode_frame(gif, last_undisposed_frame)) != GIF_OK) goto gif_decode_frame_exit; /* Get this frame's data */ assert(gif->bitmap_callbacks.bitmap_get_buffer); frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); if (!frame_data) return GIF_INSUFFICIENT_MEMORY; } } gif->decoded_frame = frame; /* Initialise the LZW decoding */ gif->set_code_size = gif_data[0]; gif->buffer_position = (unsigned int)(gif_data - gif->gif_data + 1); /* Set our code variables */ gif->code_size = gif->set_code_size + 1; gif->clear_code = (1 << gif->set_code_size); gif->end_code = gif->clear_code + 1; gif->max_code_size = gif->clear_code << 1; gif->max_code = gif->clear_code + 2; gif->curbit = gif->lastbit = 0; gif->last_byte = 2; gif->get_done = false; gif->direct = gif->buf; gif_init_LZW(gif); /* Decompress the data */ for (y = 0; y < height; y++) { if (interlace) decode_y = gif_interlaced_line(height, y) + offset_y; else decode_y = y + offset_y; frame_scanline = frame_data + offset_x + (decode_y * gif->width); /* Rather than decoding pixel by pixel, we try to burst out streams of data to remove the need for end-of data checks every pixel. */ x = width; while (x > 0) { burst_bytes = (unsigned int)(gif->stack_pointer - gif->stack); if (burst_bytes > 0) { if (burst_bytes > x) burst_bytes = x; x -= burst_bytes; while (burst_bytes-- > 0) { colour = *--gif->stack_pointer; if (((gif->frames[frame].transparency) && (colour != gif->frames[frame].transparency_index)) || (!gif->frames[frame].transparency)) *frame_scanline = colour_table[colour]; frame_scanline++; } } else { if (!gif_next_LZW(gif)) { /* Unexpected end of frame, try to recover */ if (gif->current_error == GIF_END_OF_FRAME) return_value = GIF_OK; else return_value = gif->current_error; goto gif_decode_frame_exit; } } } } } else { /* Clear our frame */ if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) { for (y = 0; y < height; y++) { frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width); if (gif->frames[frame].transparency) memset(frame_scanline, GIF_TRANSPARENT_COLOUR, width * 4); else memset(frame_scanline, colour_table[gif->background_index], width * 4); } } } gif_decode_frame_exit: /* Check if we should test for optimisation */ if (gif->frames[frame].virgin) { if (gif->bitmap_callbacks.bitmap_test_opaque) gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image); else gif->frames[frame].opaque = false; gif->frames[frame].virgin = false; } if (gif->bitmap_callbacks.bitmap_set_opaque) gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque); if (gif->bitmap_callbacks.bitmap_modified) gif->bitmap_callbacks.bitmap_modified(gif->frame_image); /* Restore the buffer position */ gif->buffer_position = save_buffer_position; /* Success! */ return return_value; } /** Skips the frame's extensions (which have been previously initialised) @return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame GIF_OK for successful decoding */ static gif_result gif_skip_frame_extensions(gif_animation *gif) { unsigned char *gif_data, *gif_end; int gif_bytes; unsigned int block_size; /* Get our buffer position etc. */ gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position); gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size); gif_bytes = (unsigned int)(gif_end - gif_data); /* Skip the extensions */ while (gif_data[0] == GIF_EXTENSION_INTRODUCER) { ++gif_data; /* Switch on extension label */ switch(gif_data[0]) { /* Move the pointer to the first data sub-block * 1 byte for the extension label */ case GIF_EXTENSION_COMMENT: ++gif_data; break; /* Move the pointer to the first data sub-block * 2 bytes for the extension label and size fields * Skip the extension size itself */ default: gif_data += (2 + gif_data[1]); } /* Repeatedly skip blocks until we get a zero block or run out of data * This data is ignored by this gif decoder */ gif_bytes = (unsigned int)(gif_end - gif_data); block_size = 0; while (gif_data[0] != GIF_BLOCK_TERMINATOR) { block_size = gif_data[0] + 1; if ((gif_bytes -= block_size) < 0) return GIF_INSUFFICIENT_FRAME_DATA; gif_data += block_size; } ++gif_data; } /* Set buffer position and return */ gif->buffer_position = (unsigned int)(gif_data - gif->gif_data); return GIF_OK; } static unsigned int gif_interlaced_line(int height, int y) { if ((y << 3) < height) return (y << 3); y -= ((height + 7) >> 3); if ((y << 3) < (height - 4)) return (y << 3) + 4; y -= ((height + 3) >> 3); if ((y << 2) < (height - 2)) return (y << 2) + 2; y -= ((height + 1) >> 2); return (y << 1) + 1; } /* Releases any workspace held by the animation */ void gif_finalise(gif_animation *gif) { /* Release all our memory blocks */ if (gif->frame_image) { assert(gif->bitmap_callbacks.bitmap_destroy); gif->bitmap_callbacks.bitmap_destroy(gif->frame_image); } gif->frame_image = NULL; free(gif->frames); gif->frames = NULL; free(gif->local_colour_table); gif->local_colour_table = NULL; free(gif->global_colour_table); gif->global_colour_table = NULL; } /** * Initialise LZW decoding */ void gif_init_LZW(gif_animation *gif) { int i; gif->current_error = 0; if (gif->clear_code >= (1 << GIF_MAX_LZW)) { gif->stack_pointer = gif->stack; gif->current_error = GIF_FRAME_DATA_ERROR; return; } /* initialise our table */ memset(gif->table, 0x00, (1 << GIF_MAX_LZW) * 8); for (i = 0; i < gif->clear_code; ++i) gif->table[1][i] = i; /* update our LZW parameters */ gif->code_size = gif->set_code_size + 1; gif->max_code_size = gif->clear_code << 1; gif->max_code = gif->clear_code + 2; gif->stack_pointer = gif->stack; do { gif->firstcode = gif->oldcode = gif_next_code(gif, gif->code_size); } while (gif->firstcode == gif->clear_code); *gif->stack_pointer++ =gif->firstcode; } static bool gif_next_LZW(gif_animation *gif) { int code, incode; int block_size; int new_code; code = gif_next_code(gif, gif->code_size); if (code < 0) { gif->current_error = code; return false; } else if (code == gif->clear_code) { gif_init_LZW(gif); return true; } else if (code == gif->end_code) { /* skip to the end of our data so multi-image GIFs work */ if (gif->zero_data_block) { gif->current_error = GIF_FRAME_DATA_ERROR; return false; } block_size = 0; while (block_size != 1) { block_size = gif->gif_data[gif->buffer_position] + 1; gif->buffer_position += block_size; } gif->current_error = GIF_FRAME_DATA_ERROR; return false; } incode = code; if (code >= gif->max_code) { *gif->stack_pointer++ = gif->firstcode; code = gif->oldcode; } /* The following loop is the most important in the GIF decoding cycle as every * single pixel passes through it. * * Note: our gif->stack is always big enough to hold a complete decompressed chunk. */ while (code >= gif->clear_code) { *gif->stack_pointer++ = gif->table[1][code]; new_code = gif->table[0][code]; if (new_code < gif->clear_code) { code = new_code; break; } *gif->stack_pointer++ = gif->table[1][new_code]; code = gif->table[0][new_code]; if (code == new_code) { gif->current_error = GIF_FRAME_DATA_ERROR; return false; } } *gif->stack_pointer++ = gif->firstcode = gif->table[1][code]; if ((code = gif->max_code) < (1 << GIF_MAX_LZW)) { gif->table[0][code] = gif->oldcode; gif->table[1][code] = gif->firstcode; ++gif->max_code; if ((gif->max_code >= gif->max_code_size) && (gif->max_code_size < (1 << GIF_MAX_LZW))) { gif->max_code_size = gif->max_code_size << 1; ++gif->code_size; } } gif->oldcode = incode; return true; } static int gif_next_code(gif_animation *gif, int code_size) { int i, j, end, count, ret; unsigned char *b; (void)code_size; end = gif->curbit + gif->code_size; if (end >= gif->lastbit) { if (gif->get_done) return GIF_END_OF_FRAME; gif->buf[0] = gif->direct[gif->last_byte - 2]; gif->buf[1] = gif->direct[gif->last_byte - 1]; /* get the next block */ gif->direct = gif->gif_data + gif->buffer_position; gif->zero_data_block = ((count = gif->direct[0]) == 0); if ((gif->buffer_position + count) >= gif->buffer_size) return GIF_INSUFFICIENT_FRAME_DATA; if (count == 0) gif->get_done = true; else { gif->direct -= 1; gif->buf[2] = gif->direct[2]; gif->buf[3] = gif->direct[3]; } gif->buffer_position += count + 1; /* update our variables */ gif->last_byte = 2 + count; gif->curbit = (gif->curbit - gif->lastbit) + 16; gif->lastbit = (2 + count) << 3; end = gif->curbit + gif->code_size; } i = gif->curbit >> 3; if (i < 2) b = gif->buf; else b = gif->direct; ret = b[i]; j = (end >> 3) - 1; if (i <= j) { ret |= (b[i + 1] << 8); if (i < j) ret |= (b[i + 2] << 16); } ret = (ret >> (gif->curbit % 8)) & maskTbl[gif->code_size]; gif->curbit += gif->code_size; return ret; }
gpl-2.0
olafdietsche/linux-accessfs
drivers/gpu/drm/msm/hdmi/hdmi_connector.c
292
11332
/* * Copyright (C) 2013 Red Hat * Author: Rob Clark <robdclark@gmail.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, see <http://www.gnu.org/licenses/>. */ #include <linux/gpio.h> #include "msm_kms.h" #include "hdmi.h" struct hdmi_connector { struct drm_connector base; struct hdmi *hdmi; struct work_struct hpd_work; }; #define to_hdmi_connector(x) container_of(x, struct hdmi_connector, base) static int gpio_config(struct hdmi *hdmi, bool on) { struct drm_device *dev = hdmi->dev; const struct hdmi_platform_config *config = hdmi->config; int ret; if (on) { ret = gpio_request(config->ddc_clk_gpio, "HDMI_DDC_CLK"); if (ret) { dev_err(dev->dev, "'%s'(%d) gpio_request failed: %d\n", "HDMI_DDC_CLK", config->ddc_clk_gpio, ret); goto error1; } gpio_set_value_cansleep(config->ddc_clk_gpio, 1); ret = gpio_request(config->ddc_data_gpio, "HDMI_DDC_DATA"); if (ret) { dev_err(dev->dev, "'%s'(%d) gpio_request failed: %d\n", "HDMI_DDC_DATA", config->ddc_data_gpio, ret); goto error2; } gpio_set_value_cansleep(config->ddc_data_gpio, 1); ret = gpio_request(config->hpd_gpio, "HDMI_HPD"); if (ret) { dev_err(dev->dev, "'%s'(%d) gpio_request failed: %d\n", "HDMI_HPD", config->hpd_gpio, ret); goto error3; } gpio_direction_input(config->hpd_gpio); gpio_set_value_cansleep(config->hpd_gpio, 1); if (config->mux_en_gpio != -1) { ret = gpio_request(config->mux_en_gpio, "HDMI_MUX_EN"); if (ret) { dev_err(dev->dev, "'%s'(%d) gpio_request failed: %d\n", "HDMI_MUX_SEL", config->mux_en_gpio, ret); goto error4; } gpio_set_value_cansleep(config->mux_en_gpio, 1); } if (config->mux_sel_gpio != -1) { ret = gpio_request(config->mux_sel_gpio, "HDMI_MUX_SEL"); if (ret) { dev_err(dev->dev, "'%s'(%d) gpio_request failed: %d\n", "HDMI_MUX_SEL", config->mux_sel_gpio, ret); goto error5; } gpio_set_value_cansleep(config->mux_sel_gpio, 0); } DBG("gpio on"); } else { gpio_free(config->ddc_clk_gpio); gpio_free(config->ddc_data_gpio); gpio_free(config->hpd_gpio); if (config->mux_en_gpio != -1) { gpio_set_value_cansleep(config->mux_en_gpio, 0); gpio_free(config->mux_en_gpio); } if (config->mux_sel_gpio != -1) { gpio_set_value_cansleep(config->mux_sel_gpio, 1); gpio_free(config->mux_sel_gpio); } DBG("gpio off"); } return 0; error5: if (config->mux_en_gpio != -1) gpio_free(config->mux_en_gpio); error4: gpio_free(config->hpd_gpio); error3: gpio_free(config->ddc_data_gpio); error2: gpio_free(config->ddc_clk_gpio); error1: return ret; } static int hpd_enable(struct hdmi_connector *hdmi_connector) { struct hdmi *hdmi = hdmi_connector->hdmi; const struct hdmi_platform_config *config = hdmi->config; struct drm_device *dev = hdmi_connector->base.dev; struct hdmi_phy *phy = hdmi->phy; uint32_t hpd_ctrl; int i, ret; ret = gpio_config(hdmi, true); if (ret) { dev_err(dev->dev, "failed to configure GPIOs: %d\n", ret); goto fail; } for (i = 0; i < config->hpd_clk_cnt; i++) { ret = clk_prepare_enable(hdmi->hpd_clks[i]); if (ret) { dev_err(dev->dev, "failed to enable hpd clk: %s (%d)\n", config->hpd_clk_names[i], ret); goto fail; } } for (i = 0; i < config->hpd_reg_cnt; i++) { ret = regulator_enable(hdmi->hpd_regs[i]); if (ret) { dev_err(dev->dev, "failed to enable hpd regulator: %s (%d)\n", config->hpd_reg_names[i], ret); goto fail; } } hdmi_set_mode(hdmi, false); phy->funcs->reset(phy); hdmi_set_mode(hdmi, true); hdmi_write(hdmi, REG_HDMI_USEC_REFTIMER, 0x0001001b); /* enable HPD events: */ hdmi_write(hdmi, REG_HDMI_HPD_INT_CTRL, HDMI_HPD_INT_CTRL_INT_CONNECT | HDMI_HPD_INT_CTRL_INT_EN); /* set timeout to 4.1ms (max) for hardware debounce */ hpd_ctrl = hdmi_read(hdmi, REG_HDMI_HPD_CTRL); hpd_ctrl |= HDMI_HPD_CTRL_TIMEOUT(0x1fff); /* Toggle HPD circuit to trigger HPD sense */ hdmi_write(hdmi, REG_HDMI_HPD_CTRL, ~HDMI_HPD_CTRL_ENABLE & hpd_ctrl); hdmi_write(hdmi, REG_HDMI_HPD_CTRL, HDMI_HPD_CTRL_ENABLE | hpd_ctrl); return 0; fail: return ret; } static int hdp_disable(struct hdmi_connector *hdmi_connector) { struct hdmi *hdmi = hdmi_connector->hdmi; const struct hdmi_platform_config *config = hdmi->config; struct drm_device *dev = hdmi_connector->base.dev; int i, ret = 0; /* Disable HPD interrupt */ hdmi_write(hdmi, REG_HDMI_HPD_INT_CTRL, 0); hdmi_set_mode(hdmi, false); for (i = 0; i < config->hpd_reg_cnt; i++) { ret = regulator_disable(hdmi->hpd_regs[i]); if (ret) { dev_err(dev->dev, "failed to disable hpd regulator: %s (%d)\n", config->hpd_reg_names[i], ret); goto fail; } } for (i = 0; i < config->hpd_clk_cnt; i++) clk_disable_unprepare(hdmi->hpd_clks[i]); ret = gpio_config(hdmi, false); if (ret) { dev_err(dev->dev, "failed to unconfigure GPIOs: %d\n", ret); goto fail; } return 0; fail: return ret; } static void hotplug_work(struct work_struct *work) { struct hdmi_connector *hdmi_connector = container_of(work, struct hdmi_connector, hpd_work); struct drm_connector *connector = &hdmi_connector->base; drm_helper_hpd_irq_event(connector->dev); } void hdmi_connector_irq(struct drm_connector *connector) { struct hdmi_connector *hdmi_connector = to_hdmi_connector(connector); struct msm_drm_private *priv = connector->dev->dev_private; struct hdmi *hdmi = hdmi_connector->hdmi; uint32_t hpd_int_status, hpd_int_ctrl; /* Process HPD: */ hpd_int_status = hdmi_read(hdmi, REG_HDMI_HPD_INT_STATUS); hpd_int_ctrl = hdmi_read(hdmi, REG_HDMI_HPD_INT_CTRL); if ((hpd_int_ctrl & HDMI_HPD_INT_CTRL_INT_EN) && (hpd_int_status & HDMI_HPD_INT_STATUS_INT)) { bool detected = !!(hpd_int_status & HDMI_HPD_INT_STATUS_CABLE_DETECTED); DBG("status=%04x, ctrl=%04x", hpd_int_status, hpd_int_ctrl); /* ack the irq: */ hdmi_write(hdmi, REG_HDMI_HPD_INT_CTRL, hpd_int_ctrl | HDMI_HPD_INT_CTRL_INT_ACK); /* detect disconnect if we are connected or visa versa: */ hpd_int_ctrl = HDMI_HPD_INT_CTRL_INT_EN; if (!detected) hpd_int_ctrl |= HDMI_HPD_INT_CTRL_INT_CONNECT; hdmi_write(hdmi, REG_HDMI_HPD_INT_CTRL, hpd_int_ctrl); queue_work(priv->wq, &hdmi_connector->hpd_work); } } static enum drm_connector_status hdmi_connector_detect( struct drm_connector *connector, bool force) { struct hdmi_connector *hdmi_connector = to_hdmi_connector(connector); struct hdmi *hdmi = hdmi_connector->hdmi; const struct hdmi_platform_config *config = hdmi->config; uint32_t hpd_int_status; int retry = 20; hpd_int_status = hdmi_read(hdmi, REG_HDMI_HPD_INT_STATUS); /* sense seems to in some cases be momentarily de-asserted, don't * let that trick us into thinking the monitor is gone: */ while (retry-- && !(hpd_int_status & HDMI_HPD_INT_STATUS_CABLE_DETECTED)) { /* hdmi debounce logic seems to get stuck sometimes, * read directly the gpio to get a second opinion: */ if (gpio_get_value(config->hpd_gpio)) { DBG("gpio tells us we are connected!"); hpd_int_status |= HDMI_HPD_INT_STATUS_CABLE_DETECTED; break; } mdelay(10); hpd_int_status = hdmi_read(hdmi, REG_HDMI_HPD_INT_STATUS); DBG("status=%08x", hpd_int_status); } return (hpd_int_status & HDMI_HPD_INT_STATUS_CABLE_DETECTED) ? connector_status_connected : connector_status_disconnected; } static void hdmi_connector_destroy(struct drm_connector *connector) { struct hdmi_connector *hdmi_connector = to_hdmi_connector(connector); hdp_disable(hdmi_connector); drm_sysfs_connector_remove(connector); drm_connector_cleanup(connector); hdmi_unreference(hdmi_connector->hdmi); kfree(hdmi_connector); } static int hdmi_connector_get_modes(struct drm_connector *connector) { struct hdmi_connector *hdmi_connector = to_hdmi_connector(connector); struct hdmi *hdmi = hdmi_connector->hdmi; struct edid *edid; uint32_t hdmi_ctrl; int ret = 0; hdmi_ctrl = hdmi_read(hdmi, REG_HDMI_CTRL); hdmi_write(hdmi, REG_HDMI_CTRL, hdmi_ctrl | HDMI_CTRL_ENABLE); edid = drm_get_edid(connector, hdmi->i2c); hdmi_write(hdmi, REG_HDMI_CTRL, hdmi_ctrl); drm_mode_connector_update_edid_property(connector, edid); if (edid) { ret = drm_add_edid_modes(connector, edid); kfree(edid); } return ret; } static int hdmi_connector_mode_valid(struct drm_connector *connector, struct drm_display_mode *mode) { struct hdmi_connector *hdmi_connector = to_hdmi_connector(connector); struct hdmi *hdmi = hdmi_connector->hdmi; const struct hdmi_platform_config *config = hdmi->config; struct msm_drm_private *priv = connector->dev->dev_private; struct msm_kms *kms = priv->kms; long actual, requested; requested = 1000 * mode->clock; actual = kms->funcs->round_pixclk(kms, requested, hdmi_connector->hdmi->encoder); /* for mdp5/apq8074, we manage our own pixel clk (as opposed to * mdp4/dtv stuff where pixel clk is assigned to mdp/encoder * instead): */ if (config->pwr_clk_cnt > 0) actual = clk_round_rate(hdmi->pwr_clks[0], actual); DBG("requested=%ld, actual=%ld", requested, actual); if (actual != requested) return MODE_CLOCK_RANGE; return 0; } static struct drm_encoder * hdmi_connector_best_encoder(struct drm_connector *connector) { struct hdmi_connector *hdmi_connector = to_hdmi_connector(connector); return hdmi_connector->hdmi->encoder; } static const struct drm_connector_funcs hdmi_connector_funcs = { .dpms = drm_helper_connector_dpms, .detect = hdmi_connector_detect, .fill_modes = drm_helper_probe_single_connector_modes, .destroy = hdmi_connector_destroy, }; static const struct drm_connector_helper_funcs hdmi_connector_helper_funcs = { .get_modes = hdmi_connector_get_modes, .mode_valid = hdmi_connector_mode_valid, .best_encoder = hdmi_connector_best_encoder, }; /* initialize connector */ struct drm_connector *hdmi_connector_init(struct hdmi *hdmi) { struct drm_connector *connector = NULL; struct hdmi_connector *hdmi_connector; int ret; hdmi_connector = kzalloc(sizeof(*hdmi_connector), GFP_KERNEL); if (!hdmi_connector) { ret = -ENOMEM; goto fail; } hdmi_connector->hdmi = hdmi_reference(hdmi); INIT_WORK(&hdmi_connector->hpd_work, hotplug_work); connector = &hdmi_connector->base; drm_connector_init(hdmi->dev, connector, &hdmi_connector_funcs, DRM_MODE_CONNECTOR_HDMIA); drm_connector_helper_add(connector, &hdmi_connector_helper_funcs); connector->polled = DRM_CONNECTOR_POLL_HPD; connector->interlace_allowed = 1; connector->doublescan_allowed = 0; drm_sysfs_connector_add(connector); ret = hpd_enable(hdmi_connector); if (ret) { dev_err(hdmi->dev->dev, "failed to enable HPD: %d\n", ret); goto fail; } drm_mode_connector_attach_encoder(connector, hdmi->encoder); return connector; fail: if (connector) hdmi_connector_destroy(connector); return ERR_PTR(ret); }
gpl-2.0
DmitryADP/diff_qc750
kernel/drivers/media/video/hdpvr/hdpvr-video.c
548
30464
/* * Hauppauge HD PVR USB driver - video 4 linux 2 interface * * Copyright (C) 2008 Janne Grunau (j@jannau.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, version 2. * */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/mutex.h> #include <linux/workqueue.h> #include <linux/videodev2.h> #include <media/v4l2-dev.h> #include <media/v4l2-common.h> #include <media/v4l2-ioctl.h> #include "hdpvr.h" #define BULK_URB_TIMEOUT 90 /* 0.09 seconds */ #define print_buffer_status() { \ v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev, \ "%s:%d buffer stat: %d free, %d proc\n", \ __func__, __LINE__, \ list_size(&dev->free_buff_list), \ list_size(&dev->rec_buff_list)); } struct hdpvr_fh { struct hdpvr_device *dev; }; static uint list_size(struct list_head *list) { struct list_head *tmp; uint count = 0; list_for_each(tmp, list) { count++; } return count; } /*=========================================================================*/ /* urb callback */ static void hdpvr_read_bulk_callback(struct urb *urb) { struct hdpvr_buffer *buf = (struct hdpvr_buffer *)urb->context; struct hdpvr_device *dev = buf->dev; /* marking buffer as received and wake waiting */ buf->status = BUFSTAT_READY; wake_up_interruptible(&dev->wait_data); } /*=========================================================================*/ /* bufffer bits */ /* function expects dev->io_mutex to be hold by caller */ int hdpvr_cancel_queue(struct hdpvr_device *dev) { struct hdpvr_buffer *buf; list_for_each_entry(buf, &dev->rec_buff_list, buff_list) { usb_kill_urb(buf->urb); buf->status = BUFSTAT_AVAILABLE; } list_splice_init(&dev->rec_buff_list, dev->free_buff_list.prev); return 0; } static int hdpvr_free_queue(struct list_head *q) { struct list_head *tmp; struct list_head *p; struct hdpvr_buffer *buf; struct urb *urb; for (p = q->next; p != q;) { buf = list_entry(p, struct hdpvr_buffer, buff_list); urb = buf->urb; usb_free_coherent(urb->dev, urb->transfer_buffer_length, urb->transfer_buffer, urb->transfer_dma); usb_free_urb(urb); tmp = p->next; list_del(p); kfree(buf); p = tmp; } return 0; } /* function expects dev->io_mutex to be hold by caller */ int hdpvr_free_buffers(struct hdpvr_device *dev) { hdpvr_cancel_queue(dev); hdpvr_free_queue(&dev->free_buff_list); hdpvr_free_queue(&dev->rec_buff_list); return 0; } /* function expects dev->io_mutex to be hold by caller */ int hdpvr_alloc_buffers(struct hdpvr_device *dev, uint count) { uint i; int retval = -ENOMEM; u8 *mem; struct hdpvr_buffer *buf; struct urb *urb; v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev, "allocating %u buffers\n", count); for (i = 0; i < count; i++) { buf = kzalloc(sizeof(struct hdpvr_buffer), GFP_KERNEL); if (!buf) { v4l2_err(&dev->v4l2_dev, "cannot allocate buffer\n"); goto exit; } buf->dev = dev; urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) { v4l2_err(&dev->v4l2_dev, "cannot allocate urb\n"); goto exit_urb; } buf->urb = urb; mem = usb_alloc_coherent(dev->udev, dev->bulk_in_size, GFP_KERNEL, &urb->transfer_dma); if (!mem) { v4l2_err(&dev->v4l2_dev, "cannot allocate usb transfer buffer\n"); goto exit_urb_buffer; } usb_fill_bulk_urb(buf->urb, dev->udev, usb_rcvbulkpipe(dev->udev, dev->bulk_in_endpointAddr), mem, dev->bulk_in_size, hdpvr_read_bulk_callback, buf); buf->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; buf->status = BUFSTAT_AVAILABLE; list_add_tail(&buf->buff_list, &dev->free_buff_list); } return 0; exit_urb_buffer: usb_free_urb(urb); exit_urb: kfree(buf); exit: hdpvr_free_buffers(dev); return retval; } static int hdpvr_submit_buffers(struct hdpvr_device *dev) { struct hdpvr_buffer *buf; struct urb *urb; int ret = 0, err_count = 0; mutex_lock(&dev->io_mutex); while (dev->status == STATUS_STREAMING && !list_empty(&dev->free_buff_list)) { buf = list_entry(dev->free_buff_list.next, struct hdpvr_buffer, buff_list); if (buf->status != BUFSTAT_AVAILABLE) { v4l2_err(&dev->v4l2_dev, "buffer not marked as available\n"); ret = -EFAULT; goto err; } urb = buf->urb; urb->status = 0; urb->actual_length = 0; ret = usb_submit_urb(urb, GFP_KERNEL); if (ret) { v4l2_err(&dev->v4l2_dev, "usb_submit_urb in %s returned %d\n", __func__, ret); if (++err_count > 2) break; continue; } buf->status = BUFSTAT_INPROGRESS; list_move_tail(&buf->buff_list, &dev->rec_buff_list); } err: print_buffer_status(); mutex_unlock(&dev->io_mutex); return ret; } static struct hdpvr_buffer *hdpvr_get_next_buffer(struct hdpvr_device *dev) { struct hdpvr_buffer *buf; mutex_lock(&dev->io_mutex); if (list_empty(&dev->rec_buff_list)) { mutex_unlock(&dev->io_mutex); return NULL; } buf = list_entry(dev->rec_buff_list.next, struct hdpvr_buffer, buff_list); mutex_unlock(&dev->io_mutex); return buf; } static void hdpvr_transmit_buffers(struct work_struct *work) { struct hdpvr_device *dev = container_of(work, struct hdpvr_device, worker); while (dev->status == STATUS_STREAMING) { if (hdpvr_submit_buffers(dev)) { v4l2_err(&dev->v4l2_dev, "couldn't submit buffers\n"); goto error; } if (wait_event_interruptible(dev->wait_buffer, !list_empty(&dev->free_buff_list) || dev->status != STATUS_STREAMING)) goto error; } v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev, "transmit worker exited\n"); return; error: v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev, "transmit buffers errored\n"); dev->status = STATUS_ERROR; } /* function expects dev->io_mutex to be hold by caller */ static int hdpvr_start_streaming(struct hdpvr_device *dev) { int ret; struct hdpvr_video_info *vidinf; if (dev->status == STATUS_STREAMING) return 0; else if (dev->status != STATUS_IDLE) return -EAGAIN; vidinf = get_video_info(dev); if (vidinf) { v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev, "video signal: %dx%d@%dhz\n", vidinf->width, vidinf->height, vidinf->fps); kfree(vidinf); /* start streaming 2 request */ ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0), 0xb8, 0x38, 0x1, 0, NULL, 0, 8000); v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev, "encoder start control request returned %d\n", ret); hdpvr_config_call(dev, CTRL_START_STREAMING_VALUE, 0x00); INIT_WORK(&dev->worker, hdpvr_transmit_buffers); queue_work(dev->workqueue, &dev->worker); v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev, "streaming started\n"); dev->status = STATUS_STREAMING; return 0; } msleep(250); v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev, "no video signal at input %d\n", dev->options.video_input); return -EAGAIN; } /* function expects dev->io_mutex to be hold by caller */ static int hdpvr_stop_streaming(struct hdpvr_device *dev) { int actual_length; uint c = 0; u8 *buf; if (dev->status == STATUS_IDLE) return 0; else if (dev->status != STATUS_STREAMING) return -EAGAIN; buf = kmalloc(dev->bulk_in_size, GFP_KERNEL); if (!buf) v4l2_err(&dev->v4l2_dev, "failed to allocate temporary buffer " "for emptying the internal device buffer. " "Next capture start will be slow\n"); dev->status = STATUS_SHUTTING_DOWN; hdpvr_config_call(dev, CTRL_STOP_STREAMING_VALUE, 0x00); mutex_unlock(&dev->io_mutex); wake_up_interruptible(&dev->wait_buffer); msleep(50); flush_workqueue(dev->workqueue); mutex_lock(&dev->io_mutex); /* kill the still outstanding urbs */ hdpvr_cancel_queue(dev); /* emptying the device buffer beforeshutting it down */ while (buf && ++c < 500 && !usb_bulk_msg(dev->udev, usb_rcvbulkpipe(dev->udev, dev->bulk_in_endpointAddr), buf, dev->bulk_in_size, &actual_length, BULK_URB_TIMEOUT)) { v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev, "%2d: got %d bytes\n", c, actual_length); } kfree(buf); v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev, "used %d urbs to empty device buffers\n", c-1); msleep(10); dev->status = STATUS_IDLE; return 0; } /*=======================================================================*/ /* * video 4 linux 2 file operations */ static int hdpvr_open(struct file *file) { struct hdpvr_device *dev; struct hdpvr_fh *fh; int retval = -ENOMEM; dev = (struct hdpvr_device *)video_get_drvdata(video_devdata(file)); if (!dev) { pr_err("open failing with with ENODEV\n"); retval = -ENODEV; goto err; } fh = kzalloc(sizeof(struct hdpvr_fh), GFP_KERNEL); if (!fh) { v4l2_err(&dev->v4l2_dev, "Out of memory\n"); goto err; } /* lock the device to allow correctly handling errors * in resumption */ mutex_lock(&dev->io_mutex); dev->open_count++; mutex_unlock(&dev->io_mutex); fh->dev = dev; /* save our object in the file's private structure */ file->private_data = fh; retval = 0; err: return retval; } static int hdpvr_release(struct file *file) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; if (!dev) return -ENODEV; mutex_lock(&dev->io_mutex); if (!(--dev->open_count) && dev->status == STATUS_STREAMING) hdpvr_stop_streaming(dev); mutex_unlock(&dev->io_mutex); return 0; } /* * hdpvr_v4l2_read() * will allocate buffers when called for the first time */ static ssize_t hdpvr_read(struct file *file, char __user *buffer, size_t count, loff_t *pos) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; struct hdpvr_buffer *buf = NULL; struct urb *urb; unsigned int ret = 0; int rem, cnt; if (*pos) return -ESPIPE; if (!dev) return -ENODEV; mutex_lock(&dev->io_mutex); if (dev->status == STATUS_IDLE) { if (hdpvr_start_streaming(dev)) { v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev, "start_streaming failed\n"); ret = -EIO; msleep(200); dev->status = STATUS_IDLE; mutex_unlock(&dev->io_mutex); goto err; } print_buffer_status(); } mutex_unlock(&dev->io_mutex); /* wait for the first buffer */ if (!(file->f_flags & O_NONBLOCK)) { if (wait_event_interruptible(dev->wait_data, hdpvr_get_next_buffer(dev))) return -ERESTARTSYS; } buf = hdpvr_get_next_buffer(dev); while (count > 0 && buf) { if (buf->status != BUFSTAT_READY && dev->status != STATUS_DISCONNECTED) { /* return nonblocking */ if (file->f_flags & O_NONBLOCK) { if (!ret) ret = -EAGAIN; goto err; } if (wait_event_interruptible(dev->wait_data, buf->status == BUFSTAT_READY)) { ret = -ERESTARTSYS; goto err; } } if (buf->status != BUFSTAT_READY) break; /* set remaining bytes to copy */ urb = buf->urb; rem = urb->actual_length - buf->pos; cnt = rem > count ? count : rem; if (copy_to_user(buffer, urb->transfer_buffer + buf->pos, cnt)) { v4l2_err(&dev->v4l2_dev, "read: copy_to_user failed\n"); if (!ret) ret = -EFAULT; goto err; } buf->pos += cnt; count -= cnt; buffer += cnt; ret += cnt; /* finished, take next buffer */ if (buf->pos == urb->actual_length) { mutex_lock(&dev->io_mutex); buf->pos = 0; buf->status = BUFSTAT_AVAILABLE; list_move_tail(&buf->buff_list, &dev->free_buff_list); print_buffer_status(); mutex_unlock(&dev->io_mutex); wake_up_interruptible(&dev->wait_buffer); buf = hdpvr_get_next_buffer(dev); } } err: if (!ret && !buf) ret = -EAGAIN; return ret; } static unsigned int hdpvr_poll(struct file *filp, poll_table *wait) { struct hdpvr_buffer *buf = NULL; struct hdpvr_fh *fh = filp->private_data; struct hdpvr_device *dev = fh->dev; unsigned int mask = 0; mutex_lock(&dev->io_mutex); if (!video_is_registered(dev->video_dev)) { mutex_unlock(&dev->io_mutex); return -EIO; } if (dev->status == STATUS_IDLE) { if (hdpvr_start_streaming(dev)) { v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev, "start_streaming failed\n"); dev->status = STATUS_IDLE; } print_buffer_status(); } mutex_unlock(&dev->io_mutex); buf = hdpvr_get_next_buffer(dev); /* only wait if no data is available */ if (!buf || buf->status != BUFSTAT_READY) { poll_wait(filp, &dev->wait_data, wait); buf = hdpvr_get_next_buffer(dev); } if (buf && buf->status == BUFSTAT_READY) mask |= POLLIN | POLLRDNORM; return mask; } static const struct v4l2_file_operations hdpvr_fops = { .owner = THIS_MODULE, .open = hdpvr_open, .release = hdpvr_release, .read = hdpvr_read, .poll = hdpvr_poll, .unlocked_ioctl = video_ioctl2, }; /*=======================================================================*/ /* * V4L2 ioctl handling */ static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct hdpvr_device *dev = video_drvdata(file); strcpy(cap->driver, "hdpvr"); strcpy(cap->card, "Hauppauge HD PVR"); usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info)); cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_AUDIO | V4L2_CAP_READWRITE; return 0; } static int vidioc_s_std(struct file *file, void *private_data, v4l2_std_id *std) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; u8 std_type = 1; if (*std & (V4L2_STD_NTSC | V4L2_STD_PAL_60)) std_type = 0; return hdpvr_config_call(dev, CTRL_VIDEO_STD_TYPE, std_type); } static const char *iname[] = { [HDPVR_COMPONENT] = "Component", [HDPVR_SVIDEO] = "S-Video", [HDPVR_COMPOSITE] = "Composite", }; static int vidioc_enum_input(struct file *file, void *priv, struct v4l2_input *i) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; unsigned int n; n = i->index; if (n >= HDPVR_VIDEO_INPUTS) return -EINVAL; i->type = V4L2_INPUT_TYPE_CAMERA; strncpy(i->name, iname[n], sizeof(i->name) - 1); i->name[sizeof(i->name) - 1] = '\0'; i->audioset = 1<<HDPVR_RCA_FRONT | 1<<HDPVR_RCA_BACK | 1<<HDPVR_SPDIF; i->std = dev->video_dev->tvnorms; return 0; } static int vidioc_s_input(struct file *file, void *private_data, unsigned int index) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; int retval; if (index >= HDPVR_VIDEO_INPUTS) return -EINVAL; if (dev->status != STATUS_IDLE) return -EAGAIN; retval = hdpvr_config_call(dev, CTRL_VIDEO_INPUT_VALUE, index+1); if (!retval) dev->options.video_input = index; return retval; } static int vidioc_g_input(struct file *file, void *private_data, unsigned int *index) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; *index = dev->options.video_input; return 0; } static const char *audio_iname[] = { [HDPVR_RCA_FRONT] = "RCA front", [HDPVR_RCA_BACK] = "RCA back", [HDPVR_SPDIF] = "SPDIF", }; static int vidioc_enumaudio(struct file *file, void *priv, struct v4l2_audio *audio) { unsigned int n; n = audio->index; if (n >= HDPVR_AUDIO_INPUTS) return -EINVAL; audio->capability = V4L2_AUDCAP_STEREO; strncpy(audio->name, audio_iname[n], sizeof(audio->name) - 1); audio->name[sizeof(audio->name) - 1] = '\0'; return 0; } static int vidioc_s_audio(struct file *file, void *private_data, struct v4l2_audio *audio) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; int retval; if (audio->index >= HDPVR_AUDIO_INPUTS) return -EINVAL; if (dev->status != STATUS_IDLE) return -EAGAIN; retval = hdpvr_set_audio(dev, audio->index+1, dev->options.audio_codec); if (!retval) dev->options.audio_input = audio->index; return retval; } static int vidioc_g_audio(struct file *file, void *private_data, struct v4l2_audio *audio) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; audio->index = dev->options.audio_input; audio->capability = V4L2_AUDCAP_STEREO; strncpy(audio->name, audio_iname[audio->index], sizeof(audio->name)); audio->name[sizeof(audio->name) - 1] = '\0'; return 0; } static const s32 supported_v4l2_ctrls[] = { V4L2_CID_BRIGHTNESS, V4L2_CID_CONTRAST, V4L2_CID_SATURATION, V4L2_CID_HUE, V4L2_CID_SHARPNESS, V4L2_CID_MPEG_AUDIO_ENCODING, V4L2_CID_MPEG_VIDEO_ENCODING, V4L2_CID_MPEG_VIDEO_BITRATE_MODE, V4L2_CID_MPEG_VIDEO_BITRATE, V4L2_CID_MPEG_VIDEO_BITRATE_PEAK, }; static int fill_queryctrl(struct hdpvr_options *opt, struct v4l2_queryctrl *qc, int ac3) { int err; switch (qc->id) { case V4L2_CID_BRIGHTNESS: return v4l2_ctrl_query_fill(qc, 0x0, 0xff, 1, 0x86); case V4L2_CID_CONTRAST: return v4l2_ctrl_query_fill(qc, 0x0, 0xff, 1, 0x80); case V4L2_CID_SATURATION: return v4l2_ctrl_query_fill(qc, 0x0, 0xff, 1, 0x80); case V4L2_CID_HUE: return v4l2_ctrl_query_fill(qc, 0x0, 0xff, 1, 0x80); case V4L2_CID_SHARPNESS: return v4l2_ctrl_query_fill(qc, 0x0, 0xff, 1, 0x80); case V4L2_CID_MPEG_AUDIO_ENCODING: return v4l2_ctrl_query_fill( qc, V4L2_MPEG_AUDIO_ENCODING_AAC, ac3 ? V4L2_MPEG_AUDIO_ENCODING_AC3 : V4L2_MPEG_AUDIO_ENCODING_AAC, 1, V4L2_MPEG_AUDIO_ENCODING_AAC); case V4L2_CID_MPEG_VIDEO_ENCODING: return v4l2_ctrl_query_fill( qc, V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC, V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC, 1, V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC); /* case V4L2_CID_MPEG_VIDEO_? maybe keyframe interval: */ /* return v4l2_ctrl_query_fill(qc, 0, 128, 128, 0); */ case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: return v4l2_ctrl_query_fill( qc, V4L2_MPEG_VIDEO_BITRATE_MODE_VBR, V4L2_MPEG_VIDEO_BITRATE_MODE_CBR, 1, V4L2_MPEG_VIDEO_BITRATE_MODE_CBR); case V4L2_CID_MPEG_VIDEO_BITRATE: return v4l2_ctrl_query_fill(qc, 1000000, 13500000, 100000, 6500000); case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: err = v4l2_ctrl_query_fill(qc, 1100000, 20200000, 100000, 9000000); if (!err && opt->bitrate_mode == HDPVR_CONSTANT) qc->flags |= V4L2_CTRL_FLAG_INACTIVE; return err; default: return -EINVAL; } } static int vidioc_queryctrl(struct file *file, void *private_data, struct v4l2_queryctrl *qc) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; int i, next; u32 id = qc->id; memset(qc, 0, sizeof(*qc)); next = !!(id & V4L2_CTRL_FLAG_NEXT_CTRL); qc->id = id & ~V4L2_CTRL_FLAG_NEXT_CTRL; for (i = 0; i < ARRAY_SIZE(supported_v4l2_ctrls); i++) { if (next) { if (qc->id < supported_v4l2_ctrls[i]) qc->id = supported_v4l2_ctrls[i]; else continue; } if (qc->id == supported_v4l2_ctrls[i]) return fill_queryctrl(&dev->options, qc, dev->flags & HDPVR_FLAG_AC3_CAP); if (qc->id < supported_v4l2_ctrls[i]) break; } return -EINVAL; } static int vidioc_g_ctrl(struct file *file, void *private_data, struct v4l2_control *ctrl) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: ctrl->value = dev->options.brightness; break; case V4L2_CID_CONTRAST: ctrl->value = dev->options.contrast; break; case V4L2_CID_SATURATION: ctrl->value = dev->options.saturation; break; case V4L2_CID_HUE: ctrl->value = dev->options.hue; break; case V4L2_CID_SHARPNESS: ctrl->value = dev->options.sharpness; break; default: return -EINVAL; } return 0; } static int vidioc_s_ctrl(struct file *file, void *private_data, struct v4l2_control *ctrl) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; int retval; switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: retval = hdpvr_config_call(dev, CTRL_BRIGHTNESS, ctrl->value); if (!retval) dev->options.brightness = ctrl->value; break; case V4L2_CID_CONTRAST: retval = hdpvr_config_call(dev, CTRL_CONTRAST, ctrl->value); if (!retval) dev->options.contrast = ctrl->value; break; case V4L2_CID_SATURATION: retval = hdpvr_config_call(dev, CTRL_SATURATION, ctrl->value); if (!retval) dev->options.saturation = ctrl->value; break; case V4L2_CID_HUE: retval = hdpvr_config_call(dev, CTRL_HUE, ctrl->value); if (!retval) dev->options.hue = ctrl->value; break; case V4L2_CID_SHARPNESS: retval = hdpvr_config_call(dev, CTRL_SHARPNESS, ctrl->value); if (!retval) dev->options.sharpness = ctrl->value; break; default: return -EINVAL; } return retval; } static int hdpvr_get_ctrl(struct hdpvr_options *opt, struct v4l2_ext_control *ctrl) { switch (ctrl->id) { case V4L2_CID_MPEG_AUDIO_ENCODING: ctrl->value = opt->audio_codec; break; case V4L2_CID_MPEG_VIDEO_ENCODING: ctrl->value = V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC; break; /* case V4L2_CID_MPEG_VIDEO_B_FRAMES: */ /* ctrl->value = (opt->gop_mode & 0x2) ? 0 : 128; */ /* break; */ case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: ctrl->value = opt->bitrate_mode == HDPVR_CONSTANT ? V4L2_MPEG_VIDEO_BITRATE_MODE_CBR : V4L2_MPEG_VIDEO_BITRATE_MODE_VBR; break; case V4L2_CID_MPEG_VIDEO_BITRATE: ctrl->value = opt->bitrate * 100000; break; case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: ctrl->value = opt->peak_bitrate * 100000; break; case V4L2_CID_MPEG_STREAM_TYPE: ctrl->value = V4L2_MPEG_STREAM_TYPE_MPEG2_TS; break; default: return -EINVAL; } return 0; } static int vidioc_g_ext_ctrls(struct file *file, void *priv, struct v4l2_ext_controls *ctrls) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; int i, err = 0; if (ctrls->ctrl_class == V4L2_CTRL_CLASS_MPEG) { for (i = 0; i < ctrls->count; i++) { struct v4l2_ext_control *ctrl = ctrls->controls + i; err = hdpvr_get_ctrl(&dev->options, ctrl); if (err) { ctrls->error_idx = i; break; } } return err; } return -EINVAL; } static int hdpvr_try_ctrl(struct v4l2_ext_control *ctrl, int ac3) { int ret = -EINVAL; switch (ctrl->id) { case V4L2_CID_MPEG_AUDIO_ENCODING: if (ctrl->value == V4L2_MPEG_AUDIO_ENCODING_AAC || (ac3 && ctrl->value == V4L2_MPEG_AUDIO_ENCODING_AC3)) ret = 0; break; case V4L2_CID_MPEG_VIDEO_ENCODING: if (ctrl->value == V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC) ret = 0; break; /* case V4L2_CID_MPEG_VIDEO_B_FRAMES: */ /* if (ctrl->value == 0 || ctrl->value == 128) */ /* ret = 0; */ /* break; */ case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: if (ctrl->value == V4L2_MPEG_VIDEO_BITRATE_MODE_CBR || ctrl->value == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR) ret = 0; break; case V4L2_CID_MPEG_VIDEO_BITRATE: { uint bitrate = ctrl->value / 100000; if (bitrate >= 10 && bitrate <= 135) ret = 0; break; } case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: { uint peak_bitrate = ctrl->value / 100000; if (peak_bitrate >= 10 && peak_bitrate <= 202) ret = 0; break; } case V4L2_CID_MPEG_STREAM_TYPE: if (ctrl->value == V4L2_MPEG_STREAM_TYPE_MPEG2_TS) ret = 0; break; default: return -EINVAL; } return 0; } static int vidioc_try_ext_ctrls(struct file *file, void *priv, struct v4l2_ext_controls *ctrls) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; int i, err = 0; if (ctrls->ctrl_class == V4L2_CTRL_CLASS_MPEG) { for (i = 0; i < ctrls->count; i++) { struct v4l2_ext_control *ctrl = ctrls->controls + i; err = hdpvr_try_ctrl(ctrl, dev->flags & HDPVR_FLAG_AC3_CAP); if (err) { ctrls->error_idx = i; break; } } return err; } return -EINVAL; } static int hdpvr_set_ctrl(struct hdpvr_device *dev, struct v4l2_ext_control *ctrl) { struct hdpvr_options *opt = &dev->options; int ret = 0; switch (ctrl->id) { case V4L2_CID_MPEG_AUDIO_ENCODING: if (dev->flags & HDPVR_FLAG_AC3_CAP) { opt->audio_codec = ctrl->value; ret = hdpvr_set_audio(dev, opt->audio_input, opt->audio_codec); } break; case V4L2_CID_MPEG_VIDEO_ENCODING: break; /* case V4L2_CID_MPEG_VIDEO_B_FRAMES: */ /* if (ctrl->value == 0 && !(opt->gop_mode & 0x2)) { */ /* opt->gop_mode |= 0x2; */ /* hdpvr_config_call(dev, CTRL_GOP_MODE_VALUE, */ /* opt->gop_mode); */ /* } */ /* if (ctrl->value == 128 && opt->gop_mode & 0x2) { */ /* opt->gop_mode &= ~0x2; */ /* hdpvr_config_call(dev, CTRL_GOP_MODE_VALUE, */ /* opt->gop_mode); */ /* } */ /* break; */ case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: if (ctrl->value == V4L2_MPEG_VIDEO_BITRATE_MODE_CBR && opt->bitrate_mode != HDPVR_CONSTANT) { opt->bitrate_mode = HDPVR_CONSTANT; hdpvr_config_call(dev, CTRL_BITRATE_MODE_VALUE, opt->bitrate_mode); } if (ctrl->value == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR && opt->bitrate_mode == HDPVR_CONSTANT) { opt->bitrate_mode = HDPVR_VARIABLE_AVERAGE; hdpvr_config_call(dev, CTRL_BITRATE_MODE_VALUE, opt->bitrate_mode); } break; case V4L2_CID_MPEG_VIDEO_BITRATE: { uint bitrate = ctrl->value / 100000; opt->bitrate = bitrate; if (bitrate >= opt->peak_bitrate) opt->peak_bitrate = bitrate+1; hdpvr_set_bitrate(dev); break; } case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: { uint peak_bitrate = ctrl->value / 100000; if (opt->bitrate_mode == HDPVR_CONSTANT) break; if (opt->bitrate < peak_bitrate) { opt->peak_bitrate = peak_bitrate; hdpvr_set_bitrate(dev); } else ret = -EINVAL; break; } case V4L2_CID_MPEG_STREAM_TYPE: break; default: return -EINVAL; } return ret; } static int vidioc_s_ext_ctrls(struct file *file, void *priv, struct v4l2_ext_controls *ctrls) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; int i, err = 0; if (ctrls->ctrl_class == V4L2_CTRL_CLASS_MPEG) { for (i = 0; i < ctrls->count; i++) { struct v4l2_ext_control *ctrl = ctrls->controls + i; err = hdpvr_try_ctrl(ctrl, dev->flags & HDPVR_FLAG_AC3_CAP); if (err) { ctrls->error_idx = i; break; } err = hdpvr_set_ctrl(dev, ctrl); if (err) { ctrls->error_idx = i; break; } } return err; } return -EINVAL; } static int vidioc_enum_fmt_vid_cap(struct file *file, void *private_data, struct v4l2_fmtdesc *f) { if (f->index != 0 || f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; f->flags = V4L2_FMT_FLAG_COMPRESSED; strncpy(f->description, "MPEG2-TS with AVC/AAC streams", 32); f->pixelformat = V4L2_PIX_FMT_MPEG; return 0; } static int vidioc_g_fmt_vid_cap(struct file *file, void *private_data, struct v4l2_format *f) { struct hdpvr_fh *fh = file->private_data; struct hdpvr_device *dev = fh->dev; struct hdpvr_video_info *vid_info; if (!dev) return -ENODEV; vid_info = get_video_info(dev); if (!vid_info) return -EFAULT; f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; f->fmt.pix.pixelformat = V4L2_PIX_FMT_MPEG; f->fmt.pix.width = vid_info->width; f->fmt.pix.height = vid_info->height; f->fmt.pix.sizeimage = dev->bulk_in_size; f->fmt.pix.colorspace = 0; f->fmt.pix.bytesperline = 0; f->fmt.pix.field = V4L2_FIELD_ANY; kfree(vid_info); return 0; } static int vidioc_encoder_cmd(struct file *filp, void *priv, struct v4l2_encoder_cmd *a) { struct hdpvr_fh *fh = filp->private_data; struct hdpvr_device *dev = fh->dev; int res; mutex_lock(&dev->io_mutex); memset(&a->raw, 0, sizeof(a->raw)); switch (a->cmd) { case V4L2_ENC_CMD_START: a->flags = 0; res = hdpvr_start_streaming(dev); break; case V4L2_ENC_CMD_STOP: res = hdpvr_stop_streaming(dev); break; default: v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev, "Unsupported encoder cmd %d\n", a->cmd); res = -EINVAL; } mutex_unlock(&dev->io_mutex); return res; } static int vidioc_try_encoder_cmd(struct file *filp, void *priv, struct v4l2_encoder_cmd *a) { switch (a->cmd) { case V4L2_ENC_CMD_START: case V4L2_ENC_CMD_STOP: return 0; default: return -EINVAL; } } static const struct v4l2_ioctl_ops hdpvr_ioctl_ops = { .vidioc_querycap = vidioc_querycap, .vidioc_s_std = vidioc_s_std, .vidioc_enum_input = vidioc_enum_input, .vidioc_g_input = vidioc_g_input, .vidioc_s_input = vidioc_s_input, .vidioc_enumaudio = vidioc_enumaudio, .vidioc_g_audio = vidioc_g_audio, .vidioc_s_audio = vidioc_s_audio, .vidioc_queryctrl = vidioc_queryctrl, .vidioc_g_ctrl = vidioc_g_ctrl, .vidioc_s_ctrl = vidioc_s_ctrl, .vidioc_g_ext_ctrls = vidioc_g_ext_ctrls, .vidioc_s_ext_ctrls = vidioc_s_ext_ctrls, .vidioc_try_ext_ctrls = vidioc_try_ext_ctrls, .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap, .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap, .vidioc_encoder_cmd = vidioc_encoder_cmd, .vidioc_try_encoder_cmd = vidioc_try_encoder_cmd, }; static void hdpvr_device_release(struct video_device *vdev) { struct hdpvr_device *dev = video_get_drvdata(vdev); hdpvr_delete(dev); mutex_lock(&dev->io_mutex); destroy_workqueue(dev->workqueue); mutex_unlock(&dev->io_mutex); v4l2_device_unregister(&dev->v4l2_dev); /* deregister I2C adapter */ #if defined(CONFIG_I2C) || (CONFIG_I2C_MODULE) mutex_lock(&dev->i2c_mutex); i2c_del_adapter(&dev->i2c_adapter); mutex_unlock(&dev->i2c_mutex); #endif /* CONFIG_I2C */ kfree(dev->usbc_buf); kfree(dev); } static const struct video_device hdpvr_video_template = { /* .type = VFL_TYPE_GRABBER, */ /* .type2 = VID_TYPE_CAPTURE | VID_TYPE_MPEG_ENCODER, */ .fops = &hdpvr_fops, .release = hdpvr_device_release, .ioctl_ops = &hdpvr_ioctl_ops, .tvnorms = V4L2_STD_NTSC | V4L2_STD_SECAM | V4L2_STD_PAL_B | V4L2_STD_PAL_G | V4L2_STD_PAL_H | V4L2_STD_PAL_I | V4L2_STD_PAL_D | V4L2_STD_PAL_M | V4L2_STD_PAL_N | V4L2_STD_PAL_60, .current_norm = V4L2_STD_NTSC | V4L2_STD_PAL_M | V4L2_STD_PAL_60, }; int hdpvr_register_videodev(struct hdpvr_device *dev, struct device *parent, int devnum) { /* setup and register video device */ dev->video_dev = video_device_alloc(); if (!dev->video_dev) { v4l2_err(&dev->v4l2_dev, "video_device_alloc() failed\n"); goto error; } *(dev->video_dev) = hdpvr_video_template; strcpy(dev->video_dev->name, "Hauppauge HD PVR"); dev->video_dev->parent = parent; video_set_drvdata(dev->video_dev, dev); if (video_register_device(dev->video_dev, VFL_TYPE_GRABBER, devnum)) { v4l2_err(&dev->v4l2_dev, "video_device registration failed\n"); goto error; } return 0; error: return -ENOMEM; }
gpl-2.0
fanzhidongyzby/linux
drivers/input/keyboard/cap11xx.c
548
10469
/* * Input driver for Microchip CAP11xx based capacitive touch sensors * * (c) 2014 Daniel Mack <linux@zonque.org> * * 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/module.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/of_irq.h> #include <linux/regmap.h> #include <linux/i2c.h> #include <linux/gpio/consumer.h> #define CAP11XX_REG_MAIN_CONTROL 0x00 #define CAP11XX_REG_MAIN_CONTROL_GAIN_SHIFT (6) #define CAP11XX_REG_MAIN_CONTROL_GAIN_MASK (0xc0) #define CAP11XX_REG_MAIN_CONTROL_DLSEEP BIT(4) #define CAP11XX_REG_GENERAL_STATUS 0x02 #define CAP11XX_REG_SENSOR_INPUT 0x03 #define CAP11XX_REG_NOISE_FLAG_STATUS 0x0a #define CAP11XX_REG_SENOR_DELTA(X) (0x10 + (X)) #define CAP11XX_REG_SENSITIVITY_CONTROL 0x1f #define CAP11XX_REG_CONFIG 0x20 #define CAP11XX_REG_SENSOR_ENABLE 0x21 #define CAP11XX_REG_SENSOR_CONFIG 0x22 #define CAP11XX_REG_SENSOR_CONFIG2 0x23 #define CAP11XX_REG_SAMPLING_CONFIG 0x24 #define CAP11XX_REG_CALIBRATION 0x26 #define CAP11XX_REG_INT_ENABLE 0x27 #define CAP11XX_REG_REPEAT_RATE 0x28 #define CAP11XX_REG_MT_CONFIG 0x2a #define CAP11XX_REG_MT_PATTERN_CONFIG 0x2b #define CAP11XX_REG_MT_PATTERN 0x2d #define CAP11XX_REG_RECALIB_CONFIG 0x2f #define CAP11XX_REG_SENSOR_THRESH(X) (0x30 + (X)) #define CAP11XX_REG_SENSOR_NOISE_THRESH 0x38 #define CAP11XX_REG_STANDBY_CHANNEL 0x40 #define CAP11XX_REG_STANDBY_CONFIG 0x41 #define CAP11XX_REG_STANDBY_SENSITIVITY 0x42 #define CAP11XX_REG_STANDBY_THRESH 0x43 #define CAP11XX_REG_CONFIG2 0x44 #define CAP11XX_REG_CONFIG2_ALT_POL BIT(6) #define CAP11XX_REG_SENSOR_BASE_CNT(X) (0x50 + (X)) #define CAP11XX_REG_SENSOR_CALIB (0xb1 + (X)) #define CAP11XX_REG_SENSOR_CALIB_LSB1 0xb9 #define CAP11XX_REG_SENSOR_CALIB_LSB2 0xba #define CAP11XX_REG_PRODUCT_ID 0xfd #define CAP11XX_REG_MANUFACTURER_ID 0xfe #define CAP11XX_REG_REVISION 0xff #define CAP11XX_MANUFACTURER_ID 0x5d struct cap11xx_priv { struct regmap *regmap; struct input_dev *idev; /* config */ u32 keycodes[]; }; struct cap11xx_hw_model { u8 product_id; unsigned int num_channels; }; enum { CAP1106, CAP1126, CAP1188, }; static const struct cap11xx_hw_model cap11xx_devices[] = { [CAP1106] = { .product_id = 0x55, .num_channels = 6 }, [CAP1126] = { .product_id = 0x53, .num_channels = 6 }, [CAP1188] = { .product_id = 0x50, .num_channels = 8 }, }; static const struct reg_default cap11xx_reg_defaults[] = { { CAP11XX_REG_MAIN_CONTROL, 0x00 }, { CAP11XX_REG_GENERAL_STATUS, 0x00 }, { CAP11XX_REG_SENSOR_INPUT, 0x00 }, { CAP11XX_REG_NOISE_FLAG_STATUS, 0x00 }, { CAP11XX_REG_SENSITIVITY_CONTROL, 0x2f }, { CAP11XX_REG_CONFIG, 0x20 }, { CAP11XX_REG_SENSOR_ENABLE, 0x3f }, { CAP11XX_REG_SENSOR_CONFIG, 0xa4 }, { CAP11XX_REG_SENSOR_CONFIG2, 0x07 }, { CAP11XX_REG_SAMPLING_CONFIG, 0x39 }, { CAP11XX_REG_CALIBRATION, 0x00 }, { CAP11XX_REG_INT_ENABLE, 0x3f }, { CAP11XX_REG_REPEAT_RATE, 0x3f }, { CAP11XX_REG_MT_CONFIG, 0x80 }, { CAP11XX_REG_MT_PATTERN_CONFIG, 0x00 }, { CAP11XX_REG_MT_PATTERN, 0x3f }, { CAP11XX_REG_RECALIB_CONFIG, 0x8a }, { CAP11XX_REG_SENSOR_THRESH(0), 0x40 }, { CAP11XX_REG_SENSOR_THRESH(1), 0x40 }, { CAP11XX_REG_SENSOR_THRESH(2), 0x40 }, { CAP11XX_REG_SENSOR_THRESH(3), 0x40 }, { CAP11XX_REG_SENSOR_THRESH(4), 0x40 }, { CAP11XX_REG_SENSOR_THRESH(5), 0x40 }, { CAP11XX_REG_SENSOR_NOISE_THRESH, 0x01 }, { CAP11XX_REG_STANDBY_CHANNEL, 0x00 }, { CAP11XX_REG_STANDBY_CONFIG, 0x39 }, { CAP11XX_REG_STANDBY_SENSITIVITY, 0x02 }, { CAP11XX_REG_STANDBY_THRESH, 0x40 }, { CAP11XX_REG_CONFIG2, 0x40 }, { CAP11XX_REG_SENSOR_CALIB_LSB1, 0x00 }, { CAP11XX_REG_SENSOR_CALIB_LSB2, 0x00 }, }; static bool cap11xx_volatile_reg(struct device *dev, unsigned int reg) { switch (reg) { case CAP11XX_REG_MAIN_CONTROL: case CAP11XX_REG_SENSOR_INPUT: case CAP11XX_REG_SENOR_DELTA(0): case CAP11XX_REG_SENOR_DELTA(1): case CAP11XX_REG_SENOR_DELTA(2): case CAP11XX_REG_SENOR_DELTA(3): case CAP11XX_REG_SENOR_DELTA(4): case CAP11XX_REG_SENOR_DELTA(5): case CAP11XX_REG_PRODUCT_ID: case CAP11XX_REG_MANUFACTURER_ID: case CAP11XX_REG_REVISION: return true; } return false; } static const struct regmap_config cap11xx_regmap_config = { .reg_bits = 8, .val_bits = 8, .max_register = CAP11XX_REG_REVISION, .reg_defaults = cap11xx_reg_defaults, .num_reg_defaults = ARRAY_SIZE(cap11xx_reg_defaults), .cache_type = REGCACHE_RBTREE, .volatile_reg = cap11xx_volatile_reg, }; static irqreturn_t cap11xx_thread_func(int irq_num, void *data) { struct cap11xx_priv *priv = data; unsigned int status; int ret, i; /* * Deassert interrupt. This needs to be done before reading the status * registers, which will not carry valid values otherwise. */ ret = regmap_update_bits(priv->regmap, CAP11XX_REG_MAIN_CONTROL, 1, 0); if (ret < 0) goto out; ret = regmap_read(priv->regmap, CAP11XX_REG_SENSOR_INPUT, &status); if (ret < 0) goto out; for (i = 0; i < priv->idev->keycodemax; i++) input_report_key(priv->idev, priv->keycodes[i], status & (1 << i)); input_sync(priv->idev); out: return IRQ_HANDLED; } static int cap11xx_set_sleep(struct cap11xx_priv *priv, bool sleep) { return regmap_update_bits(priv->regmap, CAP11XX_REG_MAIN_CONTROL, CAP11XX_REG_MAIN_CONTROL_DLSEEP, sleep ? CAP11XX_REG_MAIN_CONTROL_DLSEEP : 0); } static int cap11xx_input_open(struct input_dev *idev) { struct cap11xx_priv *priv = input_get_drvdata(idev); return cap11xx_set_sleep(priv, false); } static void cap11xx_input_close(struct input_dev *idev) { struct cap11xx_priv *priv = input_get_drvdata(idev); cap11xx_set_sleep(priv, true); } static int cap11xx_i2c_probe(struct i2c_client *i2c_client, const struct i2c_device_id *id) { struct device *dev = &i2c_client->dev; struct cap11xx_priv *priv; struct device_node *node; const struct cap11xx_hw_model *cap; int i, error, irq, gain = 0; unsigned int val, rev; u32 gain32; if (id->driver_data >= ARRAY_SIZE(cap11xx_devices)) { dev_err(dev, "Invalid device ID %lu\n", id->driver_data); return -EINVAL; } cap = &cap11xx_devices[id->driver_data]; if (!cap || !cap->num_channels) { dev_err(dev, "Invalid device configuration\n"); return -EINVAL; } priv = devm_kzalloc(dev, sizeof(*priv) + cap->num_channels * sizeof(priv->keycodes[0]), GFP_KERNEL); if (!priv) return -ENOMEM; priv->regmap = devm_regmap_init_i2c(i2c_client, &cap11xx_regmap_config); if (IS_ERR(priv->regmap)) return PTR_ERR(priv->regmap); error = regmap_read(priv->regmap, CAP11XX_REG_PRODUCT_ID, &val); if (error) return error; if (val != cap->product_id) { dev_err(dev, "Product ID: Got 0x%02x, expected 0x%02x\n", val, cap->product_id); return -ENXIO; } error = regmap_read(priv->regmap, CAP11XX_REG_MANUFACTURER_ID, &val); if (error) return error; if (val != CAP11XX_MANUFACTURER_ID) { dev_err(dev, "Manufacturer ID: Got 0x%02x, expected 0x%02x\n", val, CAP11XX_MANUFACTURER_ID); return -ENXIO; } error = regmap_read(priv->regmap, CAP11XX_REG_REVISION, &rev); if (error < 0) return error; dev_info(dev, "CAP11XX detected, revision 0x%02x\n", rev); i2c_set_clientdata(i2c_client, priv); node = dev->of_node; if (!of_property_read_u32(node, "microchip,sensor-gain", &gain32)) { if (is_power_of_2(gain32) && gain32 <= 8) gain = ilog2(gain32); else dev_err(dev, "Invalid sensor-gain value %d\n", gain32); } if (of_property_read_bool(node, "microchip,irq-active-high")) { error = regmap_update_bits(priv->regmap, CAP11XX_REG_CONFIG2, CAP11XX_REG_CONFIG2_ALT_POL, 0); if (error) return error; } /* Provide some useful defaults */ for (i = 0; i < cap->num_channels; i++) priv->keycodes[i] = KEY_A + i; of_property_read_u32_array(node, "linux,keycodes", priv->keycodes, cap->num_channels); error = regmap_update_bits(priv->regmap, CAP11XX_REG_MAIN_CONTROL, CAP11XX_REG_MAIN_CONTROL_GAIN_MASK, gain << CAP11XX_REG_MAIN_CONTROL_GAIN_SHIFT); if (error) return error; /* Disable autorepeat. The Linux input system has its own handling. */ error = regmap_write(priv->regmap, CAP11XX_REG_REPEAT_RATE, 0); if (error) return error; priv->idev = devm_input_allocate_device(dev); if (!priv->idev) return -ENOMEM; priv->idev->name = "CAP11XX capacitive touch sensor"; priv->idev->id.bustype = BUS_I2C; priv->idev->evbit[0] = BIT_MASK(EV_KEY); if (of_property_read_bool(node, "autorepeat")) __set_bit(EV_REP, priv->idev->evbit); for (i = 0; i < cap->num_channels; i++) __set_bit(priv->keycodes[i], priv->idev->keybit); __clear_bit(KEY_RESERVED, priv->idev->keybit); priv->idev->keycode = priv->keycodes; priv->idev->keycodesize = sizeof(priv->keycodes[0]); priv->idev->keycodemax = cap->num_channels; priv->idev->id.vendor = CAP11XX_MANUFACTURER_ID; priv->idev->id.product = cap->product_id; priv->idev->id.version = rev; priv->idev->open = cap11xx_input_open; priv->idev->close = cap11xx_input_close; input_set_drvdata(priv->idev, priv); /* * Put the device in deep sleep mode for now. * ->open() will bring it back once the it is actually needed. */ cap11xx_set_sleep(priv, true); error = input_register_device(priv->idev); if (error) return error; irq = irq_of_parse_and_map(node, 0); if (!irq) { dev_err(dev, "Unable to parse or map IRQ\n"); return -ENXIO; } error = devm_request_threaded_irq(dev, irq, NULL, cap11xx_thread_func, IRQF_ONESHOT, dev_name(dev), priv); if (error) return error; return 0; } static const struct of_device_id cap11xx_dt_ids[] = { { .compatible = "microchip,cap1106", }, { .compatible = "microchip,cap1126", }, { .compatible = "microchip,cap1188", }, {} }; MODULE_DEVICE_TABLE(of, cap11xx_dt_ids); static const struct i2c_device_id cap11xx_i2c_ids[] = { { "cap1106", CAP1106 }, { "cap1126", CAP1126 }, { "cap1188", CAP1188 }, {} }; MODULE_DEVICE_TABLE(i2c, cap11xx_i2c_ids); static struct i2c_driver cap11xx_i2c_driver = { .driver = { .name = "cap11xx", .owner = THIS_MODULE, .of_match_table = cap11xx_dt_ids, }, .id_table = cap11xx_i2c_ids, .probe = cap11xx_i2c_probe, }; module_i2c_driver(cap11xx_i2c_driver); MODULE_DESCRIPTION("Microchip CAP11XX driver"); MODULE_AUTHOR("Daniel Mack <linux@zonque.org>"); MODULE_LICENSE("GPL v2");
gpl-2.0
sch2307/android_kernel_ezboard_s100
drivers/video/console/fbcon_cw.c
804
10785
/* * linux/drivers/video/console/fbcon_ud.c -- Software Rotation - 90 degrees * * Copyright (C) 2005 Antonino Daplas <adaplas @pol.net> * * 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/module.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/fb.h> #include <linux/vt_kern.h> #include <linux/console.h> #include <asm/types.h> #include "fbcon.h" #include "fbcon_rotate.h" /* * Rotation 90 degrees */ static inline void cw_update_attr(u8 *dst, u8 *src, int attribute, struct vc_data *vc) { int i, j, offset = (vc->vc_font.height < 10) ? 1 : 2; int width = (vc->vc_font.height + 7) >> 3; u8 c, t = 0, msk = ~(0xff >> offset); for (i = 0; i < vc->vc_font.width; i++) { for (j = 0; j < width; j++) { c = *src; if (attribute & FBCON_ATTRIBUTE_UNDERLINE && !j) c |= msk; if (attribute & FBCON_ATTRIBUTE_BOLD && i) c |= *(src-width); if (attribute & FBCON_ATTRIBUTE_REVERSE) c = ~c; src++; *dst++ = c; t = c; } } } static void cw_bmove(struct vc_data *vc, struct fb_info *info, int sy, int sx, int dy, int dx, int height, int width) { struct fbcon_ops *ops = info->fbcon_par; struct fb_copyarea area; u32 vxres = GETVXRES(ops->p->scrollmode, info); area.sx = vxres - ((sy + height) * vc->vc_font.height); area.sy = sx * vc->vc_font.width; area.dx = vxres - ((dy + height) * vc->vc_font.height); area.dy = dx * vc->vc_font.width; area.width = height * vc->vc_font.height; area.height = width * vc->vc_font.width; info->fbops->fb_copyarea(info, &area); } static void cw_clear(struct vc_data *vc, struct fb_info *info, int sy, int sx, int height, int width) { struct fbcon_ops *ops = info->fbcon_par; struct fb_fillrect region; int bgshift = (vc->vc_hi_font_mask) ? 13 : 12; u32 vxres = GETVXRES(ops->p->scrollmode, info); region.color = attr_bgcol_ec(bgshift,vc,info); region.dx = vxres - ((sy + height) * vc->vc_font.height); region.dy = sx * vc->vc_font.width; region.height = width * vc->vc_font.width; region.width = height * vc->vc_font.height; region.rop = ROP_COPY; info->fbops->fb_fillrect(info, &region); } static inline void cw_putcs_aligned(struct vc_data *vc, struct fb_info *info, const u16 *s, u32 attr, u32 cnt, u32 d_pitch, u32 s_pitch, u32 cellsize, struct fb_image *image, u8 *buf, u8 *dst) { struct fbcon_ops *ops = info->fbcon_par; u16 charmask = vc->vc_hi_font_mask ? 0x1ff : 0xff; u32 idx = (vc->vc_font.height + 7) >> 3; u8 *src; while (cnt--) { src = ops->fontbuffer + (scr_readw(s++) & charmask)*cellsize; if (attr) { cw_update_attr(buf, src, attr, vc); src = buf; } if (likely(idx == 1)) __fb_pad_aligned_buffer(dst, d_pitch, src, idx, vc->vc_font.width); else fb_pad_aligned_buffer(dst, d_pitch, src, idx, vc->vc_font.width); dst += d_pitch * vc->vc_font.width; } info->fbops->fb_imageblit(info, image); } static void cw_putcs(struct vc_data *vc, struct fb_info *info, const unsigned short *s, int count, int yy, int xx, int fg, int bg) { struct fb_image image; struct fbcon_ops *ops = info->fbcon_par; u32 width = (vc->vc_font.height + 7)/8; u32 cellsize = width * vc->vc_font.width; u32 maxcnt = info->pixmap.size/cellsize; u32 scan_align = info->pixmap.scan_align - 1; u32 buf_align = info->pixmap.buf_align - 1; u32 cnt, pitch, size; u32 attribute = get_attribute(info, scr_readw(s)); u8 *dst, *buf = NULL; u32 vxres = GETVXRES(ops->p->scrollmode, info); if (!ops->fontbuffer) return; image.fg_color = fg; image.bg_color = bg; image.dx = vxres - ((yy + 1) * vc->vc_font.height); image.dy = xx * vc->vc_font.width; image.width = vc->vc_font.height; image.depth = 1; if (attribute) { buf = kmalloc(cellsize, GFP_KERNEL); if (!buf) return; } while (count) { if (count > maxcnt) cnt = maxcnt; else cnt = count; image.height = vc->vc_font.width * cnt; pitch = ((image.width + 7) >> 3) + scan_align; pitch &= ~scan_align; size = pitch * image.height + buf_align; size &= ~buf_align; dst = fb_get_buffer_offset(info, &info->pixmap, size); image.data = dst; cw_putcs_aligned(vc, info, s, attribute, cnt, pitch, width, cellsize, &image, buf, dst); image.dy += image.height; count -= cnt; s += cnt; } /* buf is always NULL except when in monochrome mode, so in this case it's a gain to check buf against NULL even though kfree() handles NULL pointers just fine */ if (unlikely(buf)) kfree(buf); } static void cw_clear_margins(struct vc_data *vc, struct fb_info *info, int bottom_only) { unsigned int cw = vc->vc_font.width; unsigned int ch = vc->vc_font.height; unsigned int rw = info->var.yres - (vc->vc_cols*cw); unsigned int bh = info->var.xres - (vc->vc_rows*ch); unsigned int rs = info->var.yres - rw; struct fb_fillrect region; int bgshift = (vc->vc_hi_font_mask) ? 13 : 12; region.color = attr_bgcol_ec(bgshift,vc,info); region.rop = ROP_COPY; if (rw && !bottom_only) { region.dx = 0; region.dy = info->var.yoffset + rs; region.height = rw; region.width = info->var.xres_virtual; info->fbops->fb_fillrect(info, &region); } if (bh) { region.dx = info->var.xoffset; region.dy = info->var.yoffset; region.height = info->var.yres; region.width = bh; info->fbops->fb_fillrect(info, &region); } } static void cw_cursor(struct vc_data *vc, struct fb_info *info, int mode, int softback_lines, int fg, int bg) { struct fb_cursor cursor; struct fbcon_ops *ops = info->fbcon_par; unsigned short charmask = vc->vc_hi_font_mask ? 0x1ff : 0xff; int w = (vc->vc_font.height + 7) >> 3, c; int y = real_y(ops->p, vc->vc_y); int attribute, use_sw = (vc->vc_cursor_type & 0x10); int err = 1, dx, dy; char *src; u32 vxres = GETVXRES(ops->p->scrollmode, info); if (!ops->fontbuffer) return; cursor.set = 0; if (softback_lines) { if (y + softback_lines >= vc->vc_rows) { mode = CM_ERASE; ops->cursor_flash = 0; return; } else y += softback_lines; } c = scr_readw((u16 *) vc->vc_pos); attribute = get_attribute(info, c); src = ops->fontbuffer + ((c & charmask) * (w * vc->vc_font.width)); if (ops->cursor_state.image.data != src || ops->cursor_reset) { ops->cursor_state.image.data = src; cursor.set |= FB_CUR_SETIMAGE; } if (attribute) { u8 *dst; dst = kmalloc(w * vc->vc_font.width, GFP_ATOMIC); if (!dst) return; kfree(ops->cursor_data); ops->cursor_data = dst; cw_update_attr(dst, src, attribute, vc); src = dst; } if (ops->cursor_state.image.fg_color != fg || ops->cursor_state.image.bg_color != bg || ops->cursor_reset) { ops->cursor_state.image.fg_color = fg; ops->cursor_state.image.bg_color = bg; cursor.set |= FB_CUR_SETCMAP; } if (ops->cursor_state.image.height != vc->vc_font.width || ops->cursor_state.image.width != vc->vc_font.height || ops->cursor_reset) { ops->cursor_state.image.height = vc->vc_font.width; ops->cursor_state.image.width = vc->vc_font.height; cursor.set |= FB_CUR_SETSIZE; } dx = vxres - ((y * vc->vc_font.height) + vc->vc_font.height); dy = vc->vc_x * vc->vc_font.width; if (ops->cursor_state.image.dx != dx || ops->cursor_state.image.dy != dy || ops->cursor_reset) { ops->cursor_state.image.dx = dx; ops->cursor_state.image.dy = dy; cursor.set |= FB_CUR_SETPOS; } if (ops->cursor_state.hot.x || ops->cursor_state.hot.y || ops->cursor_reset) { ops->cursor_state.hot.x = cursor.hot.y = 0; cursor.set |= FB_CUR_SETHOT; } if (cursor.set & FB_CUR_SETSIZE || vc->vc_cursor_type != ops->p->cursor_shape || ops->cursor_state.mask == NULL || ops->cursor_reset) { char *tmp, *mask = kmalloc(w*vc->vc_font.width, GFP_ATOMIC); int cur_height, size, i = 0; int width = (vc->vc_font.width + 7)/8; if (!mask) return; tmp = kmalloc(width * vc->vc_font.height, GFP_ATOMIC); if (!tmp) { kfree(mask); return; } kfree(ops->cursor_state.mask); ops->cursor_state.mask = mask; ops->p->cursor_shape = vc->vc_cursor_type; cursor.set |= FB_CUR_SETSHAPE; switch (ops->p->cursor_shape & CUR_HWMASK) { case CUR_NONE: cur_height = 0; break; case CUR_UNDERLINE: cur_height = (vc->vc_font.height < 10) ? 1 : 2; break; case CUR_LOWER_THIRD: cur_height = vc->vc_font.height/3; break; case CUR_LOWER_HALF: cur_height = vc->vc_font.height >> 1; break; case CUR_TWO_THIRDS: cur_height = (vc->vc_font.height << 1)/3; break; case CUR_BLOCK: default: cur_height = vc->vc_font.height; break; } size = (vc->vc_font.height - cur_height) * width; while (size--) tmp[i++] = 0; size = cur_height * width; while (size--) tmp[i++] = 0xff; memset(mask, 0, w * vc->vc_font.width); rotate_cw(tmp, mask, vc->vc_font.width, vc->vc_font.height); kfree(tmp); } switch (mode) { case CM_ERASE: ops->cursor_state.enable = 0; break; case CM_DRAW: case CM_MOVE: default: ops->cursor_state.enable = (use_sw) ? 0 : 1; break; } cursor.image.data = src; cursor.image.fg_color = ops->cursor_state.image.fg_color; cursor.image.bg_color = ops->cursor_state.image.bg_color; cursor.image.dx = ops->cursor_state.image.dx; cursor.image.dy = ops->cursor_state.image.dy; cursor.image.height = ops->cursor_state.image.height; cursor.image.width = ops->cursor_state.image.width; cursor.hot.x = ops->cursor_state.hot.x; cursor.hot.y = ops->cursor_state.hot.y; cursor.mask = ops->cursor_state.mask; cursor.enable = ops->cursor_state.enable; cursor.image.depth = 1; cursor.rop = ROP_XOR; if (info->fbops->fb_cursor) err = info->fbops->fb_cursor(info, &cursor); if (err) soft_cursor(info, &cursor); ops->cursor_reset = 0; } static int cw_update_start(struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; u32 vxres = GETVXRES(ops->p->scrollmode, info); u32 xoffset; int err; xoffset = vxres - (info->var.xres + ops->var.yoffset); ops->var.yoffset = ops->var.xoffset; ops->var.xoffset = xoffset; err = fb_pan_display(info, &ops->var); ops->var.xoffset = info->var.xoffset; ops->var.yoffset = info->var.yoffset; ops->var.vmode = info->var.vmode; return err; } void fbcon_rotate_cw(struct fbcon_ops *ops) { ops->bmove = cw_bmove; ops->clear = cw_clear; ops->putcs = cw_putcs; ops->clear_margins = cw_clear_margins; ops->cursor = cw_cursor; ops->update_start = cw_update_start; } EXPORT_SYMBOL(fbcon_rotate_cw); MODULE_AUTHOR("Antonino Daplas <adaplas@pol.net>"); MODULE_DESCRIPTION("Console Rotation (90 degrees) Support"); MODULE_LICENSE("GPL");
gpl-2.0
vitek999/Lenovo-a328
arch/powerpc/platforms/powernv/pci-ioda.c
1060
34815
/* * Support PCI/PCIe on PowerNV platforms * * Copyright 2011 Benjamin Herrenschmidt, 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. */ #undef DEBUG #include <linux/kernel.h> #include <linux/pci.h> #include <linux/delay.h> #include <linux/string.h> #include <linux/init.h> #include <linux/bootmem.h> #include <linux/irq.h> #include <linux/io.h> #include <linux/msi.h> #include <asm/sections.h> #include <asm/io.h> #include <asm/prom.h> #include <asm/pci-bridge.h> #include <asm/machdep.h> #include <asm/msi_bitmap.h> #include <asm/ppc-pci.h> #include <asm/opal.h> #include <asm/iommu.h> #include <asm/tce.h> #include <asm/xics.h> #include "powernv.h" #include "pci.h" #define define_pe_printk_level(func, kern_level) \ static int func(const struct pnv_ioda_pe *pe, const char *fmt, ...) \ { \ struct va_format vaf; \ va_list args; \ char pfix[32]; \ int r; \ \ va_start(args, fmt); \ \ vaf.fmt = fmt; \ vaf.va = &args; \ \ if (pe->pdev) \ strlcpy(pfix, dev_name(&pe->pdev->dev), \ sizeof(pfix)); \ else \ sprintf(pfix, "%04x:%02x ", \ pci_domain_nr(pe->pbus), \ pe->pbus->number); \ r = printk(kern_level "pci %s: [PE# %.3d] %pV", \ pfix, pe->pe_number, &vaf); \ \ va_end(args); \ \ return r; \ } \ define_pe_printk_level(pe_err, KERN_ERR); define_pe_printk_level(pe_warn, KERN_WARNING); define_pe_printk_level(pe_info, KERN_INFO); static int pnv_ioda_alloc_pe(struct pnv_phb *phb) { unsigned long pe; do { pe = find_next_zero_bit(phb->ioda.pe_alloc, phb->ioda.total_pe, 0); if (pe >= phb->ioda.total_pe) return IODA_INVALID_PE; } while(test_and_set_bit(pe, phb->ioda.pe_alloc)); phb->ioda.pe_array[pe].phb = phb; phb->ioda.pe_array[pe].pe_number = pe; return pe; } static void pnv_ioda_free_pe(struct pnv_phb *phb, int pe) { WARN_ON(phb->ioda.pe_array[pe].pdev); memset(&phb->ioda.pe_array[pe], 0, sizeof(struct pnv_ioda_pe)); clear_bit(pe, phb->ioda.pe_alloc); } /* Currently those 2 are only used when MSIs are enabled, this will change * but in the meantime, we need to protect them to avoid warnings */ #ifdef CONFIG_PCI_MSI static struct pnv_ioda_pe *pnv_ioda_get_pe(struct pci_dev *dev) { struct pci_controller *hose = pci_bus_to_host(dev->bus); struct pnv_phb *phb = hose->private_data; struct pci_dn *pdn = pci_get_pdn(dev); if (!pdn) return NULL; if (pdn->pe_number == IODA_INVALID_PE) return NULL; return &phb->ioda.pe_array[pdn->pe_number]; } #endif /* CONFIG_PCI_MSI */ static int pnv_ioda_configure_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe) { struct pci_dev *parent; uint8_t bcomp, dcomp, fcomp; long rc, rid_end, rid; /* Bus validation ? */ if (pe->pbus) { int count; dcomp = OPAL_IGNORE_RID_DEVICE_NUMBER; fcomp = OPAL_IGNORE_RID_FUNCTION_NUMBER; parent = pe->pbus->self; if (pe->flags & PNV_IODA_PE_BUS_ALL) count = pe->pbus->busn_res.end - pe->pbus->busn_res.start + 1; else count = 1; switch(count) { case 1: bcomp = OpalPciBusAll; break; case 2: bcomp = OpalPciBus7Bits; break; case 4: bcomp = OpalPciBus6Bits; break; case 8: bcomp = OpalPciBus5Bits; break; case 16: bcomp = OpalPciBus4Bits; break; case 32: bcomp = OpalPciBus3Bits; break; default: pr_err("%s: Number of subordinate busses %d" " unsupported\n", pci_name(pe->pbus->self), count); /* Do an exact match only */ bcomp = OpalPciBusAll; } rid_end = pe->rid + (count << 8); } else { parent = pe->pdev->bus->self; bcomp = OpalPciBusAll; dcomp = OPAL_COMPARE_RID_DEVICE_NUMBER; fcomp = OPAL_COMPARE_RID_FUNCTION_NUMBER; rid_end = pe->rid + 1; } /* * Associate PE in PELT. We need add the PE into the * corresponding PELT-V as well. Otherwise, the error * originated from the PE might contribute to other * PEs. */ rc = opal_pci_set_pe(phb->opal_id, pe->pe_number, pe->rid, bcomp, dcomp, fcomp, OPAL_MAP_PE); if (rc) { pe_err(pe, "OPAL error %ld trying to setup PELT table\n", rc); return -ENXIO; } rc = opal_pci_set_peltv(phb->opal_id, pe->pe_number, pe->pe_number, OPAL_ADD_PE_TO_DOMAIN); if (rc) pe_warn(pe, "OPAL error %d adding self to PELTV\n", rc); opal_pci_eeh_freeze_clear(phb->opal_id, pe->pe_number, OPAL_EEH_ACTION_CLEAR_FREEZE_ALL); /* Add to all parents PELT-V */ while (parent) { struct pci_dn *pdn = pci_get_pdn(parent); if (pdn && pdn->pe_number != IODA_INVALID_PE) { rc = opal_pci_set_peltv(phb->opal_id, pdn->pe_number, pe->pe_number, OPAL_ADD_PE_TO_DOMAIN); /* XXX What to do in case of error ? */ } parent = parent->bus->self; } /* Setup reverse map */ for (rid = pe->rid; rid < rid_end; rid++) phb->ioda.pe_rmap[rid] = pe->pe_number; /* Setup one MVTs on IODA1 */ if (phb->type == PNV_PHB_IODA1) { pe->mve_number = pe->pe_number; rc = opal_pci_set_mve(phb->opal_id, pe->mve_number, pe->pe_number); if (rc) { pe_err(pe, "OPAL error %ld setting up MVE %d\n", rc, pe->mve_number); pe->mve_number = -1; } else { rc = opal_pci_set_mve_enable(phb->opal_id, pe->mve_number, OPAL_ENABLE_MVE); if (rc) { pe_err(pe, "OPAL error %ld enabling MVE %d\n", rc, pe->mve_number); pe->mve_number = -1; } } } else if (phb->type == PNV_PHB_IODA2) pe->mve_number = 0; return 0; } static void pnv_ioda_link_pe_by_weight(struct pnv_phb *phb, struct pnv_ioda_pe *pe) { struct pnv_ioda_pe *lpe; list_for_each_entry(lpe, &phb->ioda.pe_dma_list, dma_link) { if (lpe->dma_weight < pe->dma_weight) { list_add_tail(&pe->dma_link, &lpe->dma_link); return; } } list_add_tail(&pe->dma_link, &phb->ioda.pe_dma_list); } static unsigned int pnv_ioda_dma_weight(struct pci_dev *dev) { /* This is quite simplistic. The "base" weight of a device * is 10. 0 means no DMA is to be accounted for it. */ /* If it's a bridge, no DMA */ if (dev->hdr_type != PCI_HEADER_TYPE_NORMAL) return 0; /* Reduce the weight of slow USB controllers */ if (dev->class == PCI_CLASS_SERIAL_USB_UHCI || dev->class == PCI_CLASS_SERIAL_USB_OHCI || dev->class == PCI_CLASS_SERIAL_USB_EHCI) return 3; /* Increase the weight of RAID (includes Obsidian) */ if ((dev->class >> 8) == PCI_CLASS_STORAGE_RAID) return 15; /* Default */ return 10; } #if 0 static struct pnv_ioda_pe *pnv_ioda_setup_dev_PE(struct pci_dev *dev) { struct pci_controller *hose = pci_bus_to_host(dev->bus); struct pnv_phb *phb = hose->private_data; struct pci_dn *pdn = pci_get_pdn(dev); struct pnv_ioda_pe *pe; int pe_num; if (!pdn) { pr_err("%s: Device tree node not associated properly\n", pci_name(dev)); return NULL; } if (pdn->pe_number != IODA_INVALID_PE) return NULL; /* PE#0 has been pre-set */ if (dev->bus->number == 0) pe_num = 0; else pe_num = pnv_ioda_alloc_pe(phb); if (pe_num == IODA_INVALID_PE) { pr_warning("%s: Not enough PE# available, disabling device\n", pci_name(dev)); return NULL; } /* NOTE: We get only one ref to the pci_dev for the pdn, not for the * pointer in the PE data structure, both should be destroyed at the * same time. However, this needs to be looked at more closely again * once we actually start removing things (Hotplug, SR-IOV, ...) * * At some point we want to remove the PDN completely anyways */ pe = &phb->ioda.pe_array[pe_num]; pci_dev_get(dev); pdn->pcidev = dev; pdn->pe_number = pe_num; pe->pdev = dev; pe->pbus = NULL; pe->tce32_seg = -1; pe->mve_number = -1; pe->rid = dev->bus->number << 8 | pdn->devfn; pe_info(pe, "Associated device to PE\n"); if (pnv_ioda_configure_pe(phb, pe)) { /* XXX What do we do here ? */ if (pe_num) pnv_ioda_free_pe(phb, pe_num); pdn->pe_number = IODA_INVALID_PE; pe->pdev = NULL; pci_dev_put(dev); return NULL; } /* Assign a DMA weight to the device */ pe->dma_weight = pnv_ioda_dma_weight(dev); if (pe->dma_weight != 0) { phb->ioda.dma_weight += pe->dma_weight; phb->ioda.dma_pe_count++; } /* Link the PE */ pnv_ioda_link_pe_by_weight(phb, pe); return pe; } #endif /* Useful for SRIOV case */ static void pnv_ioda_setup_same_PE(struct pci_bus *bus, struct pnv_ioda_pe *pe) { struct pci_dev *dev; list_for_each_entry(dev, &bus->devices, bus_list) { struct pci_dn *pdn = pci_get_pdn(dev); if (pdn == NULL) { pr_warn("%s: No device node associated with device !\n", pci_name(dev)); continue; } pci_dev_get(dev); pdn->pcidev = dev; pdn->pe_number = pe->pe_number; pe->dma_weight += pnv_ioda_dma_weight(dev); if ((pe->flags & PNV_IODA_PE_BUS_ALL) && dev->subordinate) pnv_ioda_setup_same_PE(dev->subordinate, pe); } } /* * There're 2 types of PCI bus sensitive PEs: One that is compromised of * single PCI bus. Another one that contains the primary PCI bus and its * subordinate PCI devices and buses. The second type of PE is normally * orgiriated by PCIe-to-PCI bridge or PLX switch downstream ports. */ static void pnv_ioda_setup_bus_PE(struct pci_bus *bus, int all) { struct pci_controller *hose = pci_bus_to_host(bus); struct pnv_phb *phb = hose->private_data; struct pnv_ioda_pe *pe; int pe_num; pe_num = pnv_ioda_alloc_pe(phb); if (pe_num == IODA_INVALID_PE) { pr_warning("%s: Not enough PE# available for PCI bus %04x:%02x\n", __func__, pci_domain_nr(bus), bus->number); return; } pe = &phb->ioda.pe_array[pe_num]; pe->flags = (all ? PNV_IODA_PE_BUS_ALL : PNV_IODA_PE_BUS); pe->pbus = bus; pe->pdev = NULL; pe->tce32_seg = -1; pe->mve_number = -1; pe->rid = bus->busn_res.start << 8; pe->dma_weight = 0; if (all) pe_info(pe, "Secondary bus %d..%d associated with PE#%d\n", bus->busn_res.start, bus->busn_res.end, pe_num); else pe_info(pe, "Secondary bus %d associated with PE#%d\n", bus->busn_res.start, pe_num); if (pnv_ioda_configure_pe(phb, pe)) { /* XXX What do we do here ? */ if (pe_num) pnv_ioda_free_pe(phb, pe_num); pe->pbus = NULL; return; } /* Associate it with all child devices */ pnv_ioda_setup_same_PE(bus, pe); /* Put PE to the list */ list_add_tail(&pe->list, &phb->ioda.pe_list); /* Account for one DMA PE if at least one DMA capable device exist * below the bridge */ if (pe->dma_weight != 0) { phb->ioda.dma_weight += pe->dma_weight; phb->ioda.dma_pe_count++; } /* Link the PE */ pnv_ioda_link_pe_by_weight(phb, pe); } static void pnv_ioda_setup_PEs(struct pci_bus *bus) { struct pci_dev *dev; pnv_ioda_setup_bus_PE(bus, 0); list_for_each_entry(dev, &bus->devices, bus_list) { if (dev->subordinate) { if (pci_pcie_type(dev) == PCI_EXP_TYPE_PCI_BRIDGE) pnv_ioda_setup_bus_PE(dev->subordinate, 1); else pnv_ioda_setup_PEs(dev->subordinate); } } } /* * Configure PEs so that the downstream PCI buses and devices * could have their associated PE#. Unfortunately, we didn't * figure out the way to identify the PLX bridge yet. So we * simply put the PCI bus and the subordinate behind the root * port to PE# here. The game rule here is expected to be changed * as soon as we can detected PLX bridge correctly. */ static void pnv_pci_ioda_setup_PEs(void) { struct pci_controller *hose, *tmp; list_for_each_entry_safe(hose, tmp, &hose_list, list_node) { pnv_ioda_setup_PEs(hose->bus); } } static void pnv_pci_ioda_dma_dev_setup(struct pnv_phb *phb, struct pci_dev *pdev) { struct pci_dn *pdn = pci_get_pdn(pdev); struct pnv_ioda_pe *pe; /* * The function can be called while the PE# * hasn't been assigned. Do nothing for the * case. */ if (!pdn || pdn->pe_number == IODA_INVALID_PE) return; pe = &phb->ioda.pe_array[pdn->pe_number]; set_iommu_table_base(&pdev->dev, &pe->tce32_table); } static void pnv_ioda_setup_bus_dma(struct pnv_ioda_pe *pe, struct pci_bus *bus) { struct pci_dev *dev; list_for_each_entry(dev, &bus->devices, bus_list) { set_iommu_table_base(&dev->dev, &pe->tce32_table); if (dev->subordinate) pnv_ioda_setup_bus_dma(pe, dev->subordinate); } } static void pnv_pci_ioda1_tce_invalidate(struct iommu_table *tbl, u64 *startp, u64 *endp) { u64 __iomem *invalidate = (u64 __iomem *)tbl->it_index; unsigned long start, end, inc; start = __pa(startp); end = __pa(endp); /* BML uses this case for p6/p7/galaxy2: Shift addr and put in node */ if (tbl->it_busno) { start <<= 12; end <<= 12; inc = 128 << 12; start |= tbl->it_busno; end |= tbl->it_busno; } else if (tbl->it_type & TCE_PCI_SWINV_PAIR) { /* p7ioc-style invalidation, 2 TCEs per write */ start |= (1ull << 63); end |= (1ull << 63); inc = 16; } else { /* Default (older HW) */ inc = 128; } end |= inc - 1; /* round up end to be different than start */ mb(); /* Ensure above stores are visible */ while (start <= end) { __raw_writeq(start, invalidate); start += inc; } /* * The iommu layer will do another mb() for us on build() * and we don't care on free() */ } static void pnv_pci_ioda2_tce_invalidate(struct pnv_ioda_pe *pe, struct iommu_table *tbl, u64 *startp, u64 *endp) { unsigned long start, end, inc; u64 __iomem *invalidate = (u64 __iomem *)tbl->it_index; /* We'll invalidate DMA address in PE scope */ start = 0x2ul << 60; start |= (pe->pe_number & 0xFF); end = start; /* Figure out the start, end and step */ inc = tbl->it_offset + (((u64)startp - tbl->it_base) / sizeof(u64)); start |= (inc << 12); inc = tbl->it_offset + (((u64)endp - tbl->it_base) / sizeof(u64)); end |= (inc << 12); inc = (0x1ul << 12); mb(); while (start <= end) { __raw_writeq(start, invalidate); start += inc; } } void pnv_pci_ioda_tce_invalidate(struct iommu_table *tbl, u64 *startp, u64 *endp) { struct pnv_ioda_pe *pe = container_of(tbl, struct pnv_ioda_pe, tce32_table); struct pnv_phb *phb = pe->phb; if (phb->type == PNV_PHB_IODA1) pnv_pci_ioda1_tce_invalidate(tbl, startp, endp); else pnv_pci_ioda2_tce_invalidate(pe, tbl, startp, endp); } static void pnv_pci_ioda_setup_dma_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe, unsigned int base, unsigned int segs) { struct page *tce_mem = NULL; const __be64 *swinvp; struct iommu_table *tbl; unsigned int i; int64_t rc; void *addr; /* 256M DMA window, 4K TCE pages, 8 bytes TCE */ #define TCE32_TABLE_SIZE ((0x10000000 / 0x1000) * 8) /* XXX FIXME: Handle 64-bit only DMA devices */ /* XXX FIXME: Provide 64-bit DMA facilities & non-4K TCE tables etc.. */ /* XXX FIXME: Allocate multi-level tables on PHB3 */ /* We shouldn't already have a 32-bit DMA associated */ if (WARN_ON(pe->tce32_seg >= 0)) return; /* Grab a 32-bit TCE table */ pe->tce32_seg = base; pe_info(pe, " Setting up 32-bit TCE table at %08x..%08x\n", (base << 28), ((base + segs) << 28) - 1); /* XXX Currently, we allocate one big contiguous table for the * TCEs. We only really need one chunk per 256M of TCE space * (ie per segment) but that's an optimization for later, it * requires some added smarts with our get/put_tce implementation */ tce_mem = alloc_pages_node(phb->hose->node, GFP_KERNEL, get_order(TCE32_TABLE_SIZE * segs)); if (!tce_mem) { pe_err(pe, " Failed to allocate a 32-bit TCE memory\n"); goto fail; } addr = page_address(tce_mem); memset(addr, 0, TCE32_TABLE_SIZE * segs); /* Configure HW */ for (i = 0; i < segs; i++) { rc = opal_pci_map_pe_dma_window(phb->opal_id, pe->pe_number, base + i, 1, __pa(addr) + TCE32_TABLE_SIZE * i, TCE32_TABLE_SIZE, 0x1000); if (rc) { pe_err(pe, " Failed to configure 32-bit TCE table," " err %ld\n", rc); goto fail; } } /* Setup linux iommu table */ tbl = &pe->tce32_table; pnv_pci_setup_iommu_table(tbl, addr, TCE32_TABLE_SIZE * segs, base << 28); /* OPAL variant of P7IOC SW invalidated TCEs */ swinvp = of_get_property(phb->hose->dn, "ibm,opal-tce-kill", NULL); if (swinvp) { /* We need a couple more fields -- an address and a data * to or. Since the bus is only printed out on table free * errors, and on the first pass the data will be a relative * bus number, print that out instead. */ tbl->it_busno = 0; tbl->it_index = (unsigned long)ioremap(be64_to_cpup(swinvp), 8); tbl->it_type = TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE | TCE_PCI_SWINV_PAIR; } iommu_init_table(tbl, phb->hose->node); if (pe->pdev) set_iommu_table_base(&pe->pdev->dev, tbl); else pnv_ioda_setup_bus_dma(pe, pe->pbus); return; fail: /* XXX Failure: Try to fallback to 64-bit only ? */ if (pe->tce32_seg >= 0) pe->tce32_seg = -1; if (tce_mem) __free_pages(tce_mem, get_order(TCE32_TABLE_SIZE * segs)); } static void pnv_pci_ioda2_setup_dma_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe) { struct page *tce_mem = NULL; void *addr; const __be64 *swinvp; struct iommu_table *tbl; unsigned int tce_table_size, end; int64_t rc; /* We shouldn't already have a 32-bit DMA associated */ if (WARN_ON(pe->tce32_seg >= 0)) return; /* The PE will reserve all possible 32-bits space */ pe->tce32_seg = 0; end = (1 << ilog2(phb->ioda.m32_pci_base)); tce_table_size = (end / 0x1000) * 8; pe_info(pe, "Setting up 32-bit TCE table at 0..%08x\n", end); /* Allocate TCE table */ tce_mem = alloc_pages_node(phb->hose->node, GFP_KERNEL, get_order(tce_table_size)); if (!tce_mem) { pe_err(pe, "Failed to allocate a 32-bit TCE memory\n"); goto fail; } addr = page_address(tce_mem); memset(addr, 0, tce_table_size); /* * Map TCE table through TVT. The TVE index is the PE number * shifted by 1 bit for 32-bits DMA space. */ rc = opal_pci_map_pe_dma_window(phb->opal_id, pe->pe_number, pe->pe_number << 1, 1, __pa(addr), tce_table_size, 0x1000); if (rc) { pe_err(pe, "Failed to configure 32-bit TCE table," " err %ld\n", rc); goto fail; } /* Setup linux iommu table */ tbl = &pe->tce32_table; pnv_pci_setup_iommu_table(tbl, addr, tce_table_size, 0); /* OPAL variant of PHB3 invalidated TCEs */ swinvp = of_get_property(phb->hose->dn, "ibm,opal-tce-kill", NULL); if (swinvp) { /* We need a couple more fields -- an address and a data * to or. Since the bus is only printed out on table free * errors, and on the first pass the data will be a relative * bus number, print that out instead. */ tbl->it_busno = 0; tbl->it_index = (unsigned long)ioremap(be64_to_cpup(swinvp), 8); tbl->it_type = TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE; } iommu_init_table(tbl, phb->hose->node); if (pe->pdev) set_iommu_table_base(&pe->pdev->dev, tbl); else pnv_ioda_setup_bus_dma(pe, pe->pbus); return; fail: if (pe->tce32_seg >= 0) pe->tce32_seg = -1; if (tce_mem) __free_pages(tce_mem, get_order(tce_table_size)); } static void pnv_ioda_setup_dma(struct pnv_phb *phb) { struct pci_controller *hose = phb->hose; unsigned int residual, remaining, segs, tw, base; struct pnv_ioda_pe *pe; /* If we have more PE# than segments available, hand out one * per PE until we run out and let the rest fail. If not, * then we assign at least one segment per PE, plus more based * on the amount of devices under that PE */ if (phb->ioda.dma_pe_count > phb->ioda.tce32_count) residual = 0; else residual = phb->ioda.tce32_count - phb->ioda.dma_pe_count; pr_info("PCI: Domain %04x has %ld available 32-bit DMA segments\n", hose->global_number, phb->ioda.tce32_count); pr_info("PCI: %d PE# for a total weight of %d\n", phb->ioda.dma_pe_count, phb->ioda.dma_weight); /* Walk our PE list and configure their DMA segments, hand them * out one base segment plus any residual segments based on * weight */ remaining = phb->ioda.tce32_count; tw = phb->ioda.dma_weight; base = 0; list_for_each_entry(pe, &phb->ioda.pe_dma_list, dma_link) { if (!pe->dma_weight) continue; if (!remaining) { pe_warn(pe, "No DMA32 resources available\n"); continue; } segs = 1; if (residual) { segs += ((pe->dma_weight * residual) + (tw / 2)) / tw; if (segs > remaining) segs = remaining; } /* * For IODA2 compliant PHB3, we needn't care about the weight. * The all available 32-bits DMA space will be assigned to * the specific PE. */ if (phb->type == PNV_PHB_IODA1) { pe_info(pe, "DMA weight %d, assigned %d DMA32 segments\n", pe->dma_weight, segs); pnv_pci_ioda_setup_dma_pe(phb, pe, base, segs); } else { pe_info(pe, "Assign DMA32 space\n"); segs = 0; pnv_pci_ioda2_setup_dma_pe(phb, pe); } remaining -= segs; base += segs; } } #ifdef CONFIG_PCI_MSI static void pnv_ioda2_msi_eoi(struct irq_data *d) { unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d); struct irq_chip *chip = irq_data_get_irq_chip(d); struct pnv_phb *phb = container_of(chip, struct pnv_phb, ioda.irq_chip); int64_t rc; rc = opal_pci_msi_eoi(phb->opal_id, hw_irq); WARN_ON_ONCE(rc); icp_native_eoi(d); } static int pnv_pci_ioda_msi_setup(struct pnv_phb *phb, struct pci_dev *dev, unsigned int hwirq, unsigned int virq, unsigned int is_64, struct msi_msg *msg) { struct pnv_ioda_pe *pe = pnv_ioda_get_pe(dev); struct pci_dn *pdn = pci_get_pdn(dev); struct irq_data *idata; struct irq_chip *ichip; unsigned int xive_num = hwirq - phb->msi_base; uint64_t addr64; uint32_t addr32, data; int rc; /* No PE assigned ? bail out ... no MSI for you ! */ if (pe == NULL) return -ENXIO; /* Check if we have an MVE */ if (pe->mve_number < 0) return -ENXIO; /* Force 32-bit MSI on some broken devices */ if (pdn && pdn->force_32bit_msi) is_64 = 0; /* Assign XIVE to PE */ rc = opal_pci_set_xive_pe(phb->opal_id, pe->pe_number, xive_num); if (rc) { pr_warn("%s: OPAL error %d setting XIVE %d PE\n", pci_name(dev), rc, xive_num); return -EIO; } if (is_64) { rc = opal_get_msi_64(phb->opal_id, pe->mve_number, xive_num, 1, &addr64, &data); if (rc) { pr_warn("%s: OPAL error %d getting 64-bit MSI data\n", pci_name(dev), rc); return -EIO; } msg->address_hi = addr64 >> 32; msg->address_lo = addr64 & 0xfffffffful; } else { rc = opal_get_msi_32(phb->opal_id, pe->mve_number, xive_num, 1, &addr32, &data); if (rc) { pr_warn("%s: OPAL error %d getting 32-bit MSI data\n", pci_name(dev), rc); return -EIO; } msg->address_hi = 0; msg->address_lo = addr32; } msg->data = data; /* * Change the IRQ chip for the MSI interrupts on PHB3. * The corresponding IRQ chip should be populated for * the first time. */ if (phb->type == PNV_PHB_IODA2) { if (!phb->ioda.irq_chip_init) { idata = irq_get_irq_data(virq); ichip = irq_data_get_irq_chip(idata); phb->ioda.irq_chip_init = 1; phb->ioda.irq_chip = *ichip; phb->ioda.irq_chip.irq_eoi = pnv_ioda2_msi_eoi; } irq_set_chip(virq, &phb->ioda.irq_chip); } pr_devel("%s: %s-bit MSI on hwirq %x (xive #%d)," " address=%x_%08x data=%x PE# %d\n", pci_name(dev), is_64 ? "64" : "32", hwirq, xive_num, msg->address_hi, msg->address_lo, data, pe->pe_number); return 0; } static void pnv_pci_init_ioda_msis(struct pnv_phb *phb) { unsigned int count; const __be32 *prop = of_get_property(phb->hose->dn, "ibm,opal-msi-ranges", NULL); if (!prop) { /* BML Fallback */ prop = of_get_property(phb->hose->dn, "msi-ranges", NULL); } if (!prop) return; phb->msi_base = be32_to_cpup(prop); count = be32_to_cpup(prop + 1); if (msi_bitmap_alloc(&phb->msi_bmp, count, phb->hose->dn)) { pr_err("PCI %d: Failed to allocate MSI bitmap !\n", phb->hose->global_number); return; } phb->msi_setup = pnv_pci_ioda_msi_setup; phb->msi32_support = 1; pr_info(" Allocated bitmap for %d MSIs (base IRQ 0x%x)\n", count, phb->msi_base); } #else static void pnv_pci_init_ioda_msis(struct pnv_phb *phb) { } #endif /* CONFIG_PCI_MSI */ /* * This function is supposed to be called on basis of PE from top * to bottom style. So the the I/O or MMIO segment assigned to * parent PE could be overrided by its child PEs if necessary. */ static void pnv_ioda_setup_pe_seg(struct pci_controller *hose, struct pnv_ioda_pe *pe) { struct pnv_phb *phb = hose->private_data; struct pci_bus_region region; struct resource *res; int i, index; int rc; /* * NOTE: We only care PCI bus based PE for now. For PCI * device based PE, for example SRIOV sensitive VF should * be figured out later. */ BUG_ON(!(pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL))); pci_bus_for_each_resource(pe->pbus, res, i) { if (!res || !res->flags || res->start > res->end) continue; if (res->flags & IORESOURCE_IO) { region.start = res->start - phb->ioda.io_pci_base; region.end = res->end - phb->ioda.io_pci_base; index = region.start / phb->ioda.io_segsize; while (index < phb->ioda.total_pe && region.start <= region.end) { phb->ioda.io_segmap[index] = pe->pe_number; rc = opal_pci_map_pe_mmio_window(phb->opal_id, pe->pe_number, OPAL_IO_WINDOW_TYPE, 0, index); if (rc != OPAL_SUCCESS) { pr_err("%s: OPAL error %d when mapping IO " "segment #%d to PE#%d\n", __func__, rc, index, pe->pe_number); break; } region.start += phb->ioda.io_segsize; index++; } } else if (res->flags & IORESOURCE_MEM) { /* WARNING: Assumes M32 is mem region 0 in PHB. We need to * harden that algorithm when we start supporting M64 */ region.start = res->start - hose->mem_offset[0] - phb->ioda.m32_pci_base; region.end = res->end - hose->mem_offset[0] - phb->ioda.m32_pci_base; index = region.start / phb->ioda.m32_segsize; while (index < phb->ioda.total_pe && region.start <= region.end) { phb->ioda.m32_segmap[index] = pe->pe_number; rc = opal_pci_map_pe_mmio_window(phb->opal_id, pe->pe_number, OPAL_M32_WINDOW_TYPE, 0, index); if (rc != OPAL_SUCCESS) { pr_err("%s: OPAL error %d when mapping M32 " "segment#%d to PE#%d", __func__, rc, index, pe->pe_number); break; } region.start += phb->ioda.m32_segsize; index++; } } } } static void pnv_pci_ioda_setup_seg(void) { struct pci_controller *tmp, *hose; struct pnv_phb *phb; struct pnv_ioda_pe *pe; list_for_each_entry_safe(hose, tmp, &hose_list, list_node) { phb = hose->private_data; list_for_each_entry(pe, &phb->ioda.pe_list, list) { pnv_ioda_setup_pe_seg(hose, pe); } } } static void pnv_pci_ioda_setup_DMA(void) { struct pci_controller *hose, *tmp; struct pnv_phb *phb; list_for_each_entry_safe(hose, tmp, &hose_list, list_node) { pnv_ioda_setup_dma(hose->private_data); /* Mark the PHB initialization done */ phb = hose->private_data; phb->initialized = 1; } } static void pnv_pci_ioda_fixup(void) { pnv_pci_ioda_setup_PEs(); pnv_pci_ioda_setup_seg(); pnv_pci_ioda_setup_DMA(); } /* * Returns the alignment for I/O or memory windows for P2P * bridges. That actually depends on how PEs are segmented. * For now, we return I/O or M32 segment size for PE sensitive * P2P bridges. Otherwise, the default values (4KiB for I/O, * 1MiB for memory) will be returned. * * The current PCI bus might be put into one PE, which was * create against the parent PCI bridge. For that case, we * needn't enlarge the alignment so that we can save some * resources. */ static resource_size_t pnv_pci_window_alignment(struct pci_bus *bus, unsigned long type) { struct pci_dev *bridge; struct pci_controller *hose = pci_bus_to_host(bus); struct pnv_phb *phb = hose->private_data; int num_pci_bridges = 0; bridge = bus->self; while (bridge) { if (pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE) { num_pci_bridges++; if (num_pci_bridges >= 2) return 1; } bridge = bridge->bus->self; } /* We need support prefetchable memory window later */ if (type & IORESOURCE_MEM) return phb->ioda.m32_segsize; return phb->ioda.io_segsize; } /* Prevent enabling devices for which we couldn't properly * assign a PE */ static int pnv_pci_enable_device_hook(struct pci_dev *dev) { struct pci_controller *hose = pci_bus_to_host(dev->bus); struct pnv_phb *phb = hose->private_data; struct pci_dn *pdn; /* The function is probably called while the PEs have * not be created yet. For example, resource reassignment * during PCI probe period. We just skip the check if * PEs isn't ready. */ if (!phb->initialized) return 0; pdn = pci_get_pdn(dev); if (!pdn || pdn->pe_number == IODA_INVALID_PE) return -EINVAL; return 0; } static u32 pnv_ioda_bdfn_to_pe(struct pnv_phb *phb, struct pci_bus *bus, u32 devfn) { return phb->ioda.pe_rmap[(bus->number << 8) | devfn]; } static void pnv_pci_ioda_shutdown(struct pnv_phb *phb) { opal_pci_reset(phb->opal_id, OPAL_PCI_IODA_TABLE_RESET, OPAL_ASSERT_RESET); } void __init pnv_pci_init_ioda_phb(struct device_node *np, int ioda_type) { struct pci_controller *hose; static int primary = 1; struct pnv_phb *phb; unsigned long size, m32map_off, iomap_off, pemap_off; const u64 *prop64; const u32 *prop32; u64 phb_id; void *aux; long rc; pr_info(" Initializing IODA%d OPAL PHB %s\n", ioda_type, np->full_name); prop64 = of_get_property(np, "ibm,opal-phbid", NULL); if (!prop64) { pr_err(" Missing \"ibm,opal-phbid\" property !\n"); return; } phb_id = be64_to_cpup(prop64); pr_debug(" PHB-ID : 0x%016llx\n", phb_id); phb = alloc_bootmem(sizeof(struct pnv_phb)); if (phb) { memset(phb, 0, sizeof(struct pnv_phb)); phb->hose = hose = pcibios_alloc_controller(np); } if (!phb || !phb->hose) { pr_err("PCI: Failed to allocate PCI controller for %s\n", np->full_name); return; } spin_lock_init(&phb->lock); /* XXX Use device-tree */ hose->first_busno = 0; hose->last_busno = 0xff; hose->private_data = phb; phb->opal_id = phb_id; phb->type = ioda_type; /* Detect specific models for error handling */ if (of_device_is_compatible(np, "ibm,p7ioc-pciex")) phb->model = PNV_PHB_MODEL_P7IOC; else if (of_device_is_compatible(np, "ibm,power8-pciex")) phb->model = PNV_PHB_MODEL_PHB3; else phb->model = PNV_PHB_MODEL_UNKNOWN; /* Parse 32-bit and IO ranges (if any) */ pci_process_bridge_OF_ranges(phb->hose, np, primary); primary = 0; /* Get registers */ phb->regs = of_iomap(np, 0); if (phb->regs == NULL) pr_err(" Failed to map registers !\n"); /* Initialize more IODA stuff */ prop32 = of_get_property(np, "ibm,opal-num-pes", NULL); if (!prop32) phb->ioda.total_pe = 1; else phb->ioda.total_pe = *prop32; phb->ioda.m32_size = resource_size(&hose->mem_resources[0]); /* FW Has already off top 64k of M32 space (MSI space) */ phb->ioda.m32_size += 0x10000; phb->ioda.m32_segsize = phb->ioda.m32_size / phb->ioda.total_pe; phb->ioda.m32_pci_base = hose->mem_resources[0].start - hose->mem_offset[0]; phb->ioda.io_size = hose->pci_io_size; phb->ioda.io_segsize = phb->ioda.io_size / phb->ioda.total_pe; phb->ioda.io_pci_base = 0; /* XXX calculate this ? */ /* Allocate aux data & arrays * * XXX TODO: Don't allocate io segmap on PHB3 */ size = _ALIGN_UP(phb->ioda.total_pe / 8, sizeof(unsigned long)); m32map_off = size; size += phb->ioda.total_pe * sizeof(phb->ioda.m32_segmap[0]); iomap_off = size; size += phb->ioda.total_pe * sizeof(phb->ioda.io_segmap[0]); pemap_off = size; size += phb->ioda.total_pe * sizeof(struct pnv_ioda_pe); aux = alloc_bootmem(size); memset(aux, 0, size); phb->ioda.pe_alloc = aux; phb->ioda.m32_segmap = aux + m32map_off; phb->ioda.io_segmap = aux + iomap_off; phb->ioda.pe_array = aux + pemap_off; set_bit(0, phb->ioda.pe_alloc); INIT_LIST_HEAD(&phb->ioda.pe_dma_list); INIT_LIST_HEAD(&phb->ioda.pe_list); /* Calculate how many 32-bit TCE segments we have */ phb->ioda.tce32_count = phb->ioda.m32_pci_base >> 28; /* Clear unusable m64 */ hose->mem_resources[1].flags = 0; hose->mem_resources[1].start = 0; hose->mem_resources[1].end = 0; hose->mem_resources[2].flags = 0; hose->mem_resources[2].start = 0; hose->mem_resources[2].end = 0; #if 0 /* We should really do that ... */ rc = opal_pci_set_phb_mem_window(opal->phb_id, window_type, window_num, starting_real_address, starting_pci_address, segment_size); #endif pr_info(" %d PE's M32: 0x%x [segment=0x%x] IO: 0x%x [segment=0x%x]\n", phb->ioda.total_pe, phb->ioda.m32_size, phb->ioda.m32_segsize, phb->ioda.io_size, phb->ioda.io_segsize); phb->hose->ops = &pnv_pci_ops; /* Setup RID -> PE mapping function */ phb->bdfn_to_pe = pnv_ioda_bdfn_to_pe; /* Setup TCEs */ phb->dma_dev_setup = pnv_pci_ioda_dma_dev_setup; /* Setup shutdown function for kexec */ phb->shutdown = pnv_pci_ioda_shutdown; /* Setup MSI support */ pnv_pci_init_ioda_msis(phb); /* * We pass the PCI probe flag PCI_REASSIGN_ALL_RSRC here * to let the PCI core do resource assignment. It's supposed * that the PCI core will do correct I/O and MMIO alignment * for the P2P bridge bars so that each PCI bus (excluding * the child P2P bridges) can form individual PE. */ ppc_md.pcibios_fixup = pnv_pci_ioda_fixup; ppc_md.pcibios_enable_device_hook = pnv_pci_enable_device_hook; ppc_md.pcibios_window_alignment = pnv_pci_window_alignment; pci_add_flags(PCI_REASSIGN_ALL_RSRC); /* Reset IODA tables to a clean state */ rc = opal_pci_reset(phb_id, OPAL_PCI_IODA_TABLE_RESET, OPAL_ASSERT_RESET); if (rc) pr_warning(" OPAL Error %ld performing IODA table reset !\n", rc); /* * On IODA1 map everything to PE#0, on IODA2 we assume the IODA reset * has cleared the RTT which has the same effect */ if (ioda_type == PNV_PHB_IODA1) opal_pci_set_pe(phb_id, 0, 0, 7, 1, 1 , OPAL_MAP_PE); } void pnv_pci_init_ioda2_phb(struct device_node *np) { pnv_pci_init_ioda_phb(np, PNV_PHB_IODA2); } void __init pnv_pci_init_ioda_hub(struct device_node *np) { struct device_node *phbn; const u64 *prop64; u64 hub_id; pr_info("Probing IODA IO-Hub %s\n", np->full_name); prop64 = of_get_property(np, "ibm,opal-hubid", NULL); if (!prop64) { pr_err(" Missing \"ibm,opal-hubid\" property !\n"); return; } hub_id = be64_to_cpup(prop64); pr_devel(" HUB-ID : 0x%016llx\n", hub_id); /* Count child PHBs */ for_each_child_of_node(np, phbn) { /* Look for IODA1 PHBs */ if (of_device_is_compatible(phbn, "ibm,ioda-phb")) pnv_pci_init_ioda_phb(phbn, PNV_PHB_IODA1); } }
gpl-2.0
CaptainThrowback/kernel_htc_m8whl_3.30.654.2
kernel/watchdog.c
1572
14913
/* * Detect hard and soft lockups on a system * * started by Don Zickus, Copyright (C) 2010 Red Hat, Inc. * * Note: Most of this code is borrowed heavily from the original softlockup * detector, so thanks to Ingo for the initial implementation. * Some chunks also taken from the old x86-specific nmi watchdog code, thanks * to those contributors as well. */ #define pr_fmt(fmt) "NMI watchdog: " fmt #include <linux/mm.h> #include <linux/cpu.h> #include <linux/nmi.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/freezer.h> #include <linux/kthread.h> #include <linux/lockdep.h> #include <linux/notifier.h> #include <linux/module.h> #include <linux/sysctl.h> #include <asm/irq_regs.h> #include <linux/perf_event.h> int watchdog_enabled = 1; int __read_mostly watchdog_thresh = 10; static DEFINE_PER_CPU(unsigned long, watchdog_touch_ts); static DEFINE_PER_CPU(struct task_struct *, softlockup_watchdog); static DEFINE_PER_CPU(struct hrtimer, watchdog_hrtimer); static DEFINE_PER_CPU(bool, softlockup_touch_sync); static DEFINE_PER_CPU(bool, soft_watchdog_warn); #ifdef CONFIG_HARDLOCKUP_DETECTOR static DEFINE_PER_CPU(bool, hard_watchdog_warn); static DEFINE_PER_CPU(bool, watchdog_nmi_touch); static DEFINE_PER_CPU(unsigned long, hrtimer_interrupts); static DEFINE_PER_CPU(unsigned long, hrtimer_interrupts_saved); static DEFINE_PER_CPU(struct perf_event *, watchdog_ev); #endif /* boot commands */ /* * Should we panic when a soft-lockup or hard-lockup occurs: */ #ifdef CONFIG_HARDLOCKUP_DETECTOR static int hardlockup_panic = CONFIG_BOOTPARAM_HARDLOCKUP_PANIC_VALUE; static int __init hardlockup_panic_setup(char *str) { if (!strncmp(str, "panic", 5)) hardlockup_panic = 1; else if (!strncmp(str, "nopanic", 7)) hardlockup_panic = 0; else if (!strncmp(str, "0", 1)) watchdog_enabled = 0; return 1; } __setup("nmi_watchdog=", hardlockup_panic_setup); #endif unsigned int __read_mostly softlockup_panic = CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC_VALUE; static int __init softlockup_panic_setup(char *str) { softlockup_panic = simple_strtoul(str, NULL, 0); return 1; } __setup("softlockup_panic=", softlockup_panic_setup); static int __init nowatchdog_setup(char *str) { watchdog_enabled = 0; return 1; } __setup("nowatchdog", nowatchdog_setup); /* deprecated */ static int __init nosoftlockup_setup(char *str) { watchdog_enabled = 0; return 1; } __setup("nosoftlockup", nosoftlockup_setup); /* */ /* * Hard-lockup warnings should be triggered after just a few seconds. Soft- * lockups can have false positives under extreme conditions. So we generally * want a higher threshold for soft lockups than for hard lockups. So we couple * the thresholds with a factor: we make the soft threshold twice the amount of * time the hard threshold is. */ static int get_softlockup_thresh(void) { return watchdog_thresh * 2; } /* * Returns seconds, approximately. We don't need nanosecond * resolution, and we don't need to waste time with a big divide when * 2^30ns == 1.074s. */ static unsigned long get_timestamp(int this_cpu) { return cpu_clock(this_cpu) >> 30LL; /* 2^30 ~= 10^9 */ } static unsigned long get_sample_period(void) { /* * convert watchdog_thresh from seconds to ns * the divide by 5 is to give hrtimer several chances (two * or three with the current relation between the soft * and hard thresholds) to increment before the * hardlockup detector generates a warning */ return get_softlockup_thresh() * (NSEC_PER_SEC / 5); } /* Commands for resetting the watchdog */ static void __touch_watchdog(void) { int this_cpu = raw_smp_processor_id(); __this_cpu_write(watchdog_touch_ts, get_timestamp(this_cpu)); } void touch_softlockup_watchdog(void) { __this_cpu_write(watchdog_touch_ts, 0); } EXPORT_SYMBOL(touch_softlockup_watchdog); void touch_all_softlockup_watchdogs(void) { int cpu; /* * this is done lockless * do we care if a 0 races with a timestamp? * all it means is the softlock check starts one cycle later */ for_each_online_cpu(cpu) per_cpu(watchdog_touch_ts, cpu) = 0; } #ifdef CONFIG_HARDLOCKUP_DETECTOR void touch_nmi_watchdog(void) { if (watchdog_enabled) { unsigned cpu; for_each_present_cpu(cpu) { if (per_cpu(watchdog_nmi_touch, cpu) != true) per_cpu(watchdog_nmi_touch, cpu) = true; } } touch_softlockup_watchdog(); } EXPORT_SYMBOL(touch_nmi_watchdog); #endif void touch_softlockup_watchdog_sync(void) { __raw_get_cpu_var(softlockup_touch_sync) = true; __raw_get_cpu_var(watchdog_touch_ts) = 0; } #ifdef CONFIG_HARDLOCKUP_DETECTOR /* watchdog detector functions */ static int is_hardlockup(void) { unsigned long hrint = __this_cpu_read(hrtimer_interrupts); if (__this_cpu_read(hrtimer_interrupts_saved) == hrint) return 1; __this_cpu_write(hrtimer_interrupts_saved, hrint); return 0; } #endif static int is_softlockup(unsigned long touch_ts) { unsigned long now = get_timestamp(smp_processor_id()); /* Warn about unreasonable delays: */ if (time_after(now, touch_ts + get_softlockup_thresh())) return now - touch_ts; return 0; } #ifdef CONFIG_HARDLOCKUP_DETECTOR static struct perf_event_attr wd_hw_attr = { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES, .size = sizeof(struct perf_event_attr), .pinned = 1, .disabled = 1, }; /* Callback function for perf event subsystem */ static void watchdog_overflow_callback(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { /* Ensure the watchdog never gets throttled */ event->hw.interrupts = 0; if (__this_cpu_read(watchdog_nmi_touch) == true) { __this_cpu_write(watchdog_nmi_touch, false); return; } /* check for a hardlockup * This is done by making sure our timer interrupt * is incrementing. The timer interrupt should have * fired multiple times before we overflow'd. If it hasn't * then this is a good indication the cpu is stuck */ if (is_hardlockup()) { int this_cpu = smp_processor_id(); /* only print hardlockups once */ if (__this_cpu_read(hard_watchdog_warn) == true) return; if (hardlockup_panic) panic("Watchdog detected hard LOCKUP on cpu %d", this_cpu); else WARN(1, "Watchdog detected hard LOCKUP on cpu %d", this_cpu); __this_cpu_write(hard_watchdog_warn, true); return; } __this_cpu_write(hard_watchdog_warn, false); return; } static void watchdog_interrupt_count(void) { __this_cpu_inc(hrtimer_interrupts); } #else static inline void watchdog_interrupt_count(void) { return; } #endif /* CONFIG_HARDLOCKUP_DETECTOR */ /* watchdog kicker functions */ static enum hrtimer_restart watchdog_timer_fn(struct hrtimer *hrtimer) { unsigned long touch_ts = __this_cpu_read(watchdog_touch_ts); struct pt_regs *regs = get_irq_regs(); int duration; /* kick the hardlockup detector */ watchdog_interrupt_count(); /* kick the softlockup detector */ wake_up_process(__this_cpu_read(softlockup_watchdog)); /* .. and repeat */ hrtimer_forward_now(hrtimer, ns_to_ktime(get_sample_period())); if (touch_ts == 0) { if (unlikely(__this_cpu_read(softlockup_touch_sync))) { /* * If the time stamp was touched atomically * make sure the scheduler tick is up to date. */ __this_cpu_write(softlockup_touch_sync, false); sched_clock_tick(); } __touch_watchdog(); return HRTIMER_RESTART; } /* check for a softlockup * This is done by making sure a high priority task is * being scheduled. The task touches the watchdog to * indicate it is getting cpu time. If it hasn't then * this is a good indication some task is hogging the cpu */ duration = is_softlockup(touch_ts); if (unlikely(duration)) { /* only warn once */ if (__this_cpu_read(soft_watchdog_warn) == true) return HRTIMER_RESTART; printk(KERN_EMERG "BUG: soft lockup - CPU#%d stuck for %us! [%s:%d]\n", smp_processor_id(), duration, current->comm, task_pid_nr(current)); print_modules(); print_irqtrace_events(current); if (regs) show_regs(regs); else dump_stack(); if (softlockup_panic) panic("softlockup: hung tasks"); __this_cpu_write(soft_watchdog_warn, true); } else __this_cpu_write(soft_watchdog_warn, false); return HRTIMER_RESTART; } /* * The watchdog thread - touches the timestamp. */ static int watchdog(void *unused) { struct sched_param param = { .sched_priority = 0 }; struct hrtimer *hrtimer = &__raw_get_cpu_var(watchdog_hrtimer); /* initialize timestamp */ __touch_watchdog(); /* kick off the timer for the hardlockup detector */ /* done here because hrtimer_start can only pin to smp_processor_id() */ hrtimer_start(hrtimer, ns_to_ktime(get_sample_period()), HRTIMER_MODE_REL_PINNED); set_current_state(TASK_INTERRUPTIBLE); /* * Run briefly (kicked by the hrtimer callback function) once every * get_sample_period() seconds (4 seconds by default) to reset the * softlockup timestamp. If this gets delayed for more than * 2*watchdog_thresh seconds then the debug-printout triggers in * watchdog_timer_fn(). */ while (!kthread_should_stop()) { __touch_watchdog(); schedule(); if (kthread_should_stop()) break; set_current_state(TASK_INTERRUPTIBLE); } /* * Drop the policy/priority elevation during thread exit to avoid a * scheduling latency spike. */ __set_current_state(TASK_RUNNING); sched_setscheduler(current, SCHED_NORMAL, &param); return 0; } #ifdef CONFIG_HARDLOCKUP_DETECTOR static int watchdog_nmi_enable(int cpu) { struct perf_event_attr *wd_attr; struct perf_event *event = per_cpu(watchdog_ev, cpu); /* is it already setup and enabled? */ if (event && event->state > PERF_EVENT_STATE_OFF) goto out; /* it is setup but not enabled */ if (event != NULL) goto out_enable; wd_attr = &wd_hw_attr; wd_attr->sample_period = hw_nmi_get_sample_period(watchdog_thresh); /* Try to register using hardware perf events */ event = perf_event_create_kernel_counter(wd_attr, cpu, NULL, watchdog_overflow_callback, NULL); if (!IS_ERR(event)) { pr_info("enabled, takes one hw-pmu counter.\n"); goto out_save; } /* vary the KERN level based on the returned errno */ if (PTR_ERR(event) == -EOPNOTSUPP) pr_info("disabled (cpu%i): not supported (no LAPIC?)\n", cpu); else if (PTR_ERR(event) == -ENOENT) pr_warning("disabled (cpu%i): hardware events not enabled\n", cpu); else pr_err("disabled (cpu%i): unable to create perf event: %ld\n", cpu, PTR_ERR(event)); return PTR_ERR(event); /* success path */ out_save: per_cpu(watchdog_ev, cpu) = event; out_enable: perf_event_enable(per_cpu(watchdog_ev, cpu)); out: return 0; } static void watchdog_nmi_disable(int cpu) { struct perf_event *event = per_cpu(watchdog_ev, cpu); if (event) { perf_event_disable(event); per_cpu(watchdog_ev, cpu) = NULL; /* should be in cleanup, but blocks oprofile */ perf_event_release_kernel(event); } return; } #else static int watchdog_nmi_enable(int cpu) { return 0; } static void watchdog_nmi_disable(int cpu) { return; } #endif /* CONFIG_HARDLOCKUP_DETECTOR */ /* prepare/enable/disable routines */ static void watchdog_prepare_cpu(int cpu) { struct hrtimer *hrtimer = &per_cpu(watchdog_hrtimer, cpu); WARN_ON(per_cpu(softlockup_watchdog, cpu)); hrtimer_init(hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); hrtimer->function = watchdog_timer_fn; } static int watchdog_enable(int cpu) { struct task_struct *p = per_cpu(softlockup_watchdog, cpu); int err = 0; /* enable the perf event */ err = watchdog_nmi_enable(cpu); /* Regardless of err above, fall through and start softlockup */ /* create the watchdog thread */ if (!p) { struct sched_param param = { .sched_priority = MAX_RT_PRIO-1 }; p = kthread_create_on_node(watchdog, NULL, cpu_to_node(cpu), "watchdog/%d", cpu); if (IS_ERR(p)) { pr_err("softlockup watchdog for %i failed\n", cpu); if (!err) { /* if hardlockup hasn't already set this */ err = PTR_ERR(p); /* and disable the perf event */ watchdog_nmi_disable(cpu); } goto out; } sched_setscheduler(p, SCHED_FIFO, &param); kthread_bind(p, cpu); per_cpu(watchdog_touch_ts, cpu) = 0; per_cpu(softlockup_watchdog, cpu) = p; wake_up_process(p); } out: return err; } static void watchdog_disable(int cpu) { struct task_struct *p = per_cpu(softlockup_watchdog, cpu); struct hrtimer *hrtimer = &per_cpu(watchdog_hrtimer, cpu); /* * cancel the timer first to stop incrementing the stats * and waking up the kthread */ hrtimer_cancel(hrtimer); /* disable the perf event */ watchdog_nmi_disable(cpu); /* stop the watchdog thread */ if (p) { per_cpu(softlockup_watchdog, cpu) = NULL; kthread_stop(p); } } /* sysctl functions */ #ifdef CONFIG_SYSCTL static void watchdog_enable_all_cpus(void) { int cpu; watchdog_enabled = 0; for_each_online_cpu(cpu) if (!watchdog_enable(cpu)) /* if any cpu succeeds, watchdog is considered enabled for the system */ watchdog_enabled = 1; if (!watchdog_enabled) pr_err("failed to be enabled on some cpus\n"); } static void watchdog_disable_all_cpus(void) { int cpu; for_each_online_cpu(cpu) watchdog_disable(cpu); /* if all watchdogs are disabled, then they are disabled for the system */ watchdog_enabled = 0; } /* * proc handler for /proc/sys/kernel/nmi_watchdog,watchdog_thresh */ int proc_dowatchdog(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret; ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (ret || !write) goto out; if (watchdog_enabled && watchdog_thresh) watchdog_enable_all_cpus(); else watchdog_disable_all_cpus(); out: return ret; } #endif /* CONFIG_SYSCTL */ /* * Create/destroy watchdog threads as CPUs come and go: */ static int __cpuinit cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { int hotcpu = (unsigned long)hcpu; switch (action) { case CPU_UP_PREPARE: case CPU_UP_PREPARE_FROZEN: watchdog_prepare_cpu(hotcpu); break; case CPU_ONLINE: case CPU_ONLINE_FROZEN: if (watchdog_enabled) watchdog_enable(hotcpu); break; #ifdef CONFIG_HOTPLUG_CPU case CPU_UP_CANCELED: case CPU_UP_CANCELED_FROZEN: watchdog_disable(hotcpu); break; case CPU_DEAD: case CPU_DEAD_FROZEN: watchdog_disable(hotcpu); break; #endif /* CONFIG_HOTPLUG_CPU */ } /* * hardlockup and softlockup are not important enough * to block cpu bring up. Just always succeed and * rely on printk output to flag problems. */ return NOTIFY_OK; } static struct notifier_block __cpuinitdata cpu_nfb = { .notifier_call = cpu_callback }; void __init lockup_detector_init(void) { void *cpu = (void *)(long)smp_processor_id(); int err; err = cpu_callback(&cpu_nfb, CPU_UP_PREPARE, cpu); WARN_ON(notifier_to_errno(err)); cpu_callback(&cpu_nfb, CPU_ONLINE, cpu); register_cpu_notifier(&cpu_nfb); return; }
gpl-2.0
slayher/htc-kernel-mecha-2.6.35
drivers/edac/cell_edac.c
1572
7394
/* * Cell MIC driver for ECC counting * * Copyright 2007 Benjamin Herrenschmidt, IBM Corp. * <benh@kernel.crashing.org> * * This file may be distributed under the terms of the * GNU General Public License. */ #undef DEBUG #include <linux/edac.h> #include <linux/module.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/stop_machine.h> #include <linux/io.h> #include <asm/machdep.h> #include <asm/cell-regs.h> #include "edac_core.h" struct cell_edac_priv { struct cbe_mic_tm_regs __iomem *regs; int node; int chanmask; #ifdef DEBUG u64 prev_fir; #endif }; static void cell_edac_count_ce(struct mem_ctl_info *mci, int chan, u64 ar) { struct cell_edac_priv *priv = mci->pvt_info; struct csrow_info *csrow = &mci->csrows[0]; unsigned long address, pfn, offset, syndrome; dev_dbg(mci->dev, "ECC CE err on node %d, channel %d, ar = 0x%016llx\n", priv->node, chan, ar); /* Address decoding is likely a bit bogus, to dbl check */ address = (ar & 0xffffffffe0000000ul) >> 29; if (priv->chanmask == 0x3) address = (address << 1) | chan; pfn = address >> PAGE_SHIFT; offset = address & ~PAGE_MASK; syndrome = (ar & 0x000000001fe00000ul) >> 21; /* TODO: Decoding of the error addresss */ edac_mc_handle_ce(mci, csrow->first_page + pfn, offset, syndrome, 0, chan, ""); } static void cell_edac_count_ue(struct mem_ctl_info *mci, int chan, u64 ar) { struct cell_edac_priv *priv = mci->pvt_info; struct csrow_info *csrow = &mci->csrows[0]; unsigned long address, pfn, offset; dev_dbg(mci->dev, "ECC UE err on node %d, channel %d, ar = 0x%016llx\n", priv->node, chan, ar); /* Address decoding is likely a bit bogus, to dbl check */ address = (ar & 0xffffffffe0000000ul) >> 29; if (priv->chanmask == 0x3) address = (address << 1) | chan; pfn = address >> PAGE_SHIFT; offset = address & ~PAGE_MASK; /* TODO: Decoding of the error addresss */ edac_mc_handle_ue(mci, csrow->first_page + pfn, offset, 0, ""); } static void cell_edac_check(struct mem_ctl_info *mci) { struct cell_edac_priv *priv = mci->pvt_info; u64 fir, addreg, clear = 0; fir = in_be64(&priv->regs->mic_fir); #ifdef DEBUG if (fir != priv->prev_fir) { dev_dbg(mci->dev, "fir change : 0x%016lx\n", fir); priv->prev_fir = fir; } #endif if ((priv->chanmask & 0x1) && (fir & CBE_MIC_FIR_ECC_SINGLE_0_ERR)) { addreg = in_be64(&priv->regs->mic_df_ecc_address_0); clear |= CBE_MIC_FIR_ECC_SINGLE_0_RESET; cell_edac_count_ce(mci, 0, addreg); } if ((priv->chanmask & 0x2) && (fir & CBE_MIC_FIR_ECC_SINGLE_1_ERR)) { addreg = in_be64(&priv->regs->mic_df_ecc_address_1); clear |= CBE_MIC_FIR_ECC_SINGLE_1_RESET; cell_edac_count_ce(mci, 1, addreg); } if ((priv->chanmask & 0x1) && (fir & CBE_MIC_FIR_ECC_MULTI_0_ERR)) { addreg = in_be64(&priv->regs->mic_df_ecc_address_0); clear |= CBE_MIC_FIR_ECC_MULTI_0_RESET; cell_edac_count_ue(mci, 0, addreg); } if ((priv->chanmask & 0x2) && (fir & CBE_MIC_FIR_ECC_MULTI_1_ERR)) { addreg = in_be64(&priv->regs->mic_df_ecc_address_1); clear |= CBE_MIC_FIR_ECC_MULTI_1_RESET; cell_edac_count_ue(mci, 1, addreg); } /* The procedure for clearing FIR bits is a bit ... weird */ if (clear) { fir &= ~(CBE_MIC_FIR_ECC_ERR_MASK | CBE_MIC_FIR_ECC_SET_MASK); fir |= CBE_MIC_FIR_ECC_RESET_MASK; fir &= ~clear; out_be64(&priv->regs->mic_fir, fir); (void)in_be64(&priv->regs->mic_fir); mb(); /* sync up */ #ifdef DEBUG fir = in_be64(&priv->regs->mic_fir); dev_dbg(mci->dev, "fir clear : 0x%016lx\n", fir); #endif } } static void __devinit cell_edac_init_csrows(struct mem_ctl_info *mci) { struct csrow_info *csrow = &mci->csrows[0]; struct cell_edac_priv *priv = mci->pvt_info; struct device_node *np; for (np = NULL; (np = of_find_node_by_name(np, "memory")) != NULL;) { struct resource r; /* We "know" that the Cell firmware only creates one entry * in the "memory" nodes. If that changes, this code will * need to be adapted. */ if (of_address_to_resource(np, 0, &r)) continue; if (of_node_to_nid(np) != priv->node) continue; csrow->first_page = r.start >> PAGE_SHIFT; csrow->nr_pages = (r.end - r.start + 1) >> PAGE_SHIFT; csrow->last_page = csrow->first_page + csrow->nr_pages - 1; csrow->mtype = MEM_XDR; csrow->edac_mode = EDAC_SECDED; dev_dbg(mci->dev, "Initialized on node %d, chanmask=0x%x," " first_page=0x%lx, nr_pages=0x%x\n", priv->node, priv->chanmask, csrow->first_page, csrow->nr_pages); break; } } static int __devinit cell_edac_probe(struct platform_device *pdev) { struct cbe_mic_tm_regs __iomem *regs; struct mem_ctl_info *mci; struct cell_edac_priv *priv; u64 reg; int rc, chanmask; regs = cbe_get_cpu_mic_tm_regs(cbe_node_to_cpu(pdev->id)); if (regs == NULL) return -ENODEV; edac_op_state = EDAC_OPSTATE_POLL; /* Get channel population */ reg = in_be64(&regs->mic_mnt_cfg); dev_dbg(&pdev->dev, "MIC_MNT_CFG = 0x%016llx\n", reg); chanmask = 0; if (reg & CBE_MIC_MNT_CFG_CHAN_0_POP) chanmask |= 0x1; if (reg & CBE_MIC_MNT_CFG_CHAN_1_POP) chanmask |= 0x2; if (chanmask == 0) { dev_warn(&pdev->dev, "Yuck ! No channel populated ? Aborting !\n"); return -ENODEV; } dev_dbg(&pdev->dev, "Initial FIR = 0x%016llx\n", in_be64(&regs->mic_fir)); /* Allocate & init EDAC MC data structure */ mci = edac_mc_alloc(sizeof(struct cell_edac_priv), 1, chanmask == 3 ? 2 : 1, pdev->id); if (mci == NULL) return -ENOMEM; priv = mci->pvt_info; priv->regs = regs; priv->node = pdev->id; priv->chanmask = chanmask; mci->dev = &pdev->dev; mci->mtype_cap = MEM_FLAG_XDR; mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_EC | EDAC_FLAG_SECDED; mci->edac_cap = EDAC_FLAG_EC | EDAC_FLAG_SECDED; mci->mod_name = "cell_edac"; mci->ctl_name = "MIC"; mci->dev_name = dev_name(&pdev->dev); mci->edac_check = cell_edac_check; cell_edac_init_csrows(mci); /* Register with EDAC core */ rc = edac_mc_add_mc(mci); if (rc) { dev_err(&pdev->dev, "failed to register with EDAC core\n"); edac_mc_free(mci); return rc; } return 0; } static int __devexit cell_edac_remove(struct platform_device *pdev) { struct mem_ctl_info *mci = edac_mc_del_mc(&pdev->dev); if (mci) edac_mc_free(mci); return 0; } static struct platform_driver cell_edac_driver = { .driver = { .name = "cbe-mic", .owner = THIS_MODULE, }, .probe = cell_edac_probe, .remove = __devexit_p(cell_edac_remove), }; static int __init cell_edac_init(void) { /* Sanity check registers data structure */ BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs, mic_df_ecc_address_0) != 0xf8); BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs, mic_df_ecc_address_1) != 0x1b8); BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs, mic_df_config) != 0x218); BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs, mic_fir) != 0x230); BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs, mic_mnt_cfg) != 0x210); BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs, mic_exc) != 0x208); return platform_driver_register(&cell_edac_driver); } static void __exit cell_edac_exit(void) { platform_driver_unregister(&cell_edac_driver); } module_init(cell_edac_init); module_exit(cell_edac_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Benjamin Herrenschmidt <benh@kernel.crashing.org>"); MODULE_DESCRIPTION("ECC counting for Cell MIC");
gpl-2.0
bq/aquaris-M4.5
arch/m68k/68000/timers.c
2084
3501
/***************************************************************************/ /* * timers.c - Generic hardware timer support. * * Copyright (C) 1993 Hamish Macdonald * Copyright (C) 1999 D. Jeff Dionne * Copyright (C) 2001 Georges Menie, Ken Desmet * * 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/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/clocksource.h> #include <linux/rtc.h> #include <asm/setup.h> #include <asm/pgtable.h> #include <asm/machdep.h> #include <asm/MC68VZ328.h> /***************************************************************************/ #if defined(CONFIG_DRAGEN2) /* with a 33.16 MHz clock, this will give usec resolution to the time functions */ #define CLOCK_SOURCE TCTL_CLKSOURCE_SYSCLK #define CLOCK_PRE 7 #define TICKS_PER_JIFFY 41450 #elif defined(CONFIG_XCOPILOT_BUGS) /* * The only thing I know is that CLK32 is not available on Xcopilot * I have little idea about what frequency SYSCLK has on Xcopilot. * The values for prescaler and compare registers were simply * taken from the original source */ #define CLOCK_SOURCE TCTL_CLKSOURCE_SYSCLK #define CLOCK_PRE 2 #define TICKS_PER_JIFFY 0xd7e4 #else /* default to using the 32Khz clock */ #define CLOCK_SOURCE TCTL_CLKSOURCE_32KHZ #define CLOCK_PRE 31 #define TICKS_PER_JIFFY 10 #endif static u32 m68328_tick_cnt; static irq_handler_t timer_interrupt; /***************************************************************************/ static irqreturn_t hw_tick(int irq, void *dummy) { /* Reset Timer1 */ TSTAT &= 0; m68328_tick_cnt += TICKS_PER_JIFFY; return timer_interrupt(irq, dummy); } /***************************************************************************/ static struct irqaction m68328_timer_irq = { .name = "timer", .flags = IRQF_TIMER, .handler = hw_tick, }; /***************************************************************************/ static cycle_t m68328_read_clk(struct clocksource *cs) { unsigned long flags; u32 cycles; local_irq_save(flags); cycles = m68328_tick_cnt + TCN; local_irq_restore(flags); return cycles; } /***************************************************************************/ static struct clocksource m68328_clk = { .name = "timer", .rating = 250, .read = m68328_read_clk, .mask = CLOCKSOURCE_MASK(32), .flags = CLOCK_SOURCE_IS_CONTINUOUS, }; /***************************************************************************/ void hw_timer_init(irq_handler_t handler) { /* disable timer 1 */ TCTL = 0; /* set ISR */ setup_irq(TMR_IRQ_NUM, &m68328_timer_irq); /* Restart mode, Enable int, Set clock source */ TCTL = TCTL_OM | TCTL_IRQEN | CLOCK_SOURCE; TPRER = CLOCK_PRE; TCMP = TICKS_PER_JIFFY; /* Enable timer 1 */ TCTL |= TCTL_TEN; clocksource_register_hz(&m68328_clk, TICKS_PER_JIFFY*HZ); timer_interrupt = handler; } /***************************************************************************/ int m68328_hwclk(int set, struct rtc_time *t) { if (!set) { long now = RTCTIME; t->tm_year = t->tm_mon = t->tm_mday = 1; t->tm_hour = (now >> 24) % 24; t->tm_min = (now >> 16) % 60; t->tm_sec = now % 60; } return 0; } /***************************************************************************/
gpl-2.0
MROM/android_kernel_bn_encore
fs/jffs2/dir.c
2340
23369
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright © 2001-2007 Red Hat, Inc. * Copyright © 2004-2010 David Woodhouse <dwmw2@infradead.org> * * Created by David Woodhouse <dwmw2@infradead.org> * * For licensing information, see the file 'LICENCE' in this directory. * */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/crc32.h> #include <linux/jffs2.h> #include "jffs2_fs_i.h" #include "jffs2_fs_sb.h" #include <linux/time.h> #include "nodelist.h" static int jffs2_readdir (struct file *, void *, filldir_t); static int jffs2_create (struct inode *,struct dentry *,int, struct nameidata *); static struct dentry *jffs2_lookup (struct inode *,struct dentry *, struct nameidata *); static int jffs2_link (struct dentry *,struct inode *,struct dentry *); static int jffs2_unlink (struct inode *,struct dentry *); static int jffs2_symlink (struct inode *,struct dentry *,const char *); static int jffs2_mkdir (struct inode *,struct dentry *,int); static int jffs2_rmdir (struct inode *,struct dentry *); static int jffs2_mknod (struct inode *,struct dentry *,int,dev_t); static int jffs2_rename (struct inode *, struct dentry *, struct inode *, struct dentry *); const struct file_operations jffs2_dir_operations = { .read = generic_read_dir, .readdir = jffs2_readdir, .unlocked_ioctl=jffs2_ioctl, .fsync = jffs2_fsync, .llseek = generic_file_llseek, }; const struct inode_operations jffs2_dir_inode_operations = { .create = jffs2_create, .lookup = jffs2_lookup, .link = jffs2_link, .unlink = jffs2_unlink, .symlink = jffs2_symlink, .mkdir = jffs2_mkdir, .rmdir = jffs2_rmdir, .mknod = jffs2_mknod, .rename = jffs2_rename, .check_acl = jffs2_check_acl, .setattr = jffs2_setattr, .setxattr = jffs2_setxattr, .getxattr = jffs2_getxattr, .listxattr = jffs2_listxattr, .removexattr = jffs2_removexattr }; /***********************************************************************/ /* We keep the dirent list sorted in increasing order of name hash, and we use the same hash function as the dentries. Makes this nice and simple */ static struct dentry *jffs2_lookup(struct inode *dir_i, struct dentry *target, struct nameidata *nd) { struct jffs2_inode_info *dir_f; struct jffs2_full_dirent *fd = NULL, *fd_list; uint32_t ino = 0; struct inode *inode = NULL; D1(printk(KERN_DEBUG "jffs2_lookup()\n")); if (target->d_name.len > JFFS2_MAX_NAME_LEN) return ERR_PTR(-ENAMETOOLONG); dir_f = JFFS2_INODE_INFO(dir_i); mutex_lock(&dir_f->sem); /* NB: The 2.2 backport will need to explicitly check for '.' and '..' here */ for (fd_list = dir_f->dents; fd_list && fd_list->nhash <= target->d_name.hash; fd_list = fd_list->next) { if (fd_list->nhash == target->d_name.hash && (!fd || fd_list->version > fd->version) && strlen(fd_list->name) == target->d_name.len && !strncmp(fd_list->name, target->d_name.name, target->d_name.len)) { fd = fd_list; } } if (fd) ino = fd->ino; mutex_unlock(&dir_f->sem); if (ino) { inode = jffs2_iget(dir_i->i_sb, ino); if (IS_ERR(inode)) { printk(KERN_WARNING "iget() failed for ino #%u\n", ino); return ERR_CAST(inode); } } return d_splice_alias(inode, target); } /***********************************************************************/ static int jffs2_readdir(struct file *filp, void *dirent, filldir_t filldir) { struct jffs2_inode_info *f; struct inode *inode = filp->f_path.dentry->d_inode; struct jffs2_full_dirent *fd; unsigned long offset, curofs; D1(printk(KERN_DEBUG "jffs2_readdir() for dir_i #%lu\n", filp->f_path.dentry->d_inode->i_ino)); f = JFFS2_INODE_INFO(inode); offset = filp->f_pos; if (offset == 0) { D1(printk(KERN_DEBUG "Dirent 0: \".\", ino #%lu\n", inode->i_ino)); if (filldir(dirent, ".", 1, 0, inode->i_ino, DT_DIR) < 0) goto out; offset++; } if (offset == 1) { unsigned long pino = parent_ino(filp->f_path.dentry); D1(printk(KERN_DEBUG "Dirent 1: \"..\", ino #%lu\n", pino)); if (filldir(dirent, "..", 2, 1, pino, DT_DIR) < 0) goto out; offset++; } curofs=1; mutex_lock(&f->sem); for (fd = f->dents; fd; fd = fd->next) { curofs++; /* First loop: curofs = 2; offset = 2 */ if (curofs < offset) { D2(printk(KERN_DEBUG "Skipping dirent: \"%s\", ino #%u, type %d, because curofs %ld < offset %ld\n", fd->name, fd->ino, fd->type, curofs, offset)); continue; } if (!fd->ino) { D2(printk(KERN_DEBUG "Skipping deletion dirent \"%s\"\n", fd->name)); offset++; continue; } D2(printk(KERN_DEBUG "Dirent %ld: \"%s\", ino #%u, type %d\n", offset, fd->name, fd->ino, fd->type)); if (filldir(dirent, fd->name, strlen(fd->name), offset, fd->ino, fd->type) < 0) break; offset++; } mutex_unlock(&f->sem); out: filp->f_pos = offset; return 0; } /***********************************************************************/ static int jffs2_create(struct inode *dir_i, struct dentry *dentry, int mode, struct nameidata *nd) { struct jffs2_raw_inode *ri; struct jffs2_inode_info *f, *dir_f; struct jffs2_sb_info *c; struct inode *inode; int ret; ri = jffs2_alloc_raw_inode(); if (!ri) return -ENOMEM; c = JFFS2_SB_INFO(dir_i->i_sb); D1(printk(KERN_DEBUG "jffs2_create()\n")); inode = jffs2_new_inode(dir_i, mode, ri); if (IS_ERR(inode)) { D1(printk(KERN_DEBUG "jffs2_new_inode() failed\n")); jffs2_free_raw_inode(ri); return PTR_ERR(inode); } inode->i_op = &jffs2_file_inode_operations; inode->i_fop = &jffs2_file_operations; inode->i_mapping->a_ops = &jffs2_file_address_operations; inode->i_mapping->nrpages = 0; f = JFFS2_INODE_INFO(inode); dir_f = JFFS2_INODE_INFO(dir_i); /* jffs2_do_create() will want to lock it, _after_ reserving space and taking c-alloc_sem. If we keep it locked here, lockdep gets unhappy (although it's a false positive; nothing else will be looking at this inode yet so there's no chance of AB-BA deadlock involving its f->sem). */ mutex_unlock(&f->sem); ret = jffs2_do_create(c, dir_f, f, ri, &dentry->d_name); if (ret) goto fail; dir_i->i_mtime = dir_i->i_ctime = ITIME(je32_to_cpu(ri->ctime)); jffs2_free_raw_inode(ri); D1(printk(KERN_DEBUG "jffs2_create: Created ino #%lu with mode %o, nlink %d(%d). nrpages %ld\n", inode->i_ino, inode->i_mode, inode->i_nlink, f->inocache->pino_nlink, inode->i_mapping->nrpages)); d_instantiate(dentry, inode); unlock_new_inode(inode); return 0; fail: iget_failed(inode); jffs2_free_raw_inode(ri); return ret; } /***********************************************************************/ static int jffs2_unlink(struct inode *dir_i, struct dentry *dentry) { struct jffs2_sb_info *c = JFFS2_SB_INFO(dir_i->i_sb); struct jffs2_inode_info *dir_f = JFFS2_INODE_INFO(dir_i); struct jffs2_inode_info *dead_f = JFFS2_INODE_INFO(dentry->d_inode); int ret; uint32_t now = get_seconds(); ret = jffs2_do_unlink(c, dir_f, dentry->d_name.name, dentry->d_name.len, dead_f, now); if (dead_f->inocache) dentry->d_inode->i_nlink = dead_f->inocache->pino_nlink; if (!ret) dir_i->i_mtime = dir_i->i_ctime = ITIME(now); return ret; } /***********************************************************************/ static int jffs2_link (struct dentry *old_dentry, struct inode *dir_i, struct dentry *dentry) { struct jffs2_sb_info *c = JFFS2_SB_INFO(old_dentry->d_inode->i_sb); struct jffs2_inode_info *f = JFFS2_INODE_INFO(old_dentry->d_inode); struct jffs2_inode_info *dir_f = JFFS2_INODE_INFO(dir_i); int ret; uint8_t type; uint32_t now; /* Don't let people make hard links to bad inodes. */ if (!f->inocache) return -EIO; if (S_ISDIR(old_dentry->d_inode->i_mode)) return -EPERM; /* XXX: This is ugly */ type = (old_dentry->d_inode->i_mode & S_IFMT) >> 12; if (!type) type = DT_REG; now = get_seconds(); ret = jffs2_do_link(c, dir_f, f->inocache->ino, type, dentry->d_name.name, dentry->d_name.len, now); if (!ret) { mutex_lock(&f->sem); old_dentry->d_inode->i_nlink = ++f->inocache->pino_nlink; mutex_unlock(&f->sem); d_instantiate(dentry, old_dentry->d_inode); dir_i->i_mtime = dir_i->i_ctime = ITIME(now); ihold(old_dentry->d_inode); } return ret; } /***********************************************************************/ static int jffs2_symlink (struct inode *dir_i, struct dentry *dentry, const char *target) { struct jffs2_inode_info *f, *dir_f; struct jffs2_sb_info *c; struct inode *inode; struct jffs2_raw_inode *ri; struct jffs2_raw_dirent *rd; struct jffs2_full_dnode *fn; struct jffs2_full_dirent *fd; int namelen; uint32_t alloclen; int ret, targetlen = strlen(target); /* FIXME: If you care. We'd need to use frags for the target if it grows much more than this */ if (targetlen > 254) return -ENAMETOOLONG; ri = jffs2_alloc_raw_inode(); if (!ri) return -ENOMEM; c = JFFS2_SB_INFO(dir_i->i_sb); /* Try to reserve enough space for both node and dirent. * Just the node will do for now, though */ namelen = dentry->d_name.len; ret = jffs2_reserve_space(c, sizeof(*ri) + targetlen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE); if (ret) { jffs2_free_raw_inode(ri); return ret; } inode = jffs2_new_inode(dir_i, S_IFLNK | S_IRWXUGO, ri); if (IS_ERR(inode)) { jffs2_free_raw_inode(ri); jffs2_complete_reservation(c); return PTR_ERR(inode); } inode->i_op = &jffs2_symlink_inode_operations; f = JFFS2_INODE_INFO(inode); inode->i_size = targetlen; ri->isize = ri->dsize = ri->csize = cpu_to_je32(inode->i_size); ri->totlen = cpu_to_je32(sizeof(*ri) + inode->i_size); ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)); ri->compr = JFFS2_COMPR_NONE; ri->data_crc = cpu_to_je32(crc32(0, target, targetlen)); ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); fn = jffs2_write_dnode(c, f, ri, target, targetlen, ALLOC_NORMAL); jffs2_free_raw_inode(ri); if (IS_ERR(fn)) { /* Eeek. Wave bye bye */ mutex_unlock(&f->sem); jffs2_complete_reservation(c); ret = PTR_ERR(fn); goto fail; } /* We use f->target field to store the target path. */ f->target = kmemdup(target, targetlen + 1, GFP_KERNEL); if (!f->target) { printk(KERN_WARNING "Can't allocate %d bytes of memory\n", targetlen + 1); mutex_unlock(&f->sem); jffs2_complete_reservation(c); ret = -ENOMEM; goto fail; } D1(printk(KERN_DEBUG "jffs2_symlink: symlink's target '%s' cached\n", (char *)f->target)); /* No data here. Only a metadata node, which will be obsoleted by the first data write */ f->metadata = fn; mutex_unlock(&f->sem); jffs2_complete_reservation(c); ret = jffs2_init_security(inode, dir_i, &dentry->d_name); if (ret) goto fail; ret = jffs2_init_acl_post(inode); if (ret) goto fail; ret = jffs2_reserve_space(c, sizeof(*rd)+namelen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_DIRENT_SIZE(namelen)); if (ret) goto fail; rd = jffs2_alloc_raw_dirent(); if (!rd) { /* Argh. Now we treat it like a normal delete */ jffs2_complete_reservation(c); ret = -ENOMEM; goto fail; } dir_f = JFFS2_INODE_INFO(dir_i); mutex_lock(&dir_f->sem); rd->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); rd->nodetype = cpu_to_je16(JFFS2_NODETYPE_DIRENT); rd->totlen = cpu_to_je32(sizeof(*rd) + namelen); rd->hdr_crc = cpu_to_je32(crc32(0, rd, sizeof(struct jffs2_unknown_node)-4)); rd->pino = cpu_to_je32(dir_i->i_ino); rd->version = cpu_to_je32(++dir_f->highest_version); rd->ino = cpu_to_je32(inode->i_ino); rd->mctime = cpu_to_je32(get_seconds()); rd->nsize = namelen; rd->type = DT_LNK; rd->node_crc = cpu_to_je32(crc32(0, rd, sizeof(*rd)-8)); rd->name_crc = cpu_to_je32(crc32(0, dentry->d_name.name, namelen)); fd = jffs2_write_dirent(c, dir_f, rd, dentry->d_name.name, namelen, ALLOC_NORMAL); if (IS_ERR(fd)) { /* dirent failed to write. Delete the inode normally as if it were the final unlink() */ jffs2_complete_reservation(c); jffs2_free_raw_dirent(rd); mutex_unlock(&dir_f->sem); ret = PTR_ERR(fd); goto fail; } dir_i->i_mtime = dir_i->i_ctime = ITIME(je32_to_cpu(rd->mctime)); jffs2_free_raw_dirent(rd); /* Link the fd into the inode's list, obsoleting an old one if necessary. */ jffs2_add_fd_to_list(c, fd, &dir_f->dents); mutex_unlock(&dir_f->sem); jffs2_complete_reservation(c); d_instantiate(dentry, inode); unlock_new_inode(inode); return 0; fail: iget_failed(inode); return ret; } static int jffs2_mkdir (struct inode *dir_i, struct dentry *dentry, int mode) { struct jffs2_inode_info *f, *dir_f; struct jffs2_sb_info *c; struct inode *inode; struct jffs2_raw_inode *ri; struct jffs2_raw_dirent *rd; struct jffs2_full_dnode *fn; struct jffs2_full_dirent *fd; int namelen; uint32_t alloclen; int ret; mode |= S_IFDIR; ri = jffs2_alloc_raw_inode(); if (!ri) return -ENOMEM; c = JFFS2_SB_INFO(dir_i->i_sb); /* Try to reserve enough space for both node and dirent. * Just the node will do for now, though */ namelen = dentry->d_name.len; ret = jffs2_reserve_space(c, sizeof(*ri), &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE); if (ret) { jffs2_free_raw_inode(ri); return ret; } inode = jffs2_new_inode(dir_i, mode, ri); if (IS_ERR(inode)) { jffs2_free_raw_inode(ri); jffs2_complete_reservation(c); return PTR_ERR(inode); } inode->i_op = &jffs2_dir_inode_operations; inode->i_fop = &jffs2_dir_operations; f = JFFS2_INODE_INFO(inode); /* Directories get nlink 2 at start */ inode->i_nlink = 2; /* but ic->pino_nlink is the parent ino# */ f->inocache->pino_nlink = dir_i->i_ino; ri->data_crc = cpu_to_je32(0); ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); fn = jffs2_write_dnode(c, f, ri, NULL, 0, ALLOC_NORMAL); jffs2_free_raw_inode(ri); if (IS_ERR(fn)) { /* Eeek. Wave bye bye */ mutex_unlock(&f->sem); jffs2_complete_reservation(c); ret = PTR_ERR(fn); goto fail; } /* No data here. Only a metadata node, which will be obsoleted by the first data write */ f->metadata = fn; mutex_unlock(&f->sem); jffs2_complete_reservation(c); ret = jffs2_init_security(inode, dir_i, &dentry->d_name); if (ret) goto fail; ret = jffs2_init_acl_post(inode); if (ret) goto fail; ret = jffs2_reserve_space(c, sizeof(*rd)+namelen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_DIRENT_SIZE(namelen)); if (ret) goto fail; rd = jffs2_alloc_raw_dirent(); if (!rd) { /* Argh. Now we treat it like a normal delete */ jffs2_complete_reservation(c); ret = -ENOMEM; goto fail; } dir_f = JFFS2_INODE_INFO(dir_i); mutex_lock(&dir_f->sem); rd->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); rd->nodetype = cpu_to_je16(JFFS2_NODETYPE_DIRENT); rd->totlen = cpu_to_je32(sizeof(*rd) + namelen); rd->hdr_crc = cpu_to_je32(crc32(0, rd, sizeof(struct jffs2_unknown_node)-4)); rd->pino = cpu_to_je32(dir_i->i_ino); rd->version = cpu_to_je32(++dir_f->highest_version); rd->ino = cpu_to_je32(inode->i_ino); rd->mctime = cpu_to_je32(get_seconds()); rd->nsize = namelen; rd->type = DT_DIR; rd->node_crc = cpu_to_je32(crc32(0, rd, sizeof(*rd)-8)); rd->name_crc = cpu_to_je32(crc32(0, dentry->d_name.name, namelen)); fd = jffs2_write_dirent(c, dir_f, rd, dentry->d_name.name, namelen, ALLOC_NORMAL); if (IS_ERR(fd)) { /* dirent failed to write. Delete the inode normally as if it were the final unlink() */ jffs2_complete_reservation(c); jffs2_free_raw_dirent(rd); mutex_unlock(&dir_f->sem); ret = PTR_ERR(fd); goto fail; } dir_i->i_mtime = dir_i->i_ctime = ITIME(je32_to_cpu(rd->mctime)); inc_nlink(dir_i); jffs2_free_raw_dirent(rd); /* Link the fd into the inode's list, obsoleting an old one if necessary. */ jffs2_add_fd_to_list(c, fd, &dir_f->dents); mutex_unlock(&dir_f->sem); jffs2_complete_reservation(c); d_instantiate(dentry, inode); unlock_new_inode(inode); return 0; fail: iget_failed(inode); return ret; } static int jffs2_rmdir (struct inode *dir_i, struct dentry *dentry) { struct jffs2_sb_info *c = JFFS2_SB_INFO(dir_i->i_sb); struct jffs2_inode_info *dir_f = JFFS2_INODE_INFO(dir_i); struct jffs2_inode_info *f = JFFS2_INODE_INFO(dentry->d_inode); struct jffs2_full_dirent *fd; int ret; uint32_t now = get_seconds(); for (fd = f->dents ; fd; fd = fd->next) { if (fd->ino) return -ENOTEMPTY; } ret = jffs2_do_unlink(c, dir_f, dentry->d_name.name, dentry->d_name.len, f, now); if (!ret) { dir_i->i_mtime = dir_i->i_ctime = ITIME(now); clear_nlink(dentry->d_inode); drop_nlink(dir_i); } return ret; } static int jffs2_mknod (struct inode *dir_i, struct dentry *dentry, int mode, dev_t rdev) { struct jffs2_inode_info *f, *dir_f; struct jffs2_sb_info *c; struct inode *inode; struct jffs2_raw_inode *ri; struct jffs2_raw_dirent *rd; struct jffs2_full_dnode *fn; struct jffs2_full_dirent *fd; int namelen; union jffs2_device_node dev; int devlen = 0; uint32_t alloclen; int ret; if (!new_valid_dev(rdev)) return -EINVAL; ri = jffs2_alloc_raw_inode(); if (!ri) return -ENOMEM; c = JFFS2_SB_INFO(dir_i->i_sb); if (S_ISBLK(mode) || S_ISCHR(mode)) devlen = jffs2_encode_dev(&dev, rdev); /* Try to reserve enough space for both node and dirent. * Just the node will do for now, though */ namelen = dentry->d_name.len; ret = jffs2_reserve_space(c, sizeof(*ri) + devlen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE); if (ret) { jffs2_free_raw_inode(ri); return ret; } inode = jffs2_new_inode(dir_i, mode, ri); if (IS_ERR(inode)) { jffs2_free_raw_inode(ri); jffs2_complete_reservation(c); return PTR_ERR(inode); } inode->i_op = &jffs2_file_inode_operations; init_special_inode(inode, inode->i_mode, rdev); f = JFFS2_INODE_INFO(inode); ri->dsize = ri->csize = cpu_to_je32(devlen); ri->totlen = cpu_to_je32(sizeof(*ri) + devlen); ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)); ri->compr = JFFS2_COMPR_NONE; ri->data_crc = cpu_to_je32(crc32(0, &dev, devlen)); ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); fn = jffs2_write_dnode(c, f, ri, (char *)&dev, devlen, ALLOC_NORMAL); jffs2_free_raw_inode(ri); if (IS_ERR(fn)) { /* Eeek. Wave bye bye */ mutex_unlock(&f->sem); jffs2_complete_reservation(c); ret = PTR_ERR(fn); goto fail; } /* No data here. Only a metadata node, which will be obsoleted by the first data write */ f->metadata = fn; mutex_unlock(&f->sem); jffs2_complete_reservation(c); ret = jffs2_init_security(inode, dir_i, &dentry->d_name); if (ret) goto fail; ret = jffs2_init_acl_post(inode); if (ret) goto fail; ret = jffs2_reserve_space(c, sizeof(*rd)+namelen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_DIRENT_SIZE(namelen)); if (ret) goto fail; rd = jffs2_alloc_raw_dirent(); if (!rd) { /* Argh. Now we treat it like a normal delete */ jffs2_complete_reservation(c); ret = -ENOMEM; goto fail; } dir_f = JFFS2_INODE_INFO(dir_i); mutex_lock(&dir_f->sem); rd->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); rd->nodetype = cpu_to_je16(JFFS2_NODETYPE_DIRENT); rd->totlen = cpu_to_je32(sizeof(*rd) + namelen); rd->hdr_crc = cpu_to_je32(crc32(0, rd, sizeof(struct jffs2_unknown_node)-4)); rd->pino = cpu_to_je32(dir_i->i_ino); rd->version = cpu_to_je32(++dir_f->highest_version); rd->ino = cpu_to_je32(inode->i_ino); rd->mctime = cpu_to_je32(get_seconds()); rd->nsize = namelen; /* XXX: This is ugly. */ rd->type = (mode & S_IFMT) >> 12; rd->node_crc = cpu_to_je32(crc32(0, rd, sizeof(*rd)-8)); rd->name_crc = cpu_to_je32(crc32(0, dentry->d_name.name, namelen)); fd = jffs2_write_dirent(c, dir_f, rd, dentry->d_name.name, namelen, ALLOC_NORMAL); if (IS_ERR(fd)) { /* dirent failed to write. Delete the inode normally as if it were the final unlink() */ jffs2_complete_reservation(c); jffs2_free_raw_dirent(rd); mutex_unlock(&dir_f->sem); ret = PTR_ERR(fd); goto fail; } dir_i->i_mtime = dir_i->i_ctime = ITIME(je32_to_cpu(rd->mctime)); jffs2_free_raw_dirent(rd); /* Link the fd into the inode's list, obsoleting an old one if necessary. */ jffs2_add_fd_to_list(c, fd, &dir_f->dents); mutex_unlock(&dir_f->sem); jffs2_complete_reservation(c); d_instantiate(dentry, inode); unlock_new_inode(inode); return 0; fail: iget_failed(inode); return ret; } static int jffs2_rename (struct inode *old_dir_i, struct dentry *old_dentry, struct inode *new_dir_i, struct dentry *new_dentry) { int ret; struct jffs2_sb_info *c = JFFS2_SB_INFO(old_dir_i->i_sb); struct jffs2_inode_info *victim_f = NULL; uint8_t type; uint32_t now; /* The VFS will check for us and prevent trying to rename a * file over a directory and vice versa, but if it's a directory, * the VFS can't check whether the victim is empty. The filesystem * needs to do that for itself. */ if (new_dentry->d_inode) { victim_f = JFFS2_INODE_INFO(new_dentry->d_inode); if (S_ISDIR(new_dentry->d_inode->i_mode)) { struct jffs2_full_dirent *fd; mutex_lock(&victim_f->sem); for (fd = victim_f->dents; fd; fd = fd->next) { if (fd->ino) { mutex_unlock(&victim_f->sem); return -ENOTEMPTY; } } mutex_unlock(&victim_f->sem); } } /* XXX: We probably ought to alloc enough space for both nodes at the same time. Writing the new link, then getting -ENOSPC, is quite bad :) */ /* Make a hard link */ /* XXX: This is ugly */ type = (old_dentry->d_inode->i_mode & S_IFMT) >> 12; if (!type) type = DT_REG; now = get_seconds(); ret = jffs2_do_link(c, JFFS2_INODE_INFO(new_dir_i), old_dentry->d_inode->i_ino, type, new_dentry->d_name.name, new_dentry->d_name.len, now); if (ret) return ret; if (victim_f) { /* There was a victim. Kill it off nicely */ drop_nlink(new_dentry->d_inode); /* Don't oops if the victim was a dirent pointing to an inode which didn't exist. */ if (victim_f->inocache) { mutex_lock(&victim_f->sem); if (S_ISDIR(new_dentry->d_inode->i_mode)) victim_f->inocache->pino_nlink = 0; else victim_f->inocache->pino_nlink--; mutex_unlock(&victim_f->sem); } } /* If it was a directory we moved, and there was no victim, increase i_nlink on its new parent */ if (S_ISDIR(old_dentry->d_inode->i_mode) && !victim_f) inc_nlink(new_dir_i); /* Unlink the original */ ret = jffs2_do_unlink(c, JFFS2_INODE_INFO(old_dir_i), old_dentry->d_name.name, old_dentry->d_name.len, NULL, now); /* We don't touch inode->i_nlink */ if (ret) { /* Oh shit. We really ought to make a single node which can do both atomically */ struct jffs2_inode_info *f = JFFS2_INODE_INFO(old_dentry->d_inode); mutex_lock(&f->sem); inc_nlink(old_dentry->d_inode); if (f->inocache && !S_ISDIR(old_dentry->d_inode->i_mode)) f->inocache->pino_nlink++; mutex_unlock(&f->sem); printk(KERN_NOTICE "jffs2_rename(): Link succeeded, unlink failed (err %d). You now have a hard link\n", ret); /* Might as well let the VFS know */ d_instantiate(new_dentry, old_dentry->d_inode); ihold(old_dentry->d_inode); new_dir_i->i_mtime = new_dir_i->i_ctime = ITIME(now); return ret; } if (S_ISDIR(old_dentry->d_inode->i_mode)) drop_nlink(old_dir_i); new_dir_i->i_mtime = new_dir_i->i_ctime = old_dir_i->i_mtime = old_dir_i->i_ctime = ITIME(now); return 0; }
gpl-2.0
tako0910/android_kernel_htc_valentewx
arch/microblaze/kernel/cpu/pvr.c
3108
1936
/* * Support for MicroBlaze PVR (processor version register) * * Copyright (C) 2007-2009 Michal Simek <monstr@monstr.eu> * Copyright (C) 2007-2009 PetaLogix * Copyright (C) 2007 John Williams <john.williams@petalogix.com> * * 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/kernel.h> #include <linux/compiler.h> #include <asm/system.h> #include <asm/exceptions.h> #include <asm/pvr.h> /* * Until we get an assembler that knows about the pvr registers, * this horrible cruft will have to do. * That hardcoded opcode is mfs r3, rpvrNN */ #define get_single_pvr(pvrid, val) \ { \ register unsigned tmp __asm__("r3"); \ tmp = 0x0; /* Prevent warning about unused */ \ __asm__ __volatile__ ( \ "mfs %0, rpvr" #pvrid ";" \ : "=r" (tmp) : : "memory"); \ val = tmp; \ } /* * Does the CPU support the PVR register? * return value: * 0: no PVR * 1: simple PVR * 2: full PVR * * This must work on all CPU versions, including those before the * PVR was even an option. */ int cpu_has_pvr(void) { unsigned long flags; unsigned pvr0; local_save_flags(flags); /* PVR bit in MSR tells us if there is any support */ if (!(flags & PVR_MSR_BIT)) return 0; get_single_pvr(0, pvr0); pr_debug("%s: pvr0 is 0x%08x\n", __func__, pvr0); if (pvr0 & PVR0_PVR_FULL_MASK) return 1; /* for partial PVR use static cpuinfo */ return 2; } void get_pvr(struct pvr_s *p) { get_single_pvr(0, p->pvr[0]); get_single_pvr(1, p->pvr[1]); get_single_pvr(2, p->pvr[2]); get_single_pvr(3, p->pvr[3]); get_single_pvr(4, p->pvr[4]); get_single_pvr(5, p->pvr[5]); get_single_pvr(6, p->pvr[6]); get_single_pvr(7, p->pvr[7]); get_single_pvr(8, p->pvr[8]); get_single_pvr(9, p->pvr[9]); get_single_pvr(10, p->pvr[10]); get_single_pvr(11, p->pvr[11]); }
gpl-2.0
NoelMacwan/SXDNickiUnified
sound/soc/s6000/s6000-pcm.c
4132
14093
/* * ALSA PCM interface for the Stetch s6000 family * * Author: Daniel Gloeckner, <dg@emlix.com> * Copyright: (C) 2009 emlix GmbH <info@emlix.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/init.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/dma-mapping.h> #include <linux/interrupt.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <asm/dma.h> #include <variant/dmac.h> #include "s6000-pcm.h" #define S6_PCM_PREALLOCATE_SIZE (96 * 1024) #define S6_PCM_PREALLOCATE_MAX (2048 * 1024) static struct snd_pcm_hardware s6000_pcm_hardware = { .info = (SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_JOINT_DUPLEX), .formats = (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE), .rates = (SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_5512 | \ SNDRV_PCM_RATE_8000_192000), .rate_min = 0, .rate_max = 1562500, .channels_min = 2, .channels_max = 8, .buffer_bytes_max = 0x7ffffff0, .period_bytes_min = 16, .period_bytes_max = 0xfffff0, .periods_min = 2, .periods_max = 1024, /* no limit */ .fifo_size = 0, }; struct s6000_runtime_data { spinlock_t lock; int period; /* current DMA period */ }; static void s6000_pcm_enqueue_dma(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct s6000_runtime_data *prtd = runtime->private_data; struct snd_soc_pcm_runtime *soc_runtime = substream->private_data; struct s6000_pcm_dma_params *par; int channel; unsigned int period_size; unsigned int dma_offset; dma_addr_t dma_pos; dma_addr_t src, dst; par = snd_soc_dai_get_dma_data(soc_runtime->cpu_dai, substream); period_size = snd_pcm_lib_period_bytes(substream); dma_offset = prtd->period * period_size; dma_pos = runtime->dma_addr + dma_offset; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { src = dma_pos; dst = par->sif_out; channel = par->dma_out; } else { src = par->sif_in; dst = dma_pos; channel = par->dma_in; } if (!s6dmac_channel_enabled(DMA_MASK_DMAC(channel), DMA_INDEX_CHNL(channel))) return; if (s6dmac_fifo_full(DMA_MASK_DMAC(channel), DMA_INDEX_CHNL(channel))) { printk(KERN_ERR "s6000-pcm: fifo full\n"); return; } BUG_ON(period_size & 15); s6dmac_put_fifo(DMA_MASK_DMAC(channel), DMA_INDEX_CHNL(channel), src, dst, period_size); prtd->period++; if (unlikely(prtd->period >= runtime->periods)) prtd->period = 0; } static irqreturn_t s6000_pcm_irq(int irq, void *data) { struct snd_pcm *pcm = data; struct snd_soc_pcm_runtime *runtime = pcm->private_data; struct s6000_runtime_data *prtd; unsigned int has_xrun; int i, ret = IRQ_NONE; for (i = 0; i < 2; ++i) { struct snd_pcm_substream *substream = pcm->streams[i].substream; struct s6000_pcm_dma_params *params = snd_soc_dai_get_dma_data(runtime->cpu_dai, substream); u32 channel; unsigned int pending; if (substream == SNDRV_PCM_STREAM_PLAYBACK) channel = params->dma_out; else channel = params->dma_in; has_xrun = params->check_xrun(runtime->cpu_dai); if (!channel) continue; if (unlikely(has_xrun & (1 << i)) && substream->runtime && snd_pcm_running(substream)) { dev_dbg(pcm->dev, "xrun\n"); snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN); ret = IRQ_HANDLED; } pending = s6dmac_int_sources(DMA_MASK_DMAC(channel), DMA_INDEX_CHNL(channel)); if (pending & 1) { ret = IRQ_HANDLED; if (likely(substream->runtime && snd_pcm_running(substream))) { snd_pcm_period_elapsed(substream); dev_dbg(pcm->dev, "period elapsed %x %x\n", s6dmac_cur_src(DMA_MASK_DMAC(channel), DMA_INDEX_CHNL(channel)), s6dmac_cur_dst(DMA_MASK_DMAC(channel), DMA_INDEX_CHNL(channel))); prtd = substream->runtime->private_data; spin_lock(&prtd->lock); s6000_pcm_enqueue_dma(substream); spin_unlock(&prtd->lock); } } if (unlikely(pending & ~7)) { if (pending & (1 << 3)) printk(KERN_WARNING "s6000-pcm: DMA %x Underflow\n", channel); if (pending & (1 << 4)) printk(KERN_WARNING "s6000-pcm: DMA %x Overflow\n", channel); if (pending & 0x1e0) printk(KERN_WARNING "s6000-pcm: DMA %x Master Error " "(mask %x)\n", channel, pending >> 5); } } return ret; } static int s6000_pcm_start(struct snd_pcm_substream *substream) { struct s6000_runtime_data *prtd = substream->runtime->private_data; struct snd_soc_pcm_runtime *soc_runtime = substream->private_data; struct s6000_pcm_dma_params *par; unsigned long flags; int srcinc; u32 dma; par = snd_soc_dai_get_dma_data(soc_runtime->cpu_dai, substream); spin_lock_irqsave(&prtd->lock, flags); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { srcinc = 1; dma = par->dma_out; } else { srcinc = 0; dma = par->dma_in; } s6dmac_enable_chan(DMA_MASK_DMAC(dma), DMA_INDEX_CHNL(dma), 1 /* priority 1 (0 is max) */, 0 /* peripheral requests w/o xfer length mode */, srcinc /* source address increment */, srcinc^1 /* destination address increment */, 0 /* chunksize 0 (skip impossible on this dma) */, 0 /* source skip after chunk (impossible) */, 0 /* destination skip after chunk (impossible) */, 4 /* 16 byte burst size */, -1 /* don't conserve bandwidth */, 0 /* low watermark irq descriptor threshold */, 0 /* disable hardware timestamps */, 1 /* enable channel */); s6000_pcm_enqueue_dma(substream); s6000_pcm_enqueue_dma(substream); spin_unlock_irqrestore(&prtd->lock, flags); return 0; } static int s6000_pcm_stop(struct snd_pcm_substream *substream) { struct s6000_runtime_data *prtd = substream->runtime->private_data; struct snd_soc_pcm_runtime *soc_runtime = substream->private_data; struct s6000_pcm_dma_params *par; unsigned long flags; u32 channel; par = snd_soc_dai_get_dma_data(soc_runtime->cpu_dai, substream); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) channel = par->dma_out; else channel = par->dma_in; s6dmac_set_terminal_count(DMA_MASK_DMAC(channel), DMA_INDEX_CHNL(channel), 0); spin_lock_irqsave(&prtd->lock, flags); s6dmac_disable_chan(DMA_MASK_DMAC(channel), DMA_INDEX_CHNL(channel)); spin_unlock_irqrestore(&prtd->lock, flags); return 0; } static int s6000_pcm_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_soc_pcm_runtime *soc_runtime = substream->private_data; struct s6000_pcm_dma_params *par; int ret; par = snd_soc_dai_get_dma_data(soc_runtime->cpu_dai, substream); ret = par->trigger(substream, cmd, 0); if (ret < 0) return ret; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: ret = s6000_pcm_start(substream); break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: ret = s6000_pcm_stop(substream); break; default: ret = -EINVAL; } if (ret < 0) return ret; return par->trigger(substream, cmd, 1); } static int s6000_pcm_prepare(struct snd_pcm_substream *substream) { struct s6000_runtime_data *prtd = substream->runtime->private_data; prtd->period = 0; return 0; } static snd_pcm_uframes_t s6000_pcm_pointer(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *soc_runtime = substream->private_data; struct s6000_pcm_dma_params *par; struct snd_pcm_runtime *runtime = substream->runtime; struct s6000_runtime_data *prtd = runtime->private_data; unsigned long flags; unsigned int offset; dma_addr_t count; par = snd_soc_dai_get_dma_data(soc_runtime->cpu_dai, substream); spin_lock_irqsave(&prtd->lock, flags); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) count = s6dmac_cur_src(DMA_MASK_DMAC(par->dma_out), DMA_INDEX_CHNL(par->dma_out)); else count = s6dmac_cur_dst(DMA_MASK_DMAC(par->dma_in), DMA_INDEX_CHNL(par->dma_in)); count -= runtime->dma_addr; spin_unlock_irqrestore(&prtd->lock, flags); offset = bytes_to_frames(runtime, count); if (unlikely(offset >= runtime->buffer_size)) offset = 0; return offset; } static int s6000_pcm_open(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *soc_runtime = substream->private_data; struct s6000_pcm_dma_params *par; struct snd_pcm_runtime *runtime = substream->runtime; struct s6000_runtime_data *prtd; int ret; par = snd_soc_dai_get_dma_data(soc_runtime->cpu_dai, substream); snd_soc_set_runtime_hwparams(substream, &s6000_pcm_hardware); ret = snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, 16); if (ret < 0) return ret; ret = snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 16); if (ret < 0) return ret; ret = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); if (ret < 0) return ret; if (par->same_rate) { int rate; spin_lock(&par->lock); /* needed? */ rate = par->rate; spin_unlock(&par->lock); if (rate != -1) { ret = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_RATE, rate, rate); if (ret < 0) return ret; } } prtd = kzalloc(sizeof(struct s6000_runtime_data), GFP_KERNEL); if (prtd == NULL) return -ENOMEM; spin_lock_init(&prtd->lock); runtime->private_data = prtd; return 0; } static int s6000_pcm_close(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct s6000_runtime_data *prtd = runtime->private_data; kfree(prtd); return 0; } static int s6000_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { struct snd_soc_pcm_runtime *soc_runtime = substream->private_data; struct s6000_pcm_dma_params *par; int ret; ret = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); if (ret < 0) { printk(KERN_WARNING "s6000-pcm: allocation of memory failed\n"); return ret; } par = snd_soc_dai_get_dma_data(soc_runtime->cpu_dai, substream); if (par->same_rate) { spin_lock(&par->lock); if (par->rate == -1 || !(par->in_use & ~(1 << substream->stream))) { par->rate = params_rate(hw_params); par->in_use |= 1 << substream->stream; } else if (params_rate(hw_params) != par->rate) { snd_pcm_lib_free_pages(substream); par->in_use &= ~(1 << substream->stream); ret = -EBUSY; } spin_unlock(&par->lock); } return ret; } static int s6000_pcm_hw_free(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *soc_runtime = substream->private_data; struct s6000_pcm_dma_params *par = snd_soc_dai_get_dma_data(soc_runtime->cpu_dai, substream); spin_lock(&par->lock); par->in_use &= ~(1 << substream->stream); if (!par->in_use) par->rate = -1; spin_unlock(&par->lock); return snd_pcm_lib_free_pages(substream); } static struct snd_pcm_ops s6000_pcm_ops = { .open = s6000_pcm_open, .close = s6000_pcm_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = s6000_pcm_hw_params, .hw_free = s6000_pcm_hw_free, .trigger = s6000_pcm_trigger, .prepare = s6000_pcm_prepare, .pointer = s6000_pcm_pointer, }; static void s6000_pcm_free(struct snd_pcm *pcm) { struct snd_soc_pcm_runtime *runtime = pcm->private_data; struct s6000_pcm_dma_params *params = snd_soc_dai_get_dma_data(runtime->cpu_dai, pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream); free_irq(params->irq, pcm); snd_pcm_lib_preallocate_free_for_all(pcm); } static u64 s6000_pcm_dmamask = DMA_BIT_MASK(32); static int s6000_pcm_new(struct snd_soc_pcm_runtime *runtime) { struct snd_card *card = runtime->card->snd_card; struct snd_pcm *pcm = runtime->pcm; struct s6000_pcm_dma_params *params; int res; params = snd_soc_dai_get_dma_data(runtime->cpu_dai, pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream); if (!card->dev->dma_mask) card->dev->dma_mask = &s6000_pcm_dmamask; if (!card->dev->coherent_dma_mask) card->dev->coherent_dma_mask = DMA_BIT_MASK(32); if (params->dma_in) { s6dmac_disable_chan(DMA_MASK_DMAC(params->dma_in), DMA_INDEX_CHNL(params->dma_in)); s6dmac_int_sources(DMA_MASK_DMAC(params->dma_in), DMA_INDEX_CHNL(params->dma_in)); } if (params->dma_out) { s6dmac_disable_chan(DMA_MASK_DMAC(params->dma_out), DMA_INDEX_CHNL(params->dma_out)); s6dmac_int_sources(DMA_MASK_DMAC(params->dma_out), DMA_INDEX_CHNL(params->dma_out)); } res = request_irq(params->irq, s6000_pcm_irq, IRQF_SHARED, "s6000-audio", pcm); if (res) { printk(KERN_ERR "s6000-pcm couldn't get IRQ\n"); return res; } res = snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, card->dev, S6_PCM_PREALLOCATE_SIZE, S6_PCM_PREALLOCATE_MAX); if (res) printk(KERN_WARNING "s6000-pcm: preallocation failed\n"); spin_lock_init(&params->lock); params->in_use = 0; params->rate = -1; return 0; } static struct snd_soc_platform_driver s6000_soc_platform = { .ops = &s6000_pcm_ops, .pcm_new = s6000_pcm_new, .pcm_free = s6000_pcm_free, }; static int __devinit s6000_soc_platform_probe(struct platform_device *pdev) { return snd_soc_register_platform(&pdev->dev, &s6000_soc_platform); } static int __devexit s6000_soc_platform_remove(struct platform_device *pdev) { snd_soc_unregister_platform(&pdev->dev); return 0; } static struct platform_driver s6000_pcm_driver = { .driver = { .name = "s6000-pcm-audio", .owner = THIS_MODULE, }, .probe = s6000_soc_platform_probe, .remove = __devexit_p(s6000_soc_platform_remove), }; module_platform_driver(s6000_pcm_driver); MODULE_AUTHOR("Daniel Gloeckner"); MODULE_DESCRIPTION("Stretch s6000 family PCM DMA module"); MODULE_LICENSE("GPL");
gpl-2.0
skipisz/linux
lib/string_helpers.c
4388
1702
/* * Helpers for formatting and printing strings * * Copyright 31 August 2008 James Bottomley */ #include <linux/kernel.h> #include <linux/math64.h> #include <linux/export.h> #include <linux/string_helpers.h> /** * string_get_size - get the size in the specified units * @size: The size to be converted * @units: units to use (powers of 1000 or 1024) * @buf: buffer to format to * @len: length of buffer * * This function returns a string formatted to 3 significant figures * giving the size in the required units. Returns 0 on success or * error on failure. @buf is always zero terminated. * */ int string_get_size(u64 size, const enum string_size_units units, char *buf, int len) { const char *units_10[] = { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", NULL}; const char *units_2[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", NULL }; const char **units_str[] = { [STRING_UNITS_10] = units_10, [STRING_UNITS_2] = units_2, }; const unsigned int divisor[] = { [STRING_UNITS_10] = 1000, [STRING_UNITS_2] = 1024, }; int i, j; u64 remainder = 0, sf_cap; char tmp[8]; tmp[0] = '\0'; i = 0; if (size >= divisor[units]) { while (size >= divisor[units] && units_str[units][i]) { remainder = do_div(size, divisor[units]); i++; } sf_cap = size; for (j = 0; sf_cap*10 < 1000; j++) sf_cap *= 10; if (j) { remainder *= 1000; do_div(remainder, divisor[units]); snprintf(tmp, sizeof(tmp), ".%03lld", (unsigned long long)remainder); tmp[j+1] = '\0'; } } snprintf(buf, len, "%lld%s %s", (unsigned long long)size, tmp, units_str[units][i]); return 0; } EXPORT_SYMBOL(string_get_size);
gpl-2.0
thanhphat11/android_kernel_pantech_910
sound/soc/codecs/ac97.c
4900
3738
/* * ac97.c -- ALSA Soc AC97 codec support * * Copyright 2005 Wolfson Microelectronics PLC. * Author: Liam Girdwood <lrg@slimlogic.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. * * Generic AC97 support. */ #include <linux/init.h> #include <linux/slab.h> #include <linux/kernel.h> #include <linux/device.h> #include <linux/module.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/ac97_codec.h> #include <sound/initval.h> #include <sound/soc.h> static int ac97_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_pcm_runtime *runtime = substream->runtime; struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; int reg = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ? AC97_PCM_FRONT_DAC_RATE : AC97_PCM_LR_ADC_RATE; return snd_ac97_set_rate(codec->ac97, reg, runtime->rate); } #define STD_AC97_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |\ SNDRV_PCM_RATE_22050 | SNDRV_PCM_RATE_44100 |\ SNDRV_PCM_RATE_48000) static const struct snd_soc_dai_ops ac97_dai_ops = { .prepare = ac97_prepare, }; static struct snd_soc_dai_driver ac97_dai = { .name = "ac97-hifi", .ac97_control = 1, .playback = { .stream_name = "AC97 Playback", .channels_min = 1, .channels_max = 2, .rates = STD_AC97_RATES, .formats = SND_SOC_STD_AC97_FMTS,}, .capture = { .stream_name = "AC97 Capture", .channels_min = 1, .channels_max = 2, .rates = STD_AC97_RATES, .formats = SND_SOC_STD_AC97_FMTS,}, .ops = &ac97_dai_ops, }; static unsigned int ac97_read(struct snd_soc_codec *codec, unsigned int reg) { return soc_ac97_ops.read(codec->ac97, reg); } static int ac97_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int val) { soc_ac97_ops.write(codec->ac97, reg, val); return 0; } static int ac97_soc_probe(struct snd_soc_codec *codec) { struct snd_ac97_bus *ac97_bus; struct snd_ac97_template ac97_template; int ret; /* add codec as bus device for standard ac97 */ ret = snd_ac97_bus(codec->card->snd_card, 0, &soc_ac97_ops, NULL, &ac97_bus); if (ret < 0) return ret; memset(&ac97_template, 0, sizeof(struct snd_ac97_template)); ret = snd_ac97_mixer(ac97_bus, &ac97_template, &codec->ac97); if (ret < 0) return ret; return 0; } static int ac97_soc_remove(struct snd_soc_codec *codec) { return 0; } #ifdef CONFIG_PM static int ac97_soc_suspend(struct snd_soc_codec *codec) { snd_ac97_suspend(codec->ac97); return 0; } static int ac97_soc_resume(struct snd_soc_codec *codec) { snd_ac97_resume(codec->ac97); return 0; } #else #define ac97_soc_suspend NULL #define ac97_soc_resume NULL #endif static struct snd_soc_codec_driver soc_codec_dev_ac97 = { .write = ac97_write, .read = ac97_read, .probe = ac97_soc_probe, .remove = ac97_soc_remove, .suspend = ac97_soc_suspend, .resume = ac97_soc_resume, }; static __devinit int ac97_probe(struct platform_device *pdev) { return snd_soc_register_codec(&pdev->dev, &soc_codec_dev_ac97, &ac97_dai, 1); } static int __devexit ac97_remove(struct platform_device *pdev) { snd_soc_unregister_codec(&pdev->dev); return 0; } static struct platform_driver ac97_codec_driver = { .driver = { .name = "ac97-codec", .owner = THIS_MODULE, }, .probe = ac97_probe, .remove = __devexit_p(ac97_remove), }; module_platform_driver(ac97_codec_driver); MODULE_DESCRIPTION("Soc Generic AC97 driver"); MODULE_AUTHOR("Liam Girdwood"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:ac97-codec");
gpl-2.0
Docker-J/Sail_GEE_L
drivers/media/video/gspca/sonixb.c
4900
46561
/* * sonix sn9c102 (bayer) library * * Copyright (C) 2009-2011 Jean-François Moine <http://moinejf.free.fr> * Copyright (C) 2003 2004 Michel Xhaard mxhaard@magic.fr * Add Pas106 Stefano Mozzi (C) 2004 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * 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 */ /* Some documentation on known sonixb registers: Reg Use sn9c101 / sn9c102: 0x10 high nibble red gain low nibble blue gain 0x11 low nibble green gain sn9c103: 0x05 red gain 0-127 0x06 blue gain 0-127 0x07 green gain 0-127 all: 0x08-0x0f i2c / 3wire registers 0x12 hstart 0x13 vstart 0x15 hsize (hsize = register-value * 16) 0x16 vsize (vsize = register-value * 16) 0x17 bit 0 toggle compression quality (according to sn9c102 driver) 0x18 bit 7 enables compression, bit 4-5 set image down scaling: 00 scale 1, 01 scale 1/2, 10, scale 1/4 0x19 high-nibble is sensor clock divider, changes exposure on sensors which use a clock generated by the bridge. Some sensors have their own clock. 0x1c auto_exposure area (for avg_lum) startx (startx = register-value * 32) 0x1d auto_exposure area (for avg_lum) starty (starty = register-value * 32) 0x1e auto_exposure area (for avg_lum) stopx (hsize = (0x1e - 0x1c) * 32) 0x1f auto_exposure area (for avg_lum) stopy (vsize = (0x1f - 0x1d) * 32) */ #define MODULE_NAME "sonixb" #include <linux/input.h> #include "gspca.h" MODULE_AUTHOR("Jean-François Moine <http://moinejf.free.fr>"); MODULE_DESCRIPTION("GSPCA/SN9C102 USB Camera Driver"); MODULE_LICENSE("GPL"); /* controls */ enum e_ctrl { BRIGHTNESS, GAIN, EXPOSURE, AUTOGAIN, FREQ, NCTRLS /* number of controls */ }; /* specific webcam descriptor */ struct sd { struct gspca_dev gspca_dev; /* !! must be the first item */ struct gspca_ctrl ctrls[NCTRLS]; atomic_t avg_lum; int prev_avg_lum; int exp_too_low_cnt; int exp_too_high_cnt; int header_read; u8 header[12]; /* Header without sof marker */ unsigned char autogain_ignore_frames; unsigned char frames_to_drop; __u8 bridge; /* Type of bridge */ #define BRIDGE_101 0 #define BRIDGE_102 0 /* We make no difference between 101 and 102 */ #define BRIDGE_103 1 __u8 sensor; /* Type of image sensor chip */ #define SENSOR_HV7131D 0 #define SENSOR_HV7131R 1 #define SENSOR_OV6650 2 #define SENSOR_OV7630 3 #define SENSOR_PAS106 4 #define SENSOR_PAS202 5 #define SENSOR_TAS5110C 6 #define SENSOR_TAS5110D 7 #define SENSOR_TAS5130CXX 8 __u8 reg11; }; typedef const __u8 sensor_init_t[8]; struct sensor_data { const __u8 *bridge_init; sensor_init_t *sensor_init; int sensor_init_size; int flags; unsigned ctrl_dis; __u8 sensor_addr; }; /* sensor_data flags */ #define F_GAIN 0x01 /* has gain */ #define F_SIF 0x02 /* sif or vga */ #define F_COARSE_EXPO 0x04 /* exposure control is coarse */ /* priv field of struct v4l2_pix_format flags (do not use low nibble!) */ #define MODE_RAW 0x10 /* raw bayer mode */ #define MODE_REDUCED_SIF 0x20 /* vga mode (320x240 / 160x120) on sif cam */ /* ctrl_dis helper macros */ #define NO_EXPO ((1 << EXPOSURE) | (1 << AUTOGAIN)) #define NO_FREQ (1 << FREQ) #define NO_BRIGHTNESS (1 << BRIGHTNESS) #define COMP 0xc7 /* 0x87 //0x07 */ #define COMP1 0xc9 /* 0x89 //0x09 */ #define MCK_INIT 0x63 #define MCK_INIT1 0x20 /*fixme: Bayer - 0x50 for JPEG ??*/ #define SYS_CLK 0x04 #define SENS(bridge, sensor, _flags, _ctrl_dis, _sensor_addr) \ { \ .bridge_init = bridge, \ .sensor_init = sensor, \ .sensor_init_size = sizeof(sensor), \ .flags = _flags, .ctrl_dis = _ctrl_dis, .sensor_addr = _sensor_addr \ } /* We calculate the autogain at the end of the transfer of a frame, at this moment a frame with the old settings is being captured and transmitted. So if we adjust the gain or exposure we must ignore atleast the next frame for the new settings to come into effect before doing any other adjustments. */ #define AUTOGAIN_IGNORE_FRAMES 1 /* V4L2 controls supported by the driver */ static void setbrightness(struct gspca_dev *gspca_dev); static void setgain(struct gspca_dev *gspca_dev); static void setexposure(struct gspca_dev *gspca_dev); static int sd_setautogain(struct gspca_dev *gspca_dev, __s32 val); static void setfreq(struct gspca_dev *gspca_dev); static const struct ctrl sd_ctrls[NCTRLS] = { [BRIGHTNESS] = { { .id = V4L2_CID_BRIGHTNESS, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Brightness", .minimum = 0, .maximum = 255, .step = 1, .default_value = 127, }, .set_control = setbrightness }, [GAIN] = { { .id = V4L2_CID_GAIN, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Gain", .minimum = 0, .maximum = 255, .step = 1, #define GAIN_KNEE 230 .default_value = 127, }, .set_control = setgain }, [EXPOSURE] = { { .id = V4L2_CID_EXPOSURE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Exposure", .minimum = 0, .maximum = 1023, .step = 1, .default_value = 66, /* 33 ms / 30 fps (except on PASXXX) */ #define EXPOSURE_KNEE 200 /* 100 ms / 10 fps (except on PASXXX) */ .flags = 0, }, .set_control = setexposure }, /* for coarse exposure */ #define COARSE_EXPOSURE_MIN 2 #define COARSE_EXPOSURE_MAX 15 #define COARSE_EXPOSURE_DEF 2 /* 30 fps */ [AUTOGAIN] = { { .id = V4L2_CID_AUTOGAIN, .type = V4L2_CTRL_TYPE_BOOLEAN, .name = "Automatic Gain (and Exposure)", .minimum = 0, .maximum = 1, .step = 1, #define AUTOGAIN_DEF 1 .default_value = AUTOGAIN_DEF, .flags = V4L2_CTRL_FLAG_UPDATE }, .set = sd_setautogain, }, [FREQ] = { { .id = V4L2_CID_POWER_LINE_FREQUENCY, .type = V4L2_CTRL_TYPE_MENU, .name = "Light frequency filter", .minimum = 0, .maximum = 2, /* 0: 0, 1: 50Hz, 2:60Hz */ .step = 1, #define FREQ_DEF 0 .default_value = FREQ_DEF, }, .set_control = setfreq }, }; static const struct v4l2_pix_format vga_mode[] = { {160, 120, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE, .bytesperline = 160, .sizeimage = 160 * 120, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 2 | MODE_RAW}, {160, 120, V4L2_PIX_FMT_SN9C10X, V4L2_FIELD_NONE, .bytesperline = 160, .sizeimage = 160 * 120 * 5 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 2}, {320, 240, V4L2_PIX_FMT_SN9C10X, V4L2_FIELD_NONE, .bytesperline = 320, .sizeimage = 320 * 240 * 5 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 1}, {640, 480, V4L2_PIX_FMT_SN9C10X, V4L2_FIELD_NONE, .bytesperline = 640, .sizeimage = 640 * 480 * 5 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 0}, }; static const struct v4l2_pix_format sif_mode[] = { {160, 120, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE, .bytesperline = 160, .sizeimage = 160 * 120, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 1 | MODE_RAW | MODE_REDUCED_SIF}, {160, 120, V4L2_PIX_FMT_SN9C10X, V4L2_FIELD_NONE, .bytesperline = 160, .sizeimage = 160 * 120 * 5 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 1 | MODE_REDUCED_SIF}, {176, 144, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE, .bytesperline = 176, .sizeimage = 176 * 144, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 1 | MODE_RAW}, {176, 144, V4L2_PIX_FMT_SN9C10X, V4L2_FIELD_NONE, .bytesperline = 176, .sizeimage = 176 * 144 * 5 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 1}, {320, 240, V4L2_PIX_FMT_SN9C10X, V4L2_FIELD_NONE, .bytesperline = 320, .sizeimage = 320 * 240 * 5 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 0 | MODE_REDUCED_SIF}, {352, 288, V4L2_PIX_FMT_SN9C10X, V4L2_FIELD_NONE, .bytesperline = 352, .sizeimage = 352 * 288 * 5 / 4, .colorspace = V4L2_COLORSPACE_SRGB, .priv = 0}, }; static const __u8 initHv7131d[] = { 0x04, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x80, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x28, 0x1e, 0x60, 0x8e, 0x42, }; static const __u8 hv7131d_sensor_init[][8] = { {0xa0, 0x11, 0x01, 0x04, 0x00, 0x00, 0x00, 0x17}, {0xa0, 0x11, 0x02, 0x00, 0x00, 0x00, 0x00, 0x17}, {0xa0, 0x11, 0x28, 0x00, 0x00, 0x00, 0x00, 0x17}, {0xa0, 0x11, 0x30, 0x30, 0x00, 0x00, 0x00, 0x17}, /* reset level */ {0xa0, 0x11, 0x34, 0x02, 0x00, 0x00, 0x00, 0x17}, /* pixel bias volt */ }; static const __u8 initHv7131r[] = { 0x46, 0x77, 0x00, 0x04, 0x00, 0x00, 0x00, 0x80, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x00, 0x28, 0x1e, 0x60, 0x8a, 0x20, }; static const __u8 hv7131r_sensor_init[][8] = { {0xc0, 0x11, 0x31, 0x38, 0x2a, 0x2e, 0x00, 0x10}, {0xa0, 0x11, 0x01, 0x08, 0x2a, 0x2e, 0x00, 0x10}, {0xb0, 0x11, 0x20, 0x00, 0xd0, 0x2e, 0x00, 0x10}, {0xc0, 0x11, 0x25, 0x03, 0x0e, 0x28, 0x00, 0x16}, {0xa0, 0x11, 0x30, 0x10, 0x0e, 0x28, 0x00, 0x15}, }; static const __u8 initOv6650[] = { 0x44, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x0a, 0x16, 0x12, 0x68, 0x8b, 0x10, }; static const __u8 ov6650_sensor_init[][8] = { /* Bright, contrast, etc are set through SCBB interface. * AVCAP on win2 do not send any data on this controls. */ /* Anyway, some registers appears to alter bright and constrat */ /* Reset sensor */ {0xa0, 0x60, 0x12, 0x80, 0x00, 0x00, 0x00, 0x10}, /* Set clock register 0x11 low nibble is clock divider */ {0xd0, 0x60, 0x11, 0xc0, 0x1b, 0x18, 0xc1, 0x10}, /* Next some unknown stuff */ {0xb0, 0x60, 0x15, 0x00, 0x02, 0x18, 0xc1, 0x10}, /* {0xa0, 0x60, 0x1b, 0x01, 0x02, 0x18, 0xc1, 0x10}, * THIS SET GREEN SCREEN * (pixels could be innverted in decode kind of "brg", * but blue wont be there. Avoid this data ... */ {0xd0, 0x60, 0x26, 0x01, 0x14, 0xd8, 0xa4, 0x10}, /* format out? */ {0xd0, 0x60, 0x26, 0x01, 0x14, 0xd8, 0xa4, 0x10}, {0xa0, 0x60, 0x30, 0x3d, 0x0a, 0xd8, 0xa4, 0x10}, /* Enable rgb brightness control */ {0xa0, 0x60, 0x61, 0x08, 0x00, 0x00, 0x00, 0x10}, /* HDG: Note windows uses the line below, which sets both register 0x60 and 0x61 I believe these registers of the ov6650 are identical as those of the ov7630, because if this is true the windows settings add a bit additional red gain and a lot additional blue gain, which matches my findings that the windows settings make blue much too blue and red a little too red. {0xb0, 0x60, 0x60, 0x66, 0x68, 0xd8, 0xa4, 0x10}, */ /* Some more unknown stuff */ {0xa0, 0x60, 0x68, 0x04, 0x68, 0xd8, 0xa4, 0x10}, {0xd0, 0x60, 0x17, 0x24, 0xd6, 0x04, 0x94, 0x10}, /* Clipreg */ }; static const __u8 initOv7630[] = { 0x04, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, /* r01 .. r08 */ 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* r09 .. r10 */ 0x00, 0x01, 0x01, 0x0a, /* r11 .. r14 */ 0x28, 0x1e, /* H & V sizes r15 .. r16 */ 0x68, 0x8f, MCK_INIT1, /* r17 .. r19 */ }; static const __u8 ov7630_sensor_init[][8] = { {0xa0, 0x21, 0x12, 0x80, 0x00, 0x00, 0x00, 0x10}, {0xb0, 0x21, 0x01, 0x77, 0x3a, 0x00, 0x00, 0x10}, /* {0xd0, 0x21, 0x12, 0x7c, 0x01, 0x80, 0x34, 0x10}, jfm */ {0xd0, 0x21, 0x12, 0x5c, 0x00, 0x80, 0x34, 0x10}, /* jfm */ {0xa0, 0x21, 0x1b, 0x04, 0x00, 0x80, 0x34, 0x10}, {0xa0, 0x21, 0x20, 0x44, 0x00, 0x80, 0x34, 0x10}, {0xa0, 0x21, 0x23, 0xee, 0x00, 0x80, 0x34, 0x10}, {0xd0, 0x21, 0x26, 0xa0, 0x9a, 0xa0, 0x30, 0x10}, {0xb0, 0x21, 0x2a, 0x80, 0x00, 0xa0, 0x30, 0x10}, {0xb0, 0x21, 0x2f, 0x3d, 0x24, 0xa0, 0x30, 0x10}, {0xa0, 0x21, 0x32, 0x86, 0x24, 0xa0, 0x30, 0x10}, {0xb0, 0x21, 0x60, 0xa9, 0x4a, 0xa0, 0x30, 0x10}, /* {0xb0, 0x21, 0x60, 0xa9, 0x42, 0xa0, 0x30, 0x10}, * jfm */ {0xa0, 0x21, 0x65, 0x00, 0x42, 0xa0, 0x30, 0x10}, {0xa0, 0x21, 0x69, 0x38, 0x42, 0xa0, 0x30, 0x10}, {0xc0, 0x21, 0x6f, 0x88, 0x0b, 0x00, 0x30, 0x10}, {0xc0, 0x21, 0x74, 0x21, 0x8e, 0x00, 0x30, 0x10}, {0xa0, 0x21, 0x7d, 0xf7, 0x8e, 0x00, 0x30, 0x10}, {0xd0, 0x21, 0x17, 0x1c, 0xbd, 0x06, 0xf6, 0x10}, }; static const __u8 initPas106[] = { 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x16, 0x12, 0x24, COMP1, MCK_INIT1, }; /* compression 0x86 mckinit1 0x2b */ /* "Known" PAS106B registers: 0x02 clock divider 0x03 Variable framerate bits 4-11 0x04 Var framerate bits 0-3, one must leave the 4 msb's at 0 !! The variable framerate control must never be set lower then 300, which sets the framerate at 90 / reg02, otherwise vsync is lost. 0x05 Shutter Time Line Offset, this can be used as an exposure control: 0 = use full frame time, 255 = no exposure at all Note this may never be larger then "var-framerate control" / 2 - 2. When var-framerate control is < 514, no exposure is reached at the max allowed value for the framerate control value, rather then at 255. 0x06 Shutter Time Pixel Offset, like reg05 this influences exposure, but only a very little bit, leave at 0xcd 0x07 offset sign bit (bit0 1 > negative offset) 0x08 offset 0x09 Blue Gain 0x0a Green1 Gain 0x0b Green2 Gain 0x0c Red Gain 0x0e Global gain 0x13 Write 1 to commit settings to sensor */ static const __u8 pas106_sensor_init[][8] = { /* Pixel Clock Divider 6 */ { 0xa1, 0x40, 0x02, 0x04, 0x00, 0x00, 0x00, 0x14 }, /* Frame Time MSB (also seen as 0x12) */ { 0xa1, 0x40, 0x03, 0x13, 0x00, 0x00, 0x00, 0x14 }, /* Frame Time LSB (also seen as 0x05) */ { 0xa1, 0x40, 0x04, 0x06, 0x00, 0x00, 0x00, 0x14 }, /* Shutter Time Line Offset (also seen as 0x6d) */ { 0xa1, 0x40, 0x05, 0x65, 0x00, 0x00, 0x00, 0x14 }, /* Shutter Time Pixel Offset (also seen as 0xb1) */ { 0xa1, 0x40, 0x06, 0xcd, 0x00, 0x00, 0x00, 0x14 }, /* Black Level Subtract Sign (also seen 0x00) */ { 0xa1, 0x40, 0x07, 0xc1, 0x00, 0x00, 0x00, 0x14 }, /* Black Level Subtract Level (also seen 0x01) */ { 0xa1, 0x40, 0x08, 0x06, 0x00, 0x00, 0x00, 0x14 }, { 0xa1, 0x40, 0x08, 0x06, 0x00, 0x00, 0x00, 0x14 }, /* Color Gain B Pixel 5 a */ { 0xa1, 0x40, 0x09, 0x05, 0x00, 0x00, 0x00, 0x14 }, /* Color Gain G1 Pixel 1 5 */ { 0xa1, 0x40, 0x0a, 0x04, 0x00, 0x00, 0x00, 0x14 }, /* Color Gain G2 Pixel 1 0 5 */ { 0xa1, 0x40, 0x0b, 0x04, 0x00, 0x00, 0x00, 0x14 }, /* Color Gain R Pixel 3 1 */ { 0xa1, 0x40, 0x0c, 0x05, 0x00, 0x00, 0x00, 0x14 }, /* Color GainH Pixel */ { 0xa1, 0x40, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x14 }, /* Global Gain */ { 0xa1, 0x40, 0x0e, 0x0e, 0x00, 0x00, 0x00, 0x14 }, /* Contrast */ { 0xa1, 0x40, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x14 }, /* H&V synchro polarity */ { 0xa1, 0x40, 0x10, 0x06, 0x00, 0x00, 0x00, 0x14 }, /* ?default */ { 0xa1, 0x40, 0x11, 0x06, 0x00, 0x00, 0x00, 0x14 }, /* DAC scale */ { 0xa1, 0x40, 0x12, 0x06, 0x00, 0x00, 0x00, 0x14 }, /* ?default */ { 0xa1, 0x40, 0x14, 0x02, 0x00, 0x00, 0x00, 0x14 }, /* Validate Settings */ { 0xa1, 0x40, 0x13, 0x01, 0x00, 0x00, 0x00, 0x14 }, }; static const __u8 initPas202[] = { 0x44, 0x44, 0x21, 0x30, 0x00, 0x00, 0x00, 0x80, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x03, 0x0a, 0x28, 0x1e, 0x20, 0x89, 0x20, }; /* "Known" PAS202BCB registers: 0x02 clock divider 0x04 Variable framerate bits 6-11 (*) 0x05 Var framerate bits 0-5, one must leave the 2 msb's at 0 !! 0x07 Blue Gain 0x08 Green Gain 0x09 Red Gain 0x0b offset sign bit (bit0 1 > negative offset) 0x0c offset 0x0e Unknown image is slightly brighter when bit 0 is 0, if reg0f is 0 too, leave at 1 otherwise we get a jump in our exposure control 0x0f Exposure 0-255, 0 = use full frame time, 255 = no exposure at all 0x10 Master gain 0 - 31 0x11 write 1 to apply changes (*) The variable framerate control must never be set lower then 500 which sets the framerate at 30 / reg02, otherwise vsync is lost. */ static const __u8 pas202_sensor_init[][8] = { /* Set the clock divider to 4 -> 30 / 4 = 7.5 fps, we would like to set it lower, but for some reason the bridge starts missing vsync's then */ {0xa0, 0x40, 0x02, 0x04, 0x00, 0x00, 0x00, 0x10}, {0xd0, 0x40, 0x04, 0x07, 0x34, 0x00, 0x09, 0x10}, {0xd0, 0x40, 0x08, 0x01, 0x00, 0x00, 0x01, 0x10}, {0xd0, 0x40, 0x0c, 0x00, 0x0c, 0x01, 0x32, 0x10}, {0xd0, 0x40, 0x10, 0x00, 0x01, 0x00, 0x63, 0x10}, {0xa0, 0x40, 0x15, 0x70, 0x01, 0x00, 0x63, 0x10}, {0xa0, 0x40, 0x18, 0x00, 0x01, 0x00, 0x63, 0x10}, {0xa0, 0x40, 0x11, 0x01, 0x01, 0x00, 0x63, 0x10}, {0xa0, 0x40, 0x03, 0x56, 0x01, 0x00, 0x63, 0x10}, {0xa0, 0x40, 0x11, 0x01, 0x01, 0x00, 0x63, 0x10}, }; static const __u8 initTas5110c[] = { 0x44, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x09, 0x0a, 0x16, 0x12, 0x60, 0x86, 0x2b, }; /* Same as above, except a different hstart */ static const __u8 initTas5110d[] = { 0x44, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x09, 0x0a, 0x16, 0x12, 0x60, 0x86, 0x2b, }; /* tas5110c is 3 wire, tas5110d is 2 wire (regular i2c) */ static const __u8 tas5110c_sensor_init[][8] = { {0x30, 0x11, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x10}, {0x30, 0x11, 0x02, 0x20, 0xa9, 0x00, 0x00, 0x10}, }; /* Known TAS5110D registers * reg02: gain, bit order reversed!! 0 == max gain, 255 == min gain * reg03: bit3: vflip, bit4: ~hflip, bit7: ~gainboost (~ == inverted) * Note: writing reg03 seems to only work when written together with 02 */ static const __u8 tas5110d_sensor_init[][8] = { {0xa0, 0x61, 0x9a, 0xca, 0x00, 0x00, 0x00, 0x17}, /* reset */ }; static const __u8 initTas5130[] = { 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x0c, 0x0a, 0x28, 0x1e, 0x60, COMP, MCK_INIT, }; static const __u8 tas5130_sensor_init[][8] = { /* {0x30, 0x11, 0x00, 0x40, 0x47, 0x00, 0x00, 0x10}, * shutter 0x47 short exposure? */ {0x30, 0x11, 0x00, 0x40, 0x01, 0x00, 0x00, 0x10}, /* shutter 0x01 long exposure */ {0x30, 0x11, 0x02, 0x20, 0x70, 0x00, 0x00, 0x10}, }; static const struct sensor_data sensor_data[] = { SENS(initHv7131d, hv7131d_sensor_init, F_GAIN, NO_BRIGHTNESS|NO_FREQ, 0), SENS(initHv7131r, hv7131r_sensor_init, 0, NO_BRIGHTNESS|NO_EXPO|NO_FREQ, 0), SENS(initOv6650, ov6650_sensor_init, F_GAIN|F_SIF, 0, 0x60), SENS(initOv7630, ov7630_sensor_init, F_GAIN, 0, 0x21), SENS(initPas106, pas106_sensor_init, F_GAIN|F_SIF, NO_FREQ, 0), SENS(initPas202, pas202_sensor_init, F_GAIN, NO_FREQ, 0), SENS(initTas5110c, tas5110c_sensor_init, F_GAIN|F_SIF|F_COARSE_EXPO, NO_BRIGHTNESS|NO_FREQ, 0), SENS(initTas5110d, tas5110d_sensor_init, F_GAIN|F_SIF|F_COARSE_EXPO, NO_BRIGHTNESS|NO_FREQ, 0), SENS(initTas5130, tas5130_sensor_init, F_GAIN, NO_BRIGHTNESS|NO_EXPO|NO_FREQ, 0), }; /* get one byte in gspca_dev->usb_buf */ static void reg_r(struct gspca_dev *gspca_dev, __u16 value) { usb_control_msg(gspca_dev->dev, usb_rcvctrlpipe(gspca_dev->dev, 0), 0, /* request */ USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE, value, 0, /* index */ gspca_dev->usb_buf, 1, 500); } static void reg_w(struct gspca_dev *gspca_dev, __u16 value, const __u8 *buffer, int len) { #ifdef GSPCA_DEBUG if (len > USB_BUF_SZ) { PDEBUG(D_ERR|D_PACK, "reg_w: buffer overflow"); return; } #endif memcpy(gspca_dev->usb_buf, buffer, len); usb_control_msg(gspca_dev->dev, usb_sndctrlpipe(gspca_dev->dev, 0), 0x08, /* request */ USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE, value, 0, /* index */ gspca_dev->usb_buf, len, 500); } static int i2c_w(struct gspca_dev *gspca_dev, const __u8 *buffer) { int retry = 60; /* is i2c ready */ reg_w(gspca_dev, 0x08, buffer, 8); while (retry--) { msleep(10); reg_r(gspca_dev, 0x08); if (gspca_dev->usb_buf[0] & 0x04) { if (gspca_dev->usb_buf[0] & 0x08) return -1; return 0; } } return -1; } static void i2c_w_vector(struct gspca_dev *gspca_dev, const __u8 buffer[][8], int len) { for (;;) { reg_w(gspca_dev, 0x08, *buffer, 8); len -= 8; if (len <= 0) break; buffer++; } } static void setbrightness(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; switch (sd->sensor) { case SENSOR_OV6650: case SENSOR_OV7630: { __u8 i2cOV[] = {0xa0, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x10}; /* change reg 0x06 */ i2cOV[1] = sensor_data[sd->sensor].sensor_addr; i2cOV[3] = sd->ctrls[BRIGHTNESS].val; if (i2c_w(gspca_dev, i2cOV) < 0) goto err; break; } case SENSOR_PAS106: case SENSOR_PAS202: { __u8 i2cpbright[] = {0xb0, 0x40, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x16}; __u8 i2cpdoit[] = {0xa0, 0x40, 0x11, 0x01, 0x00, 0x00, 0x00, 0x16}; /* PAS106 uses reg 7 and 8 instead of b and c */ if (sd->sensor == SENSOR_PAS106) { i2cpbright[2] = 7; i2cpdoit[2] = 0x13; } if (sd->ctrls[BRIGHTNESS].val < 127) { /* change reg 0x0b, signreg */ i2cpbright[3] = 0x01; /* set reg 0x0c, offset */ i2cpbright[4] = 127 - sd->ctrls[BRIGHTNESS].val; } else i2cpbright[4] = sd->ctrls[BRIGHTNESS].val - 127; if (i2c_w(gspca_dev, i2cpbright) < 0) goto err; if (i2c_w(gspca_dev, i2cpdoit) < 0) goto err; break; } } return; err: PDEBUG(D_ERR, "i2c error brightness"); } static void setsensorgain(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; u8 gain = sd->ctrls[GAIN].val; switch (sd->sensor) { case SENSOR_HV7131D: { __u8 i2c[] = {0xc0, 0x11, 0x31, 0x00, 0x00, 0x00, 0x00, 0x17}; i2c[3] = 0x3f - (gain / 4); i2c[4] = 0x3f - (gain / 4); i2c[5] = 0x3f - (gain / 4); if (i2c_w(gspca_dev, i2c) < 0) goto err; break; } case SENSOR_TAS5110C: case SENSOR_TAS5130CXX: { __u8 i2c[] = {0x30, 0x11, 0x02, 0x20, 0x70, 0x00, 0x00, 0x10}; i2c[4] = 255 - gain; if (i2c_w(gspca_dev, i2c) < 0) goto err; break; } case SENSOR_TAS5110D: { __u8 i2c[] = { 0xb0, 0x61, 0x02, 0x00, 0x10, 0x00, 0x00, 0x17 }; gain = 255 - gain; /* The bits in the register are the wrong way around!! */ i2c[3] |= (gain & 0x80) >> 7; i2c[3] |= (gain & 0x40) >> 5; i2c[3] |= (gain & 0x20) >> 3; i2c[3] |= (gain & 0x10) >> 1; i2c[3] |= (gain & 0x08) << 1; i2c[3] |= (gain & 0x04) << 3; i2c[3] |= (gain & 0x02) << 5; i2c[3] |= (gain & 0x01) << 7; if (i2c_w(gspca_dev, i2c) < 0) goto err; break; } case SENSOR_OV6650: gain >>= 1; /* fall thru */ case SENSOR_OV7630: { __u8 i2c[] = {0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10}; i2c[1] = sensor_data[sd->sensor].sensor_addr; i2c[3] = gain >> 2; if (i2c_w(gspca_dev, i2c) < 0) goto err; break; } case SENSOR_PAS106: case SENSOR_PAS202: { __u8 i2cpgain[] = {0xa0, 0x40, 0x10, 0x00, 0x00, 0x00, 0x00, 0x15}; __u8 i2cpcolorgain[] = {0xc0, 0x40, 0x07, 0x00, 0x00, 0x00, 0x00, 0x15}; __u8 i2cpdoit[] = {0xa0, 0x40, 0x11, 0x01, 0x00, 0x00, 0x00, 0x16}; /* PAS106 uses different regs (and has split green gains) */ if (sd->sensor == SENSOR_PAS106) { i2cpgain[2] = 0x0e; i2cpcolorgain[0] = 0xd0; i2cpcolorgain[2] = 0x09; i2cpdoit[2] = 0x13; } i2cpgain[3] = gain >> 3; i2cpcolorgain[3] = gain >> 4; i2cpcolorgain[4] = gain >> 4; i2cpcolorgain[5] = gain >> 4; i2cpcolorgain[6] = gain >> 4; if (i2c_w(gspca_dev, i2cpgain) < 0) goto err; if (i2c_w(gspca_dev, i2cpcolorgain) < 0) goto err; if (i2c_w(gspca_dev, i2cpdoit) < 0) goto err; break; } } return; err: PDEBUG(D_ERR, "i2c error gain"); } static void setgain(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; __u8 gain; __u8 buf[3] = { 0, 0, 0 }; if (sensor_data[sd->sensor].flags & F_GAIN) { /* Use the sensor gain to do the actual gain */ setsensorgain(gspca_dev); return; } if (sd->bridge == BRIDGE_103) { gain = sd->ctrls[GAIN].val >> 1; buf[0] = gain; /* Red */ buf[1] = gain; /* Green */ buf[2] = gain; /* Blue */ reg_w(gspca_dev, 0x05, buf, 3); } else { gain = sd->ctrls[GAIN].val >> 4; buf[0] = gain << 4 | gain; /* Red and blue */ buf[1] = gain; /* Green */ reg_w(gspca_dev, 0x10, buf, 2); } } static void setexposure(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; switch (sd->sensor) { case SENSOR_HV7131D: { /* Note the datasheet wrongly says line mode exposure uses reg 0x26 and 0x27, testing has shown 0x25 + 0x26 */ __u8 i2c[] = {0xc0, 0x11, 0x25, 0x00, 0x00, 0x00, 0x00, 0x17}; /* The HV7131D's exposure goes from 0 - 65535, we scale our exposure of 0-1023 to 0-6138. There are 2 reasons for this: 1) This puts our exposure knee of 200 at approx the point where the framerate starts dropping 2) At 6138 the framerate has already dropped to 2 fps, going any lower makes little sense */ u16 reg = sd->ctrls[EXPOSURE].val * 6; i2c[3] = reg >> 8; i2c[4] = reg & 0xff; if (i2c_w(gspca_dev, i2c) != 0) goto err; break; } case SENSOR_TAS5110C: case SENSOR_TAS5110D: { /* register 19's high nibble contains the sn9c10x clock divider The high nibble configures the no fps according to the formula: 60 / high_nibble. With a maximum of 30 fps */ u8 reg = sd->ctrls[EXPOSURE].val; reg = (reg << 4) | 0x0b; reg_w(gspca_dev, 0x19, &reg, 1); break; } case SENSOR_OV6650: case SENSOR_OV7630: { /* The ov6650 / ov7630 have 2 registers which both influence exposure, register 11, whose low nibble sets the nr off fps according to: fps = 30 / (low_nibble + 1) The fps configures the maximum exposure setting, but it is possible to use less exposure then what the fps maximum allows by setting register 10. register 10 configures the actual exposure as quotient of the full exposure, with 0 being no exposure at all (not very useful) and reg10_max being max exposure possible at that framerate. The code maps our 0 - 510 ms exposure ctrl to these 2 registers, trying to keep fps as high as possible. */ __u8 i2c[] = {0xb0, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x10}; int reg10, reg11, reg10_max; /* ov6645 datasheet says reg10_max is 9a, but that uses tline * 2 * reg10 as formula for calculating texpo, the ov6650 probably uses the same formula as the 7730 which uses tline * 4 * reg10, which explains why the reg10max we've found experimentally for the ov6650 is exactly half that of the ov6645. The ov7630 datasheet says the max is 0x41. */ if (sd->sensor == SENSOR_OV6650) { reg10_max = 0x4d; i2c[4] = 0xc0; /* OV6650 needs non default vsync pol */ } else reg10_max = 0x41; reg11 = (15 * sd->ctrls[EXPOSURE].val + 999) / 1000; if (reg11 < 1) reg11 = 1; else if (reg11 > 16) reg11 = 16; /* In 640x480, if the reg11 has less than 4, the image is unstable (the bridge goes into a higher compression mode which we have not reverse engineered yet). */ if (gspca_dev->width == 640 && reg11 < 4) reg11 = 4; /* frame exposure time in ms = 1000 * reg11 / 30 -> reg10 = (sd->ctrls[EXPOSURE].val / 2) * reg10_max / (1000 * reg11 / 30) */ reg10 = (sd->ctrls[EXPOSURE].val * 15 * reg10_max) / (1000 * reg11); /* Don't allow this to get below 10 when using autogain, the steps become very large (relatively) when below 10 causing the image to oscilate from much too dark, to much too bright and back again. */ if (sd->ctrls[AUTOGAIN].val && reg10 < 10) reg10 = 10; else if (reg10 > reg10_max) reg10 = reg10_max; /* Write reg 10 and reg11 low nibble */ i2c[1] = sensor_data[sd->sensor].sensor_addr; i2c[3] = reg10; i2c[4] |= reg11 - 1; /* If register 11 didn't change, don't change it */ if (sd->reg11 == reg11) i2c[0] = 0xa0; if (i2c_w(gspca_dev, i2c) == 0) sd->reg11 = reg11; else goto err; break; } case SENSOR_PAS202: { __u8 i2cpframerate[] = {0xb0, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, 0x16}; __u8 i2cpexpo[] = {0xa0, 0x40, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x16}; const __u8 i2cpdoit[] = {0xa0, 0x40, 0x11, 0x01, 0x00, 0x00, 0x00, 0x16}; int framerate_ctrl; /* The exposure knee for the autogain algorithm is 200 (100 ms / 10 fps on other sensors), for values below this use the control for setting the partial frame expose time, above that use variable framerate. This way we run at max framerate (640x480@7.5 fps, 320x240@10fps) until the knee is reached. Using the variable framerate control above 200 is better then playing around with both clockdiv + partial frame exposure times (like we are doing with the ov chips), as that sometimes leads to jumps in the exposure control, which are bad for auto exposure. */ if (sd->ctrls[EXPOSURE].val < 200) { i2cpexpo[3] = 255 - (sd->ctrls[EXPOSURE].val * 255) / 200; framerate_ctrl = 500; } else { /* The PAS202's exposure control goes from 0 - 4095, but anything below 500 causes vsync issues, so scale our 200-1023 to 500-4095 */ framerate_ctrl = (sd->ctrls[EXPOSURE].val - 200) * 1000 / 229 + 500; } i2cpframerate[3] = framerate_ctrl >> 6; i2cpframerate[4] = framerate_ctrl & 0x3f; if (i2c_w(gspca_dev, i2cpframerate) < 0) goto err; if (i2c_w(gspca_dev, i2cpexpo) < 0) goto err; if (i2c_w(gspca_dev, i2cpdoit) < 0) goto err; break; } case SENSOR_PAS106: { __u8 i2cpframerate[] = {0xb1, 0x40, 0x03, 0x00, 0x00, 0x00, 0x00, 0x14}; __u8 i2cpexpo[] = {0xa1, 0x40, 0x05, 0x00, 0x00, 0x00, 0x00, 0x14}; const __u8 i2cpdoit[] = {0xa1, 0x40, 0x13, 0x01, 0x00, 0x00, 0x00, 0x14}; int framerate_ctrl; /* For values below 150 use partial frame exposure, above that use framerate ctrl */ if (sd->ctrls[EXPOSURE].val < 150) { i2cpexpo[3] = 150 - sd->ctrls[EXPOSURE].val; framerate_ctrl = 300; } else { /* The PAS106's exposure control goes from 0 - 4095, but anything below 300 causes vsync issues, so scale our 150-1023 to 300-4095 */ framerate_ctrl = (sd->ctrls[EXPOSURE].val - 150) * 1000 / 230 + 300; } i2cpframerate[3] = framerate_ctrl >> 4; i2cpframerate[4] = framerate_ctrl & 0x0f; if (i2c_w(gspca_dev, i2cpframerate) < 0) goto err; if (i2c_w(gspca_dev, i2cpexpo) < 0) goto err; if (i2c_w(gspca_dev, i2cpdoit) < 0) goto err; break; } } return; err: PDEBUG(D_ERR, "i2c error exposure"); } static void setfreq(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; switch (sd->sensor) { case SENSOR_OV6650: case SENSOR_OV7630: { /* Framerate adjust register for artificial light 50 hz flicker compensation, for the ov6650 this is identical to ov6630 0x2b register, see ov6630 datasheet. 0x4f / 0x8a -> (30 fps -> 25 fps), 0x00 -> no adjustment */ __u8 i2c[] = {0xa0, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x00, 0x10}; switch (sd->ctrls[FREQ].val) { default: /* case 0: * no filter*/ /* case 2: * 60 hz */ i2c[3] = 0; break; case 1: /* 50 hz */ i2c[3] = (sd->sensor == SENSOR_OV6650) ? 0x4f : 0x8a; break; } i2c[1] = sensor_data[sd->sensor].sensor_addr; if (i2c_w(gspca_dev, i2c) < 0) PDEBUG(D_ERR, "i2c error setfreq"); break; } } } #include "autogain_functions.h" static void do_autogain(struct gspca_dev *gspca_dev) { int deadzone, desired_avg_lum, result; struct sd *sd = (struct sd *) gspca_dev; int avg_lum = atomic_read(&sd->avg_lum); if ((gspca_dev->ctrl_dis & (1 << AUTOGAIN)) || avg_lum == -1 || !sd->ctrls[AUTOGAIN].val) return; if (sd->autogain_ignore_frames > 0) { sd->autogain_ignore_frames--; return; } /* SIF / VGA sensors have a different autoexposure area and thus different avg_lum values for the same picture brightness */ if (sensor_data[sd->sensor].flags & F_SIF) { deadzone = 500; /* SIF sensors tend to overexpose, so keep this small */ desired_avg_lum = 5000; } else { deadzone = 1500; desired_avg_lum = 13000; } if (sensor_data[sd->sensor].flags & F_COARSE_EXPO) result = coarse_grained_expo_autogain(gspca_dev, avg_lum, sd->ctrls[BRIGHTNESS].val * desired_avg_lum / 127, deadzone); else result = auto_gain_n_exposure(gspca_dev, avg_lum, sd->ctrls[BRIGHTNESS].val * desired_avg_lum / 127, deadzone, GAIN_KNEE, EXPOSURE_KNEE); if (result) { PDEBUG(D_FRAM, "autogain: gain changed: gain: %d expo: %d", (int) sd->ctrls[GAIN].val, (int) sd->ctrls[EXPOSURE].val); sd->autogain_ignore_frames = AUTOGAIN_IGNORE_FRAMES; } } /* this function is called at probe time */ static int sd_config(struct gspca_dev *gspca_dev, const struct usb_device_id *id) { struct sd *sd = (struct sd *) gspca_dev; struct cam *cam; reg_r(gspca_dev, 0x00); if (gspca_dev->usb_buf[0] != 0x10) return -ENODEV; /* copy the webcam info from the device id */ sd->sensor = id->driver_info >> 8; sd->bridge = id->driver_info & 0xff; gspca_dev->ctrl_dis = sensor_data[sd->sensor].ctrl_dis; #if AUTOGAIN_DEF if (!(gspca_dev->ctrl_dis & (1 << AUTOGAIN))) gspca_dev->ctrl_inac = (1 << GAIN) | (1 << EXPOSURE); #endif cam = &gspca_dev->cam; cam->ctrls = sd->ctrls; if (!(sensor_data[sd->sensor].flags & F_SIF)) { cam->cam_mode = vga_mode; cam->nmodes = ARRAY_SIZE(vga_mode); } else { cam->cam_mode = sif_mode; cam->nmodes = ARRAY_SIZE(sif_mode); } cam->npkt = 36; /* 36 packets per ISOC message */ return 0; } /* this function is called at probe and resume time */ static int sd_init(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; const __u8 stop = 0x09; /* Disable stream turn of LED */ if (sensor_data[sd->sensor].flags & F_COARSE_EXPO) { sd->ctrls[EXPOSURE].min = COARSE_EXPOSURE_MIN; sd->ctrls[EXPOSURE].max = COARSE_EXPOSURE_MAX; sd->ctrls[EXPOSURE].def = COARSE_EXPOSURE_DEF; if (sd->ctrls[EXPOSURE].val > COARSE_EXPOSURE_MAX) sd->ctrls[EXPOSURE].val = COARSE_EXPOSURE_DEF; } reg_w(gspca_dev, 0x01, &stop, 1); return 0; } /* -- start the camera -- */ static int sd_start(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; struct cam *cam = &gspca_dev->cam; int i, mode; __u8 regs[0x31]; mode = cam->cam_mode[gspca_dev->curr_mode].priv & 0x07; /* Copy registers 0x01 - 0x19 from the template */ memcpy(&regs[0x01], sensor_data[sd->sensor].bridge_init, 0x19); /* Set the mode */ regs[0x18] |= mode << 4; /* Set bridge gain to 1.0 */ if (sd->bridge == BRIDGE_103) { regs[0x05] = 0x20; /* Red */ regs[0x06] = 0x20; /* Green */ regs[0x07] = 0x20; /* Blue */ } else { regs[0x10] = 0x00; /* Red and blue */ regs[0x11] = 0x00; /* Green */ } /* Setup pixel numbers and auto exposure window */ if (sensor_data[sd->sensor].flags & F_SIF) { regs[0x1a] = 0x14; /* HO_SIZE 640, makes no sense */ regs[0x1b] = 0x0a; /* VO_SIZE 320, makes no sense */ regs[0x1c] = 0x02; /* AE H-start 64 */ regs[0x1d] = 0x02; /* AE V-start 64 */ regs[0x1e] = 0x09; /* AE H-end 288 */ regs[0x1f] = 0x07; /* AE V-end 224 */ } else { regs[0x1a] = 0x1d; /* HO_SIZE 960, makes no sense */ regs[0x1b] = 0x10; /* VO_SIZE 512, makes no sense */ regs[0x1c] = 0x05; /* AE H-start 160 */ regs[0x1d] = 0x03; /* AE V-start 96 */ regs[0x1e] = 0x0f; /* AE H-end 480 */ regs[0x1f] = 0x0c; /* AE V-end 384 */ } /* Setup the gamma table (only used with the sn9c103 bridge) */ for (i = 0; i < 16; i++) regs[0x20 + i] = i * 16; regs[0x20 + i] = 255; /* Special cases where some regs depend on mode or bridge */ switch (sd->sensor) { case SENSOR_TAS5130CXX: /* FIXME / TESTME probably not mode specific at all most likely the upper nibble of 0x19 is exposure (clock divider) just as with the tas5110, we need someone to test this. */ regs[0x19] = mode ? 0x23 : 0x43; break; case SENSOR_OV7630: /* FIXME / TESTME for some reason with the 101/102 bridge the clock is set to 12 Mhz (reg1 == 0x04), rather then 24. Also the hstart needs to go from 1 to 2 when using a 103, which is likely related. This does not seem right. */ if (sd->bridge == BRIDGE_103) { regs[0x01] = 0x44; /* Select 24 Mhz clock */ regs[0x12] = 0x02; /* Set hstart to 2 */ } } /* Disable compression when the raw bayer format has been selected */ if (cam->cam_mode[gspca_dev->curr_mode].priv & MODE_RAW) regs[0x18] &= ~0x80; /* Vga mode emulation on SIF sensor? */ if (cam->cam_mode[gspca_dev->curr_mode].priv & MODE_REDUCED_SIF) { regs[0x12] += 16; /* hstart adjust */ regs[0x13] += 24; /* vstart adjust */ regs[0x15] = 320 / 16; /* hsize */ regs[0x16] = 240 / 16; /* vsize */ } /* reg 0x01 bit 2 video transfert on */ reg_w(gspca_dev, 0x01, &regs[0x01], 1); /* reg 0x17 SensorClk enable inv Clk 0x60 */ reg_w(gspca_dev, 0x17, &regs[0x17], 1); /* Set the registers from the template */ reg_w(gspca_dev, 0x01, &regs[0x01], (sd->bridge == BRIDGE_103) ? 0x30 : 0x1f); /* Init the sensor */ i2c_w_vector(gspca_dev, sensor_data[sd->sensor].sensor_init, sensor_data[sd->sensor].sensor_init_size); /* Mode / bridge specific sensor setup */ switch (sd->sensor) { case SENSOR_PAS202: { const __u8 i2cpclockdiv[] = {0xa0, 0x40, 0x02, 0x03, 0x00, 0x00, 0x00, 0x10}; /* clockdiv from 4 to 3 (7.5 -> 10 fps) when in low res mode */ if (mode) i2c_w(gspca_dev, i2cpclockdiv); break; } case SENSOR_OV7630: /* FIXME / TESTME We should be able to handle this identical for the 101/102 and the 103 case */ if (sd->bridge == BRIDGE_103) { const __u8 i2c[] = { 0xa0, 0x21, 0x13, 0x80, 0x00, 0x00, 0x00, 0x10 }; i2c_w(gspca_dev, i2c); } break; } /* H_size V_size 0x28, 0x1e -> 640x480. 0x16, 0x12 -> 352x288 */ reg_w(gspca_dev, 0x15, &regs[0x15], 2); /* compression register */ reg_w(gspca_dev, 0x18, &regs[0x18], 1); /* H_start */ reg_w(gspca_dev, 0x12, &regs[0x12], 1); /* V_START */ reg_w(gspca_dev, 0x13, &regs[0x13], 1); /* reset 0x17 SensorClk enable inv Clk 0x60 */ /*fixme: ov7630 [17]=68 8f (+20 if 102)*/ reg_w(gspca_dev, 0x17, &regs[0x17], 1); /*MCKSIZE ->3 */ /*fixme: not ov7630*/ reg_w(gspca_dev, 0x19, &regs[0x19], 1); /* AE_STRX AE_STRY AE_ENDX AE_ENDY */ reg_w(gspca_dev, 0x1c, &regs[0x1c], 4); /* Enable video transfert */ reg_w(gspca_dev, 0x01, &regs[0x01], 1); /* Compression */ reg_w(gspca_dev, 0x18, &regs[0x18], 2); msleep(20); sd->reg11 = -1; setgain(gspca_dev); setbrightness(gspca_dev); setexposure(gspca_dev); setfreq(gspca_dev); sd->frames_to_drop = 0; sd->autogain_ignore_frames = 0; sd->exp_too_high_cnt = 0; sd->exp_too_low_cnt = 0; atomic_set(&sd->avg_lum, -1); return 0; } static void sd_stopN(struct gspca_dev *gspca_dev) { sd_init(gspca_dev); } static u8* find_sof(struct gspca_dev *gspca_dev, u8 *data, int len) { struct sd *sd = (struct sd *) gspca_dev; int i, header_size = (sd->bridge == BRIDGE_103) ? 18 : 12; /* frames start with: * ff ff 00 c4 c4 96 synchro * 00 (unknown) * xx (frame sequence / size / compression) * (xx) (idem - extra byte for sn9c103) * ll mm brightness sum inside auto exposure * ll mm brightness sum outside auto exposure * (xx xx xx xx xx) audio values for snc103 */ for (i = 0; i < len; i++) { switch (sd->header_read) { case 0: if (data[i] == 0xff) sd->header_read++; break; case 1: if (data[i] == 0xff) sd->header_read++; else sd->header_read = 0; break; case 2: if (data[i] == 0x00) sd->header_read++; else if (data[i] != 0xff) sd->header_read = 0; break; case 3: if (data[i] == 0xc4) sd->header_read++; else if (data[i] == 0xff) sd->header_read = 1; else sd->header_read = 0; break; case 4: if (data[i] == 0xc4) sd->header_read++; else if (data[i] == 0xff) sd->header_read = 1; else sd->header_read = 0; break; case 5: if (data[i] == 0x96) sd->header_read++; else if (data[i] == 0xff) sd->header_read = 1; else sd->header_read = 0; break; default: sd->header[sd->header_read - 6] = data[i]; sd->header_read++; if (sd->header_read == header_size) { sd->header_read = 0; return data + i + 1; } } } return NULL; } static void sd_pkt_scan(struct gspca_dev *gspca_dev, u8 *data, /* isoc packet */ int len) /* iso packet length */ { int fr_h_sz = 0, lum_offset = 0, len_after_sof = 0; struct sd *sd = (struct sd *) gspca_dev; struct cam *cam = &gspca_dev->cam; u8 *sof; sof = find_sof(gspca_dev, data, len); if (sof) { if (sd->bridge == BRIDGE_103) { fr_h_sz = 18; lum_offset = 3; } else { fr_h_sz = 12; lum_offset = 2; } len_after_sof = len - (sof - data); len = (sof - data) - fr_h_sz; if (len < 0) len = 0; } if (cam->cam_mode[gspca_dev->curr_mode].priv & MODE_RAW) { /* In raw mode we sometimes get some garbage after the frame ignore this */ int used; int size = cam->cam_mode[gspca_dev->curr_mode].sizeimage; used = gspca_dev->image_len; if (used + len > size) len = size - used; } gspca_frame_add(gspca_dev, INTER_PACKET, data, len); if (sof) { int lum = sd->header[lum_offset] + (sd->header[lum_offset + 1] << 8); /* When exposure changes midway a frame we get a lum of 0 in this case drop 2 frames as the frames directly after an exposure change have an unstable image. Sometimes lum *really* is 0 (cam used in low light with low exposure setting), so do not drop frames if the previous lum was 0 too. */ if (lum == 0 && sd->prev_avg_lum != 0) { lum = -1; sd->frames_to_drop = 2; sd->prev_avg_lum = 0; } else sd->prev_avg_lum = lum; atomic_set(&sd->avg_lum, lum); if (sd->frames_to_drop) sd->frames_to_drop--; else gspca_frame_add(gspca_dev, LAST_PACKET, NULL, 0); gspca_frame_add(gspca_dev, FIRST_PACKET, sof, len_after_sof); } } static int sd_setautogain(struct gspca_dev *gspca_dev, __s32 val) { struct sd *sd = (struct sd *) gspca_dev; sd->ctrls[AUTOGAIN].val = val; sd->exp_too_high_cnt = 0; sd->exp_too_low_cnt = 0; /* when switching to autogain set defaults to make sure we are on a valid point of the autogain gain / exposure knee graph, and give this change time to take effect before doing autogain. */ if (sd->ctrls[AUTOGAIN].val && !(sensor_data[sd->sensor].flags & F_COARSE_EXPO)) { sd->ctrls[EXPOSURE].val = sd->ctrls[EXPOSURE].def; sd->ctrls[GAIN].val = sd->ctrls[GAIN].def; if (gspca_dev->streaming) { sd->autogain_ignore_frames = AUTOGAIN_IGNORE_FRAMES; setexposure(gspca_dev); setgain(gspca_dev); } } if (sd->ctrls[AUTOGAIN].val) gspca_dev->ctrl_inac = (1 << GAIN) | (1 << EXPOSURE); else gspca_dev->ctrl_inac = 0; return 0; } static int sd_querymenu(struct gspca_dev *gspca_dev, struct v4l2_querymenu *menu) { switch (menu->id) { case V4L2_CID_POWER_LINE_FREQUENCY: switch (menu->index) { case 0: /* V4L2_CID_POWER_LINE_FREQUENCY_DISABLED */ strcpy((char *) menu->name, "NoFliker"); return 0; case 1: /* V4L2_CID_POWER_LINE_FREQUENCY_50HZ */ strcpy((char *) menu->name, "50 Hz"); return 0; case 2: /* V4L2_CID_POWER_LINE_FREQUENCY_60HZ */ strcpy((char *) menu->name, "60 Hz"); return 0; } break; } return -EINVAL; } #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE) static int sd_int_pkt_scan(struct gspca_dev *gspca_dev, u8 *data, /* interrupt packet data */ int len) /* interrupt packet length */ { int ret = -EINVAL; if (len == 1 && data[0] == 1) { input_report_key(gspca_dev->input_dev, KEY_CAMERA, 1); input_sync(gspca_dev->input_dev); input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0); input_sync(gspca_dev->input_dev); ret = 0; } return ret; } #endif /* sub-driver description */ static const struct sd_desc sd_desc = { .name = MODULE_NAME, .ctrls = sd_ctrls, .nctrls = ARRAY_SIZE(sd_ctrls), .config = sd_config, .init = sd_init, .start = sd_start, .stopN = sd_stopN, .pkt_scan = sd_pkt_scan, .querymenu = sd_querymenu, .dq_callback = do_autogain, #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE) .int_pkt_scan = sd_int_pkt_scan, #endif }; /* -- module initialisation -- */ #define SB(sensor, bridge) \ .driver_info = (SENSOR_ ## sensor << 8) | BRIDGE_ ## bridge static const struct usb_device_id device_table[] = { {USB_DEVICE(0x0c45, 0x6001), SB(TAS5110C, 102)}, /* TAS5110C1B */ {USB_DEVICE(0x0c45, 0x6005), SB(TAS5110C, 101)}, /* TAS5110C1B */ {USB_DEVICE(0x0c45, 0x6007), SB(TAS5110D, 101)}, /* TAS5110D */ {USB_DEVICE(0x0c45, 0x6009), SB(PAS106, 101)}, {USB_DEVICE(0x0c45, 0x600d), SB(PAS106, 101)}, {USB_DEVICE(0x0c45, 0x6011), SB(OV6650, 101)}, {USB_DEVICE(0x0c45, 0x6019), SB(OV7630, 101)}, #if !defined CONFIG_USB_SN9C102 && !defined CONFIG_USB_SN9C102_MODULE {USB_DEVICE(0x0c45, 0x6024), SB(TAS5130CXX, 102)}, {USB_DEVICE(0x0c45, 0x6025), SB(TAS5130CXX, 102)}, #endif {USB_DEVICE(0x0c45, 0x6028), SB(PAS202, 102)}, {USB_DEVICE(0x0c45, 0x6029), SB(PAS106, 102)}, {USB_DEVICE(0x0c45, 0x602a), SB(HV7131D, 102)}, /* {USB_DEVICE(0x0c45, 0x602b), SB(MI0343, 102)}, */ {USB_DEVICE(0x0c45, 0x602c), SB(OV7630, 102)}, {USB_DEVICE(0x0c45, 0x602d), SB(HV7131R, 102)}, {USB_DEVICE(0x0c45, 0x602e), SB(OV7630, 102)}, /* {USB_DEVICE(0x0c45, 0x6030), SB(MI03XX, 102)}, */ /* MI0343 MI0360 MI0330 */ /* {USB_DEVICE(0x0c45, 0x6082), SB(MI03XX, 103)}, */ /* MI0343 MI0360 */ {USB_DEVICE(0x0c45, 0x6083), SB(HV7131D, 103)}, {USB_DEVICE(0x0c45, 0x608c), SB(HV7131R, 103)}, /* {USB_DEVICE(0x0c45, 0x608e), SB(CISVF10, 103)}, */ {USB_DEVICE(0x0c45, 0x608f), SB(OV7630, 103)}, {USB_DEVICE(0x0c45, 0x60a8), SB(PAS106, 103)}, {USB_DEVICE(0x0c45, 0x60aa), SB(TAS5130CXX, 103)}, {USB_DEVICE(0x0c45, 0x60af), SB(PAS202, 103)}, {USB_DEVICE(0x0c45, 0x60b0), SB(OV7630, 103)}, {} }; MODULE_DEVICE_TABLE(usb, device_table); /* -- device connect -- */ static int sd_probe(struct usb_interface *intf, const struct usb_device_id *id) { return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd), THIS_MODULE); } static struct usb_driver sd_driver = { .name = MODULE_NAME, .id_table = device_table, .probe = sd_probe, .disconnect = gspca_disconnect, #ifdef CONFIG_PM .suspend = gspca_suspend, .resume = gspca_resume, #endif }; module_usb_driver(sd_driver);
gpl-2.0
Stane1983/android_kernel_xiaomi_dior_DEPRECATED
sound/sh/sh_dac_audio.c
4900
10907
/* * sh_dac_audio.c - SuperH DAC audio driver for ALSA * * Copyright (c) 2009 by Rafael Ignacio Zurita <rizurita@yahoo.com> * * * Based on sh_dac_audio.c (Copyright (C) 2004, 2005 by Andriy Skulysh) * * This program is free software; you can redistribute it and/or modify * it under the terms of the 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/hrtimer.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/module.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/pcm.h> #include <sound/sh_dac_audio.h> #include <asm/clock.h> #include <asm/hd64461.h> #include <mach/hp6xx.h> #include <cpu/dac.h> MODULE_AUTHOR("Rafael Ignacio Zurita <rizurita@yahoo.com>"); MODULE_DESCRIPTION("SuperH DAC audio driver"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{SuperH DAC audio support}}"); /* Module Parameters */ static int index = SNDRV_DEFAULT_IDX1; static char *id = SNDRV_DEFAULT_STR1; module_param(index, int, 0444); MODULE_PARM_DESC(index, "Index value for SuperH DAC audio."); module_param(id, charp, 0444); MODULE_PARM_DESC(id, "ID string for SuperH DAC audio."); /* main struct */ struct snd_sh_dac { struct snd_card *card; struct snd_pcm_substream *substream; struct hrtimer hrtimer; ktime_t wakeups_per_second; int rate; int empty; char *data_buffer, *buffer_begin, *buffer_end; int processed; /* bytes proccesed, to compare with period_size */ int buffer_size; struct dac_audio_pdata *pdata; }; static void dac_audio_start_timer(struct snd_sh_dac *chip) { hrtimer_start(&chip->hrtimer, chip->wakeups_per_second, HRTIMER_MODE_REL); } static void dac_audio_stop_timer(struct snd_sh_dac *chip) { hrtimer_cancel(&chip->hrtimer); } static void dac_audio_reset(struct snd_sh_dac *chip) { dac_audio_stop_timer(chip); chip->buffer_begin = chip->buffer_end = chip->data_buffer; chip->processed = 0; chip->empty = 1; } static void dac_audio_set_rate(struct snd_sh_dac *chip) { chip->wakeups_per_second = ktime_set(0, 1000000000 / chip->rate); } /* PCM INTERFACE */ static struct snd_pcm_hardware snd_sh_dac_pcm_hw = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_HALF_DUPLEX), .formats = SNDRV_PCM_FMTBIT_U8, .rates = SNDRV_PCM_RATE_8000, .rate_min = 8000, .rate_max = 8000, .channels_min = 1, .channels_max = 1, .buffer_bytes_max = (48*1024), .period_bytes_min = 1, .period_bytes_max = (48*1024), .periods_min = 1, .periods_max = 1024, }; static int snd_sh_dac_pcm_open(struct snd_pcm_substream *substream) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; runtime->hw = snd_sh_dac_pcm_hw; chip->substream = substream; chip->buffer_begin = chip->buffer_end = chip->data_buffer; chip->processed = 0; chip->empty = 1; chip->pdata->start(chip->pdata); return 0; } static int snd_sh_dac_pcm_close(struct snd_pcm_substream *substream) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); chip->substream = NULL; dac_audio_stop_timer(chip); chip->pdata->stop(chip->pdata); return 0; } static int snd_sh_dac_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); } static int snd_sh_dac_pcm_hw_free(struct snd_pcm_substream *substream) { return snd_pcm_lib_free_pages(substream); } static int snd_sh_dac_pcm_prepare(struct snd_pcm_substream *substream) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = chip->substream->runtime; chip->buffer_size = runtime->buffer_size; memset(chip->data_buffer, 0, chip->pdata->buffer_size); return 0; } static int snd_sh_dac_pcm_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); switch (cmd) { case SNDRV_PCM_TRIGGER_START: dac_audio_start_timer(chip); break; case SNDRV_PCM_TRIGGER_STOP: chip->buffer_begin = chip->buffer_end = chip->data_buffer; chip->processed = 0; chip->empty = 1; dac_audio_stop_timer(chip); break; default: return -EINVAL; } return 0; } static int snd_sh_dac_pcm_copy(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, void __user *src, snd_pcm_uframes_t count) { /* channel is not used (interleaved data) */ struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; ssize_t b_count = frames_to_bytes(runtime , count); ssize_t b_pos = frames_to_bytes(runtime , pos); if (count < 0) return -EINVAL; if (!count) return 0; memcpy_toio(chip->data_buffer + b_pos, src, b_count); chip->buffer_end = chip->data_buffer + b_pos + b_count; if (chip->empty) { chip->empty = 0; dac_audio_start_timer(chip); } return 0; } static int snd_sh_dac_pcm_silence(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, snd_pcm_uframes_t count) { /* channel is not used (interleaved data) */ struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; ssize_t b_count = frames_to_bytes(runtime , count); ssize_t b_pos = frames_to_bytes(runtime , pos); if (count < 0) return -EINVAL; if (!count) return 0; memset_io(chip->data_buffer + b_pos, 0, b_count); chip->buffer_end = chip->data_buffer + b_pos + b_count; if (chip->empty) { chip->empty = 0; dac_audio_start_timer(chip); } return 0; } static snd_pcm_uframes_t snd_sh_dac_pcm_pointer(struct snd_pcm_substream *substream) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); int pointer = chip->buffer_begin - chip->data_buffer; return pointer; } /* pcm ops */ static struct snd_pcm_ops snd_sh_dac_pcm_ops = { .open = snd_sh_dac_pcm_open, .close = snd_sh_dac_pcm_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_sh_dac_pcm_hw_params, .hw_free = snd_sh_dac_pcm_hw_free, .prepare = snd_sh_dac_pcm_prepare, .trigger = snd_sh_dac_pcm_trigger, .pointer = snd_sh_dac_pcm_pointer, .copy = snd_sh_dac_pcm_copy, .silence = snd_sh_dac_pcm_silence, .mmap = snd_pcm_lib_mmap_iomem, }; static int __devinit snd_sh_dac_pcm(struct snd_sh_dac *chip, int device) { int err; struct snd_pcm *pcm; /* device should be always 0 for us */ err = snd_pcm_new(chip->card, "SH_DAC PCM", device, 1, 0, &pcm); if (err < 0) return err; pcm->private_data = chip; strcpy(pcm->name, "SH_DAC PCM"); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_sh_dac_pcm_ops); /* buffer size=48K */ snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS, snd_dma_continuous_data(GFP_KERNEL), 48 * 1024, 48 * 1024); return 0; } /* END OF PCM INTERFACE */ /* driver .remove -- destructor */ static int snd_sh_dac_remove(struct platform_device *devptr) { snd_card_free(platform_get_drvdata(devptr)); platform_set_drvdata(devptr, NULL); return 0; } /* free -- it has been defined by create */ static int snd_sh_dac_free(struct snd_sh_dac *chip) { /* release the data */ kfree(chip->data_buffer); kfree(chip); return 0; } static int snd_sh_dac_dev_free(struct snd_device *device) { struct snd_sh_dac *chip = device->device_data; return snd_sh_dac_free(chip); } static enum hrtimer_restart sh_dac_audio_timer(struct hrtimer *handle) { struct snd_sh_dac *chip = container_of(handle, struct snd_sh_dac, hrtimer); struct snd_pcm_runtime *runtime = chip->substream->runtime; ssize_t b_ps = frames_to_bytes(runtime, runtime->period_size); if (!chip->empty) { sh_dac_output(*chip->buffer_begin, chip->pdata->channel); chip->buffer_begin++; chip->processed++; if (chip->processed >= b_ps) { chip->processed -= b_ps; snd_pcm_period_elapsed(chip->substream); } if (chip->buffer_begin == (chip->data_buffer + chip->buffer_size - 1)) chip->buffer_begin = chip->data_buffer; if (chip->buffer_begin == chip->buffer_end) chip->empty = 1; } if (!chip->empty) hrtimer_start(&chip->hrtimer, chip->wakeups_per_second, HRTIMER_MODE_REL); return HRTIMER_NORESTART; } /* create -- chip-specific constructor for the cards components */ static int __devinit snd_sh_dac_create(struct snd_card *card, struct platform_device *devptr, struct snd_sh_dac **rchip) { struct snd_sh_dac *chip; int err; static struct snd_device_ops ops = { .dev_free = snd_sh_dac_dev_free, }; *rchip = NULL; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (chip == NULL) return -ENOMEM; chip->card = card; hrtimer_init(&chip->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); chip->hrtimer.function = sh_dac_audio_timer; dac_audio_reset(chip); chip->rate = 8000; dac_audio_set_rate(chip); chip->pdata = devptr->dev.platform_data; chip->data_buffer = kmalloc(chip->pdata->buffer_size, GFP_KERNEL); if (chip->data_buffer == NULL) { kfree(chip); return -ENOMEM; } err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops); if (err < 0) { snd_sh_dac_free(chip); return err; } *rchip = chip; return 0; } /* driver .probe -- constructor */ static int __devinit snd_sh_dac_probe(struct platform_device *devptr) { struct snd_sh_dac *chip; struct snd_card *card; int err; err = snd_card_create(index, id, THIS_MODULE, 0, &card); if (err < 0) { snd_printk(KERN_ERR "cannot allocate the card\n"); return err; } err = snd_sh_dac_create(card, devptr, &chip); if (err < 0) goto probe_error; err = snd_sh_dac_pcm(chip, 0); if (err < 0) goto probe_error; strcpy(card->driver, "snd_sh_dac"); strcpy(card->shortname, "SuperH DAC audio driver"); printk(KERN_INFO "%s %s", card->longname, card->shortname); err = snd_card_register(card); if (err < 0) goto probe_error; snd_printk("ALSA driver for SuperH DAC audio"); platform_set_drvdata(devptr, card); return 0; probe_error: snd_card_free(card); return err; } /* * "driver" definition */ static struct platform_driver driver = { .probe = snd_sh_dac_probe, .remove = snd_sh_dac_remove, .driver = { .name = "dac_audio", }, }; module_platform_driver(driver);
gpl-2.0
shane87/android_kernel_lge_g3
sound/sh/sh_dac_audio.c
4900
10907
/* * sh_dac_audio.c - SuperH DAC audio driver for ALSA * * Copyright (c) 2009 by Rafael Ignacio Zurita <rizurita@yahoo.com> * * * Based on sh_dac_audio.c (Copyright (C) 2004, 2005 by Andriy Skulysh) * * This program is free software; you can redistribute it and/or modify * it under the terms of the 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/hrtimer.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/module.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/pcm.h> #include <sound/sh_dac_audio.h> #include <asm/clock.h> #include <asm/hd64461.h> #include <mach/hp6xx.h> #include <cpu/dac.h> MODULE_AUTHOR("Rafael Ignacio Zurita <rizurita@yahoo.com>"); MODULE_DESCRIPTION("SuperH DAC audio driver"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{SuperH DAC audio support}}"); /* Module Parameters */ static int index = SNDRV_DEFAULT_IDX1; static char *id = SNDRV_DEFAULT_STR1; module_param(index, int, 0444); MODULE_PARM_DESC(index, "Index value for SuperH DAC audio."); module_param(id, charp, 0444); MODULE_PARM_DESC(id, "ID string for SuperH DAC audio."); /* main struct */ struct snd_sh_dac { struct snd_card *card; struct snd_pcm_substream *substream; struct hrtimer hrtimer; ktime_t wakeups_per_second; int rate; int empty; char *data_buffer, *buffer_begin, *buffer_end; int processed; /* bytes proccesed, to compare with period_size */ int buffer_size; struct dac_audio_pdata *pdata; }; static void dac_audio_start_timer(struct snd_sh_dac *chip) { hrtimer_start(&chip->hrtimer, chip->wakeups_per_second, HRTIMER_MODE_REL); } static void dac_audio_stop_timer(struct snd_sh_dac *chip) { hrtimer_cancel(&chip->hrtimer); } static void dac_audio_reset(struct snd_sh_dac *chip) { dac_audio_stop_timer(chip); chip->buffer_begin = chip->buffer_end = chip->data_buffer; chip->processed = 0; chip->empty = 1; } static void dac_audio_set_rate(struct snd_sh_dac *chip) { chip->wakeups_per_second = ktime_set(0, 1000000000 / chip->rate); } /* PCM INTERFACE */ static struct snd_pcm_hardware snd_sh_dac_pcm_hw = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_HALF_DUPLEX), .formats = SNDRV_PCM_FMTBIT_U8, .rates = SNDRV_PCM_RATE_8000, .rate_min = 8000, .rate_max = 8000, .channels_min = 1, .channels_max = 1, .buffer_bytes_max = (48*1024), .period_bytes_min = 1, .period_bytes_max = (48*1024), .periods_min = 1, .periods_max = 1024, }; static int snd_sh_dac_pcm_open(struct snd_pcm_substream *substream) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; runtime->hw = snd_sh_dac_pcm_hw; chip->substream = substream; chip->buffer_begin = chip->buffer_end = chip->data_buffer; chip->processed = 0; chip->empty = 1; chip->pdata->start(chip->pdata); return 0; } static int snd_sh_dac_pcm_close(struct snd_pcm_substream *substream) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); chip->substream = NULL; dac_audio_stop_timer(chip); chip->pdata->stop(chip->pdata); return 0; } static int snd_sh_dac_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); } static int snd_sh_dac_pcm_hw_free(struct snd_pcm_substream *substream) { return snd_pcm_lib_free_pages(substream); } static int snd_sh_dac_pcm_prepare(struct snd_pcm_substream *substream) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = chip->substream->runtime; chip->buffer_size = runtime->buffer_size; memset(chip->data_buffer, 0, chip->pdata->buffer_size); return 0; } static int snd_sh_dac_pcm_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); switch (cmd) { case SNDRV_PCM_TRIGGER_START: dac_audio_start_timer(chip); break; case SNDRV_PCM_TRIGGER_STOP: chip->buffer_begin = chip->buffer_end = chip->data_buffer; chip->processed = 0; chip->empty = 1; dac_audio_stop_timer(chip); break; default: return -EINVAL; } return 0; } static int snd_sh_dac_pcm_copy(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, void __user *src, snd_pcm_uframes_t count) { /* channel is not used (interleaved data) */ struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; ssize_t b_count = frames_to_bytes(runtime , count); ssize_t b_pos = frames_to_bytes(runtime , pos); if (count < 0) return -EINVAL; if (!count) return 0; memcpy_toio(chip->data_buffer + b_pos, src, b_count); chip->buffer_end = chip->data_buffer + b_pos + b_count; if (chip->empty) { chip->empty = 0; dac_audio_start_timer(chip); } return 0; } static int snd_sh_dac_pcm_silence(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, snd_pcm_uframes_t count) { /* channel is not used (interleaved data) */ struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; ssize_t b_count = frames_to_bytes(runtime , count); ssize_t b_pos = frames_to_bytes(runtime , pos); if (count < 0) return -EINVAL; if (!count) return 0; memset_io(chip->data_buffer + b_pos, 0, b_count); chip->buffer_end = chip->data_buffer + b_pos + b_count; if (chip->empty) { chip->empty = 0; dac_audio_start_timer(chip); } return 0; } static snd_pcm_uframes_t snd_sh_dac_pcm_pointer(struct snd_pcm_substream *substream) { struct snd_sh_dac *chip = snd_pcm_substream_chip(substream); int pointer = chip->buffer_begin - chip->data_buffer; return pointer; } /* pcm ops */ static struct snd_pcm_ops snd_sh_dac_pcm_ops = { .open = snd_sh_dac_pcm_open, .close = snd_sh_dac_pcm_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_sh_dac_pcm_hw_params, .hw_free = snd_sh_dac_pcm_hw_free, .prepare = snd_sh_dac_pcm_prepare, .trigger = snd_sh_dac_pcm_trigger, .pointer = snd_sh_dac_pcm_pointer, .copy = snd_sh_dac_pcm_copy, .silence = snd_sh_dac_pcm_silence, .mmap = snd_pcm_lib_mmap_iomem, }; static int __devinit snd_sh_dac_pcm(struct snd_sh_dac *chip, int device) { int err; struct snd_pcm *pcm; /* device should be always 0 for us */ err = snd_pcm_new(chip->card, "SH_DAC PCM", device, 1, 0, &pcm); if (err < 0) return err; pcm->private_data = chip; strcpy(pcm->name, "SH_DAC PCM"); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_sh_dac_pcm_ops); /* buffer size=48K */ snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS, snd_dma_continuous_data(GFP_KERNEL), 48 * 1024, 48 * 1024); return 0; } /* END OF PCM INTERFACE */ /* driver .remove -- destructor */ static int snd_sh_dac_remove(struct platform_device *devptr) { snd_card_free(platform_get_drvdata(devptr)); platform_set_drvdata(devptr, NULL); return 0; } /* free -- it has been defined by create */ static int snd_sh_dac_free(struct snd_sh_dac *chip) { /* release the data */ kfree(chip->data_buffer); kfree(chip); return 0; } static int snd_sh_dac_dev_free(struct snd_device *device) { struct snd_sh_dac *chip = device->device_data; return snd_sh_dac_free(chip); } static enum hrtimer_restart sh_dac_audio_timer(struct hrtimer *handle) { struct snd_sh_dac *chip = container_of(handle, struct snd_sh_dac, hrtimer); struct snd_pcm_runtime *runtime = chip->substream->runtime; ssize_t b_ps = frames_to_bytes(runtime, runtime->period_size); if (!chip->empty) { sh_dac_output(*chip->buffer_begin, chip->pdata->channel); chip->buffer_begin++; chip->processed++; if (chip->processed >= b_ps) { chip->processed -= b_ps; snd_pcm_period_elapsed(chip->substream); } if (chip->buffer_begin == (chip->data_buffer + chip->buffer_size - 1)) chip->buffer_begin = chip->data_buffer; if (chip->buffer_begin == chip->buffer_end) chip->empty = 1; } if (!chip->empty) hrtimer_start(&chip->hrtimer, chip->wakeups_per_second, HRTIMER_MODE_REL); return HRTIMER_NORESTART; } /* create -- chip-specific constructor for the cards components */ static int __devinit snd_sh_dac_create(struct snd_card *card, struct platform_device *devptr, struct snd_sh_dac **rchip) { struct snd_sh_dac *chip; int err; static struct snd_device_ops ops = { .dev_free = snd_sh_dac_dev_free, }; *rchip = NULL; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (chip == NULL) return -ENOMEM; chip->card = card; hrtimer_init(&chip->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); chip->hrtimer.function = sh_dac_audio_timer; dac_audio_reset(chip); chip->rate = 8000; dac_audio_set_rate(chip); chip->pdata = devptr->dev.platform_data; chip->data_buffer = kmalloc(chip->pdata->buffer_size, GFP_KERNEL); if (chip->data_buffer == NULL) { kfree(chip); return -ENOMEM; } err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops); if (err < 0) { snd_sh_dac_free(chip); return err; } *rchip = chip; return 0; } /* driver .probe -- constructor */ static int __devinit snd_sh_dac_probe(struct platform_device *devptr) { struct snd_sh_dac *chip; struct snd_card *card; int err; err = snd_card_create(index, id, THIS_MODULE, 0, &card); if (err < 0) { snd_printk(KERN_ERR "cannot allocate the card\n"); return err; } err = snd_sh_dac_create(card, devptr, &chip); if (err < 0) goto probe_error; err = snd_sh_dac_pcm(chip, 0); if (err < 0) goto probe_error; strcpy(card->driver, "snd_sh_dac"); strcpy(card->shortname, "SuperH DAC audio driver"); printk(KERN_INFO "%s %s", card->longname, card->shortname); err = snd_card_register(card); if (err < 0) goto probe_error; snd_printk("ALSA driver for SuperH DAC audio"); platform_set_drvdata(devptr, card); return 0; probe_error: snd_card_free(card); return err; } /* * "driver" definition */ static struct platform_driver driver = { .probe = snd_sh_dac_probe, .remove = snd_sh_dac_remove, .driver = { .name = "dac_audio", }, }; module_platform_driver(driver);
gpl-2.0
hernstrom/linux
drivers/pcmcia/m32r_pcc.c
8228
16812
/* * drivers/pcmcia/m32r_pcc.c * * Device driver for the PCMCIA functionality of M32R. * * Copyright (c) 2001, 2002, 2003, 2004 * Hiroyuki Kondo, Naoto Sugai, Hayato Fujiwara */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/string.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/timer.h> #include <linux/ioport.h> #include <linux/delay.h> #include <linux/workqueue.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/bitops.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/addrspace.h> #include <pcmcia/ss.h> /* XXX: should be moved into asm/irq.h */ #define PCC0_IRQ 24 #define PCC1_IRQ 25 #include "m32r_pcc.h" #define CHAOS_PCC_DEBUG #ifdef CHAOS_PCC_DEBUG static volatile u_short dummy_readbuf; #endif #define PCC_DEBUG_DBEX /* Poll status interval -- 0 means default to interrupt */ static int poll_interval = 0; typedef enum pcc_space { as_none = 0, as_comm, as_attr, as_io } pcc_as_t; typedef struct pcc_socket { u_short type, flags; struct pcmcia_socket socket; unsigned int number; unsigned int ioaddr; u_long mapaddr; u_long base; /* PCC register base */ u_char cs_irq, intr; pccard_io_map io_map[MAX_IO_WIN]; pccard_mem_map mem_map[MAX_WIN]; u_char io_win; u_char mem_win; pcc_as_t current_space; u_char last_iodbex; #ifdef CHAOS_PCC_DEBUG u_char last_iosize; #endif #ifdef CONFIG_PROC_FS struct proc_dir_entry *proc; #endif } pcc_socket_t; static int pcc_sockets = 0; static pcc_socket_t socket[M32R_MAX_PCC] = { { 0, }, /* ... */ }; /*====================================================================*/ static unsigned int pcc_get(u_short, unsigned int); static void pcc_set(u_short, unsigned int , unsigned int ); static DEFINE_SPINLOCK(pcc_lock); void pcc_iorw(int sock, unsigned long port, void *buf, size_t size, size_t nmemb, int wr, int flag) { u_long addr; u_long flags; int need_ex; #ifdef PCC_DEBUG_DBEX int _dbex; #endif pcc_socket_t *t = &socket[sock]; #ifdef CHAOS_PCC_DEBUG int map_changed = 0; #endif /* Need lock ? */ spin_lock_irqsave(&pcc_lock, flags); /* * Check if need dbex */ need_ex = (size > 1 && flag == 0) ? PCMOD_DBEX : 0; #ifdef PCC_DEBUG_DBEX _dbex = need_ex; need_ex = 0; #endif /* * calculate access address */ addr = t->mapaddr + port - t->ioaddr + KSEG1; /* XXX */ /* * Check current mapping */ if (t->current_space != as_io || t->last_iodbex != need_ex) { u_long cbsz; /* * Disable first */ pcc_set(sock, PCCR, 0); /* * Set mode and io address */ cbsz = (t->flags & MAP_16BIT) ? 0 : PCMOD_CBSZ; pcc_set(sock, PCMOD, PCMOD_AS_IO | cbsz | need_ex); pcc_set(sock, PCADR, addr & 0x1ff00000); /* * Enable and read it */ pcc_set(sock, PCCR, 1); #ifdef CHAOS_PCC_DEBUG #if 0 map_changed = (t->current_space == as_attr && size == 2); /* XXX */ #else map_changed = 1; #endif #endif t->current_space = as_io; } /* * access to IO space */ if (size == 1) { /* Byte */ unsigned char *bp = (unsigned char *)buf; #ifdef CHAOS_DEBUG if (map_changed) { dummy_readbuf = readb(addr); } #endif if (wr) { /* write Byte */ while (nmemb--) { writeb(*bp++, addr); } } else { /* read Byte */ while (nmemb--) { *bp++ = readb(addr); } } } else { /* Word */ unsigned short *bp = (unsigned short *)buf; #ifdef CHAOS_PCC_DEBUG if (map_changed) { dummy_readbuf = readw(addr); } #endif if (wr) { /* write Word */ while (nmemb--) { #ifdef PCC_DEBUG_DBEX if (_dbex) { unsigned char *cp = (unsigned char *)bp; unsigned short tmp; tmp = cp[1] << 8 | cp[0]; writew(tmp, addr); bp++; } else #endif writew(*bp++, addr); } } else { /* read Word */ while (nmemb--) { #ifdef PCC_DEBUG_DBEX if (_dbex) { unsigned char *cp = (unsigned char *)bp; unsigned short tmp; tmp = readw(addr); cp[0] = tmp & 0xff; cp[1] = (tmp >> 8) & 0xff; bp++; } else #endif *bp++ = readw(addr); } } } #if 1 /* addr is no longer used */ if ((addr = pcc_get(sock, PCIRC)) & PCIRC_BWERR) { printk("m32r_pcc: BWERR detected : port 0x%04lx : iosize %dbit\n", port, size * 8); pcc_set(sock, PCIRC, addr); } #endif /* * save state */ t->last_iosize = size; t->last_iodbex = need_ex; /* Need lock ? */ spin_unlock_irqrestore(&pcc_lock,flags); return; } void pcc_ioread(int sock, unsigned long port, void *buf, size_t size, size_t nmemb, int flag) { pcc_iorw(sock, port, buf, size, nmemb, 0, flag); } void pcc_iowrite(int sock, unsigned long port, void *buf, size_t size, size_t nmemb, int flag) { pcc_iorw(sock, port, buf, size, nmemb, 1, flag); } /*====================================================================*/ #define IS_REGISTERED 0x2000 #define IS_ALIVE 0x8000 typedef struct pcc_t { char *name; u_short flags; } pcc_t; static pcc_t pcc[] = { { "xnux2", 0 }, { "xnux2", 0 }, }; static irqreturn_t pcc_interrupt(int, void *); /*====================================================================*/ static struct timer_list poll_timer; static unsigned int pcc_get(u_short sock, unsigned int reg) { return inl(socket[sock].base + reg); } static void pcc_set(u_short sock, unsigned int reg, unsigned int data) { outl(data, socket[sock].base + reg); } /*====================================================================== See if a card is present, powered up, in IO mode, and already bound to a (non PC Card) Linux driver. We leave these alone. We make an exception for cards that seem to be serial devices. ======================================================================*/ static int __init is_alive(u_short sock) { unsigned int stat; unsigned int f; stat = pcc_get(sock, PCIRC); f = (stat & (PCIRC_CDIN1 | PCIRC_CDIN2)) >> 16; if(!f){ printk("m32r_pcc: No Card is detected at socket %d : stat = 0x%08x\n",stat,sock); return 0; } if(f!=3) printk("m32r_pcc: Insertion fail (%.8x) at socket %d\n",stat,sock); else printk("m32r_pcc: Card is Inserted at socket %d(%.8x)\n",sock,stat); return 0; } static void add_pcc_socket(ulong base, int irq, ulong mapaddr, unsigned int ioaddr) { pcc_socket_t *t = &socket[pcc_sockets]; /* add sockets */ t->ioaddr = ioaddr; t->mapaddr = mapaddr; t->base = base; #ifdef CHAOS_PCC_DEBUG t->flags = MAP_16BIT; #else t->flags = 0; #endif if (is_alive(pcc_sockets)) t->flags |= IS_ALIVE; /* add pcc */ if (t->base > 0) { request_region(t->base, 0x20, "m32r-pcc"); } printk(KERN_INFO " %s ", pcc[pcc_sockets].name); printk("pcc at 0x%08lx\n", t->base); /* Update socket interrupt information, capabilities */ t->socket.features |= (SS_CAP_PCCARD | SS_CAP_STATIC_MAP); t->socket.map_size = M32R_PCC_MAPSIZE; t->socket.io_offset = ioaddr; /* use for io access offset */ t->socket.irq_mask = 0; t->socket.pci_irq = 2 + pcc_sockets; /* XXX */ request_irq(irq, pcc_interrupt, 0, "m32r-pcc", pcc_interrupt); pcc_sockets++; return; } /*====================================================================*/ static irqreturn_t pcc_interrupt(int irq, void *dev) { int i, j, irc; u_int events, active; int handled = 0; pr_debug("m32r_pcc: pcc_interrupt(%d)\n", irq); for (j = 0; j < 20; j++) { active = 0; for (i = 0; i < pcc_sockets; i++) { if ((socket[i].cs_irq != irq) && (socket[i].socket.pci_irq != irq)) continue; handled = 1; irc = pcc_get(i, PCIRC); irc >>=16; pr_debug("m32r_pcc: interrupt: socket %d pcirc 0x%02x ", i, irc); if (!irc) continue; events = (irc) ? SS_DETECT : 0; events |= (pcc_get(i,PCCR) & PCCR_PCEN) ? SS_READY : 0; pr_debug("m32r_pcc: event 0x%02x\n", events); if (events) pcmcia_parse_events(&socket[i].socket, events); active |= events; active = 0; } if (!active) break; } if (j == 20) printk(KERN_NOTICE "m32r-pcc: infinite loop in interrupt handler\n"); pr_debug("m32r_pcc: interrupt done\n"); return IRQ_RETVAL(handled); } /* pcc_interrupt */ static void pcc_interrupt_wrapper(u_long data) { pcc_interrupt(0, NULL); init_timer(&poll_timer); poll_timer.expires = jiffies + poll_interval; add_timer(&poll_timer); } /*====================================================================*/ static int _pcc_get_status(u_short sock, u_int *value) { u_int status; status = pcc_get(sock,PCIRC); *value = ((status & PCIRC_CDIN1) && (status & PCIRC_CDIN2)) ? SS_DETECT : 0; status = pcc_get(sock,PCCR); #if 0 *value |= (status & PCCR_PCEN) ? SS_READY : 0; #else *value |= SS_READY; /* XXX: always */ #endif status = pcc_get(sock,PCCSIGCR); *value |= (status & PCCSIGCR_VEN) ? SS_POWERON : 0; pr_debug("m32r_pcc: GetStatus(%d) = %#4.4x\n", sock, *value); return 0; } /* _get_status */ /*====================================================================*/ static int _pcc_set_socket(u_short sock, socket_state_t *state) { u_long reg = 0; pr_debug("m32r_pcc: SetSocket(%d, flags %#3.3x, Vcc %d, Vpp %d, " "io_irq %d, csc_mask %#2.2x)", sock, state->flags, state->Vcc, state->Vpp, state->io_irq, state->csc_mask); if (state->Vcc) { /* * 5V only */ if (state->Vcc == 50) { reg |= PCCSIGCR_VEN; } else { return -EINVAL; } } if (state->flags & SS_RESET) { pr_debug("m32r_pcc: :RESET\n"); reg |= PCCSIGCR_CRST; } if (state->flags & SS_OUTPUT_ENA){ pr_debug("m32r_pcc: :OUTPUT_ENA\n"); /* bit clear */ } else { reg |= PCCSIGCR_SEN; } pcc_set(sock,PCCSIGCR,reg); if(state->flags & SS_IOCARD){ pr_debug("m32r_pcc: :IOCARD"); } if (state->flags & SS_PWR_AUTO) { pr_debug("m32r_pcc: :PWR_AUTO"); } if (state->csc_mask & SS_DETECT) pr_debug("m32r_pcc: :csc-SS_DETECT"); if (state->flags & SS_IOCARD) { if (state->csc_mask & SS_STSCHG) pr_debug("m32r_pcc: :STSCHG"); } else { if (state->csc_mask & SS_BATDEAD) pr_debug("m32r_pcc: :BATDEAD"); if (state->csc_mask & SS_BATWARN) pr_debug("m32r_pcc: :BATWARN"); if (state->csc_mask & SS_READY) pr_debug("m32r_pcc: :READY"); } pr_debug("m32r_pcc: \n"); return 0; } /* _set_socket */ /*====================================================================*/ static int _pcc_set_io_map(u_short sock, struct pccard_io_map *io) { u_char map; pr_debug("m32r_pcc: SetIOMap(%d, %d, %#2.2x, %d ns, " "%#llx-%#llx)\n", sock, io->map, io->flags, io->speed, (unsigned long long)io->start, (unsigned long long)io->stop); map = io->map; return 0; } /* _set_io_map */ /*====================================================================*/ static int _pcc_set_mem_map(u_short sock, struct pccard_mem_map *mem) { u_char map = mem->map; u_long mode; u_long addr; pcc_socket_t *t = &socket[sock]; #ifdef CHAOS_PCC_DEBUG #if 0 pcc_as_t last = t->current_space; #endif #endif pr_debug("m32r_pcc: SetMemMap(%d, %d, %#2.2x, %d ns, " "%#llx, %#x)\n", sock, map, mem->flags, mem->speed, (unsigned long long)mem->static_start, mem->card_start); /* * sanity check */ if ((map > MAX_WIN) || (mem->card_start > 0x3ffffff)){ return -EINVAL; } /* * de-activate */ if ((mem->flags & MAP_ACTIVE) == 0) { t->current_space = as_none; return 0; } /* * Disable first */ pcc_set(sock, PCCR, 0); /* * Set mode */ if (mem->flags & MAP_ATTRIB) { mode = PCMOD_AS_ATTRIB | PCMOD_CBSZ; t->current_space = as_attr; } else { mode = 0; /* common memory */ t->current_space = as_comm; } pcc_set(sock, PCMOD, mode); /* * Set address */ addr = t->mapaddr + (mem->card_start & M32R_PCC_MAPMASK); pcc_set(sock, PCADR, addr); mem->static_start = addr + mem->card_start; /* * Enable again */ pcc_set(sock, PCCR, 1); #ifdef CHAOS_PCC_DEBUG #if 0 if (last != as_attr) { #else if (1) { #endif dummy_readbuf = *(u_char *)(addr + KSEG1); } #endif return 0; } /* _set_mem_map */ #if 0 /* driver model ordering issue */ /*====================================================================== Routines for accessing socket information and register dumps via /proc/bus/pccard/... ======================================================================*/ static ssize_t show_info(struct class_device *class_dev, char *buf) { pcc_socket_t *s = container_of(class_dev, struct pcc_socket, socket.dev); return sprintf(buf, "type: %s\nbase addr: 0x%08lx\n", pcc[s->type].name, s->base); } static ssize_t show_exca(struct class_device *class_dev, char *buf) { /* FIXME */ return 0; } static CLASS_DEVICE_ATTR(info, S_IRUGO, show_info, NULL); static CLASS_DEVICE_ATTR(exca, S_IRUGO, show_exca, NULL); #endif /*====================================================================*/ /* this is horribly ugly... proper locking needs to be done here at * some time... */ #define LOCKED(x) do { \ int retval; \ unsigned long flags; \ spin_lock_irqsave(&pcc_lock, flags); \ retval = x; \ spin_unlock_irqrestore(&pcc_lock, flags); \ return retval; \ } while (0) static int pcc_get_status(struct pcmcia_socket *s, u_int *value) { unsigned int sock = container_of(s, struct pcc_socket, socket)->number; if (socket[sock].flags & IS_ALIVE) { *value = 0; return -EINVAL; } LOCKED(_pcc_get_status(sock, value)); } static int pcc_set_socket(struct pcmcia_socket *s, socket_state_t *state) { unsigned int sock = container_of(s, struct pcc_socket, socket)->number; if (socket[sock].flags & IS_ALIVE) return -EINVAL; LOCKED(_pcc_set_socket(sock, state)); } static int pcc_set_io_map(struct pcmcia_socket *s, struct pccard_io_map *io) { unsigned int sock = container_of(s, struct pcc_socket, socket)->number; if (socket[sock].flags & IS_ALIVE) return -EINVAL; LOCKED(_pcc_set_io_map(sock, io)); } static int pcc_set_mem_map(struct pcmcia_socket *s, struct pccard_mem_map *mem) { unsigned int sock = container_of(s, struct pcc_socket, socket)->number; if (socket[sock].flags & IS_ALIVE) return -EINVAL; LOCKED(_pcc_set_mem_map(sock, mem)); } static int pcc_init(struct pcmcia_socket *s) { pr_debug("m32r_pcc: init call\n"); return 0; } static struct pccard_operations pcc_operations = { .init = pcc_init, .get_status = pcc_get_status, .set_socket = pcc_set_socket, .set_io_map = pcc_set_io_map, .set_mem_map = pcc_set_mem_map, }; /*====================================================================*/ static struct platform_driver pcc_driver = { .driver = { .name = "pcc", .owner = THIS_MODULE, }, }; static struct platform_device pcc_device = { .name = "pcc", .id = 0, }; /*====================================================================*/ static int __init init_m32r_pcc(void) { int i, ret; ret = platform_driver_register(&pcc_driver); if (ret) return ret; ret = platform_device_register(&pcc_device); if (ret){ platform_driver_unregister(&pcc_driver); return ret; } printk(KERN_INFO "m32r PCC probe:\n"); pcc_sockets = 0; add_pcc_socket(M32R_PCC0_BASE, PCC0_IRQ, M32R_PCC0_MAPBASE, 0x1000); #ifdef CONFIG_M32RPCC_SLOT2 add_pcc_socket(M32R_PCC1_BASE, PCC1_IRQ, M32R_PCC1_MAPBASE, 0x2000); #endif if (pcc_sockets == 0) { printk("socket is not found.\n"); platform_device_unregister(&pcc_device); platform_driver_unregister(&pcc_driver); return -ENODEV; } /* Set up interrupt handler(s) */ for (i = 0 ; i < pcc_sockets ; i++) { socket[i].socket.dev.parent = &pcc_device.dev; socket[i].socket.ops = &pcc_operations; socket[i].socket.resource_ops = &pccard_static_ops; socket[i].socket.owner = THIS_MODULE; socket[i].number = i; ret = pcmcia_register_socket(&socket[i].socket); if (!ret) socket[i].flags |= IS_REGISTERED; #if 0 /* driver model ordering issue */ class_device_create_file(&socket[i].socket.dev, &class_device_attr_info); class_device_create_file(&socket[i].socket.dev, &class_device_attr_exca); #endif } /* Finally, schedule a polling interrupt */ if (poll_interval != 0) { poll_timer.function = pcc_interrupt_wrapper; poll_timer.data = 0; init_timer(&poll_timer); poll_timer.expires = jiffies + poll_interval; add_timer(&poll_timer); } return 0; } /* init_m32r_pcc */ static void __exit exit_m32r_pcc(void) { int i; for (i = 0; i < pcc_sockets; i++) if (socket[i].flags & IS_REGISTERED) pcmcia_unregister_socket(&socket[i].socket); platform_device_unregister(&pcc_device); if (poll_interval != 0) del_timer_sync(&poll_timer); platform_driver_unregister(&pcc_driver); } /* exit_m32r_pcc */ module_init(init_m32r_pcc); module_exit(exit_m32r_pcc); MODULE_LICENSE("Dual MPL/GPL"); /*====================================================================*/
gpl-2.0
yajnab/android_kernel_samsung_i8260
arch/mips/loongson/lemote-2f/machtype.c
8740
1639
/* * Copyright (C) 2009 Lemote Inc. * Author: Wu Zhangjin, wuzhangjin@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. */ #include <asm/bootinfo.h> #include <loongson.h> void __init mach_prom_init_machtype(void) { /* We share the same kernel image file among Lemote 2F family * of machines, and provide the machtype= kernel command line * to users to indicate their machine, this command line will * be passed by the latest PMON automatically. and fortunately, * up to now, we can get the machine type from the PMON_VER= * commandline directly except the NAS machine, In the old * machines, this will help the users a lot. * * If no "machtype=" passed, get machine type from "PMON_VER=". * PMON_VER=LM8089 Lemote 8.9'' netbook * LM8101 Lemote 10.1'' netbook * (The above two netbooks have the same kernel support) * LM6XXX Lemote FuLoong(2F) box series * LM9XXX Lemote LynLoong PC series */ if (strstr(arcs_cmdline, "PMON_VER=LM")) { if (strstr(arcs_cmdline, "PMON_VER=LM8")) mips_machtype = MACH_LEMOTE_YL2F89; else if (strstr(arcs_cmdline, "PMON_VER=LM6")) mips_machtype = MACH_LEMOTE_FL2F; else if (strstr(arcs_cmdline, "PMON_VER=LM9")) mips_machtype = MACH_LEMOTE_LL2F; else mips_machtype = MACH_LEMOTE_NAS; strcat(arcs_cmdline, " machtype="); strcat(arcs_cmdline, get_system_type()); strcat(arcs_cmdline, " "); } }
gpl-2.0
pronobis/linux_kernel_arm_N8000
drivers/rtc/rtc-au1xxx.c
10020
3636
/* * Au1xxx counter0 (aka Time-Of-Year counter) RTC interface driver. * * Copyright (C) 2008 Manuel Lauss <mano@roarinelk.homelinux.net> * * 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. */ /* All current Au1xxx SoCs have 2 counters fed by an external 32.768 kHz * crystal. Counter 0, which keeps counting during sleep/powerdown, is * used to count seconds since the beginning of the unix epoch. * * The counters must be configured and enabled by bootloader/board code; * no checks as to whether they really get a proper 32.768kHz clock are * made as this would take far too long. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/rtc.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/io.h> #include <asm/mach-au1x00/au1000.h> /* 32kHz clock enabled and detected */ #define CNTR_OK (SYS_CNTRL_E0 | SYS_CNTRL_32S) static int au1xtoy_rtc_read_time(struct device *dev, struct rtc_time *tm) { unsigned long t; t = au_readl(SYS_TOYREAD); rtc_time_to_tm(t, tm); return rtc_valid_tm(tm); } static int au1xtoy_rtc_set_time(struct device *dev, struct rtc_time *tm) { unsigned long t; rtc_tm_to_time(tm, &t); au_writel(t, SYS_TOYWRITE); au_sync(); /* wait for the pending register write to succeed. This can * take up to 6 seconds... */ while (au_readl(SYS_COUNTER_CNTRL) & SYS_CNTRL_C0S) msleep(1); return 0; } static struct rtc_class_ops au1xtoy_rtc_ops = { .read_time = au1xtoy_rtc_read_time, .set_time = au1xtoy_rtc_set_time, }; static int __devinit au1xtoy_rtc_probe(struct platform_device *pdev) { struct rtc_device *rtcdev; unsigned long t; int ret; t = au_readl(SYS_COUNTER_CNTRL); if (!(t & CNTR_OK)) { dev_err(&pdev->dev, "counters not working; aborting.\n"); ret = -ENODEV; goto out_err; } ret = -ETIMEDOUT; /* set counter0 tickrate to 1Hz if necessary */ if (au_readl(SYS_TOYTRIM) != 32767) { /* wait until hardware gives access to TRIM register */ t = 0x00100000; while ((au_readl(SYS_COUNTER_CNTRL) & SYS_CNTRL_T0S) && --t) msleep(1); if (!t) { /* timed out waiting for register access; assume * counters are unusable. */ dev_err(&pdev->dev, "timeout waiting for access\n"); goto out_err; } /* set 1Hz TOY tick rate */ au_writel(32767, SYS_TOYTRIM); au_sync(); } /* wait until the hardware allows writes to the counter reg */ while (au_readl(SYS_COUNTER_CNTRL) & SYS_CNTRL_C0S) msleep(1); rtcdev = rtc_device_register("rtc-au1xxx", &pdev->dev, &au1xtoy_rtc_ops, THIS_MODULE); if (IS_ERR(rtcdev)) { ret = PTR_ERR(rtcdev); goto out_err; } platform_set_drvdata(pdev, rtcdev); return 0; out_err: return ret; } static int __devexit au1xtoy_rtc_remove(struct platform_device *pdev) { struct rtc_device *rtcdev = platform_get_drvdata(pdev); rtc_device_unregister(rtcdev); platform_set_drvdata(pdev, NULL); return 0; } static struct platform_driver au1xrtc_driver = { .driver = { .name = "rtc-au1xxx", .owner = THIS_MODULE, }, .remove = __devexit_p(au1xtoy_rtc_remove), }; static int __init au1xtoy_rtc_init(void) { return platform_driver_probe(&au1xrtc_driver, au1xtoy_rtc_probe); } static void __exit au1xtoy_rtc_exit(void) { platform_driver_unregister(&au1xrtc_driver); } module_init(au1xtoy_rtc_init); module_exit(au1xtoy_rtc_exit); MODULE_DESCRIPTION("Au1xxx TOY-counter-based RTC driver"); MODULE_AUTHOR("Manuel Lauss <manuel.lauss@gmail.com>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:rtc-au1xxx");
gpl-2.0
InfinitiveOS-Devices/android_kernel_sony_apq8064
drivers/rtc/rtc-au1xxx.c
10020
3636
/* * Au1xxx counter0 (aka Time-Of-Year counter) RTC interface driver. * * Copyright (C) 2008 Manuel Lauss <mano@roarinelk.homelinux.net> * * 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. */ /* All current Au1xxx SoCs have 2 counters fed by an external 32.768 kHz * crystal. Counter 0, which keeps counting during sleep/powerdown, is * used to count seconds since the beginning of the unix epoch. * * The counters must be configured and enabled by bootloader/board code; * no checks as to whether they really get a proper 32.768kHz clock are * made as this would take far too long. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/rtc.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/io.h> #include <asm/mach-au1x00/au1000.h> /* 32kHz clock enabled and detected */ #define CNTR_OK (SYS_CNTRL_E0 | SYS_CNTRL_32S) static int au1xtoy_rtc_read_time(struct device *dev, struct rtc_time *tm) { unsigned long t; t = au_readl(SYS_TOYREAD); rtc_time_to_tm(t, tm); return rtc_valid_tm(tm); } static int au1xtoy_rtc_set_time(struct device *dev, struct rtc_time *tm) { unsigned long t; rtc_tm_to_time(tm, &t); au_writel(t, SYS_TOYWRITE); au_sync(); /* wait for the pending register write to succeed. This can * take up to 6 seconds... */ while (au_readl(SYS_COUNTER_CNTRL) & SYS_CNTRL_C0S) msleep(1); return 0; } static struct rtc_class_ops au1xtoy_rtc_ops = { .read_time = au1xtoy_rtc_read_time, .set_time = au1xtoy_rtc_set_time, }; static int __devinit au1xtoy_rtc_probe(struct platform_device *pdev) { struct rtc_device *rtcdev; unsigned long t; int ret; t = au_readl(SYS_COUNTER_CNTRL); if (!(t & CNTR_OK)) { dev_err(&pdev->dev, "counters not working; aborting.\n"); ret = -ENODEV; goto out_err; } ret = -ETIMEDOUT; /* set counter0 tickrate to 1Hz if necessary */ if (au_readl(SYS_TOYTRIM) != 32767) { /* wait until hardware gives access to TRIM register */ t = 0x00100000; while ((au_readl(SYS_COUNTER_CNTRL) & SYS_CNTRL_T0S) && --t) msleep(1); if (!t) { /* timed out waiting for register access; assume * counters are unusable. */ dev_err(&pdev->dev, "timeout waiting for access\n"); goto out_err; } /* set 1Hz TOY tick rate */ au_writel(32767, SYS_TOYTRIM); au_sync(); } /* wait until the hardware allows writes to the counter reg */ while (au_readl(SYS_COUNTER_CNTRL) & SYS_CNTRL_C0S) msleep(1); rtcdev = rtc_device_register("rtc-au1xxx", &pdev->dev, &au1xtoy_rtc_ops, THIS_MODULE); if (IS_ERR(rtcdev)) { ret = PTR_ERR(rtcdev); goto out_err; } platform_set_drvdata(pdev, rtcdev); return 0; out_err: return ret; } static int __devexit au1xtoy_rtc_remove(struct platform_device *pdev) { struct rtc_device *rtcdev = platform_get_drvdata(pdev); rtc_device_unregister(rtcdev); platform_set_drvdata(pdev, NULL); return 0; } static struct platform_driver au1xrtc_driver = { .driver = { .name = "rtc-au1xxx", .owner = THIS_MODULE, }, .remove = __devexit_p(au1xtoy_rtc_remove), }; static int __init au1xtoy_rtc_init(void) { return platform_driver_probe(&au1xrtc_driver, au1xtoy_rtc_probe); } static void __exit au1xtoy_rtc_exit(void) { platform_driver_unregister(&au1xrtc_driver); } module_init(au1xtoy_rtc_init); module_exit(au1xtoy_rtc_exit); MODULE_DESCRIPTION("Au1xxx TOY-counter-based RTC driver"); MODULE_AUTHOR("Manuel Lauss <manuel.lauss@gmail.com>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:rtc-au1xxx");
gpl-2.0
superr/android_kernel_n9510_n9520
drivers/staging/tidspbridge/dynload/reloc_table_c6000.c
11300
2294
/* * reloc_table_c6000.c * * DSP-BIOS Bridge driver support functions for TI OMAP processors. * * Copyright (C) 2005-2006 Texas Instruments, Inc. * * This package 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 PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* Tables generated for c6000 */ #define HASH_FUNC(zz) (((((zz) + 1) * 1845UL) >> 11) & 63) #define HASH_L(zz) ((zz) >> 8) #define HASH_I(zz) ((zz) & 0xFF) static const u16 rop_map1[] = { 0, 1, 2, 20, 4, 5, 6, 15, 80, 81, 82, 83, 84, 85, 86, 87, 17, 18, 19, 21, 16, 16394, 16404, 65535, 65535, 65535, 65535, 65535, 65535, 32, 65535, 65535, 65535, 65535, 65535, 65535, 40, 112, 113, 65535, 16384, 16385, 16386, 16387, 16388, 16389, 16390, 16391, 16392, 16393, 16395, 16396, 16397, 16398, 16399, 16400, 16401, 16402, 16403, 16405, 16406, 65535, 65535, 65535 }; static const s16 rop_map2[] = { -256, -255, -254, -245, -253, -252, -251, -250, -241, -240, -239, -238, -237, -236, 1813, 5142, -248, -247, 778, -244, -249, -221, -211, -1, -1, -1, -1, -1, -1, -243, -1, -1, -1, -1, -1, -1, -242, -233, -232, -1, -231, -230, -229, -228, -227, -226, -225, -224, -223, 5410, -220, -219, -218, -217, -216, -215, -214, -213, 5676, -210, -209, -1, -1, -1 }; static const u16 rop_action[] = { 2560, 2304, 2304, 2432, 2432, 2560, 2176, 2304, 2560, 3200, 3328, 3584, 3456, 2304, 4208, 20788, 21812, 3415, 3245, 2311, 4359, 19764, 2311, 3191, 3280, 6656, 7680, 8704, 9728, 10752, 11776, 12800, 13824, 14848, 15872, 16896, 17920, 18944, 0, 0, 0, 0, 1536, 1536, 1536, 5632, 512, 0 }; static const u16 rop_info[] = { 0, 35, 35, 35, 35, 35, 35, 35, 35, 39, 39, 39, 39, 35, 34, 283, 299, 4135, 4391, 291, 33059, 283, 295, 4647, 4135, 64, 64, 128, 64, 64, 64, 64, 64, 64, 64, 64, 64, 128, 201, 197, 74, 70, 208, 196, 200, 192, 192, 66 };
gpl-2.0
liudanking/linux-kernel
arch/alpha/kernel/io.c
13860
12416
/* * Alpha IO and memory functions. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/string.h> #include <linux/module.h> #include <asm/io.h> /* Out-of-line versions of the i/o routines that redirect into the platform-specific version. Note that "platform-specific" may mean "generic", which bumps through the machine vector. */ unsigned int ioread8(void __iomem *addr) { unsigned int ret = IO_CONCAT(__IO_PREFIX,ioread8)(addr); mb(); return ret; } unsigned int ioread16(void __iomem *addr) { unsigned int ret = IO_CONCAT(__IO_PREFIX,ioread16)(addr); mb(); return ret; } unsigned int ioread32(void __iomem *addr) { unsigned int ret = IO_CONCAT(__IO_PREFIX,ioread32)(addr); mb(); return ret; } void iowrite8(u8 b, void __iomem *addr) { IO_CONCAT(__IO_PREFIX,iowrite8)(b, addr); mb(); } void iowrite16(u16 b, void __iomem *addr) { IO_CONCAT(__IO_PREFIX,iowrite16)(b, addr); mb(); } void iowrite32(u32 b, void __iomem *addr) { IO_CONCAT(__IO_PREFIX,iowrite32)(b, addr); mb(); } EXPORT_SYMBOL(ioread8); EXPORT_SYMBOL(ioread16); EXPORT_SYMBOL(ioread32); EXPORT_SYMBOL(iowrite8); EXPORT_SYMBOL(iowrite16); EXPORT_SYMBOL(iowrite32); u8 inb(unsigned long port) { return ioread8(ioport_map(port, 1)); } u16 inw(unsigned long port) { return ioread16(ioport_map(port, 2)); } u32 inl(unsigned long port) { return ioread32(ioport_map(port, 4)); } void outb(u8 b, unsigned long port) { iowrite8(b, ioport_map(port, 1)); } void outw(u16 b, unsigned long port) { iowrite16(b, ioport_map(port, 2)); } void outl(u32 b, unsigned long port) { iowrite32(b, ioport_map(port, 4)); } EXPORT_SYMBOL(inb); EXPORT_SYMBOL(inw); EXPORT_SYMBOL(inl); EXPORT_SYMBOL(outb); EXPORT_SYMBOL(outw); EXPORT_SYMBOL(outl); u8 __raw_readb(const volatile void __iomem *addr) { return IO_CONCAT(__IO_PREFIX,readb)(addr); } u16 __raw_readw(const volatile void __iomem *addr) { return IO_CONCAT(__IO_PREFIX,readw)(addr); } u32 __raw_readl(const volatile void __iomem *addr) { return IO_CONCAT(__IO_PREFIX,readl)(addr); } u64 __raw_readq(const volatile void __iomem *addr) { return IO_CONCAT(__IO_PREFIX,readq)(addr); } void __raw_writeb(u8 b, volatile void __iomem *addr) { IO_CONCAT(__IO_PREFIX,writeb)(b, addr); } void __raw_writew(u16 b, volatile void __iomem *addr) { IO_CONCAT(__IO_PREFIX,writew)(b, addr); } void __raw_writel(u32 b, volatile void __iomem *addr) { IO_CONCAT(__IO_PREFIX,writel)(b, addr); } void __raw_writeq(u64 b, volatile void __iomem *addr) { IO_CONCAT(__IO_PREFIX,writeq)(b, addr); } EXPORT_SYMBOL(__raw_readb); EXPORT_SYMBOL(__raw_readw); EXPORT_SYMBOL(__raw_readl); EXPORT_SYMBOL(__raw_readq); EXPORT_SYMBOL(__raw_writeb); EXPORT_SYMBOL(__raw_writew); EXPORT_SYMBOL(__raw_writel); EXPORT_SYMBOL(__raw_writeq); u8 readb(const volatile void __iomem *addr) { u8 ret = __raw_readb(addr); mb(); return ret; } u16 readw(const volatile void __iomem *addr) { u16 ret = __raw_readw(addr); mb(); return ret; } u32 readl(const volatile void __iomem *addr) { u32 ret = __raw_readl(addr); mb(); return ret; } u64 readq(const volatile void __iomem *addr) { u64 ret = __raw_readq(addr); mb(); return ret; } void writeb(u8 b, volatile void __iomem *addr) { __raw_writeb(b, addr); mb(); } void writew(u16 b, volatile void __iomem *addr) { __raw_writew(b, addr); mb(); } void writel(u32 b, volatile void __iomem *addr) { __raw_writel(b, addr); mb(); } void writeq(u64 b, volatile void __iomem *addr) { __raw_writeq(b, addr); mb(); } EXPORT_SYMBOL(readb); EXPORT_SYMBOL(readw); EXPORT_SYMBOL(readl); EXPORT_SYMBOL(readq); EXPORT_SYMBOL(writeb); EXPORT_SYMBOL(writew); EXPORT_SYMBOL(writel); EXPORT_SYMBOL(writeq); /* * Read COUNT 8-bit bytes from port PORT into memory starting at SRC. */ void ioread8_rep(void __iomem *port, void *dst, unsigned long count) { while ((unsigned long)dst & 0x3) { if (!count) return; count--; *(unsigned char *)dst = ioread8(port); dst += 1; } while (count >= 4) { unsigned int w; count -= 4; w = ioread8(port); w |= ioread8(port) << 8; w |= ioread8(port) << 16; w |= ioread8(port) << 24; *(unsigned int *)dst = w; dst += 4; } while (count) { --count; *(unsigned char *)dst = ioread8(port); dst += 1; } } void insb(unsigned long port, void *dst, unsigned long count) { ioread8_rep(ioport_map(port, 1), dst, count); } EXPORT_SYMBOL(ioread8_rep); EXPORT_SYMBOL(insb); /* * Read COUNT 16-bit words from port PORT into memory starting at * SRC. SRC must be at least short aligned. This is used by the * IDE driver to read disk sectors. Performance is important, but * the interfaces seems to be slow: just using the inlined version * of the inw() breaks things. */ void ioread16_rep(void __iomem *port, void *dst, unsigned long count) { if (unlikely((unsigned long)dst & 0x3)) { if (!count) return; BUG_ON((unsigned long)dst & 0x1); count--; *(unsigned short *)dst = ioread16(port); dst += 2; } while (count >= 2) { unsigned int w; count -= 2; w = ioread16(port); w |= ioread16(port) << 16; *(unsigned int *)dst = w; dst += 4; } if (count) { *(unsigned short*)dst = ioread16(port); } } void insw(unsigned long port, void *dst, unsigned long count) { ioread16_rep(ioport_map(port, 2), dst, count); } EXPORT_SYMBOL(ioread16_rep); EXPORT_SYMBOL(insw); /* * Read COUNT 32-bit words from port PORT into memory starting at * SRC. Now works with any alignment in SRC. Performance is important, * but the interfaces seems to be slow: just using the inlined version * of the inl() breaks things. */ void ioread32_rep(void __iomem *port, void *dst, unsigned long count) { if (unlikely((unsigned long)dst & 0x3)) { while (count--) { struct S { int x __attribute__((packed)); }; ((struct S *)dst)->x = ioread32(port); dst += 4; } } else { /* Buffer 32-bit aligned. */ while (count--) { *(unsigned int *)dst = ioread32(port); dst += 4; } } } void insl(unsigned long port, void *dst, unsigned long count) { ioread32_rep(ioport_map(port, 4), dst, count); } EXPORT_SYMBOL(ioread32_rep); EXPORT_SYMBOL(insl); /* * Like insb but in the opposite direction. * Don't worry as much about doing aligned memory transfers: * doing byte reads the "slow" way isn't nearly as slow as * doing byte writes the slow way (no r-m-w cycle). */ void iowrite8_rep(void __iomem *port, const void *xsrc, unsigned long count) { const unsigned char *src = xsrc; while (count--) iowrite8(*src++, port); } void outsb(unsigned long port, const void *src, unsigned long count) { iowrite8_rep(ioport_map(port, 1), src, count); } EXPORT_SYMBOL(iowrite8_rep); EXPORT_SYMBOL(outsb); /* * Like insw but in the opposite direction. This is used by the IDE * driver to write disk sectors. Performance is important, but the * interfaces seems to be slow: just using the inlined version of the * outw() breaks things. */ void iowrite16_rep(void __iomem *port, const void *src, unsigned long count) { if (unlikely((unsigned long)src & 0x3)) { if (!count) return; BUG_ON((unsigned long)src & 0x1); iowrite16(*(unsigned short *)src, port); src += 2; --count; } while (count >= 2) { unsigned int w; count -= 2; w = *(unsigned int *)src; src += 4; iowrite16(w >> 0, port); iowrite16(w >> 16, port); } if (count) { iowrite16(*(unsigned short *)src, port); } } void outsw(unsigned long port, const void *src, unsigned long count) { iowrite16_rep(ioport_map(port, 2), src, count); } EXPORT_SYMBOL(iowrite16_rep); EXPORT_SYMBOL(outsw); /* * Like insl but in the opposite direction. This is used by the IDE * driver to write disk sectors. Works with any alignment in SRC. * Performance is important, but the interfaces seems to be slow: * just using the inlined version of the outl() breaks things. */ void iowrite32_rep(void __iomem *port, const void *src, unsigned long count) { if (unlikely((unsigned long)src & 0x3)) { while (count--) { struct S { int x __attribute__((packed)); }; iowrite32(((struct S *)src)->x, port); src += 4; } } else { /* Buffer 32-bit aligned. */ while (count--) { iowrite32(*(unsigned int *)src, port); src += 4; } } } void outsl(unsigned long port, const void *src, unsigned long count) { iowrite32_rep(ioport_map(port, 4), src, count); } EXPORT_SYMBOL(iowrite32_rep); EXPORT_SYMBOL(outsl); /* * Copy data from IO memory space to "real" memory space. * This needs to be optimized. */ void memcpy_fromio(void *to, const volatile void __iomem *from, long count) { /* Optimize co-aligned transfers. Everything else gets handled a byte at a time. */ if (count >= 8 && ((u64)to & 7) == ((u64)from & 7)) { count -= 8; do { *(u64 *)to = __raw_readq(from); count -= 8; to += 8; from += 8; } while (count >= 0); count += 8; } if (count >= 4 && ((u64)to & 3) == ((u64)from & 3)) { count -= 4; do { *(u32 *)to = __raw_readl(from); count -= 4; to += 4; from += 4; } while (count >= 0); count += 4; } if (count >= 2 && ((u64)to & 1) == ((u64)from & 1)) { count -= 2; do { *(u16 *)to = __raw_readw(from); count -= 2; to += 2; from += 2; } while (count >= 0); count += 2; } while (count > 0) { *(u8 *) to = __raw_readb(from); count--; to++; from++; } mb(); } EXPORT_SYMBOL(memcpy_fromio); /* * Copy data from "real" memory space to IO memory space. * This needs to be optimized. */ void memcpy_toio(volatile void __iomem *to, const void *from, long count) { /* Optimize co-aligned transfers. Everything else gets handled a byte at a time. */ /* FIXME -- align FROM. */ if (count >= 8 && ((u64)to & 7) == ((u64)from & 7)) { count -= 8; do { __raw_writeq(*(const u64 *)from, to); count -= 8; to += 8; from += 8; } while (count >= 0); count += 8; } if (count >= 4 && ((u64)to & 3) == ((u64)from & 3)) { count -= 4; do { __raw_writel(*(const u32 *)from, to); count -= 4; to += 4; from += 4; } while (count >= 0); count += 4; } if (count >= 2 && ((u64)to & 1) == ((u64)from & 1)) { count -= 2; do { __raw_writew(*(const u16 *)from, to); count -= 2; to += 2; from += 2; } while (count >= 0); count += 2; } while (count > 0) { __raw_writeb(*(const u8 *) from, to); count--; to++; from++; } mb(); } EXPORT_SYMBOL(memcpy_toio); /* * "memset" on IO memory space. */ void _memset_c_io(volatile void __iomem *to, unsigned long c, long count) { /* Handle any initial odd byte */ if (count > 0 && ((u64)to & 1)) { __raw_writeb(c, to); to++; count--; } /* Handle any initial odd halfword */ if (count >= 2 && ((u64)to & 2)) { __raw_writew(c, to); to += 2; count -= 2; } /* Handle any initial odd word */ if (count >= 4 && ((u64)to & 4)) { __raw_writel(c, to); to += 4; count -= 4; } /* Handle all full-sized quadwords: we're aligned (or have a small count) */ count -= 8; if (count >= 0) { do { __raw_writeq(c, to); to += 8; count -= 8; } while (count >= 0); } count += 8; /* The tail is word-aligned if we still have count >= 4 */ if (count >= 4) { __raw_writel(c, to); to += 4; count -= 4; } /* The tail is half-word aligned if we have count >= 2 */ if (count >= 2) { __raw_writew(c, to); to += 2; count -= 2; } /* And finally, one last byte.. */ if (count) { __raw_writeb(c, to); } mb(); } EXPORT_SYMBOL(_memset_c_io); /* A version of memcpy used by the vga console routines to move data around arbitrarily between screen and main memory. */ void scr_memcpyw(u16 *d, const u16 *s, unsigned int count) { const u16 __iomem *ios = (const u16 __iomem *) s; u16 __iomem *iod = (u16 __iomem *) d; int s_isio = __is_ioaddr(s); int d_isio = __is_ioaddr(d); if (s_isio) { if (d_isio) { /* FIXME: Should handle unaligned ops and operation widening. */ count /= 2; while (count--) { u16 tmp = __raw_readw(ios++); __raw_writew(tmp, iod++); } } else memcpy_fromio(d, ios, count); } else { if (d_isio) memcpy_toio(iod, s, count); else memcpy(d, s, count); } } EXPORT_SYMBOL(scr_memcpyw); void __iomem *ioport_map(unsigned long port, unsigned int size) { return IO_CONCAT(__IO_PREFIX,ioportmap) (port); } void ioport_unmap(void __iomem *addr) { } EXPORT_SYMBOL(ioport_map); EXPORT_SYMBOL(ioport_unmap);
gpl-2.0
aviksil/xbmc-eden-flattened-linaro
lib/liblame/ACM/ACMStream.cpp
37
12584
/** * * Lame ACM wrapper, encode/decode MP3 based RIFF/AVI files in MS Windows * * Copyright (c) 2002 Steve Lhomme <steve.lhomme at free.fr> * * This 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /*! \author Steve Lhomme \version \$Id: ACMStream.cpp,v 1.12.2.1 2008/11/01 20:41:47 robert Exp $ */ #if !defined(STRICT) #define STRICT #endif // STRICT #include <assert.h> #include <windows.h> #include "adebug.h" #include "ACMStream.h" #include <lame.h> // static methods ACMStream * ACMStream::Create() { ACMStream * Result; Result = new ACMStream; return Result; } const bool ACMStream::Erase(const ACMStream * a_ACMStream) { delete a_ACMStream; return true; } // class methods ACMStream::ACMStream() : m_WorkingBufferUseSize(0), gfp(NULL) { /// \todo get the debug level from the registry my_debug = new ADbg(DEBUG_LEVEL_CREATION); if (my_debug != NULL) { unsigned char DebugFileName[512]; my_debug->setPrefix("LAMEstream"); /// \todo get it from the registry my_debug->setIncludeTime(true); /// \todo get it from the registry // Check in the registry if we have to Output Debug information DebugFileName[0] = '\0'; HKEY OssKey; if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, "SOFTWARE\\MUKOLI", 0, KEY_READ , &OssKey ) == ERROR_SUCCESS) { DWORD DataType; DWORD DebugFileNameSize = 512; if (RegQueryValueEx( OssKey, "DebugFile", NULL, &DataType, DebugFileName, &DebugFileNameSize ) == ERROR_SUCCESS) { if (DataType == REG_SZ) { my_debug->setUseFile(true); my_debug->setDebugFile((char *)DebugFileName); my_debug->OutPut("Debug file is %s",(char *)DebugFileName); } } } my_debug->OutPut(DEBUG_LEVEL_FUNC_START, "ACMStream Creation (0X%08X)",this); } else { ADbg debug; debug.OutPut("ACMStream::ACMACMStream : Impossible to create my_debug"); } } ACMStream::~ACMStream() { // release memory - encoding is finished if (gfp) lame_close( gfp ); if (my_debug != NULL) { my_debug->OutPut(DEBUG_LEVEL_FUNC_START, "ACMStream Deletion (0X%08X)",this); delete my_debug; } } bool ACMStream::init(const int nSamplesPerSec, const int nOutputSamplesPerSec, const int nChannels, const int nAvgBytesPerSec, const vbr_mode mode) { bool bResult = false; my_SamplesPerSec = nSamplesPerSec; my_OutBytesPerSec = nOutputSamplesPerSec; my_Channels = nChannels; my_AvgBytesPerSec = nAvgBytesPerSec; my_VBRMode = mode; bResult = true; return bResult; } bool ACMStream::open(const AEncodeProperties & the_Properties) { bool bResult = false; // Init the MP3 Stream // Init the global flags structure gfp = lame_init(); // Set input sample frequency lame_set_in_samplerate( gfp, my_SamplesPerSec ); // Set output sample frequency lame_set_out_samplerate( gfp, my_OutBytesPerSec ); lame_set_num_channels( gfp, my_Channels ); if (my_Channels == 1) lame_set_mode( gfp, MONO ); else lame_set_mode( gfp, (MPEG_mode_e)the_Properties.GetChannelModeValue()) ; /// \todo Get the mode from the default configuration // lame_set_VBR( gfp, vbr_off ); /// \note VBR not supported for the moment lame_set_VBR( gfp, my_VBRMode ); /// \note VBR not supported for the moment if (my_VBRMode == vbr_abr) { lame_set_VBR_q( gfp, 1 ); lame_set_VBR_mean_bitrate_kbps( gfp, (my_AvgBytesPerSec * 8 + 500) / 1000 ); if (24000 > lame_get_in_samplerate( gfp )) { // For MPEG-II lame_set_VBR_min_bitrate_kbps( gfp, 8); lame_set_VBR_max_bitrate_kbps( gfp, 160); } else { // For MPEG-I lame_set_VBR_min_bitrate_kbps( gfp, 32); lame_set_VBR_max_bitrate_kbps( gfp, 320); } } // Set bitrate lame_set_brate( gfp, my_AvgBytesPerSec * 8 / 1000 ); /// \todo Get the mode from the default configuration // Set copyright flag? lame_set_copyright( gfp, the_Properties.GetCopyrightMode()?1:0 ); // Do we have to tag it as non original lame_set_original( gfp, the_Properties.GetOriginalMode()?1:0 ); // Add CRC? lame_set_error_protection( gfp, the_Properties.GetCRCMode()?1:0 ); // Set private bit? lame_set_extension( gfp, the_Properties.GetPrivateMode()?1:0 ); // INFO tag support not possible in ACM - it requires rewinding // output stream to the beginning after encoding is finished. lame_set_bWriteVbrTag( gfp, 0 ); if (0 == lame_init_params( gfp )) { //LAME encoding call will accept any number of samples. if ( 0 == lame_get_version( gfp ) ) { // For MPEG-II, only 576 samples per frame per channel my_SamplesPerBlock = 576 * lame_get_num_channels( gfp ); } else { // For MPEG-I, 1152 samples per frame per channel my_SamplesPerBlock = 1152 * lame_get_num_channels( gfp ); } } my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "version =%d",lame_get_version( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Layer =3"); switch ( lame_get_mode( gfp ) ) { case STEREO: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Stereo" ); break; case JOINT_STEREO: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Joint-Stereo" ); break; case DUAL_CHANNEL: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Forced Stereo" ); break; case MONO: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Mono" ); break; case NOT_SET: /* FALLTROUGH */ default: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Error (unknown)" ); break; } my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "sampling frequency =%.1f kHz", lame_get_in_samplerate( gfp ) /1000.0 ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "bitrate =%d kbps", lame_get_brate( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Vbr Min bitrate =%d kbps", lame_get_VBR_min_bitrate_kbps( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Vbr Max bitrate =%d kbps", lame_get_VBR_max_bitrate_kbps( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Quality Setting =%d", lame_get_quality( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Low pass frequency =%d", lame_get_lowpassfreq( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Low pass width =%d", lame_get_lowpasswidth( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "High pass frequency =%d", lame_get_highpassfreq( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "High pass width =%d", lame_get_highpasswidth( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "No Short Blocks =%d", lame_get_no_short_blocks( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "de-emphasis =%d", lame_get_emphasis( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "private flag =%d", lame_get_extension( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "copyright flag =%d", lame_get_copyright( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "original flag =%d", lame_get_original( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "CRC =%s", lame_get_error_protection( gfp ) ? "on" : "off" ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Fast mode =%s", ( lame_get_quality( gfp ) )? "enabled" : "disabled" ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Force mid/side stereo =%s", ( lame_get_force_ms( gfp ) )?"enabled":"disabled" ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Disable Resorvoir =%d", lame_get_disable_reservoir( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "VBR =%s, VBR_q =%d, VBR method =", ( lame_get_VBR( gfp ) !=vbr_off ) ? "enabled": "disabled", lame_get_VBR_q( gfp ) ); switch ( lame_get_VBR( gfp ) ) { case vbr_off: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_off" ); break; case vbr_mt : my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_mt" ); break; case vbr_rh : my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_rh" ); break; case vbr_mtrh: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_mtrh" ); break; case vbr_abr: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_abr (average bitrate %d kbps)", lame_get_VBR_mean_bitrate_kbps( gfp ) ); break; default: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "error, unknown VBR setting"); break; } my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Write VBR Header =%s\n", ( lame_get_bWriteVbrTag( gfp ) ) ?"Yes":"No"); #ifdef FROM_DLL beConfig.format.LHV1.dwReSampleRate = my_OutBytesPerSec; // force the user resampling #endif // FROM_DLL bResult = true; return bResult; } bool ACMStream::close(LPBYTE pOutputBuffer, DWORD *pOutputSize) { bool bResult = false; int nOutputSamples = 0; nOutputSamples = lame_encode_flush( gfp, pOutputBuffer, 0 ); if ( nOutputSamples < 0 ) { // BUFFER_TOO_SMALL *pOutputSize = 0; } else { *pOutputSize = nOutputSamples; bResult = true; } // lame will be closed in destructor //lame_close( gfp ); return bResult; } DWORD ACMStream::GetOutputSizeForInput(const DWORD the_SrcLength) const { /* double OutputInputRatio; if (my_VBRMode == vbr_off) OutputInputRatio = double(my_AvgBytesPerSec) / double(my_OutBytesPerSec * 2); else // reserve the space for 320 kbps OutputInputRatio = 40000.0 / double(my_OutBytesPerSec * 2); OutputInputRatio *= 1.15; // allow 15% more*/ DWORD Result; // Result = DWORD(double(the_SrcLength) * OutputInputRatio); Result = DWORD(1.25*the_SrcLength + 7200); my_debug->OutPut(DEBUG_LEVEL_FUNC_CODE, "Result = %d",Result); return Result; } bool ACMStream::ConvertBuffer(LPACMDRVSTREAMHEADER a_StreamHeader) { bool result; if (my_debug != NULL) { my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "enter ACMStream::ConvertBuffer"); } DWORD InSize = a_StreamHeader->cbSrcLength / 2, OutSize = a_StreamHeader->cbDstLength; // 2 for 8<->16 bits // Encode it int dwSamples; int nOutputSamples = 0; dwSamples = InSize / lame_get_num_channels( gfp ); if ( 1 == lame_get_num_channels( gfp ) ) { nOutputSamples = lame_encode_buffer(gfp,(PSHORT)a_StreamHeader->pbSrc,(PSHORT)a_StreamHeader->pbSrc,dwSamples,a_StreamHeader->pbDst,a_StreamHeader->cbDstLength); } else { nOutputSamples = lame_encode_buffer_interleaved(gfp,(PSHORT)a_StreamHeader->pbSrc,dwSamples,a_StreamHeader->pbDst,a_StreamHeader->cbDstLength); } a_StreamHeader->cbSrcLengthUsed = a_StreamHeader->cbSrcLength; a_StreamHeader->cbDstLengthUsed = nOutputSamples; result = a_StreamHeader->cbDstLengthUsed <= a_StreamHeader->cbDstLength; my_debug->OutPut(DEBUG_LEVEL_FUNC_CODE, "UsedSize = %d / EncodedSize = %d, result = %d (%d <= %d)", InSize, OutSize, result, a_StreamHeader->cbDstLengthUsed, a_StreamHeader->cbDstLength); if (my_debug != NULL) { my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "ACMStream::ConvertBuffer result = %d (0x%02X 0x%02X)",result,a_StreamHeader->pbDst[0],a_StreamHeader->pbDst[1]); } return result; } /* map frequency to a valid MP3 sample frequency * * Robert Hegemann 2000-07-01 */ static int map2MP3Frequency(int freq) { if (freq <= 8000) return 8000; if (freq <= 11025) return 11025; if (freq <= 12000) return 12000; if (freq <= 16000) return 16000; if (freq <= 22050) return 22050; if (freq <= 24000) return 24000; if (freq <= 32000) return 32000; if (freq <= 44100) return 44100; return 48000; } unsigned int ACMStream::GetOutputSampleRate(int samples_per_sec, int bitrate, int channels) { if (bitrate==0) bitrate = (64000*channels)/8; /// \todo pass through the same LAME routine unsigned int OutputFrequency; double compression_ratio = double(samples_per_sec * 16 * channels / (bitrate * 8)); if (compression_ratio > 13.) OutputFrequency = map2MP3Frequency( int((10. * bitrate * 8) / (16 * channels))); else OutputFrequency = map2MP3Frequency( int(0.97 * samples_per_sec) ); return OutputFrequency; }
gpl-2.0
jefby/uboot-arndale-octa-hyp
board/freescale/p1_p2_rdb/p1_p2_rdb.c
37
7999
/* * Copyright 2009-2011 Freescale Semiconductor, Inc. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <command.h> #include <asm/processor.h> #include <asm/mmu.h> #include <asm/cache.h> #include <asm/immap_85xx.h> #include <asm/fsl_serdes.h> #include <asm/io.h> #include <miiphy.h> #include <libfdt.h> #include <fdt_support.h> #include <fsl_mdio.h> #include <tsec.h> #include <vsc7385.h> #include <netdev.h> #include <rtc.h> #include <i2c.h> #include <hwconfig.h> DECLARE_GLOBAL_DATA_PTR; #define VSC7385_RST_SET 0x00080000 #define SLIC_RST_SET 0x00040000 #define SGMII_PHY_RST_SET 0x00020000 #define PCIE_RST_SET 0x00010000 #define RGMII_PHY_RST_SET 0x02000000 #define USB_RST_CLR 0x04000000 #define USB2_PORT_OUT_EN 0x01000000 #define GPIO_DIR 0x060f0000 #define BOARD_PERI_RST_SET VSC7385_RST_SET | SLIC_RST_SET | \ SGMII_PHY_RST_SET | PCIE_RST_SET | \ RGMII_PHY_RST_SET #define SYSCLK_MASK 0x00200000 #define BOARDREV_MASK 0x10100000 #define BOARDREV_C 0x00100000 #define BOARDREV_D 0x00000000 #define SYSCLK_66 66666666 #define SYSCLK_100 100000000 unsigned long get_board_sys_clk(ulong dummy) { volatile ccsr_gpio_t *pgpio = (void *)(CONFIG_SYS_MPC85xx_GPIO_ADDR); u32 val_gpdat, sysclk_gpio; val_gpdat = in_be32(&pgpio->gpdat); sysclk_gpio = val_gpdat & SYSCLK_MASK; if(sysclk_gpio == 0) return SYSCLK_66; else return SYSCLK_100; return 0; } #ifdef CONFIG_MMC int board_early_init_f (void) { volatile ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); setbits_be32(&gur->pmuxcr, (MPC85xx_PMUXCR_SDHC_CD | MPC85xx_PMUXCR_SDHC_WP)); return 0; } #endif int checkboard (void) { u32 val_gpdat, board_rev_gpio; volatile ccsr_gpio_t *pgpio = (void *)(CONFIG_SYS_MPC85xx_GPIO_ADDR); char board_rev = 0; struct cpu_type *cpu; val_gpdat = in_be32(&pgpio->gpdat); board_rev_gpio = val_gpdat & BOARDREV_MASK; if (board_rev_gpio == BOARDREV_C) board_rev = 'C'; else if (board_rev_gpio == BOARDREV_D) board_rev = 'D'; else panic ("Unexpected Board REV %x detected!!\n", board_rev_gpio); cpu = gd->arch.cpu; printf ("Board: %sRDB Rev%c\n", cpu->name, board_rev); setbits_be32(&pgpio->gpdir, GPIO_DIR); /* * Bringing the following peripherals out of reset via GPIOs * 0 = reset and 1 = out of reset * GPIO12 - Reset to Ethernet Switch * GPIO13 - Reset to SLIC/SLAC devices * GPIO14 - Reset to SGMII_PHY_N * GPIO15 - Reset to PCIe slots * GPIO6 - Reset to RGMII PHY * GPIO5 - Reset to USB3300 devices 1 = reset and 0 = out of reset */ clrsetbits_be32(&pgpio->gpdat, USB_RST_CLR, BOARD_PERI_RST_SET); return 0; } int misc_init_r(void) { #if defined(CONFIG_SDCARD) || defined(CONFIG_SPIFLASH) ccsr_gur_t *gur = (void *)CONFIG_SYS_MPC85xx_GUTS_ADDR; ccsr_gpio_t *gpio = (void *)CONFIG_SYS_MPC85xx_GPIO_ADDR; setbits_be32(&gpio->gpdir, USB2_PORT_OUT_EN); setbits_be32(&gpio->gpdat, USB2_PORT_OUT_EN); setbits_be32(&gur->pmuxcr, MPC85xx_PMUXCR_ELBC_OFF_USB2_ON); #endif return 0; } int board_early_init_r(void) { const unsigned int flashbase = CONFIG_SYS_FLASH_BASE; const u8 flash_esel = find_tlb_idx((void *)flashbase, 1); volatile ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); unsigned int orig_bus = i2c_get_bus_num(); u8 i2c_data; i2c_set_bus_num(1); if (i2c_read(CONFIG_SYS_I2C_PCA9557_ADDR, 0, 1, &i2c_data, sizeof(i2c_data)) == 0) { if (i2c_data & 0x2) puts("NOR Flash Bank : Secondary\n"); else puts("NOR Flash Bank : Primary\n"); if (i2c_data & 0x1) { setbits_be32(&gur->pmuxcr, MPC85xx_PMUXCR_SD_DATA); puts("SD/MMC : 8-bit Mode\n"); puts("eSPI : Disabled\n"); } else { puts("SD/MMC : 4-bit Mode\n"); puts("eSPI : Enabled\n"); } } else { puts("Failed reading I2C Chip 0x18 on bus 1\n"); } i2c_set_bus_num(orig_bus); /* * Remap Boot flash region to caching-inhibited * so that flash can be erased properly. */ /* Flush d-cache and invalidate i-cache of any FLASH data */ flush_dcache(); invalidate_icache(); /* invalidate existing TLB entry for flash */ disable_tlb(flash_esel); set_tlb(1, flashbase, CONFIG_SYS_FLASH_BASE_PHYS, MAS3_SX|MAS3_SW|MAS3_SR, MAS2_I|MAS2_G, 0, flash_esel, BOOKE_PAGESZ_16M, 1); rtc_reset(); return 0; } #ifdef CONFIG_TSEC_ENET int board_eth_init(bd_t *bis) { struct fsl_pq_mdio_info mdio_info; struct tsec_info_struct tsec_info[4]; int num = 0; char *tmp; unsigned int vscfw_addr; #ifdef CONFIG_TSEC1 SET_STD_TSEC_INFO(tsec_info[num], 1); num++; #endif #ifdef CONFIG_TSEC2 SET_STD_TSEC_INFO(tsec_info[num], 2); num++; #endif #ifdef CONFIG_TSEC3 SET_STD_TSEC_INFO(tsec_info[num], 3); if (is_serdes_configured(SGMII_TSEC3)) { puts("eTSEC3 is in sgmii mode.\n"); tsec_info[num].flags |= TSEC_SGMII; } num++; #endif if (!num) { printf("No TSECs initialized\n"); return 0; } #ifdef CONFIG_VSC7385_ENET /* If a VSC7385 microcode image is present, then upload it. */ if ((tmp = getenv ("vscfw_addr")) != NULL) { vscfw_addr = simple_strtoul (tmp, NULL, 16); printf("uploading VSC7385 microcode from %x\n", vscfw_addr); if (vsc7385_upload_firmware((void *) vscfw_addr, CONFIG_VSC7385_IMAGE_SIZE)) puts("Failure uploading VSC7385 microcode.\n"); } else puts("No address specified for VSC7385 microcode.\n"); #endif mdio_info.regs = (struct tsec_mii_mng *)CONFIG_SYS_MDIO_BASE_ADDR; mdio_info.name = DEFAULT_MII_NAME; fsl_pq_mdio_init(bis, &mdio_info); tsec_eth_init(bis, tsec_info, num); return pci_eth_init(bis); } #endif #if defined(CONFIG_OF_BOARD_SETUP) extern void ft_pci_board_setup(void *blob); void ft_board_setup(void *blob, bd_t *bd) { const char *soc_usb_compat = "fsl-usb2-dr"; int err, usb1_off, usb2_off; phys_addr_t base; phys_size_t size; ft_cpu_setup(blob, bd); base = getenv_bootm_low(); size = getenv_bootm_size(); #if defined(CONFIG_PCI) ft_pci_board_setup(blob); #endif /* #if defined(CONFIG_PCI) */ fdt_fixup_memory(blob, (u64)base, (u64)size); #if defined(CONFIG_HAS_FSL_DR_USB) fdt_fixup_dr_usb(blob, bd); #endif #if defined(CONFIG_SDCARD) || defined(CONFIG_SPIFLASH) /* Delete eLBC node as it is muxed with USB2 controller */ if (hwconfig("usb2")) { const char *soc_elbc_compat = "fsl,p1020-elbc"; int off = fdt_node_offset_by_compatible(blob, -1, soc_elbc_compat); if (off < 0) { printf("WARNING: could not find compatible node" " %s: %s.\n", soc_elbc_compat, fdt_strerror(off)); return; } err = fdt_del_node(blob, off); if (err < 0) { printf("WARNING: could not remove %s: %s.\n", soc_elbc_compat, fdt_strerror(err)); } return; } #endif /* Delete USB2 node as it is muxed with eLBC */ usb1_off = fdt_node_offset_by_compatible(blob, -1, soc_usb_compat); if (usb1_off < 0) { printf("WARNING: could not find compatible node" " %s: %s.\n", soc_usb_compat, fdt_strerror(usb1_off)); return; } usb2_off = fdt_node_offset_by_compatible(blob, usb1_off, soc_usb_compat); if (usb2_off < 0) { printf("WARNING: could not find compatible node" " %s: %s.\n", soc_usb_compat, fdt_strerror(usb2_off)); return; } err = fdt_del_node(blob, usb2_off); if (err < 0) printf("WARNING: could not remove %s: %s.\n", soc_usb_compat, fdt_strerror(err)); } #endif
gpl-2.0
MyAOSP/kernel_htc_msm8960
drivers/ata/ata_piix.c
37
51671
/* * ata_piix.c - Intel PATA/SATA controllers * * Maintained by: Jeff Garzik <jgarzik@pobox.com> * Please ALWAYS copy linux-ide@vger.kernel.org * on emails. * * * Copyright 2003-2005 Red Hat Inc * Copyright 2003-2005 Jeff Garzik * * * Copyright header from piix.c: * * Copyright (C) 1998-1999 Andrzej Krzysztofowicz, Author and Maintainer * Copyright (C) 1998-2000 Andre Hedrick <andre@linux-ide.org> * Copyright (C) 2003 Red Hat Inc * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * * * libata documentation is available via 'make {ps|pdf}docs', * as Documentation/DocBook/libata.* * * Hardware documentation available at http://developer.intel.com/ * * Documentation * Publicly available from Intel web site. Errata documentation * is also publicly available. As an aide to anyone hacking on this * driver the list of errata that are relevant is below, going back to * PIIX4. Older device documentation is now a bit tricky to find. * * The chipsets all follow very much the same design. The original Triton * series chipsets do _not_ support independent device timings, but this * is fixed in Triton II. With the odd mobile exception the chips then * change little except in gaining more modes until SATA arrives. This * driver supports only the chips with independent timing (that is those * with SITRE and the 0x44 timing register). See pata_oldpiix and pata_mpiix * for the early chip drivers. * * Errata of note: * * Unfixable * PIIX4 errata #9 - Only on ultra obscure hw * ICH3 errata #13 - Not observed to affect real hw * by Intel * * Things we must deal with * PIIX4 errata #10 - BM IDE hang with non UDMA * (must stop/start dma to recover) * 440MX errata #15 - As PIIX4 errata #10 * PIIX4 errata #15 - Must not read control registers * during a PIO transfer * 440MX errata #13 - As PIIX4 errata #15 * ICH2 errata #21 - DMA mode 0 doesn't work right * ICH0/1 errata #55 - As ICH2 errata #21 * ICH2 spec c #9 - Extra operations needed to handle * drive hotswap [NOT YET SUPPORTED] * ICH2 spec c #20 - IDE PRD must not cross a 64K boundary * and must be dword aligned * ICH2 spec c #24 - UDMA mode 4,5 t85/86 should be 6ns not 3.3 * ICH7 errata #16 - MWDMA1 timings are incorrect * * Should have been BIOS fixed: * 450NX: errata #19 - DMA hangs on old 450NX * 450NX: errata #20 - DMA hangs on old 450NX * 450NX: errata #25 - Corruption with DMA on old 450NX * ICH3 errata #15 - IDE deadlock under high load * (BIOS must set dev 31 fn 0 bit 23) * ICH3 errata #18 - Don't use native mode */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/gfp.h> #include <scsi/scsi_host.h> #include <linux/libata.h> #include <linux/dmi.h> #define DRV_NAME "ata_piix" #define DRV_VERSION "2.13" enum { PIIX_IOCFG = 0x54, /* IDE I/O configuration register */ ICH5_PMR = 0x90, /* port mapping register */ ICH5_PCS = 0x92, /* port control and status */ PIIX_SIDPR_BAR = 5, PIIX_SIDPR_LEN = 16, PIIX_SIDPR_IDX = 0, PIIX_SIDPR_DATA = 4, PIIX_FLAG_CHECKINTR = (1 << 28), /* make sure PCI INTx enabled */ PIIX_FLAG_SIDPR = (1 << 29), /* SATA idx/data pair regs */ PIIX_PATA_FLAGS = ATA_FLAG_SLAVE_POSS, PIIX_SATA_FLAGS = ATA_FLAG_SATA | PIIX_FLAG_CHECKINTR, PIIX_FLAG_PIO16 = (1 << 30), /*support 16bit PIO only*/ PIIX_80C_PRI = (1 << 5) | (1 << 4), PIIX_80C_SEC = (1 << 7) | (1 << 6), /* constants for mapping table */ P0 = 0, /* port 0 */ P1 = 1, /* port 1 */ P2 = 2, /* port 2 */ P3 = 3, /* port 3 */ IDE = -1, /* IDE */ NA = -2, /* not available */ RV = -3, /* reserved */ PIIX_AHCI_DEVICE = 6, /* host->flags bits */ PIIX_HOST_BROKEN_SUSPEND = (1 << 24), }; enum piix_controller_ids { /* controller IDs */ piix_pata_mwdma, /* PIIX3 MWDMA only */ piix_pata_33, /* PIIX4 at 33Mhz */ ich_pata_33, /* ICH up to UDMA 33 only */ ich_pata_66, /* ICH up to 66 Mhz */ ich_pata_100, /* ICH up to UDMA 100 */ ich_pata_100_nomwdma1, /* ICH up to UDMA 100 but with no MWDMA1*/ ich5_sata, ich6_sata, ich6m_sata, ich8_sata, ich8_2port_sata, ich8m_apple_sata, /* locks up on second port enable */ tolapai_sata, piix_pata_vmw, /* PIIX4 for VMware, spurious DMA_ERR */ ich8_sata_snb, ich8_2port_sata_snb, ich8_2port_sata_byt, }; struct piix_map_db { const u32 mask; const u16 port_enable; const int map[][4]; }; struct piix_host_priv { const int *map; u32 saved_iocfg; void __iomem *sidpr; }; static int piix_init_one(struct pci_dev *pdev, const struct pci_device_id *ent); static void piix_remove_one(struct pci_dev *pdev); static int piix_pata_prereset(struct ata_link *link, unsigned long deadline); static void piix_set_piomode(struct ata_port *ap, struct ata_device *adev); static void piix_set_dmamode(struct ata_port *ap, struct ata_device *adev); static void ich_set_dmamode(struct ata_port *ap, struct ata_device *adev); static int ich_pata_cable_detect(struct ata_port *ap); static u8 piix_vmw_bmdma_status(struct ata_port *ap); static int piix_sidpr_scr_read(struct ata_link *link, unsigned int reg, u32 *val); static int piix_sidpr_scr_write(struct ata_link *link, unsigned int reg, u32 val); static int piix_sidpr_set_lpm(struct ata_link *link, enum ata_lpm_policy policy, unsigned hints); static bool piix_irq_check(struct ata_port *ap); static int piix_port_start(struct ata_port *ap); #ifdef CONFIG_PM static int piix_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg); static int piix_pci_device_resume(struct pci_dev *pdev); #endif static unsigned int in_module_init = 1; static const struct pci_device_id piix_pci_tbl[] = { /* Intel PIIX3 for the 430HX etc */ { 0x8086, 0x7010, PCI_ANY_ID, PCI_ANY_ID, 0, 0, piix_pata_mwdma }, /* VMware ICH4 */ { 0x8086, 0x7111, 0x15ad, 0x1976, 0, 0, piix_pata_vmw }, /* Intel PIIX4 for the 430TX/440BX/MX chipset: UDMA 33 */ /* Also PIIX4E (fn3 rev 2) and PIIX4M (fn3 rev 3) */ { 0x8086, 0x7111, PCI_ANY_ID, PCI_ANY_ID, 0, 0, piix_pata_33 }, /* Intel PIIX4 */ { 0x8086, 0x7199, PCI_ANY_ID, PCI_ANY_ID, 0, 0, piix_pata_33 }, /* Intel PIIX4 */ { 0x8086, 0x7601, PCI_ANY_ID, PCI_ANY_ID, 0, 0, piix_pata_33 }, /* Intel PIIX */ { 0x8086, 0x84CA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, piix_pata_33 }, /* Intel ICH (i810, i815, i840) UDMA 66*/ { 0x8086, 0x2411, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_66 }, /* Intel ICH0 : UDMA 33*/ { 0x8086, 0x2421, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_33 }, /* Intel ICH2M */ { 0x8086, 0x244A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* Intel ICH2 (i810E2, i845, 850, 860) UDMA 100 */ { 0x8086, 0x244B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* Intel ICH3M */ { 0x8086, 0x248A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* Intel ICH3 (E7500/1) UDMA 100 */ { 0x8086, 0x248B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* Intel ICH4-L */ { 0x8086, 0x24C1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* Intel ICH4 (i845GV, i845E, i852, i855) UDMA 100 */ { 0x8086, 0x24CA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, { 0x8086, 0x24CB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* Intel ICH5 */ { 0x8086, 0x24DB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* C-ICH (i810E2) */ { 0x8086, 0x245B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* ESB (855GME/875P + 6300ESB) UDMA 100 */ { 0x8086, 0x25A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* ICH6 (and 6) (i915) UDMA 100 */ { 0x8086, 0x266F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* ICH7/7-R (i945, i975) UDMA 100*/ { 0x8086, 0x27DF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100_nomwdma1 }, { 0x8086, 0x269E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100_nomwdma1 }, /* ICH8 Mobile PATA Controller */ { 0x8086, 0x2850, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich_pata_100 }, /* SATA ports */ /* 82801EB (ICH5) */ { 0x8086, 0x24d1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich5_sata }, /* 82801EB (ICH5) */ { 0x8086, 0x24df, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich5_sata }, /* 6300ESB (ICH5 variant with broken PCS present bits) */ { 0x8086, 0x25a3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich5_sata }, /* 6300ESB pretending RAID */ { 0x8086, 0x25b0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich5_sata }, /* 82801FB/FW (ICH6/ICH6W) */ { 0x8086, 0x2651, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich6_sata }, /* 82801FR/FRW (ICH6R/ICH6RW) */ { 0x8086, 0x2652, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich6_sata }, /* 82801FBM ICH6M (ICH6R with only port 0 and 2 implemented). * Attach iff the controller is in IDE mode. */ { 0x8086, 0x2653, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE << 8, 0xffff00, ich6m_sata }, /* 82801GB/GR/GH (ICH7, identical to ICH6) */ { 0x8086, 0x27c0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich6_sata }, /* 2801GBM/GHM (ICH7M, identical to ICH6M) */ { 0x8086, 0x27c4, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich6m_sata }, /* Enterprise Southbridge 2 (631xESB/632xESB) */ { 0x8086, 0x2680, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich6_sata }, /* SATA Controller 1 IDE (ICH8) */ { 0x8086, 0x2820, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller 2 IDE (ICH8) */ { 0x8086, 0x2825, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* Mobile SATA Controller IDE (ICH8M), Apple */ { 0x8086, 0x2828, 0x106b, 0x00a0, 0, 0, ich8m_apple_sata }, { 0x8086, 0x2828, 0x106b, 0x00a1, 0, 0, ich8m_apple_sata }, { 0x8086, 0x2828, 0x106b, 0x00a3, 0, 0, ich8m_apple_sata }, /* Mobile SATA Controller IDE (ICH8M) */ { 0x8086, 0x2828, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller IDE (ICH9) */ { 0x8086, 0x2920, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller IDE (ICH9) */ { 0x8086, 0x2921, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (ICH9) */ { 0x8086, 0x2926, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (ICH9M) */ { 0x8086, 0x2928, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (ICH9M) */ { 0x8086, 0x292d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (ICH9M) */ { 0x8086, 0x292e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller IDE (Tolapai) */ { 0x8086, 0x5028, PCI_ANY_ID, PCI_ANY_ID, 0, 0, tolapai_sata }, /* SATA Controller IDE (ICH10) */ { 0x8086, 0x3a00, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller IDE (ICH10) */ { 0x8086, 0x3a06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (ICH10) */ { 0x8086, 0x3a20, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller IDE (ICH10) */ { 0x8086, 0x3a26, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (PCH) */ { 0x8086, 0x3b20, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller IDE (PCH) */ { 0x8086, 0x3b21, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (PCH) */ { 0x8086, 0x3b26, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (PCH) */ { 0x8086, 0x3b28, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller IDE (PCH) */ { 0x8086, 0x3b2d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (PCH) */ { 0x8086, 0x3b2e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata }, /* SATA Controller IDE (CPT) */ { 0x8086, 0x1c00, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (CPT) */ { 0x8086, 0x1c01, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (CPT) */ { 0x8086, 0x1c08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (CPT) */ { 0x8086, 0x1c09, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (PBG) */ { 0x8086, 0x1d00, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (PBG) */ { 0x8086, 0x1d08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (Panther Point) */ { 0x8086, 0x1e00, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (Panther Point) */ { 0x8086, 0x1e01, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (Panther Point) */ { 0x8086, 0x1e08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (Panther Point) */ { 0x8086, 0x1e09, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (Lynx Point) */ { 0x8086, 0x8c00, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (Lynx Point) */ { 0x8086, 0x8c01, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (Lynx Point) */ { 0x8086, 0x8c08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata_snb }, /* SATA Controller IDE (Lynx Point) */ { 0x8086, 0x8c09, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (DH89xxCC) */ { 0x8086, 0x2326, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (Avoton) */ { 0x8086, 0x1f20, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (Avoton) */ { 0x8086, 0x1f21, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (Avoton) */ { 0x8086, 0x1f30, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (Avoton) */ { 0x8086, 0x1f31, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (Wellsburg) */ { 0x8086, 0x8d00, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (Wellsburg) */ { 0x8086, 0x8d08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (Wellsburg) */ { 0x8086, 0x8d60, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_sata_snb }, /* SATA Controller IDE (Wellsburg) */ { 0x8086, 0x8d68, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata }, /* SATA Controller IDE (BayTrail) */ { 0x8086, 0x0F20, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata_byt }, { 0x8086, 0x0F21, PCI_ANY_ID, PCI_ANY_ID, 0, 0, ich8_2port_sata_byt }, { } /* terminate list */ }; static struct pci_driver piix_pci_driver = { .name = DRV_NAME, .id_table = piix_pci_tbl, .probe = piix_init_one, .remove = piix_remove_one, #ifdef CONFIG_PM .suspend = piix_pci_device_suspend, .resume = piix_pci_device_resume, #endif }; static struct scsi_host_template piix_sht = { ATA_BMDMA_SHT(DRV_NAME), }; static struct ata_port_operations piix_sata_ops = { .inherits = &ata_bmdma32_port_ops, .sff_irq_check = piix_irq_check, .port_start = piix_port_start, }; static struct ata_port_operations piix_pata_ops = { .inherits = &piix_sata_ops, .cable_detect = ata_cable_40wire, .set_piomode = piix_set_piomode, .set_dmamode = piix_set_dmamode, .prereset = piix_pata_prereset, }; static struct ata_port_operations piix_vmw_ops = { .inherits = &piix_pata_ops, .bmdma_status = piix_vmw_bmdma_status, }; static struct ata_port_operations ich_pata_ops = { .inherits = &piix_pata_ops, .cable_detect = ich_pata_cable_detect, .set_dmamode = ich_set_dmamode, }; static struct device_attribute *piix_sidpr_shost_attrs[] = { &dev_attr_link_power_management_policy, NULL }; static struct scsi_host_template piix_sidpr_sht = { ATA_BMDMA_SHT(DRV_NAME), .shost_attrs = piix_sidpr_shost_attrs, }; static struct ata_port_operations piix_sidpr_sata_ops = { .inherits = &piix_sata_ops, .hardreset = sata_std_hardreset, .scr_read = piix_sidpr_scr_read, .scr_write = piix_sidpr_scr_write, .set_lpm = piix_sidpr_set_lpm, }; static const struct piix_map_db ich5_map_db = { .mask = 0x7, .port_enable = 0x3, .map = { /* PM PS SM SS MAP */ { P0, NA, P1, NA }, /* 000b */ { P1, NA, P0, NA }, /* 001b */ { RV, RV, RV, RV }, { RV, RV, RV, RV }, { P0, P1, IDE, IDE }, /* 100b */ { P1, P0, IDE, IDE }, /* 101b */ { IDE, IDE, P0, P1 }, /* 110b */ { IDE, IDE, P1, P0 }, /* 111b */ }, }; static const struct piix_map_db ich6_map_db = { .mask = 0x3, .port_enable = 0xf, .map = { /* PM PS SM SS MAP */ { P0, P2, P1, P3 }, /* 00b */ { IDE, IDE, P1, P3 }, /* 01b */ { P0, P2, IDE, IDE }, /* 10b */ { RV, RV, RV, RV }, }, }; static const struct piix_map_db ich6m_map_db = { .mask = 0x3, .port_enable = 0x5, /* Map 01b isn't specified in the doc but some notebooks use * it anyway. MAP 01b have been spotted on both ICH6M and * ICH7M. */ .map = { /* PM PS SM SS MAP */ { P0, P2, NA, NA }, /* 00b */ { IDE, IDE, P1, P3 }, /* 01b */ { P0, P2, IDE, IDE }, /* 10b */ { RV, RV, RV, RV }, }, }; static const struct piix_map_db ich8_map_db = { .mask = 0x3, .port_enable = 0xf, .map = { /* PM PS SM SS MAP */ { P0, P2, P1, P3 }, /* 00b (hardwired when in AHCI) */ { RV, RV, RV, RV }, { P0, P2, IDE, IDE }, /* 10b (IDE mode) */ { RV, RV, RV, RV }, }, }; static const struct piix_map_db ich8_2port_map_db = { .mask = 0x3, .port_enable = 0x3, .map = { /* PM PS SM SS MAP */ { P0, NA, P1, NA }, /* 00b */ { RV, RV, RV, RV }, /* 01b */ { RV, RV, RV, RV }, /* 10b */ { RV, RV, RV, RV }, }, }; static const struct piix_map_db ich8m_apple_map_db = { .mask = 0x3, .port_enable = 0x1, .map = { /* PM PS SM SS MAP */ { P0, NA, NA, NA }, /* 00b */ { RV, RV, RV, RV }, { P0, P2, IDE, IDE }, /* 10b */ { RV, RV, RV, RV }, }, }; static const struct piix_map_db tolapai_map_db = { .mask = 0x3, .port_enable = 0x3, .map = { /* PM PS SM SS MAP */ { P0, NA, P1, NA }, /* 00b */ { RV, RV, RV, RV }, /* 01b */ { RV, RV, RV, RV }, /* 10b */ { RV, RV, RV, RV }, }, }; static const struct piix_map_db *piix_map_db_table[] = { [ich5_sata] = &ich5_map_db, [ich6_sata] = &ich6_map_db, [ich6m_sata] = &ich6m_map_db, [ich8_sata] = &ich8_map_db, [ich8_2port_sata] = &ich8_2port_map_db, [ich8m_apple_sata] = &ich8m_apple_map_db, [tolapai_sata] = &tolapai_map_db, [ich8_sata_snb] = &ich8_map_db, [ich8_2port_sata_snb] = &ich8_2port_map_db, [ich8_2port_sata_byt] = &ich8_2port_map_db, }; static struct ata_port_info piix_port_info[] = { [piix_pata_mwdma] = /* PIIX3 MWDMA only */ { .flags = PIIX_PATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA12_ONLY, /* mwdma1-2 ?? CHECK 0 should be ok but slow */ .port_ops = &piix_pata_ops, }, [piix_pata_33] = /* PIIX4 at 33MHz */ { .flags = PIIX_PATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA12_ONLY, /* mwdma1-2 ?? CHECK 0 should be ok but slow */ .udma_mask = ATA_UDMA2, .port_ops = &piix_pata_ops, }, [ich_pata_33] = /* ICH0 - ICH at 33Mhz*/ { .flags = PIIX_PATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA12_ONLY, /* Check: maybe MWDMA0 is ok */ .udma_mask = ATA_UDMA2, .port_ops = &ich_pata_ops, }, [ich_pata_66] = /* ICH controllers up to 66MHz */ { .flags = PIIX_PATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA12_ONLY, /* MWDMA0 is broken on chip */ .udma_mask = ATA_UDMA4, .port_ops = &ich_pata_ops, }, [ich_pata_100] = { .flags = PIIX_PATA_FLAGS | PIIX_FLAG_CHECKINTR, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA12_ONLY, .udma_mask = ATA_UDMA5, .port_ops = &ich_pata_ops, }, [ich_pata_100_nomwdma1] = { .flags = PIIX_PATA_FLAGS | PIIX_FLAG_CHECKINTR, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2_ONLY, .udma_mask = ATA_UDMA5, .port_ops = &ich_pata_ops, }, [ich5_sata] = { .flags = PIIX_SATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [ich6_sata] = { .flags = PIIX_SATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [ich6m_sata] = { .flags = PIIX_SATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [ich8_sata] = { .flags = PIIX_SATA_FLAGS | PIIX_FLAG_SIDPR, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [ich8_2port_sata] = { .flags = PIIX_SATA_FLAGS | PIIX_FLAG_SIDPR, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [tolapai_sata] = { .flags = PIIX_SATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [ich8m_apple_sata] = { .flags = PIIX_SATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [piix_pata_vmw] = { .flags = PIIX_PATA_FLAGS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA12_ONLY, /* mwdma1-2 ?? CHECK 0 should be ok but slow */ .udma_mask = ATA_UDMA2, .port_ops = &piix_vmw_ops, }, /* * some Sandybridge chipsets have broken 32 mode up to now, * see https://bugzilla.kernel.org/show_bug.cgi?id=40592 */ [ich8_sata_snb] = { .flags = PIIX_SATA_FLAGS | PIIX_FLAG_SIDPR | PIIX_FLAG_PIO16, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [ich8_2port_sata_snb] = { .flags = PIIX_SATA_FLAGS | PIIX_FLAG_SIDPR | PIIX_FLAG_PIO16, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, [ich8_2port_sata_byt] = { .flags = PIIX_SATA_FLAGS | PIIX_FLAG_SIDPR | PIIX_FLAG_PIO16, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &piix_sata_ops, }, }; static struct pci_bits piix_enable_bits[] = { { 0x41U, 1U, 0x80UL, 0x80UL }, /* port 0 */ { 0x43U, 1U, 0x80UL, 0x80UL }, /* port 1 */ }; MODULE_AUTHOR("Andre Hedrick, Alan Cox, Andrzej Krzysztofowicz, Jeff Garzik"); MODULE_DESCRIPTION("SCSI low-level driver for Intel PIIX/ICH ATA controllers"); MODULE_LICENSE("GPL"); MODULE_DEVICE_TABLE(pci, piix_pci_tbl); MODULE_VERSION(DRV_VERSION); struct ich_laptop { u16 device; u16 subvendor; u16 subdevice; }; /* * List of laptops that use short cables rather than 80 wire */ static const struct ich_laptop ich_laptop[] = { /* devid, subvendor, subdev */ { 0x27DF, 0x0005, 0x0280 }, /* ICH7 on Acer 5602WLMi */ { 0x27DF, 0x1025, 0x0102 }, /* ICH7 on Acer 5602aWLMi */ { 0x27DF, 0x1025, 0x0110 }, /* ICH7 on Acer 3682WLMi */ { 0x27DF, 0x1028, 0x02b0 }, /* ICH7 on unknown Dell */ { 0x27DF, 0x1043, 0x1267 }, /* ICH7 on Asus W5F */ { 0x27DF, 0x103C, 0x30A1 }, /* ICH7 on HP Compaq nc2400 */ { 0x27DF, 0x103C, 0x361a }, /* ICH7 on unknown HP */ { 0x27DF, 0x1071, 0xD221 }, /* ICH7 on Hercules EC-900 */ { 0x27DF, 0x152D, 0x0778 }, /* ICH7 on unknown Intel */ { 0x24CA, 0x1025, 0x0061 }, /* ICH4 on ACER Aspire 2023WLMi */ { 0x24CA, 0x1025, 0x003d }, /* ICH4 on ACER TM290 */ { 0x266F, 0x1025, 0x0066 }, /* ICH6 on ACER Aspire 1694WLMi */ { 0x2653, 0x1043, 0x82D8 }, /* ICH6M on Asus Eee 701 */ { 0x27df, 0x104d, 0x900e }, /* ICH7 on Sony TZ-90 */ /* end marker */ { 0, } }; static int piix_port_start(struct ata_port *ap) { if (!(ap->flags & PIIX_FLAG_PIO16)) ap->pflags |= ATA_PFLAG_PIO32 | ATA_PFLAG_PIO32CHANGE; return ata_bmdma_port_start(ap); } /** * ich_pata_cable_detect - Probe host controller cable detect info * @ap: Port for which cable detect info is desired * * Read 80c cable indicator from ATA PCI device's PCI config * register. This register is normally set by firmware (BIOS). * * LOCKING: * None (inherited from caller). */ static int ich_pata_cable_detect(struct ata_port *ap) { struct pci_dev *pdev = to_pci_dev(ap->host->dev); struct piix_host_priv *hpriv = ap->host->private_data; const struct ich_laptop *lap = &ich_laptop[0]; u8 mask; /* Check for specials - Acer Aspire 5602WLMi */ while (lap->device) { if (lap->device == pdev->device && lap->subvendor == pdev->subsystem_vendor && lap->subdevice == pdev->subsystem_device) return ATA_CBL_PATA40_SHORT; lap++; } /* check BIOS cable detect results */ mask = ap->port_no == 0 ? PIIX_80C_PRI : PIIX_80C_SEC; if ((hpriv->saved_iocfg & mask) == 0) return ATA_CBL_PATA40; return ATA_CBL_PATA80; } /** * piix_pata_prereset - prereset for PATA host controller * @link: Target link * @deadline: deadline jiffies for the operation * * LOCKING: * None (inherited from caller). */ static int piix_pata_prereset(struct ata_link *link, unsigned long deadline) { struct ata_port *ap = link->ap; struct pci_dev *pdev = to_pci_dev(ap->host->dev); if (!pci_test_config_bits(pdev, &piix_enable_bits[ap->port_no])) return -ENOENT; return ata_sff_prereset(link, deadline); } static DEFINE_SPINLOCK(piix_lock); static void piix_set_timings(struct ata_port *ap, struct ata_device *adev, u8 pio) { struct pci_dev *dev = to_pci_dev(ap->host->dev); unsigned long flags; unsigned int is_slave = (adev->devno != 0); unsigned int master_port= ap->port_no ? 0x42 : 0x40; unsigned int slave_port = 0x44; u16 master_data; u8 slave_data; u8 udma_enable; int control = 0; /* * See Intel Document 298600-004 for the timing programing rules * for ICH controllers. */ static const /* ISP RTC */ u8 timings[][2] = { { 0, 0 }, { 0, 0 }, { 1, 0 }, { 2, 1 }, { 2, 3 }, }; if (pio >= 2) control |= 1; /* TIME1 enable */ if (ata_pio_need_iordy(adev)) control |= 2; /* IE enable */ /* Intel specifies that the PPE functionality is for disk only */ if (adev->class == ATA_DEV_ATA) control |= 4; /* PPE enable */ /* * If the drive MWDMA is faster than it can do PIO then * we must force PIO into PIO0 */ if (adev->pio_mode < XFER_PIO_0 + pio) /* Enable DMA timing only */ control |= 8; /* PIO cycles in PIO0 */ spin_lock_irqsave(&piix_lock, flags); /* PIO configuration clears DTE unconditionally. It will be * programmed in set_dmamode which is guaranteed to be called * after set_piomode if any DMA mode is available. */ pci_read_config_word(dev, master_port, &master_data); if (is_slave) { /* clear TIME1|IE1|PPE1|DTE1 */ master_data &= 0xff0f; /* enable PPE1, IE1 and TIME1 as needed */ master_data |= (control << 4); pci_read_config_byte(dev, slave_port, &slave_data); slave_data &= (ap->port_no ? 0x0f : 0xf0); /* Load the timing nibble for this slave */ slave_data |= ((timings[pio][0] << 2) | timings[pio][1]) << (ap->port_no ? 4 : 0); } else { /* clear ISP|RCT|TIME0|IE0|PPE0|DTE0 */ master_data &= 0xccf0; /* Enable PPE, IE and TIME as appropriate */ master_data |= control; /* load ISP and RCT */ master_data |= (timings[pio][0] << 12) | (timings[pio][1] << 8); } /* Enable SITRE (separate slave timing register) */ master_data |= 0x4000; pci_write_config_word(dev, master_port, master_data); if (is_slave) pci_write_config_byte(dev, slave_port, slave_data); /* Ensure the UDMA bit is off - it will be turned back on if UDMA is selected */ if (ap->udma_mask) { pci_read_config_byte(dev, 0x48, &udma_enable); udma_enable &= ~(1 << (2 * ap->port_no + adev->devno)); pci_write_config_byte(dev, 0x48, udma_enable); } spin_unlock_irqrestore(&piix_lock, flags); } /** * piix_set_piomode - Initialize host controller PATA PIO timings * @ap: Port whose timings we are configuring * @adev: Drive in question * * Set PIO mode for device, in host controller PCI config space. * * LOCKING: * None (inherited from caller). */ static void piix_set_piomode(struct ata_port *ap, struct ata_device *adev) { piix_set_timings(ap, adev, adev->pio_mode - XFER_PIO_0); } /** * do_pata_set_dmamode - Initialize host controller PATA PIO timings * @ap: Port whose timings we are configuring * @adev: Drive in question * @isich: set if the chip is an ICH device * * Set UDMA mode for device, in host controller PCI config space. * * LOCKING: * None (inherited from caller). */ static void do_pata_set_dmamode(struct ata_port *ap, struct ata_device *adev, int isich) { struct pci_dev *dev = to_pci_dev(ap->host->dev); unsigned long flags; u8 speed = adev->dma_mode; int devid = adev->devno + 2 * ap->port_no; u8 udma_enable = 0; if (speed >= XFER_UDMA_0) { unsigned int udma = speed - XFER_UDMA_0; u16 udma_timing; u16 ideconf; int u_clock, u_speed; spin_lock_irqsave(&piix_lock, flags); pci_read_config_byte(dev, 0x48, &udma_enable); /* * UDMA is handled by a combination of clock switching and * selection of dividers * * Handy rule: Odd modes are UDMATIMx 01, even are 02 * except UDMA0 which is 00 */ u_speed = min(2 - (udma & 1), udma); if (udma == 5) u_clock = 0x1000; /* 100Mhz */ else if (udma > 2) u_clock = 1; /* 66Mhz */ else u_clock = 0; /* 33Mhz */ udma_enable |= (1 << devid); /* Load the CT/RP selection */ pci_read_config_word(dev, 0x4A, &udma_timing); udma_timing &= ~(3 << (4 * devid)); udma_timing |= u_speed << (4 * devid); pci_write_config_word(dev, 0x4A, udma_timing); if (isich) { /* Select a 33/66/100Mhz clock */ pci_read_config_word(dev, 0x54, &ideconf); ideconf &= ~(0x1001 << devid); ideconf |= u_clock << devid; /* For ICH or later we should set bit 10 for better performance (WR_PingPong_En) */ pci_write_config_word(dev, 0x54, ideconf); } pci_write_config_byte(dev, 0x48, udma_enable); spin_unlock_irqrestore(&piix_lock, flags); } else { /* MWDMA is driven by the PIO timings. */ unsigned int mwdma = speed - XFER_MW_DMA_0; const unsigned int needed_pio[3] = { XFER_PIO_0, XFER_PIO_3, XFER_PIO_4 }; int pio = needed_pio[mwdma] - XFER_PIO_0; /* XFER_PIO_0 is never used currently */ piix_set_timings(ap, adev, pio); } } /** * piix_set_dmamode - Initialize host controller PATA DMA timings * @ap: Port whose timings we are configuring * @adev: um * * Set MW/UDMA mode for device, in host controller PCI config space. * * LOCKING: * None (inherited from caller). */ static void piix_set_dmamode(struct ata_port *ap, struct ata_device *adev) { do_pata_set_dmamode(ap, adev, 0); } /** * ich_set_dmamode - Initialize host controller PATA DMA timings * @ap: Port whose timings we are configuring * @adev: um * * Set MW/UDMA mode for device, in host controller PCI config space. * * LOCKING: * None (inherited from caller). */ static void ich_set_dmamode(struct ata_port *ap, struct ata_device *adev) { do_pata_set_dmamode(ap, adev, 1); } /* * Serial ATA Index/Data Pair Superset Registers access * * Beginning from ICH8, there's a sane way to access SCRs using index * and data register pair located at BAR5 which means that we have * separate SCRs for master and slave. This is handled using libata * slave_link facility. */ static const int piix_sidx_map[] = { [SCR_STATUS] = 0, [SCR_ERROR] = 2, [SCR_CONTROL] = 1, }; static void piix_sidpr_sel(struct ata_link *link, unsigned int reg) { struct ata_port *ap = link->ap; struct piix_host_priv *hpriv = ap->host->private_data; iowrite32(((ap->port_no * 2 + link->pmp) << 8) | piix_sidx_map[reg], hpriv->sidpr + PIIX_SIDPR_IDX); } static int piix_sidpr_scr_read(struct ata_link *link, unsigned int reg, u32 *val) { struct piix_host_priv *hpriv = link->ap->host->private_data; if (reg >= ARRAY_SIZE(piix_sidx_map)) return -EINVAL; piix_sidpr_sel(link, reg); *val = ioread32(hpriv->sidpr + PIIX_SIDPR_DATA); return 0; } static int piix_sidpr_scr_write(struct ata_link *link, unsigned int reg, u32 val) { struct piix_host_priv *hpriv = link->ap->host->private_data; if (reg >= ARRAY_SIZE(piix_sidx_map)) return -EINVAL; piix_sidpr_sel(link, reg); iowrite32(val, hpriv->sidpr + PIIX_SIDPR_DATA); return 0; } static int piix_sidpr_set_lpm(struct ata_link *link, enum ata_lpm_policy policy, unsigned hints) { return sata_link_scr_lpm(link, policy, false); } static bool piix_irq_check(struct ata_port *ap) { if (unlikely(!ap->ioaddr.bmdma_addr)) return false; return ap->ops->bmdma_status(ap) & ATA_DMA_INTR; } #ifdef CONFIG_PM static int piix_broken_suspend(void) { static const struct dmi_system_id sysids[] = { { .ident = "TECRA M3", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "TECRA M3"), }, }, { .ident = "TECRA M3", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Tecra M3"), }, }, { .ident = "TECRA M4", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Tecra M4"), }, }, { .ident = "TECRA M4", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "TECRA M4"), }, }, { .ident = "TECRA M5", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "TECRA M5"), }, }, { .ident = "TECRA M6", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "TECRA M6"), }, }, { .ident = "TECRA M7", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "TECRA M7"), }, }, { .ident = "TECRA A8", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "TECRA A8"), }, }, { .ident = "Satellite R20", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Satellite R20"), }, }, { .ident = "Satellite R25", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Satellite R25"), }, }, { .ident = "Satellite U200", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Satellite U200"), }, }, { .ident = "Satellite U200", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "SATELLITE U200"), }, }, { .ident = "Satellite Pro U200", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "SATELLITE PRO U200"), }, }, { .ident = "Satellite U205", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Satellite U205"), }, }, { .ident = "SATELLITE U205", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "SATELLITE U205"), }, }, { .ident = "Satellite Pro A120", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Satellite Pro A120"), }, }, { .ident = "Portege M500", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "PORTEGE M500"), }, }, { .ident = "VGN-BX297XP", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "VGN-BX297XP"), }, }, { } /* terminate list */ }; static const char *oemstrs[] = { "Tecra M3,", }; int i; if (dmi_check_system(sysids)) return 1; for (i = 0; i < ARRAY_SIZE(oemstrs); i++) if (dmi_find_device(DMI_DEV_TYPE_OEM_STRING, oemstrs[i], NULL)) return 1; /* TECRA M4 sometimes forgets its identify and reports bogus * DMI information. As the bogus information is a bit * generic, match as many entries as possible. This manual * matching is necessary because dmi_system_id.matches is * limited to four entries. */ if (dmi_match(DMI_SYS_VENDOR, "TOSHIBA") && dmi_match(DMI_PRODUCT_NAME, "000000") && dmi_match(DMI_PRODUCT_VERSION, "000000") && dmi_match(DMI_PRODUCT_SERIAL, "000000") && dmi_match(DMI_BOARD_VENDOR, "TOSHIBA") && dmi_match(DMI_BOARD_NAME, "Portable PC") && dmi_match(DMI_BOARD_VERSION, "Version A0")) return 1; return 0; } static int piix_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg) { struct ata_host *host = dev_get_drvdata(&pdev->dev); unsigned long flags; int rc = 0; rc = ata_host_suspend(host, mesg); if (rc) return rc; /* Some braindamaged ACPI suspend implementations expect the * controller to be awake on entry; otherwise, it burns cpu * cycles and power trying to do something to the sleeping * beauty. */ if (piix_broken_suspend() && (mesg.event & PM_EVENT_SLEEP)) { pci_save_state(pdev); /* mark its power state as "unknown", since we don't * know if e.g. the BIOS will change its device state * when we suspend. */ if (pdev->current_state == PCI_D0) pdev->current_state = PCI_UNKNOWN; /* tell resume that it's waking up from broken suspend */ spin_lock_irqsave(&host->lock, flags); host->flags |= PIIX_HOST_BROKEN_SUSPEND; spin_unlock_irqrestore(&host->lock, flags); } else ata_pci_device_do_suspend(pdev, mesg); return 0; } static int piix_pci_device_resume(struct pci_dev *pdev) { struct ata_host *host = dev_get_drvdata(&pdev->dev); unsigned long flags; int rc; if (host->flags & PIIX_HOST_BROKEN_SUSPEND) { spin_lock_irqsave(&host->lock, flags); host->flags &= ~PIIX_HOST_BROKEN_SUSPEND; spin_unlock_irqrestore(&host->lock, flags); pci_set_power_state(pdev, PCI_D0); pci_restore_state(pdev); /* PCI device wasn't disabled during suspend. Use * pci_reenable_device() to avoid affecting the enable * count. */ rc = pci_reenable_device(pdev); if (rc) dev_err(&pdev->dev, "failed to enable device after resume (%d)\n", rc); } else rc = ata_pci_device_do_resume(pdev); if (rc == 0) ata_host_resume(host); return rc; } #endif static u8 piix_vmw_bmdma_status(struct ata_port *ap) { return ata_bmdma_status(ap) & ~ATA_DMA_ERR; } #define AHCI_PCI_BAR 5 #define AHCI_GLOBAL_CTL 0x04 #define AHCI_ENABLE (1 << 31) static int piix_disable_ahci(struct pci_dev *pdev) { void __iomem *mmio; u32 tmp; int rc = 0; /* BUG: pci_enable_device has not yet been called. This * works because this device is usually set up by BIOS. */ if (!pci_resource_start(pdev, AHCI_PCI_BAR) || !pci_resource_len(pdev, AHCI_PCI_BAR)) return 0; mmio = pci_iomap(pdev, AHCI_PCI_BAR, 64); if (!mmio) return -ENOMEM; tmp = ioread32(mmio + AHCI_GLOBAL_CTL); if (tmp & AHCI_ENABLE) { tmp &= ~AHCI_ENABLE; iowrite32(tmp, mmio + AHCI_GLOBAL_CTL); tmp = ioread32(mmio + AHCI_GLOBAL_CTL); if (tmp & AHCI_ENABLE) rc = -EIO; } pci_iounmap(pdev, mmio); return rc; } /** * piix_check_450nx_errata - Check for problem 450NX setup * @ata_dev: the PCI device to check * * Check for the present of 450NX errata #19 and errata #25. If * they are found return an error code so we can turn off DMA */ static int __devinit piix_check_450nx_errata(struct pci_dev *ata_dev) { struct pci_dev *pdev = NULL; u16 cfg; int no_piix_dma = 0; while ((pdev = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82454NX, pdev)) != NULL) { /* Look for 450NX PXB. Check for problem configurations A PCI quirk checks bit 6 already */ pci_read_config_word(pdev, 0x41, &cfg); /* Only on the original revision: IDE DMA can hang */ if (pdev->revision == 0x00) no_piix_dma = 1; /* On all revisions below 5 PXB bus lock must be disabled for IDE */ else if (cfg & (1<<14) && pdev->revision < 5) no_piix_dma = 2; } if (no_piix_dma) dev_warn(&ata_dev->dev, "450NX errata present, disabling IDE DMA%s\n", no_piix_dma == 2 ? " - a BIOS update may resolve this" : ""); return no_piix_dma; } static void __devinit piix_init_pcs(struct ata_host *host, const struct piix_map_db *map_db) { struct pci_dev *pdev = to_pci_dev(host->dev); u16 pcs, new_pcs; pci_read_config_word(pdev, ICH5_PCS, &pcs); new_pcs = pcs | map_db->port_enable; if (new_pcs != pcs) { DPRINTK("updating PCS from 0x%x to 0x%x\n", pcs, new_pcs); pci_write_config_word(pdev, ICH5_PCS, new_pcs); msleep(150); } } static const int *__devinit piix_init_sata_map(struct pci_dev *pdev, struct ata_port_info *pinfo, const struct piix_map_db *map_db) { const int *map; int i, invalid_map = 0; u8 map_value; pci_read_config_byte(pdev, ICH5_PMR, &map_value); map = map_db->map[map_value & map_db->mask]; dev_info(&pdev->dev, "MAP ["); for (i = 0; i < 4; i++) { switch (map[i]) { case RV: invalid_map = 1; pr_cont(" XX"); break; case NA: pr_cont(" --"); break; case IDE: WARN_ON((i & 1) || map[i + 1] != IDE); pinfo[i / 2] = piix_port_info[ich_pata_100]; i++; pr_cont(" IDE IDE"); break; default: pr_cont(" P%d", map[i]); if (i & 1) pinfo[i / 2].flags |= ATA_FLAG_SLAVE_POSS; break; } } pr_cont(" ]\n"); if (invalid_map) dev_err(&pdev->dev, "invalid MAP value %u\n", map_value); return map; } static bool piix_no_sidpr(struct ata_host *host) { struct pci_dev *pdev = to_pci_dev(host->dev); /* * Samsung DB-P70 only has three ATA ports exposed and * curiously the unconnected first port reports link online * while not responding to SRST protocol causing excessive * detection delay. * * Unfortunately, the system doesn't carry enough DMI * information to identify the machine but does have subsystem * vendor and device set. As it's unclear whether the * subsystem vendor/device is used only for this specific * board, the port can't be disabled solely with the * information; however, turning off SIDPR access works around * the problem. Turn it off. * * This problem is reported in bnc#441240. * * https://bugzilla.novell.com/show_bug.cgi?id=441420 */ if (pdev->vendor == PCI_VENDOR_ID_INTEL && pdev->device == 0x2920 && pdev->subsystem_vendor == PCI_VENDOR_ID_SAMSUNG && pdev->subsystem_device == 0xb049) { dev_warn(host->dev, "Samsung DB-P70 detected, disabling SIDPR\n"); return true; } return false; } static int __devinit piix_init_sidpr(struct ata_host *host) { struct pci_dev *pdev = to_pci_dev(host->dev); struct piix_host_priv *hpriv = host->private_data; struct ata_link *link0 = &host->ports[0]->link; u32 scontrol; int i, rc; /* check for availability */ for (i = 0; i < 4; i++) if (hpriv->map[i] == IDE) return 0; /* is it blacklisted? */ if (piix_no_sidpr(host)) return 0; if (!(host->ports[0]->flags & PIIX_FLAG_SIDPR)) return 0; if (pci_resource_start(pdev, PIIX_SIDPR_BAR) == 0 || pci_resource_len(pdev, PIIX_SIDPR_BAR) != PIIX_SIDPR_LEN) return 0; if (pcim_iomap_regions(pdev, 1 << PIIX_SIDPR_BAR, DRV_NAME)) return 0; hpriv->sidpr = pcim_iomap_table(pdev)[PIIX_SIDPR_BAR]; /* SCR access via SIDPR doesn't work on some configurations. * Give it a test drive by inhibiting power save modes which * we'll do anyway. */ piix_sidpr_scr_read(link0, SCR_CONTROL, &scontrol); /* if IPM is already 3, SCR access is probably working. Don't * un-inhibit power save modes as BIOS might have inhibited * them for a reason. */ if ((scontrol & 0xf00) != 0x300) { scontrol |= 0x300; piix_sidpr_scr_write(link0, SCR_CONTROL, scontrol); piix_sidpr_scr_read(link0, SCR_CONTROL, &scontrol); if ((scontrol & 0xf00) != 0x300) { dev_info(host->dev, "SCR access via SIDPR is available but doesn't work\n"); return 0; } } /* okay, SCRs available, set ops and ask libata for slave_link */ for (i = 0; i < 2; i++) { struct ata_port *ap = host->ports[i]; ap->ops = &piix_sidpr_sata_ops; if (ap->flags & ATA_FLAG_SLAVE_POSS) { rc = ata_slave_link_init(ap); if (rc) return rc; } } return 0; } static void piix_iocfg_bit18_quirk(struct ata_host *host) { static const struct dmi_system_id sysids[] = { { /* Clevo M570U sets IOCFG bit 18 if the cdrom * isn't used to boot the system which * disables the channel. */ .ident = "M570U", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Clevo Co."), DMI_MATCH(DMI_PRODUCT_NAME, "M570U"), }, }, { } /* terminate list */ }; struct pci_dev *pdev = to_pci_dev(host->dev); struct piix_host_priv *hpriv = host->private_data; if (!dmi_check_system(sysids)) return; /* The datasheet says that bit 18 is NOOP but certain systems * seem to use it to disable a channel. Clear the bit on the * affected systems. */ if (hpriv->saved_iocfg & (1 << 18)) { dev_info(&pdev->dev, "applying IOCFG bit18 quirk\n"); pci_write_config_dword(pdev, PIIX_IOCFG, hpriv->saved_iocfg & ~(1 << 18)); } } static bool piix_broken_system_poweroff(struct pci_dev *pdev) { static const struct dmi_system_id broken_systems[] = { { .ident = "HP Compaq 2510p", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq 2510p"), }, /* PCI slot number of the controller */ .driver_data = (void *)0x1FUL, }, { .ident = "HP Compaq nc6000", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq nc6000"), }, /* PCI slot number of the controller */ .driver_data = (void *)0x1FUL, }, { } /* terminate list */ }; const struct dmi_system_id *dmi = dmi_first_match(broken_systems); if (dmi) { unsigned long slot = (unsigned long)dmi->driver_data; /* apply the quirk only to on-board controllers */ return slot == PCI_SLOT(pdev->devfn); } return false; } static int prefer_ms_hyperv = 1; module_param(prefer_ms_hyperv, int, 0); static void piix_ignore_devices_quirk(struct ata_host *host) { #if IS_ENABLED(CONFIG_HYPERV_STORAGE) static const struct dmi_system_id ignore_hyperv[] = { { /* On Hyper-V hypervisors the disks are exposed on * both the emulated SATA controller and on the * paravirtualised drivers. The CD/DVD devices * are only exposed on the emulated controller. * Request we ignore ATA devices on this host. */ .ident = "Hyper-V Virtual Machine", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "Virtual Machine"), }, }, { } /* terminate list */ }; static const struct dmi_system_id allow_virtual_pc[] = { { /* In MS Virtual PC guests the DMI ident is nearly * identical to a Hyper-V guest. One difference is the * product version which is used here to identify * a Virtual PC guest. This entry allows ata_piix to * drive the emulated hardware. */ .ident = "MS Virtual PC 2007", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "Virtual Machine"), DMI_MATCH(DMI_PRODUCT_VERSION, "VS2005R2"), }, }, { } /* terminate list */ }; const struct dmi_system_id *ignore = dmi_first_match(ignore_hyperv); const struct dmi_system_id *allow = dmi_first_match(allow_virtual_pc); if (ignore && !allow && prefer_ms_hyperv) { host->flags |= ATA_HOST_IGNORE_ATA; dev_info(host->dev, "%s detected, ATA device ignore set\n", ignore->ident); } #endif } /** * piix_init_one - Register PIIX ATA PCI device with kernel services * @pdev: PCI device to register * @ent: Entry in piix_pci_tbl matching with @pdev * * Called from kernel PCI layer. We probe for combined mode (sigh), * and then hand over control to libata, for it to do the rest. * * LOCKING: * Inherited from PCI layer (may sleep). * * RETURNS: * Zero on success, or -ERRNO value. */ static int __devinit piix_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct device *dev = &pdev->dev; struct ata_port_info port_info[2]; const struct ata_port_info *ppi[] = { &port_info[0], &port_info[1] }; struct scsi_host_template *sht = &piix_sht; unsigned long port_flags; struct ata_host *host; struct piix_host_priv *hpriv; int rc; ata_print_version_once(&pdev->dev, DRV_VERSION); /* no hotplugging support for later devices (FIXME) */ if (!in_module_init && ent->driver_data >= ich5_sata) return -ENODEV; if (piix_broken_system_poweroff(pdev)) { piix_port_info[ent->driver_data].flags |= ATA_FLAG_NO_POWEROFF_SPINDOWN | ATA_FLAG_NO_HIBERNATE_SPINDOWN; dev_info(&pdev->dev, "quirky BIOS, skipping spindown " "on poweroff and hibernation\n"); } port_info[0] = piix_port_info[ent->driver_data]; port_info[1] = piix_port_info[ent->driver_data]; port_flags = port_info[0].flags; /* enable device and prepare host */ rc = pcim_enable_device(pdev); if (rc) return rc; hpriv = devm_kzalloc(dev, sizeof(*hpriv), GFP_KERNEL); if (!hpriv) return -ENOMEM; /* Save IOCFG, this will be used for cable detection, quirk * detection and restoration on detach. This is necessary * because some ACPI implementations mess up cable related * bits on _STM. Reported on kernel bz#11879. */ pci_read_config_dword(pdev, PIIX_IOCFG, &hpriv->saved_iocfg); /* ICH6R may be driven by either ata_piix or ahci driver * regardless of BIOS configuration. Make sure AHCI mode is * off. */ if (pdev->vendor == PCI_VENDOR_ID_INTEL && pdev->device == 0x2652) { rc = piix_disable_ahci(pdev); if (rc) return rc; } /* SATA map init can change port_info, do it before prepping host */ if (port_flags & ATA_FLAG_SATA) hpriv->map = piix_init_sata_map(pdev, port_info, piix_map_db_table[ent->driver_data]); rc = ata_pci_bmdma_prepare_host(pdev, ppi, &host); if (rc) return rc; host->private_data = hpriv; /* initialize controller */ if (port_flags & ATA_FLAG_SATA) { piix_init_pcs(host, piix_map_db_table[ent->driver_data]); rc = piix_init_sidpr(host); if (rc) return rc; if (host->ports[0]->ops == &piix_sidpr_sata_ops) sht = &piix_sidpr_sht; } /* apply IOCFG bit18 quirk */ piix_iocfg_bit18_quirk(host); /* On ICH5, some BIOSen disable the interrupt using the * PCI_COMMAND_INTX_DISABLE bit added in PCI 2.3. * On ICH6, this bit has the same effect, but only when * MSI is disabled (and it is disabled, as we don't use * message-signalled interrupts currently). */ if (port_flags & PIIX_FLAG_CHECKINTR) pci_intx(pdev, 1); if (piix_check_450nx_errata(pdev)) { /* This writes into the master table but it does not really matter for this errata as we will apply it to all the PIIX devices on the board */ host->ports[0]->mwdma_mask = 0; host->ports[0]->udma_mask = 0; host->ports[1]->mwdma_mask = 0; host->ports[1]->udma_mask = 0; } host->flags |= ATA_HOST_PARALLEL_SCAN; /* Allow hosts to specify device types to ignore when scanning. */ piix_ignore_devices_quirk(host); pci_set_master(pdev); return ata_pci_sff_activate_host(host, ata_bmdma_interrupt, sht); } static void piix_remove_one(struct pci_dev *pdev) { struct ata_host *host = dev_get_drvdata(&pdev->dev); struct piix_host_priv *hpriv = host->private_data; pci_write_config_dword(pdev, PIIX_IOCFG, hpriv->saved_iocfg); ata_pci_remove_one(pdev); } static int __init piix_init(void) { int rc; DPRINTK("pci_register_driver\n"); rc = pci_register_driver(&piix_pci_driver); if (rc) return rc; in_module_init = 0; DPRINTK("done\n"); return 0; } static void __exit piix_exit(void) { pci_unregister_driver(&piix_pci_driver); } module_init(piix_init); module_exit(piix_exit);
gpl-2.0
dan-htc-touch/kernel_samsung_hlte
drivers/power/power_supply_sysfs.c
37
8910
/* * Sysfs interface for the universal power supply monitor class * * Copyright © 2007 David Woodhouse <dwmw2@infradead.org> * Copyright © 2007 Anton Vorontsov <cbou@mail.ru> * Copyright © 2004 Szabolcs Gyurko * Copyright © 2003 Ian Molton <spyro@f2s.com> * * Modified: 2004, Oct Szabolcs Gyurko * * You may use this code as per GPL version 2 */ #include <linux/ctype.h> #include <linux/device.h> #include <linux/power_supply.h> #include <linux/slab.h> #include <linux/stat.h> #include "power_supply.h" /* * This is because the name "current" breaks the device attr macro. * The "current" word resolves to "(get_current())" so instead of * "current" "(get_current())" appears in the sysfs. * * The source of this definition is the device.h which calls __ATTR * macro in sysfs.h which calls the __stringify macro. * * Only modification that the name is not tried to be resolved * (as a macro let's say). */ #define POWER_SUPPLY_ATTR(_name) \ { \ .attr = { .name = #_name }, \ .show = power_supply_show_property, \ .store = power_supply_store_property, \ } static struct device_attribute power_supply_attrs[]; static ssize_t power_supply_show_property(struct device *dev, struct device_attribute *attr, char *buf) { static char *type_text[] = { "Unknown", "Battery", "UPS", "Mains", "USB", "USB_DCP", "USB_CDP", "USB_ACA", "BMS", "MISC", "Wireless", "CARDOCK", "UARTOFF", "OTG", "LAN_HUB", "MHL_500", "MHL_900", "MHL_1500", "MHL_USB", "SMART_OTG", "SMART_NOTG", "POWER_SHARING", "WIRELESS_REMOVE" }; static char *status_text[] = { "Unknown", "Charging", "Discharging", "Not charging", "Full" }; static char *charge_type[] = { "Unknown", "N/A", "Trickle", "Fast", "Slow" }; static char *health_text[] = { "Unknown", "Good", "Overheat", "Warm", "Dead", "Over voltage", "Unspecified failure", "Cold", "Cool", "Under voltage" }; static char *technology_text[] = { "Unknown", "NiMH", "Li-ion", "Li-poly", "LiFe", "NiCd", "LiMn" }; static char *capacity_level_text[] = { "Unknown", "Critical", "Low", "Normal", "High", "Full" }; static char *scope_text[] = { "Unknown", "System", "Device" }; ssize_t ret = 0; struct power_supply *psy = dev_get_drvdata(dev); const ptrdiff_t off = attr - power_supply_attrs; union power_supply_propval value; if (off == POWER_SUPPLY_PROP_TYPE) value.intval = psy->type; else ret = psy->get_property(psy, off, &value); if (ret < 0) { if (ret == -ENODATA) dev_dbg(dev, "driver has no data for `%s' property\n", attr->attr.name); else if (ret != -ENODEV) dev_err(dev, "driver failed to report `%s' property: %zd\n", attr->attr.name, ret); return ret; } if (off == POWER_SUPPLY_PROP_STATUS) return sprintf(buf, "%s\n", status_text[value.intval]); else if (off == POWER_SUPPLY_PROP_CHARGE_TYPE) return sprintf(buf, "%s\n", charge_type[value.intval]); else if (off == POWER_SUPPLY_PROP_HEALTH) return sprintf(buf, "%s\n", health_text[value.intval]); else if (off == POWER_SUPPLY_PROP_TECHNOLOGY) return sprintf(buf, "%s\n", technology_text[value.intval]); else if (off == POWER_SUPPLY_PROP_CAPACITY_LEVEL) return sprintf(buf, "%s\n", capacity_level_text[value.intval]); else if (off == POWER_SUPPLY_PROP_TYPE) return sprintf(buf, "%s\n", type_text[value.intval]); else if (off == POWER_SUPPLY_PROP_SCOPE) return sprintf(buf, "%s\n", scope_text[value.intval]); else if (off >= POWER_SUPPLY_PROP_MODEL_NAME) return sprintf(buf, "%s\n", value.strval); return sprintf(buf, "%d\n", value.intval); } static ssize_t power_supply_store_property(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { ssize_t ret; struct power_supply *psy = dev_get_drvdata(dev); const ptrdiff_t off = attr - power_supply_attrs; union power_supply_propval value; long long_val; /* TODO: support other types than int */ ret = strict_strtol(buf, 10, &long_val); if (ret < 0) return ret; value.intval = long_val; ret = psy->set_property(psy, off, &value); if (ret < 0) return ret; return count; } /* Must be in the same order as POWER_SUPPLY_PROP_* */ static struct device_attribute power_supply_attrs[] = { /* Properties of type `int' */ POWER_SUPPLY_ATTR(status), POWER_SUPPLY_ATTR(charge_type), POWER_SUPPLY_ATTR(health), POWER_SUPPLY_ATTR(present), POWER_SUPPLY_ATTR(online), POWER_SUPPLY_ATTR(charging_enabled), POWER_SUPPLY_ATTR(technology), POWER_SUPPLY_ATTR(cycle_count), POWER_SUPPLY_ATTR(voltage_max), POWER_SUPPLY_ATTR(voltage_min), POWER_SUPPLY_ATTR(voltage_max_design), POWER_SUPPLY_ATTR(voltage_min_design), POWER_SUPPLY_ATTR(voltage_now), POWER_SUPPLY_ATTR(voltage_avg), POWER_SUPPLY_ATTR(input_voltage_regulation), POWER_SUPPLY_ATTR(voltage_ocv), POWER_SUPPLY_ATTR(current_max), POWER_SUPPLY_ATTR(input_current_max), POWER_SUPPLY_ATTR(input_current_trim), POWER_SUPPLY_ATTR(current_now), POWER_SUPPLY_ATTR(current_avg), POWER_SUPPLY_ATTR(power_now), POWER_SUPPLY_ATTR(power_avg), POWER_SUPPLY_ATTR(charge_full_design), POWER_SUPPLY_ATTR(charge_empty_design), POWER_SUPPLY_ATTR(charge_full), POWER_SUPPLY_ATTR(charge_empty), POWER_SUPPLY_ATTR(charge_now), POWER_SUPPLY_ATTR(charge_avg), POWER_SUPPLY_ATTR(charge_counter), POWER_SUPPLY_ATTR(charge_counter_shadow), POWER_SUPPLY_ATTR(energy_full_design), POWER_SUPPLY_ATTR(energy_empty_design), POWER_SUPPLY_ATTR(energy_full), POWER_SUPPLY_ATTR(energy_empty), POWER_SUPPLY_ATTR(energy_now), POWER_SUPPLY_ATTR(energy_avg), POWER_SUPPLY_ATTR(capacity), POWER_SUPPLY_ATTR(capacity_level), POWER_SUPPLY_ATTR(temp), POWER_SUPPLY_ATTR(temp_cool), POWER_SUPPLY_ATTR(temp_warm), POWER_SUPPLY_ATTR(temp_ambient), POWER_SUPPLY_ATTR(time_to_empty_now), POWER_SUPPLY_ATTR(time_to_empty_avg), POWER_SUPPLY_ATTR(time_to_full_now), POWER_SUPPLY_ATTR(time_to_full_avg), POWER_SUPPLY_ATTR(type), POWER_SUPPLY_ATTR(scope), POWER_SUPPLY_ATTR(system_temp_level), POWER_SUPPLY_ATTR(resistance), /* Properties of type `const char *' */ POWER_SUPPLY_ATTR(model_name), POWER_SUPPLY_ATTR(manufacturer), POWER_SUPPLY_ATTR(serial_number), }; static struct attribute * __power_supply_attrs[ARRAY_SIZE(power_supply_attrs) + 1]; static umode_t power_supply_attr_is_visible(struct kobject *kobj, struct attribute *attr, int attrno) { struct device *dev = container_of(kobj, struct device, kobj); struct power_supply *psy = dev_get_drvdata(dev); umode_t mode = S_IRUSR | S_IRGRP | S_IROTH; int i; if (attrno == POWER_SUPPLY_PROP_TYPE) return mode; for (i = 0; i < psy->num_properties; i++) { int property = psy->properties[i]; if (property == attrno) { if (psy->property_is_writeable && psy->property_is_writeable(psy, property) > 0) mode |= S_IWUSR; return mode; } } return 0; } static struct attribute_group power_supply_attr_group = { .attrs = __power_supply_attrs, .is_visible = power_supply_attr_is_visible, }; static const struct attribute_group *power_supply_attr_groups[] = { &power_supply_attr_group, NULL, }; void power_supply_init_attrs(struct device_type *dev_type) { int i; dev_type->groups = power_supply_attr_groups; for (i = 0; i < ARRAY_SIZE(power_supply_attrs); i++) __power_supply_attrs[i] = &power_supply_attrs[i].attr; } static char *kstruprdup(const char *str, gfp_t gfp) { char *ret, *ustr; ustr = ret = kmalloc(strlen(str) + 1, gfp); if (!ret) return NULL; while (*str) *ustr++ = toupper(*str++); *ustr = 0; return ret; } int power_supply_uevent(struct device *dev, struct kobj_uevent_env *env) { struct power_supply *psy = dev_get_drvdata(dev); int ret = 0, j; char *prop_buf; char *attrname; dev_dbg(dev, "uevent\n"); if (!psy || !psy->dev) { dev_dbg(dev, "No power supply yet\n"); return ret; } dev_dbg(dev, "POWER_SUPPLY_NAME=%s\n", psy->name); ret = add_uevent_var(env, "POWER_SUPPLY_NAME=%s", psy->name); if (ret) return ret; prop_buf = (char *)get_zeroed_page(GFP_KERNEL); if (!prop_buf) return -ENOMEM; for (j = 0; j < psy->num_properties; j++) { struct device_attribute *attr; char *line; attr = &power_supply_attrs[psy->properties[j]]; ret = power_supply_show_property(dev, attr, prop_buf); if (ret == -ENODEV || ret == -ENODATA) { /* When a battery is absent, we expect -ENODEV. Don't abort; send the uevent with at least the the PRESENT=0 property */ ret = 0; continue; } if (ret < 0) goto out; line = strchr(prop_buf, '\n'); if (line) *line = 0; attrname = kstruprdup(attr->attr.name, GFP_KERNEL); if (!attrname) { ret = -ENOMEM; goto out; } dev_dbg(dev, "prop %s=%s\n", attrname, prop_buf); ret = add_uevent_var(env, "POWER_SUPPLY_%s=%s", attrname, prop_buf); kfree(attrname); if (ret) goto out; } out: free_page((unsigned long)prop_buf); return ret; }
gpl-2.0
rsalveti/xbmc-eden
lib/ffmpeg/libavcodec/sh4/idct_sh4.c
37
9806
/* * idct for sh4 * * Copyright (c) 2001-2003 BERO <bero@geocities.co.jp> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavcodec/dsputil.h" #include "dsputil_sh4.h" #include "sh4.h" #define c1 1.38703984532214752434 /* sqrt(2)*cos(1*pi/16) */ #define c2 1.30656296487637657577 /* sqrt(2)*cos(2*pi/16) */ #define c3 1.17587560241935884520 /* sqrt(2)*cos(3*pi/16) */ #define c4 1.00000000000000000000 /* sqrt(2)*cos(4*pi/16) */ #define c5 0.78569495838710234903 /* sqrt(2)*cos(5*pi/16) */ #define c6 0.54119610014619712324 /* sqrt(2)*cos(6*pi/16) */ #define c7 0.27589937928294311353 /* sqrt(2)*cos(7*pi/16) */ static const float even_table[] __attribute__ ((aligned(8))) = { c4, c4, c4, c4, c2, c6,-c6,-c2, c4,-c4,-c4, c4, c6,-c2, c2,-c6 }; static const float odd_table[] __attribute__ ((aligned(8))) = { c1, c3, c5, c7, c3,-c7,-c1,-c5, c5,-c1, c7, c3, c7,-c5, c3,-c1 }; #undef c1 #undef c2 #undef c3 #undef c4 #undef c5 #undef c6 #undef c7 #if 1 #define load_matrix(table) \ do { \ const float *t = table; \ __asm__ volatile( \ " fschg\n" \ " fmov @%0+,xd0\n" \ " fmov @%0+,xd2\n" \ " fmov @%0+,xd4\n" \ " fmov @%0+,xd6\n" \ " fmov @%0+,xd8\n" \ " fmov @%0+,xd10\n" \ " fmov @%0+,xd12\n" \ " fmov @%0+,xd14\n" \ " fschg\n" \ : "+r"(t) \ ); \ } while (0) #define ftrv() \ __asm__ volatile("ftrv xmtrx,fv0" \ : "+f"(fr0),"+f"(fr1),"+f"(fr2),"+f"(fr3)); #define DEFREG \ register float fr0 __asm__("fr0"); \ register float fr1 __asm__("fr1"); \ register float fr2 __asm__("fr2"); \ register float fr3 __asm__("fr3") #else /* generic C code for check */ static void ftrv_(const float xf[],float fv[]) { float f0,f1,f2,f3; f0 = fv[0]; f1 = fv[1]; f2 = fv[2]; f3 = fv[3]; fv[0] = xf[0]*f0 + xf[4]*f1 + xf[ 8]*f2 + xf[12]*f3; fv[1] = xf[1]*f0 + xf[5]*f1 + xf[ 9]*f2 + xf[13]*f3; fv[2] = xf[2]*f0 + xf[6]*f1 + xf[10]*f2 + xf[14]*f3; fv[3] = xf[3]*f0 + xf[7]*f1 + xf[11]*f2 + xf[15]*f3; } static void load_matrix_(float xf[],const float table[]) { int i; for(i=0;i<16;i++) xf[i]=table[i]; } #define ftrv() ftrv_(xf,fv) #define load_matrix(table) load_matrix_(xf,table) #define DEFREG \ float fv[4],xf[16] #define fr0 fv[0] #define fr1 fv[1] #define fr2 fv[2] #define fr3 fv[3] #endif #if 1 #define DESCALE(x,n) (x)*(1.0f/(1<<(n))) #else #define DESCALE(x,n) (((int)(x)+(1<<(n-1)))>>(n)) #endif /* this code work worse on gcc cvs. 3.2.3 work fine */ #if 1 //optimized void idct_sh4(DCTELEM *block) { DEFREG; int i; float tblock[8*8],*fblock; int ofs1,ofs2,ofs3; int fpscr; fp_single_enter(fpscr); /* row */ /* even part */ load_matrix(even_table); fblock = tblock+4; i = 8; do { fr0 = block[0]; fr1 = block[2]; fr2 = block[4]; fr3 = block[6]; block+=8; ftrv(); *--fblock = fr3; *--fblock = fr2; *--fblock = fr1; *--fblock = fr0; fblock+=8+4; } while(--i); block-=8*8; fblock-=8*8+4; load_matrix(odd_table); i = 8; do { float t0,t1,t2,t3; fr0 = block[1]; fr1 = block[3]; fr2 = block[5]; fr3 = block[7]; block+=8; ftrv(); t0 = *fblock++; t1 = *fblock++; t2 = *fblock++; t3 = *fblock++; fblock+=4; *--fblock = t0 - fr0; *--fblock = t1 - fr1; *--fblock = t2 - fr2; *--fblock = t3 - fr3; *--fblock = t3 + fr3; *--fblock = t2 + fr2; *--fblock = t1 + fr1; *--fblock = t0 + fr0; fblock+=8; } while(--i); block-=8*8; fblock-=8*8; /* col */ /* even part */ load_matrix(even_table); ofs1 = sizeof(float)*2*8; ofs2 = sizeof(float)*4*8; ofs3 = sizeof(float)*6*8; i = 8; #define OA(fblock,ofs) *(float*)((char*)fblock + ofs) do { fr0 = OA(fblock, 0); fr1 = OA(fblock,ofs1); fr2 = OA(fblock,ofs2); fr3 = OA(fblock,ofs3); ftrv(); OA(fblock,0 ) = fr0; OA(fblock,ofs1) = fr1; OA(fblock,ofs2) = fr2; OA(fblock,ofs3) = fr3; fblock++; } while(--i); fblock-=8; load_matrix(odd_table); i=8; do { float t0,t1,t2,t3; t0 = OA(fblock, 0); /* [8*0] */ t1 = OA(fblock,ofs1); /* [8*2] */ t2 = OA(fblock,ofs2); /* [8*4] */ t3 = OA(fblock,ofs3); /* [8*6] */ fblock+=8; fr0 = OA(fblock, 0); /* [8*1] */ fr1 = OA(fblock,ofs1); /* [8*3] */ fr2 = OA(fblock,ofs2); /* [8*5] */ fr3 = OA(fblock,ofs3); /* [8*7] */ fblock+=-8+1; ftrv(); block[8*0] = DESCALE(t0 + fr0,3); block[8*7] = DESCALE(t0 - fr0,3); block[8*1] = DESCALE(t1 + fr1,3); block[8*6] = DESCALE(t1 - fr1,3); block[8*2] = DESCALE(t2 + fr2,3); block[8*5] = DESCALE(t2 - fr2,3); block[8*3] = DESCALE(t3 + fr3,3); block[8*4] = DESCALE(t3 - fr3,3); block++; } while(--i); fp_single_leave(fpscr); } #else void idct_sh4(DCTELEM *block) { DEFREG; int i; float tblock[8*8],*fblock; /* row */ /* even part */ load_matrix(even_table); fblock = tblock; i = 8; do { fr0 = block[0]; fr1 = block[2]; fr2 = block[4]; fr3 = block[6]; block+=8; ftrv(); fblock[0] = fr0; fblock[2] = fr1; fblock[4] = fr2; fblock[6] = fr3; fblock+=8; } while(--i); block-=8*8; fblock-=8*8; load_matrix(odd_table); i = 8; do { float t0,t1,t2,t3; fr0 = block[1]; fr1 = block[3]; fr2 = block[5]; fr3 = block[7]; block+=8; ftrv(); t0 = fblock[0]; t1 = fblock[2]; t2 = fblock[4]; t3 = fblock[6]; fblock[0] = t0 + fr0; fblock[7] = t0 - fr0; fblock[1] = t1 + fr1; fblock[6] = t1 - fr1; fblock[2] = t2 + fr2; fblock[5] = t2 - fr2; fblock[3] = t3 + fr3; fblock[4] = t3 - fr3; fblock+=8; } while(--i); block-=8*8; fblock-=8*8; /* col */ /* even part */ load_matrix(even_table); i = 8; do { fr0 = fblock[8*0]; fr1 = fblock[8*2]; fr2 = fblock[8*4]; fr3 = fblock[8*6]; ftrv(); fblock[8*0] = fr0; fblock[8*2] = fr1; fblock[8*4] = fr2; fblock[8*6] = fr3; fblock++; } while(--i); fblock-=8; load_matrix(odd_table); i=8; do { float t0,t1,t2,t3; fr0 = fblock[8*1]; fr1 = fblock[8*3]; fr2 = fblock[8*5]; fr3 = fblock[8*7]; ftrv(); t0 = fblock[8*0]; t1 = fblock[8*2]; t2 = fblock[8*4]; t3 = fblock[8*6]; fblock++; block[8*0] = DESCALE(t0 + fr0,3); block[8*7] = DESCALE(t0 - fr0,3); block[8*1] = DESCALE(t1 + fr1,3); block[8*6] = DESCALE(t1 - fr1,3); block[8*2] = DESCALE(t2 + fr2,3); block[8*5] = DESCALE(t2 - fr2,3); block[8*3] = DESCALE(t3 + fr3,3); block[8*4] = DESCALE(t3 - fr3,3); block++; } while(--i); } #endif
gpl-2.0
Distrotech/mysql
storage/myisam/mi_test2.c
37
30837
/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. 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; 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. You 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 */ /* Test av isam-databas: stor test */ #ifndef USE_MY_FUNC /* We want to be able to dbug this !! */ #define USE_MY_FUNC #endif #ifdef DBUG_OFF #undef DBUG_OFF #endif #include "myisamdef.h" #include <m_ctype.h> #include <my_bit.h> #define STANDARD_LENGTH 37 #define MYISAM_KEYS 6 #define MAX_PARTS 4 #if !defined(labs) #define labs(a) abs(a) #endif static void get_options(int argc, char *argv[]); static uint rnd(uint max_value); static void fix_length(uchar *record,uint length); static void put_blob_in_record(uchar *blob_pos,char **blob_buffer); static void copy_key(struct st_myisam_info *info,uint inx, uchar *record,uchar *key); static int verbose=0,testflag=0, first_key=0,async_io=0,key_cacheing=0,write_cacheing=0,locking=0, rec_pointer_size=0,pack_fields=1,use_log=0,silent=0, opt_quick_mode=0; static int pack_seg=HA_SPACE_PACK,pack_type=HA_PACK_KEY,remove_count=-1, create_flag=0; static ulong key_cache_size=IO_SIZE*16; static uint key_cache_block_size= KEY_CACHE_BLOCK_SIZE; static uint keys=MYISAM_KEYS,recant=1000; static uint use_blob=0; static uint16 key1[1001],key3[5000]; static uchar record[300],record2[300],key[100],key2[100]; static uchar read_record[300],read_record2[300],read_record3[300]; static HA_KEYSEG glob_keyseg[MYISAM_KEYS][MAX_PARTS]; /* Test program */ int main(int argc, char *argv[]) { uint i; int j,n1,n2,n3,error,k; uint write_count,update,dupp_keys,opt_delete,start,length,blob_pos, reclength,ant,found_parts; my_off_t lastpos; ha_rows range_records,records; MI_INFO *file; MI_KEYDEF keyinfo[10]; MI_COLUMNDEF recinfo[10]; MI_ISAMINFO info; const char *filename; char *blob_buffer; MI_CREATE_INFO create_info; MY_INIT(argv[0]); filename= "test2"; get_options(argc,argv); if (! async_io) my_disable_async_io=1; reclength=STANDARD_LENGTH+60+(use_blob ? 8 : 0); blob_pos=STANDARD_LENGTH+60; keyinfo[0].seg= &glob_keyseg[0][0]; keyinfo[0].seg[0].start=0; keyinfo[0].seg[0].length=6; keyinfo[0].seg[0].type=HA_KEYTYPE_TEXT; keyinfo[0].seg[0].language= default_charset_info->number; keyinfo[0].seg[0].flag=(uint8) pack_seg; keyinfo[0].seg[0].null_bit=0; keyinfo[0].seg[0].null_pos=0; keyinfo[0].key_alg=HA_KEY_ALG_BTREE; keyinfo[0].keysegs=1; keyinfo[0].flag = pack_type; keyinfo[0].block_length= 0; /* Default block length */ keyinfo[1].seg= &glob_keyseg[1][0]; keyinfo[1].seg[0].start=7; keyinfo[1].seg[0].length=6; keyinfo[1].seg[0].type=HA_KEYTYPE_BINARY; keyinfo[1].seg[0].flag=0; keyinfo[1].seg[0].null_bit=0; keyinfo[1].seg[0].null_pos=0; keyinfo[1].seg[1].start=0; /* two part key */ keyinfo[1].seg[1].length=6; keyinfo[1].seg[1].type=HA_KEYTYPE_NUM; keyinfo[1].seg[1].flag=HA_REVERSE_SORT; keyinfo[1].seg[1].null_bit=0; keyinfo[1].seg[1].null_pos=0; keyinfo[1].key_alg=HA_KEY_ALG_BTREE; keyinfo[1].keysegs=2; keyinfo[1].flag =0; keyinfo[1].block_length= MI_MIN_KEY_BLOCK_LENGTH; /* Diff blocklength */ keyinfo[2].seg= &glob_keyseg[2][0]; keyinfo[2].seg[0].start=12; keyinfo[2].seg[0].length=8; keyinfo[2].seg[0].type=HA_KEYTYPE_BINARY; keyinfo[2].seg[0].flag=HA_REVERSE_SORT; keyinfo[2].seg[0].null_bit=0; keyinfo[2].seg[0].null_pos=0; keyinfo[2].key_alg=HA_KEY_ALG_BTREE; keyinfo[2].keysegs=1; keyinfo[2].flag =HA_NOSAME; keyinfo[2].block_length= 0; /* Default block length */ keyinfo[3].seg= &glob_keyseg[3][0]; keyinfo[3].seg[0].start=0; keyinfo[3].seg[0].length=reclength-(use_blob ? 8 : 0); keyinfo[3].seg[0].type=HA_KEYTYPE_TEXT; keyinfo[3].seg[0].language=default_charset_info->number; keyinfo[3].seg[0].flag=(uint8) pack_seg; keyinfo[3].seg[0].null_bit=0; keyinfo[3].seg[0].null_pos=0; keyinfo[3].key_alg=HA_KEY_ALG_BTREE; keyinfo[3].keysegs=1; keyinfo[3].flag = pack_type; keyinfo[3].block_length= 0; /* Default block length */ keyinfo[4].seg= &glob_keyseg[4][0]; keyinfo[4].seg[0].start=0; keyinfo[4].seg[0].length=5; keyinfo[4].seg[0].type=HA_KEYTYPE_TEXT; keyinfo[4].seg[0].language=default_charset_info->number; keyinfo[4].seg[0].flag=0; keyinfo[4].seg[0].null_bit=0; keyinfo[4].seg[0].null_pos=0; keyinfo[4].key_alg=HA_KEY_ALG_BTREE; keyinfo[4].keysegs=1; keyinfo[4].flag = pack_type; keyinfo[4].block_length= 0; /* Default block length */ keyinfo[5].seg= &glob_keyseg[5][0]; keyinfo[5].seg[0].start=0; keyinfo[5].seg[0].length=4; keyinfo[5].seg[0].type=HA_KEYTYPE_TEXT; keyinfo[5].seg[0].language=default_charset_info->number; keyinfo[5].seg[0].flag=pack_seg; keyinfo[5].seg[0].null_bit=0; keyinfo[5].seg[0].null_pos=0; keyinfo[5].key_alg=HA_KEY_ALG_BTREE; keyinfo[5].keysegs=1; keyinfo[5].flag = pack_type; keyinfo[5].block_length= 0; /* Default block length */ recinfo[0].type=pack_fields ? FIELD_SKIP_PRESPACE : 0; recinfo[0].length=7; recinfo[0].null_bit=0; recinfo[0].null_pos=0; recinfo[1].type=pack_fields ? FIELD_SKIP_PRESPACE : 0; recinfo[1].length=5; recinfo[1].null_bit=0; recinfo[1].null_pos=0; recinfo[2].type=pack_fields ? FIELD_SKIP_PRESPACE : 0; recinfo[2].length=9; recinfo[2].null_bit=0; recinfo[2].null_pos=0; recinfo[3].type=FIELD_NORMAL; recinfo[3].length=STANDARD_LENGTH-7-5-9-4; recinfo[3].null_bit=0; recinfo[3].null_pos=0; recinfo[4].type=pack_fields ? FIELD_SKIP_ZERO : 0; recinfo[4].length=4; recinfo[4].null_bit=0; recinfo[4].null_pos=0; recinfo[5].type=pack_fields ? FIELD_SKIP_ENDSPACE : 0; recinfo[5].length=60; recinfo[5].null_bit=0; recinfo[5].null_pos=0; if (use_blob) { recinfo[6].type=FIELD_BLOB; recinfo[6].length=4+portable_sizeof_char_ptr; recinfo[6].null_bit=0; recinfo[6].null_pos=0; } write_count=update=dupp_keys=opt_delete=0; blob_buffer=0; for (i=1000 ; i>0 ; i--) key1[i]=0; for (i=4999 ; i>0 ; i--) key3[i]=0; if (!silent) printf("- Creating isam-file\n"); /* DBUG_PUSH(""); */ /* my_delete(filename,MYF(0)); */ /* Remove old locks under gdb */ file= 0; bzero((char*) &create_info,sizeof(create_info)); create_info.max_rows=(ha_rows) (rec_pointer_size ? (1L << (rec_pointer_size*8))/ reclength : 0); create_info.reloc_rows=(ha_rows) 100; if (mi_create(filename,keys,&keyinfo[first_key], use_blob ? 7 : 6, &recinfo[0], 0,(MI_UNIQUEDEF*) 0, &create_info,create_flag)) goto err; if (use_log) mi_log(1); if (!(file=mi_open(filename,2,HA_OPEN_ABORT_IF_LOCKED))) goto err; if (!silent) printf("- Writing key:s\n"); if (key_cacheing) init_key_cache(dflt_key_cache,key_cache_block_size,key_cache_size,0,0); if (locking) mi_lock_database(file,F_WRLCK); if (write_cacheing) mi_extra(file,HA_EXTRA_WRITE_CACHE,0); if (opt_quick_mode) mi_extra(file,HA_EXTRA_QUICK,0); for (i=0 ; i < recant ; i++) { n1=rnd(1000); n2=rnd(100); n3=rnd(5000); sprintf((char*) record,"%6d:%4d:%8d:Pos: %4d ",n1,n2,n3,write_count); int4store(record+STANDARD_LENGTH-4,(long) i); fix_length(record,(uint) STANDARD_LENGTH+rnd(60)); put_blob_in_record(record+blob_pos,&blob_buffer); DBUG_PRINT("test",("record: %d",i)); if (mi_write(file,record)) { if (my_errno != HA_ERR_FOUND_DUPP_KEY || key3[n3] == 0) { printf("Error: %d in write at record: %d\n",my_errno,i); goto err; } if (verbose) printf(" Double key: %d\n",n3); } else { if (key3[n3] == 1 && first_key <3 && first_key+keys >= 3) { printf("Error: Didn't get error when writing second key: '%8d'\n",n3); goto err; } write_count++; key1[n1]++; key3[n3]=1; } /* Check if we can find key without flushing database */ if (i == recant/2) { for (j=rnd(1000)+1 ; j>0 && key1[j] == 0 ; j--) ; if (!j) for (j=999 ; j>0 && key1[j] == 0 ; j--) ; sprintf((char*) key,"%6d",j); if (mi_rkey(file,read_record,0,key,HA_WHOLE_KEY,HA_READ_KEY_EXACT)) { printf("Test in loop: Can't find key: \"%s\"\n",key); goto err; } } } if (testflag==1) goto end; if (write_cacheing) { if (mi_extra(file,HA_EXTRA_NO_CACHE,0)) { puts("got error from mi_extra(HA_EXTRA_NO_CACHE)"); goto end; } } if (key_cacheing) resize_key_cache(dflt_key_cache,key_cache_block_size,key_cache_size*2,0,0); if (!silent) printf("- Delete\n"); for (i=0 ; i<recant/10 ; i++) { for (j=rnd(1000)+1 ; j>0 && key1[j] == 0 ; j--) ; if (j != 0) { sprintf((char*) key,"%6d",j); if (mi_rkey(file,read_record,0,key,HA_WHOLE_KEY,HA_READ_KEY_EXACT)) { printf("can't find key1: \"%s\"\n",key); goto err; } if (opt_delete == (uint) remove_count) /* While testing */ goto end; if (mi_delete(file,read_record)) { printf("error: %d; can't delete record: \"%s\"\n", my_errno,read_record); goto err; } opt_delete++; key1[atoi((char*) read_record+keyinfo[0].seg[0].start)]--; key3[atoi((char*) read_record+keyinfo[2].seg[0].start)]=0; } else puts("Warning: Skipping delete test because no dupplicate keys"); } if (testflag==2) goto end; if (!silent) printf("- Update\n"); for (i=0 ; i<recant/10 ; i++) { n1=rnd(1000); n2=rnd(100); n3=rnd(5000); sprintf((char*) record2,"%6d:%4d:%8d:XXX: %4d ",n1,n2,n3,update); int4store(record2+STANDARD_LENGTH-4,(long) i); fix_length(record2,(uint) STANDARD_LENGTH+rnd(60)); for (j=rnd(1000)+1 ; j>0 && key1[j] == 0 ; j--) ; if (j != 0) { sprintf((char*) key,"%6d",j); if (mi_rkey(file,read_record,0,key,HA_WHOLE_KEY,HA_READ_KEY_EXACT)) { printf("can't find key1: \"%s\"\n",(char*) key); goto err; } if (use_blob) { if (i & 1) put_blob_in_record(record+blob_pos,&blob_buffer); else bmove(record+blob_pos,read_record+blob_pos,8); } if (mi_update(file,read_record,record2)) { if (my_errno != HA_ERR_FOUND_DUPP_KEY || key3[n3] == 0) { printf("error: %d; can't update:\nFrom: \"%s\"\nTo: \"%s\"\n", my_errno,read_record,record2); goto err; } if (verbose) printf("Double key when tried to update:\nFrom: \"%s\"\nTo: \"%s\"\n",record,record2); } else { key1[atoi((char*) read_record+keyinfo[0].seg[0].start)]--; key3[atoi((char*) read_record+keyinfo[2].seg[0].start)]=0; key1[n1]++; key3[n3]=1; update++; } } } if (testflag == 3) goto end; for (i=999, dupp_keys=j=0 ; i>0 ; i--) { if (key1[i] > dupp_keys) { dupp_keys=key1[i]; j=i; } } sprintf((char*) key,"%6d",j); start=keyinfo[0].seg[0].start; length=keyinfo[0].seg[0].length; if (dupp_keys) { if (!silent) printf("- Same key: first - next -> last - prev -> first\n"); DBUG_PRINT("progpos",("first - next -> last - prev -> first")); if (verbose) printf(" Using key: \"%s\" Keys: %d\n",key,dupp_keys); if (mi_rkey(file,read_record,0,key,HA_WHOLE_KEY,HA_READ_KEY_EXACT)) goto err; if (mi_rsame(file,read_record2,-1)) goto err; if (memcmp(read_record,read_record2,reclength) != 0) { printf("mi_rsame didn't find same record\n"); goto end; } info.recpos=mi_position(file); if (mi_rfirst(file,read_record2,0) || mi_rsame_with_pos(file,read_record2,0,info.recpos) || memcmp(read_record,read_record2,reclength) != 0) { printf("mi_rsame_with_pos didn't find same record\n"); goto end; } { int skr=mi_rnext(file,read_record2,0); if ((skr && my_errno != HA_ERR_END_OF_FILE) || mi_rprev(file,read_record2,-1) || memcmp(read_record,read_record2,reclength) != 0) { printf("mi_rsame_with_pos lost position\n"); goto end; } } ant=1; while (mi_rnext(file,read_record2,0) == 0 && memcmp(read_record2+start,key,length) == 0) ant++; if (ant != dupp_keys) { printf("next: Found: %d keys of %d\n",ant,dupp_keys); goto end; } ant=0; while (mi_rprev(file,read_record3,0) == 0 && memcmp(read_record3+start,key,length) == 0) ant++; if (ant != dupp_keys) { printf("prev: Found: %d records of %d\n",ant,dupp_keys); goto end; } /* Check of mi_rnext_same */ if (mi_rkey(file,read_record,0,key,HA_WHOLE_KEY,HA_READ_KEY_EXACT)) goto err; ant=1; while (!mi_rnext_same(file,read_record3) && ant < dupp_keys+10) ant++; if (ant != dupp_keys || my_errno != HA_ERR_END_OF_FILE) { printf("mi_rnext_same: Found: %d records of %d\n",ant,dupp_keys); goto end; } } if (!silent) printf("- All keys: first - next -> last - prev -> first\n"); DBUG_PRINT("progpos",("All keys: first - next -> last - prev -> first")); ant=1; if (mi_rfirst(file,read_record,0)) { printf("Can't find first record\n"); goto end; } while ((error=mi_rnext(file,read_record3,0)) == 0 && ant < write_count+10) ant++; if (ant != write_count - opt_delete || error != HA_ERR_END_OF_FILE) { printf("next: I found: %d records of %d (error: %d)\n", ant, write_count - opt_delete, error); goto end; } if (mi_rlast(file,read_record2,0) || memcmp(read_record2,read_record3,reclength)) { printf("Can't find last record\n"); DBUG_DUMP("record2",(uchar*) read_record2,reclength); DBUG_DUMP("record3",(uchar*) read_record3,reclength); goto end; } ant=1; while (mi_rprev(file,read_record3,0) == 0 && ant < write_count+10) ant++; if (ant != write_count - opt_delete) { printf("prev: I found: %d records of %d\n",ant,write_count); goto end; } if (memcmp(read_record,read_record3,reclength)) { printf("Can't find first record\n"); goto end; } if (!silent) printf("- Test if: Read first - next - prev - prev - next == first\n"); DBUG_PRINT("progpos",("- Read first - next - prev - prev - next == first")); if (mi_rfirst(file,read_record,0) || mi_rnext(file,read_record3,0) || mi_rprev(file,read_record3,0) || mi_rprev(file,read_record3,0) == 0 || mi_rnext(file,read_record3,0)) goto err; if (memcmp(read_record,read_record3,reclength) != 0) printf("Can't find first record\n"); if (!silent) printf("- Test if: Read last - prev - next - next - prev == last\n"); DBUG_PRINT("progpos",("Read last - prev - next - next - prev == last")); if (mi_rlast(file,read_record2,0) || mi_rprev(file,read_record3,0) || mi_rnext(file,read_record3,0) || mi_rnext(file,read_record3,0) == 0 || mi_rprev(file,read_record3,0)) goto err; if (memcmp(read_record2,read_record3,reclength)) printf("Can't find last record\n"); #ifdef NOT_ANYMORE if (!silent) puts("- Test read key-part"); strmov(key2,key); for(i=strlen(key2) ; i-- > 1 ;) { key2[i]=0; /* The following row is just to catch some bugs in the key code */ bzero((char*) file->lastkey,file->s->base.max_key_length*2); if (mi_rkey(file,read_record,0,key2,(uint) i,HA_READ_PREFIX)) goto err; if (memcmp(read_record+start,key,(uint) i)) { puts("Didn't find right record"); goto end; } } #endif if (dupp_keys > 2) { if (!silent) printf("- Read key (first) - next - delete - next -> last\n"); DBUG_PRINT("progpos",("first - next - delete - next -> last")); if (mi_rkey(file,read_record,0,key,HA_WHOLE_KEY,HA_READ_KEY_EXACT)) goto err; if (mi_rnext(file,read_record3,0)) goto err; if (mi_delete(file,read_record3)) goto err; opt_delete++; ant=1; while (mi_rnext(file,read_record3,0) == 0 && memcmp(read_record3+start,key,length) == 0) ant++; if (ant != dupp_keys-1) { printf("next: I can only find: %d keys of %d\n",ant,dupp_keys-1); goto end; } } if (dupp_keys>4) { if (!silent) printf("- Read last of key - prev - delete - prev -> first\n"); DBUG_PRINT("progpos",("last - prev - delete - prev -> first")); if (mi_rprev(file,read_record3,0)) goto err; if (mi_rprev(file,read_record3,0)) goto err; if (mi_delete(file,read_record3)) goto err; opt_delete++; ant=1; while (mi_rprev(file,read_record3,0) == 0 && memcmp(read_record3+start,key,length) == 0) ant++; if (ant != dupp_keys-2) { printf("next: I can only find: %d keys of %d\n",ant,dupp_keys-2); goto end; } } if (dupp_keys > 6) { if (!silent) printf("- Read first - delete - next -> last\n"); DBUG_PRINT("progpos",("first - delete - next -> last")); if (mi_rkey(file,read_record3,0,key,HA_WHOLE_KEY,HA_READ_KEY_EXACT)) goto err; if (mi_delete(file,read_record3)) goto err; opt_delete++; ant=1; if (mi_rnext(file,read_record,0)) goto err; /* Skall finnas poster */ while (mi_rnext(file,read_record3,0) == 0 && memcmp(read_record3+start,key,length) == 0) ant++; if (ant != dupp_keys-3) { printf("next: I can only find: %d keys of %d\n",ant,dupp_keys-3); goto end; } if (!silent) printf("- Read last - delete - prev -> first\n"); DBUG_PRINT("progpos",("last - delete - prev -> first")); if (mi_rprev(file,read_record3,0)) goto err; if (mi_delete(file,read_record3)) goto err; opt_delete++; ant=0; while (mi_rprev(file,read_record3,0) == 0 && memcmp(read_record3+start,key,length) == 0) ant++; if (ant != dupp_keys-4) { printf("next: I can only find: %d keys of %d\n",ant,dupp_keys-4); goto end; } } if (!silent) puts("- Test if: Read rrnd - same"); DBUG_PRINT("progpos",("Read rrnd - same")); for (i=0 ; i < write_count ; i++) { if (mi_rrnd(file,read_record,i == 0 ? 0L : HA_OFFSET_ERROR) == 0) break; } if (i == write_count) goto err; bmove(read_record2,read_record,reclength); for (i=min(2,keys) ; i-- > 0 ;) { if (mi_rsame(file,read_record2,(int) i)) goto err; if (memcmp(read_record,read_record2,reclength) != 0) { printf("is_rsame didn't find same record\n"); goto end; } } if (!silent) puts("- Test mi_records_in_range"); mi_status(file,&info,HA_STATUS_VARIABLE); for (i=0 ; i < info.keys ; i++) { key_range min_key, max_key; if (mi_rfirst(file,read_record,(int) i) || mi_rlast(file,read_record2,(int) i)) goto err; copy_key(file,(uint) i,(uchar*) read_record,(uchar*) key); copy_key(file,(uint) i,(uchar*) read_record2,(uchar*) key2); min_key.key= key; min_key.keypart_map= HA_WHOLE_KEY; min_key.flag= HA_READ_KEY_EXACT; max_key.key= key2; max_key.keypart_map= HA_WHOLE_KEY; max_key.flag= HA_READ_AFTER_KEY; range_records= mi_records_in_range(file,(int) i, &min_key, &max_key); if (range_records < info.records*8/10 || range_records > info.records*12/10) { printf("mi_records_range returned %ld; Should be about %ld\n", (long) range_records,(long) info.records); goto end; } if (verbose) { printf("mi_records_range returned %ld; Exact is %ld (diff: %4.2g %%)\n", (long) range_records, (long) info.records, labs((long) range_records - (long) info.records)*100.0/ info.records); } } for (i=0 ; i < 5 ; i++) { for (j=rnd(1000)+1 ; j>0 && key1[j] == 0 ; j--) ; for (k=rnd(1000)+1 ; k>0 && key1[k] == 0 ; k--) ; if (j != 0 && k != 0) { key_range min_key, max_key; if (j > k) swap_variables(int, j, k); sprintf((char*) key,"%6d",j); sprintf((char*) key2,"%6d",k); min_key.key= key; min_key.length= USE_WHOLE_KEY; min_key.flag= HA_READ_AFTER_KEY; max_key.key= key2; max_key.length= USE_WHOLE_KEY; max_key.flag= HA_READ_BEFORE_KEY; range_records= mi_records_in_range(file, 0, &min_key, &max_key); records=0; for (j++ ; j < k ; j++) records+=key1[j]; if ((long) range_records < (long) records*7/10-2 || (long) range_records > (long) records*14/10+2) { printf("mi_records_range for key: %d returned %lu; Should be about %lu\n", i, (ulong) range_records, (ulong) records); goto end; } if (verbose && records) { printf("mi_records_range returned %lu; Exact is %lu (diff: %4.2g %%)\n", (ulong) range_records, (ulong) records, labs((long) range_records-(long) records)*100.0/records); } } } if (!silent) printf("- mi_info\n"); mi_status(file,&info,HA_STATUS_VARIABLE | HA_STATUS_CONST); if (info.records != write_count-opt_delete || info.deleted > opt_delete + update || info.keys != keys) { puts("Wrong info from mi_info"); printf("Got: records: %lu delete: %lu i_keys: %d\n", (ulong) info.records, (ulong) info.deleted, info.keys); } if (verbose) { char buff[80]; get_date(buff,3,info.create_time); printf("info: Created %s\n",buff); get_date(buff,3,info.check_time); printf("info: checked %s\n",buff); get_date(buff,3,info.update_time); printf("info: Modified %s\n",buff); } mi_panic(HA_PANIC_WRITE); mi_panic(HA_PANIC_READ); if (mi_is_changed(file)) puts("Warning: mi_is_changed reported that datafile was changed"); if (!silent) printf("- mi_extra(CACHE) + mi_rrnd.... + mi_extra(NO_CACHE)\n"); if (mi_reset(file) || mi_extra(file,HA_EXTRA_CACHE,0)) { if (locking || (!use_blob && !pack_fields)) { puts("got error from mi_extra(HA_EXTRA_CACHE)"); goto end; } } ant=0; while ((error=mi_rrnd(file,record,HA_OFFSET_ERROR)) != HA_ERR_END_OF_FILE && ant < write_count + 10) ant+= error ? 0 : 1; if (ant != write_count-opt_delete) { printf("rrnd with cache: I can only find: %d records of %d\n", ant,write_count-opt_delete); goto end; } if (mi_extra(file,HA_EXTRA_NO_CACHE,0)) { puts("got error from mi_extra(HA_EXTRA_NO_CACHE)"); goto end; } ant=0; mi_scan_init(file); while ((error=mi_scan(file,record)) != HA_ERR_END_OF_FILE && ant < write_count + 10) ant+= error ? 0 : 1; if (ant != write_count-opt_delete) { printf("scan with cache: I can only find: %d records of %d\n", ant,write_count-opt_delete); goto end; } if (testflag == 4) goto end; if (!silent) printf("- Removing keys\n"); DBUG_PRINT("progpos",("Removing keys")); lastpos = HA_OFFSET_ERROR; /* DBUG_POP(); */ mi_reset(file); found_parts=0; while ((error=mi_rrnd(file,read_record,HA_OFFSET_ERROR)) != HA_ERR_END_OF_FILE) { info.recpos=mi_position(file); if (lastpos >= info.recpos && lastpos != HA_OFFSET_ERROR) { printf("mi_rrnd didn't advance filepointer; old: %ld, new: %ld\n", (long) lastpos, (long) info.recpos); goto err; } lastpos=info.recpos; if (error == 0) { if (opt_delete == (uint) remove_count) /* While testing */ goto end; if (mi_rsame(file,read_record,-1)) { printf("can't find record %lx\n",(long) info.recpos); goto err; } if (use_blob) { ulong blob_length,pos; uchar *ptr; longget(blob_length,read_record+blob_pos+4); ptr=(uchar*) blob_length; longget(blob_length,read_record+blob_pos); for (pos=0 ; pos < blob_length ; pos++) { if (ptr[pos] != (uchar) (blob_length+pos)) { printf("found blob with wrong info at %ld\n",(long) lastpos); use_blob=0; break; } } } if (mi_delete(file,read_record)) { printf("can't delete record: %6.6s, delete_count: %d\n", read_record, opt_delete); goto err; } opt_delete++; } else found_parts++; } if (my_errno != HA_ERR_END_OF_FILE && my_errno != HA_ERR_RECORD_DELETED) printf("error: %d from mi_rrnd\n",my_errno); if (write_count != opt_delete) { printf("Deleted only %d of %d records (%d parts)\n",opt_delete,write_count, found_parts); goto err; } end: if (mi_close(file)) goto err; mi_panic(HA_PANIC_CLOSE); /* Should close log */ if (!silent) { printf("\nFollowing test have been made:\n"); printf("Write records: %d\nUpdate records: %d\nSame-key-read: %d\nDelete records: %d\n", write_count,update,dupp_keys,opt_delete); if (rec_pointer_size) printf("Record pointer size: %d\n",rec_pointer_size); printf("myisam_block_size: %lu\n", myisam_block_size); if (key_cacheing) { puts("Key cache used"); printf("key_cache_block_size: %u\n", key_cache_block_size); if (write_cacheing) puts("Key cache resized"); } if (write_cacheing) puts("Write cacheing used"); if (write_cacheing) puts("quick mode"); if (async_io && locking) puts("Asyncron io with locking used"); else if (locking) puts("Locking used"); if (use_blob) puts("blobs used"); printf("key cache status: \n\ blocks used:%10lu\n\ not flushed:%10lu\n\ w_requests: %10lu\n\ writes: %10lu\n\ r_requests: %10lu\n\ reads: %10lu\n", dflt_key_cache->blocks_used, dflt_key_cache->global_blocks_changed, (ulong) dflt_key_cache->global_cache_w_requests, (ulong) dflt_key_cache->global_cache_write, (ulong) dflt_key_cache->global_cache_r_requests, (ulong) dflt_key_cache->global_cache_read); } end_key_cache(dflt_key_cache,1); if (blob_buffer) my_free(blob_buffer); my_end(silent ? MY_CHECK_ERROR : MY_CHECK_ERROR | MY_GIVE_INFO); return(0); err: printf("got error: %d when using MyISAM-database\n",my_errno); if (file) (void) mi_close(file); return(1); } /* main */ /* l{ser optioner */ /* OBS! intierar endast DEBUG - ingen debuggning h{r ! */ static void get_options(int argc, char **argv) { char *pos,*progname; progname= argv[0]; while (--argc >0 && *(pos = *(++argv)) == '-' ) { switch(*++pos) { case 'B': pack_type= HA_BINARY_PACK_KEY; break; case 'b': use_blob=1; break; case 'K': /* Use key cacheing */ key_cacheing=1; if (*++pos) key_cache_size=atol(pos); break; case 'W': /* Use write cacheing */ write_cacheing=1; if (*++pos) my_default_record_cache_size=atoi(pos); break; case 'd': remove_count= atoi(++pos); break; case 'i': if (*++pos) srand(atoi(pos)); break; case 'l': use_log=1; break; case 'L': locking=1; break; case 'A': /* use asyncron io */ async_io=1; if (*++pos) my_default_record_cache_size=atoi(pos); break; case 'v': /* verbose */ verbose=1; break; case 'm': /* records */ if ((recant=atoi(++pos)) < 10) { fprintf(stderr,"record count must be >= 10\n"); exit(1); } break; case 'e': /* myisam_block_length */ if ((myisam_block_size= atoi(++pos)) < MI_MIN_KEY_BLOCK_LENGTH || myisam_block_size > MI_MAX_KEY_BLOCK_LENGTH) { fprintf(stderr,"Wrong myisam_block_length\n"); exit(1); } myisam_block_size= my_round_up_to_next_power(myisam_block_size); break; case 'E': /* myisam_block_length */ if ((key_cache_block_size=atoi(++pos)) < MI_MIN_KEY_BLOCK_LENGTH || key_cache_block_size > MI_MAX_KEY_BLOCK_LENGTH) { fprintf(stderr,"Wrong key_cache_block_size\n"); exit(1); } key_cache_block_size= my_round_up_to_next_power(key_cache_block_size); break; case 'f': if ((first_key=atoi(++pos)) < 0 || first_key >= MYISAM_KEYS) first_key=0; break; case 'k': if ((keys=(uint) atoi(++pos)) < 1 || keys > (uint) (MYISAM_KEYS-first_key)) keys=MYISAM_KEYS-first_key; break; case 'P': pack_type=0; /* Don't use DIFF_LENGTH */ pack_seg=0; break; case 'R': /* Length of record pointer */ rec_pointer_size=atoi(++pos); if (rec_pointer_size > 7) rec_pointer_size=0; break; case 'S': pack_fields=0; /* Static-length-records */ break; case 's': silent=1; break; case 't': testflag=atoi(++pos); /* testmod */ break; case 'q': opt_quick_mode=1; break; case 'c': create_flag|= HA_CREATE_CHECKSUM; break; case 'D': create_flag|=HA_CREATE_DELAY_KEY_WRITE; break; case '?': case 'I': case 'V': printf("%s Ver 1.2 for %s at %s\n",progname,SYSTEM_TYPE,MACHINE_TYPE); puts("By Monty, for your professional use\n"); printf("Usage: %s [-?AbBcDIKLPRqSsVWltv] [-k#] [-f#] [-m#] [-e#] [-E#] [-t#]\n", progname); exit(0); case '#': DBUG_PUSH (++pos); break; default: printf("Illegal option: '%c'\n",*pos); break; } } return; } /* get options */ /* Get a random value 0 <= x <= n */ static uint rnd(uint max_value) { return (uint) ((rand() & 32767)/32767.0*max_value); } /* rnd */ /* Create a variable length record */ static void fix_length(uchar *rec, uint length) { bmove(rec+STANDARD_LENGTH, "0123456789012345678901234567890123456789012345678901234567890", length-STANDARD_LENGTH); strfill((char*) rec+length,STANDARD_LENGTH+60-length,' '); } /* fix_length */ /* Put maybe a blob in record */ static void put_blob_in_record(uchar *blob_pos, char **blob_buffer) { ulong i,length; if (use_blob) { if (rnd(10) == 0) { if (! *blob_buffer && !(*blob_buffer=my_malloc((uint) use_blob,MYF(MY_WME)))) { use_blob=0; return; } length=rnd(use_blob); for (i=0 ; i < length ; i++) (*blob_buffer)[i]=(char) (length+i); int4store(blob_pos,length); memcpy(blob_pos+4, blob_buffer, sizeof(char*)); } else { int4store(blob_pos,0); } } return; } static void copy_key(MI_INFO *info,uint inx,uchar *rec,uchar *key_buff) { HA_KEYSEG *keyseg; for (keyseg=info->s->keyinfo[inx].seg ; keyseg->type ; keyseg++) { memcpy(key_buff,rec+keyseg->start,(size_t) keyseg->length); key_buff+=keyseg->length; } return; } #include "mi_extrafunc.h"
gpl-2.0
artemh/asuswrt-merlin
release/src-rt-7.14.114.x/src/linux/linux-2.6.36/drivers/staging/wlan-ng/prism2sta.c
293
58913
/* src/prism2/driver/prism2sta.c * * Implements the station functionality for prism2 * * 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 implements the module and linux pcmcia routines for the * prism2 driver. * * -------------------------------------------------------------------- */ #include <linux/version.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/types.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/wireless.h> #include <linux/netdevice.h> #include <linux/workqueue.h> #include <linux/byteorder/generic.h> #include <linux/ctype.h> #include <linux/io.h> #include <linux/delay.h> #include <asm/byteorder.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/bitops.h> #include "p80211types.h" #include "p80211hdr.h" #include "p80211mgmt.h" #include "p80211conv.h" #include "p80211msg.h" #include "p80211netdev.h" #include "p80211req.h" #include "p80211metadef.h" #include "p80211metastruct.h" #include "hfa384x.h" #include "prism2mgmt.h" /* Create a string of printable chars from something that might not be */ /* It's recommended that the str be 4*len + 1 bytes long */ #define wlan_mkprintstr(buf, buflen, str, strlen) \ { \ int i = 0; \ int j = 0; \ memset(str, 0, (strlen)); \ for (i = 0; i < (buflen); i++) { \ if (isprint((buf)[i])) { \ (str)[j] = (buf)[i]; \ j++; \ } else { \ (str)[j] = '\\'; \ (str)[j+1] = 'x'; \ (str)[j+2] = hex_asc_hi((buf)[i]); \ (str)[j+3] = hex_asc_lo((buf)[i]); \ j += 4; \ } \ } \ } static char *dev_info = "prism2_usb"; static wlandevice_t *create_wlan(void); int prism2_reset_holdtime = 30; /* Reset hold time in ms */ int prism2_reset_settletime = 100; /* Reset settle time in ms */ static int prism2_doreset; /* Do a reset at init? */ module_param(prism2_doreset, int, 0644); MODULE_PARM_DESC(prism2_doreset, "Issue a reset on initialization"); module_param(prism2_reset_holdtime, int, 0644); MODULE_PARM_DESC(prism2_reset_holdtime, "reset hold time in ms"); module_param(prism2_reset_settletime, int, 0644); MODULE_PARM_DESC(prism2_reset_settletime, "reset settle time in ms"); MODULE_LICENSE("Dual MPL/GPL"); void prism2_connect_result(wlandevice_t *wlandev, u8 failed); void prism2_disconnected(wlandevice_t *wlandev); void prism2_roamed(wlandevice_t *wlandev); static int prism2sta_open(wlandevice_t *wlandev); static int prism2sta_close(wlandevice_t *wlandev); static void prism2sta_reset(wlandevice_t *wlandev); static int prism2sta_txframe(wlandevice_t *wlandev, struct sk_buff *skb, union p80211_hdr *p80211_hdr, struct p80211_metawep *p80211_wep); static int prism2sta_mlmerequest(wlandevice_t *wlandev, struct p80211msg *msg); static int prism2sta_getcardinfo(wlandevice_t *wlandev); static int prism2sta_globalsetup(wlandevice_t *wlandev); static int prism2sta_setmulticast(wlandevice_t *wlandev, netdevice_t *dev); static void prism2sta_inf_handover(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_tallies(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_hostscanresults(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_scanresults(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_chinforesults(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_linkstatus(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_assocstatus(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_authreq(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_authreq_defer(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); static void prism2sta_inf_psusercnt(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf); /*---------------------------------------------------------------- * prism2sta_open * * WLAN device open method. Called from p80211netdev when kernel * device open (start) method is called in response to the * SIOCSIIFFLAGS ioctl changing the flags bit IFF_UP * from clear to set. * * Arguments: * wlandev wlan device structure * * Returns: * 0 success * >0 f/w reported error * <0 driver reported error * * Side effects: * * Call context: * process thread ----------------------------------------------------------------*/ static int prism2sta_open(wlandevice_t *wlandev) { /* We don't currently have to do anything else. * The setup of the MAC should be subsequently completed via * the mlme commands. * Higher layers know we're ready from dev->start==1 and * dev->tbusy==0. Our rx path knows to pass up received/ * frames because of dev->flags&IFF_UP is true. */ return 0; } /*---------------------------------------------------------------- * prism2sta_close * * WLAN device close method. Called from p80211netdev when kernel * device close method is called in response to the * SIOCSIIFFLAGS ioctl changing the flags bit IFF_UP * from set to clear. * * Arguments: * wlandev wlan device structure * * Returns: * 0 success * >0 f/w reported error * <0 driver reported error * * Side effects: * * Call context: * process thread ----------------------------------------------------------------*/ static int prism2sta_close(wlandevice_t *wlandev) { /* We don't currently have to do anything else. * Higher layers know we're not ready from dev->start==0 and * dev->tbusy==1. Our rx path knows to not pass up received * frames because of dev->flags&IFF_UP is false. */ return 0; } /*---------------------------------------------------------------- * prism2sta_reset * * Not currently implented. * * Arguments: * wlandev wlan device structure * none * * Returns: * nothing * * Side effects: * * Call context: * process thread ----------------------------------------------------------------*/ static void prism2sta_reset(wlandevice_t *wlandev) { return; } /*---------------------------------------------------------------- * prism2sta_txframe * * Takes a frame from p80211 and queues it for transmission. * * Arguments: * wlandev wlan device structure * pb packet buffer struct. Contains an 802.11 * data frame. * p80211_hdr points to the 802.11 header for the packet. * Returns: * 0 Success and more buffs available * 1 Success but no more buffs * 2 Allocation failure * 4 Buffer full or queue busy * * Side effects: * * Call context: * process thread ----------------------------------------------------------------*/ static int prism2sta_txframe(wlandevice_t *wlandev, struct sk_buff *skb, union p80211_hdr *p80211_hdr, struct p80211_metawep *p80211_wep) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; int result; /* If necessary, set the 802.11 WEP bit */ if ((wlandev->hostwep & (HOSTWEP_PRIVACYINVOKED | HOSTWEP_ENCRYPT)) == HOSTWEP_PRIVACYINVOKED) { p80211_hdr->a3.fc |= cpu_to_le16(WLAN_SET_FC_ISWEP(1)); } result = hfa384x_drvr_txframe(hw, skb, p80211_hdr, p80211_wep); return result; } /*---------------------------------------------------------------- * prism2sta_mlmerequest * * wlan command message handler. All we do here is pass the message * over to the prism2sta_mgmt_handler. * * Arguments: * wlandev wlan device structure * msg wlan command message * Returns: * 0 success * <0 successful acceptance of message, but we're * waiting for an async process to finish before * we're done with the msg. When the asynch * process is done, we'll call the p80211 * function p80211req_confirm() . * >0 An error occurred while we were handling * the message. * * Side effects: * * Call context: * process thread ----------------------------------------------------------------*/ static int prism2sta_mlmerequest(wlandevice_t *wlandev, struct p80211msg *msg) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; int result = 0; switch (msg->msgcode) { case DIDmsg_dot11req_mibget: pr_debug("Received mibget request\n"); result = prism2mgmt_mibset_mibget(wlandev, msg); break; case DIDmsg_dot11req_mibset: pr_debug("Received mibset request\n"); result = prism2mgmt_mibset_mibget(wlandev, msg); break; case DIDmsg_dot11req_scan: pr_debug("Received scan request\n"); result = prism2mgmt_scan(wlandev, msg); break; case DIDmsg_dot11req_scan_results: pr_debug("Received scan_results request\n"); result = prism2mgmt_scan_results(wlandev, msg); break; case DIDmsg_dot11req_start: pr_debug("Received mlme start request\n"); result = prism2mgmt_start(wlandev, msg); break; /* * Prism2 specific messages */ case DIDmsg_p2req_readpda: pr_debug("Received mlme readpda request\n"); result = prism2mgmt_readpda(wlandev, msg); break; case DIDmsg_p2req_ramdl_state: pr_debug("Received mlme ramdl_state request\n"); result = prism2mgmt_ramdl_state(wlandev, msg); break; case DIDmsg_p2req_ramdl_write: pr_debug("Received mlme ramdl_write request\n"); result = prism2mgmt_ramdl_write(wlandev, msg); break; case DIDmsg_p2req_flashdl_state: pr_debug("Received mlme flashdl_state request\n"); result = prism2mgmt_flashdl_state(wlandev, msg); break; case DIDmsg_p2req_flashdl_write: pr_debug("Received mlme flashdl_write request\n"); result = prism2mgmt_flashdl_write(wlandev, msg); break; /* * Linux specific messages */ case DIDmsg_lnxreq_hostwep: break; /* ignore me. */ case DIDmsg_lnxreq_ifstate: { struct p80211msg_lnxreq_ifstate *ifstatemsg; pr_debug("Received mlme ifstate request\n"); ifstatemsg = (struct p80211msg_lnxreq_ifstate *) msg; result = prism2sta_ifstate(wlandev, ifstatemsg->ifstate.data); ifstatemsg->resultcode.status = P80211ENUM_msgitem_status_data_ok; ifstatemsg->resultcode.data = result; result = 0; } break; case DIDmsg_lnxreq_wlansniff: pr_debug("Received mlme wlansniff request\n"); result = prism2mgmt_wlansniff(wlandev, msg); break; case DIDmsg_lnxreq_autojoin: pr_debug("Received mlme autojoin request\n"); result = prism2mgmt_autojoin(wlandev, msg); break; case DIDmsg_lnxreq_commsquality:{ struct p80211msg_lnxreq_commsquality *qualmsg; pr_debug("Received commsquality request\n"); qualmsg = (struct p80211msg_lnxreq_commsquality *) msg; qualmsg->link.status = P80211ENUM_msgitem_status_data_ok; qualmsg->level.status = P80211ENUM_msgitem_status_data_ok; qualmsg->noise.status = P80211ENUM_msgitem_status_data_ok; qualmsg->link.data = le16_to_cpu(hw->qual.CQ_currBSS); qualmsg->level.data = le16_to_cpu(hw->qual.ASL_currBSS); qualmsg->noise.data = le16_to_cpu(hw->qual.ANL_currFC); qualmsg->txrate.data = hw->txrate; break; } default: printk(KERN_WARNING "Unknown mgmt request message 0x%08x", msg->msgcode); break; } return result; } /*---------------------------------------------------------------- * prism2sta_ifstate * * Interface state. This is the primary WLAN interface enable/disable * handler. Following the driver/load/deviceprobe sequence, this * function must be called with a state of "enable" before any other * commands will be accepted. * * Arguments: * wlandev wlan device structure * msgp ptr to msg buffer * * Returns: * A p80211 message resultcode value. * * Side effects: * * Call context: * process thread (usually) * interrupt ----------------------------------------------------------------*/ u32 prism2sta_ifstate(wlandevice_t *wlandev, u32 ifstate) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; u32 result; result = P80211ENUM_resultcode_implementation_failure; pr_debug("Current MSD state(%d), requesting(%d)\n", wlandev->msdstate, ifstate); switch (ifstate) { case P80211ENUM_ifstate_fwload: switch (wlandev->msdstate) { case WLAN_MSD_HWPRESENT: wlandev->msdstate = WLAN_MSD_FWLOAD_PENDING; /* * Initialize the device+driver sufficiently * for firmware loading. */ result = hfa384x_drvr_start(hw); if (result) { printk(KERN_ERR "hfa384x_drvr_start() failed," "result=%d\n", (int)result); result = P80211ENUM_resultcode_implementation_failure; wlandev->msdstate = WLAN_MSD_HWPRESENT; break; } wlandev->msdstate = WLAN_MSD_FWLOAD; result = P80211ENUM_resultcode_success; break; case WLAN_MSD_FWLOAD: hfa384x_cmd_initialize(hw); result = P80211ENUM_resultcode_success; break; case WLAN_MSD_RUNNING: printk(KERN_WARNING "Cannot enter fwload state from enable state," "you must disable first.\n"); result = P80211ENUM_resultcode_invalid_parameters; break; case WLAN_MSD_HWFAIL: default: /* probe() had a problem or the msdstate contains * an unrecognized value, there's nothing we can do. */ result = P80211ENUM_resultcode_implementation_failure; break; } break; case P80211ENUM_ifstate_enable: switch (wlandev->msdstate) { case WLAN_MSD_HWPRESENT: case WLAN_MSD_FWLOAD: wlandev->msdstate = WLAN_MSD_RUNNING_PENDING; /* Initialize the device+driver for full * operation. Note that this might me an FWLOAD to * to RUNNING transition so we must not do a chip * or board level reset. Note that on failure, * the MSD state is set to HWPRESENT because we * can't make any assumptions about the state * of the hardware or a previous firmware load. */ result = hfa384x_drvr_start(hw); if (result) { printk(KERN_ERR "hfa384x_drvr_start() failed," "result=%d\n", (int)result); result = P80211ENUM_resultcode_implementation_failure; wlandev->msdstate = WLAN_MSD_HWPRESENT; break; } result = prism2sta_getcardinfo(wlandev); if (result) { printk(KERN_ERR "prism2sta_getcardinfo() failed," "result=%d\n", (int)result); result = P80211ENUM_resultcode_implementation_failure; hfa384x_drvr_stop(hw); wlandev->msdstate = WLAN_MSD_HWPRESENT; break; } result = prism2sta_globalsetup(wlandev); if (result) { printk(KERN_ERR "prism2sta_globalsetup() failed," "result=%d\n", (int)result); result = P80211ENUM_resultcode_implementation_failure; hfa384x_drvr_stop(hw); wlandev->msdstate = WLAN_MSD_HWPRESENT; break; } wlandev->msdstate = WLAN_MSD_RUNNING; hw->join_ap = 0; hw->join_retries = 60; result = P80211ENUM_resultcode_success; break; case WLAN_MSD_RUNNING: /* Do nothing, we're already in this state. */ result = P80211ENUM_resultcode_success; break; case WLAN_MSD_HWFAIL: default: /* probe() had a problem or the msdstate contains * an unrecognized value, there's nothing we can do. */ result = P80211ENUM_resultcode_implementation_failure; break; } break; case P80211ENUM_ifstate_disable: switch (wlandev->msdstate) { case WLAN_MSD_HWPRESENT: /* Do nothing, we're already in this state. */ result = P80211ENUM_resultcode_success; break; case WLAN_MSD_FWLOAD: case WLAN_MSD_RUNNING: wlandev->msdstate = WLAN_MSD_HWPRESENT_PENDING; /* * TODO: Shut down the MAC completely. Here a chip * or board level reset is probably called for. * After a "disable" _all_ results are lost, even * those from a fwload. */ if (!wlandev->hwremoved) netif_carrier_off(wlandev->netdev); hfa384x_drvr_stop(hw); wlandev->macmode = WLAN_MACMODE_NONE; wlandev->msdstate = WLAN_MSD_HWPRESENT; result = P80211ENUM_resultcode_success; break; case WLAN_MSD_HWFAIL: default: /* probe() had a problem or the msdstate contains * an unrecognized value, there's nothing we can do. */ result = P80211ENUM_resultcode_implementation_failure; break; } break; default: result = P80211ENUM_resultcode_invalid_parameters; break; } return result; } /*---------------------------------------------------------------- * prism2sta_getcardinfo * * Collect the NICID, firmware version and any other identifiers * we'd like to have in host-side data structures. * * Arguments: * wlandev wlan device structure * * Returns: * 0 success * >0 f/w reported error * <0 driver reported error * * Side effects: * * Call context: * Either. ----------------------------------------------------------------*/ static int prism2sta_getcardinfo(wlandevice_t *wlandev) { int result = 0; hfa384x_t *hw = (hfa384x_t *) wlandev->priv; u16 temp; u8 snum[HFA384x_RID_NICSERIALNUMBER_LEN]; char pstr[(HFA384x_RID_NICSERIALNUMBER_LEN * 4) + 1]; /* Collect version and compatibility info */ /* Some are critical, some are not */ /* NIC identity */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_NICIDENTITY, &hw->ident_nic, sizeof(hfa384x_compident_t)); if (result) { printk(KERN_ERR "Failed to retrieve NICIDENTITY\n"); goto failed; } /* get all the nic id fields in host byte order */ hw->ident_nic.id = le16_to_cpu(hw->ident_nic.id); hw->ident_nic.variant = le16_to_cpu(hw->ident_nic.variant); hw->ident_nic.major = le16_to_cpu(hw->ident_nic.major); hw->ident_nic.minor = le16_to_cpu(hw->ident_nic.minor); printk(KERN_INFO "ident: nic h/w: id=0x%02x %d.%d.%d\n", hw->ident_nic.id, hw->ident_nic.major, hw->ident_nic.minor, hw->ident_nic.variant); /* Primary f/w identity */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_PRIIDENTITY, &hw->ident_pri_fw, sizeof(hfa384x_compident_t)); if (result) { printk(KERN_ERR "Failed to retrieve PRIIDENTITY\n"); goto failed; } /* get all the private fw id fields in host byte order */ hw->ident_pri_fw.id = le16_to_cpu(hw->ident_pri_fw.id); hw->ident_pri_fw.variant = le16_to_cpu(hw->ident_pri_fw.variant); hw->ident_pri_fw.major = le16_to_cpu(hw->ident_pri_fw.major); hw->ident_pri_fw.minor = le16_to_cpu(hw->ident_pri_fw.minor); printk(KERN_INFO "ident: pri f/w: id=0x%02x %d.%d.%d\n", hw->ident_pri_fw.id, hw->ident_pri_fw.major, hw->ident_pri_fw.minor, hw->ident_pri_fw.variant); /* Station (Secondary?) f/w identity */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_STAIDENTITY, &hw->ident_sta_fw, sizeof(hfa384x_compident_t)); if (result) { printk(KERN_ERR "Failed to retrieve STAIDENTITY\n"); goto failed; } if (hw->ident_nic.id < 0x8000) { printk(KERN_ERR "FATAL: Card is not an Intersil Prism2/2.5/3\n"); result = -1; goto failed; } /* get all the station fw id fields in host byte order */ hw->ident_sta_fw.id = le16_to_cpu(hw->ident_sta_fw.id); hw->ident_sta_fw.variant = le16_to_cpu(hw->ident_sta_fw.variant); hw->ident_sta_fw.major = le16_to_cpu(hw->ident_sta_fw.major); hw->ident_sta_fw.minor = le16_to_cpu(hw->ident_sta_fw.minor); /* strip out the 'special' variant bits */ hw->mm_mods = hw->ident_sta_fw.variant & (BIT(14) | BIT(15)); hw->ident_sta_fw.variant &= ~((u16) (BIT(14) | BIT(15))); if (hw->ident_sta_fw.id == 0x1f) { printk(KERN_INFO "ident: sta f/w: id=0x%02x %d.%d.%d\n", hw->ident_sta_fw.id, hw->ident_sta_fw.major, hw->ident_sta_fw.minor, hw->ident_sta_fw.variant); } else { printk(KERN_INFO "ident: ap f/w: id=0x%02x %d.%d.%d\n", hw->ident_sta_fw.id, hw->ident_sta_fw.major, hw->ident_sta_fw.minor, hw->ident_sta_fw.variant); printk(KERN_ERR "Unsupported Tertiary AP firmeare loaded!\n"); goto failed; } /* Compatibility range, Modem supplier */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_MFISUPRANGE, &hw->cap_sup_mfi, sizeof(hfa384x_caplevel_t)); if (result) { printk(KERN_ERR "Failed to retrieve MFISUPRANGE\n"); goto failed; } /* get all the Compatibility range, modem interface supplier fields in byte order */ hw->cap_sup_mfi.role = le16_to_cpu(hw->cap_sup_mfi.role); hw->cap_sup_mfi.id = le16_to_cpu(hw->cap_sup_mfi.id); hw->cap_sup_mfi.variant = le16_to_cpu(hw->cap_sup_mfi.variant); hw->cap_sup_mfi.bottom = le16_to_cpu(hw->cap_sup_mfi.bottom); hw->cap_sup_mfi.top = le16_to_cpu(hw->cap_sup_mfi.top); printk(KERN_INFO "MFI:SUP:role=0x%02x:id=0x%02x:var=0x%02x:b/t=%d/%d\n", hw->cap_sup_mfi.role, hw->cap_sup_mfi.id, hw->cap_sup_mfi.variant, hw->cap_sup_mfi.bottom, hw->cap_sup_mfi.top); /* Compatibility range, Controller supplier */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_CFISUPRANGE, &hw->cap_sup_cfi, sizeof(hfa384x_caplevel_t)); if (result) { printk(KERN_ERR "Failed to retrieve CFISUPRANGE\n"); goto failed; } /* get all the Compatibility range, controller interface supplier fields in byte order */ hw->cap_sup_cfi.role = le16_to_cpu(hw->cap_sup_cfi.role); hw->cap_sup_cfi.id = le16_to_cpu(hw->cap_sup_cfi.id); hw->cap_sup_cfi.variant = le16_to_cpu(hw->cap_sup_cfi.variant); hw->cap_sup_cfi.bottom = le16_to_cpu(hw->cap_sup_cfi.bottom); hw->cap_sup_cfi.top = le16_to_cpu(hw->cap_sup_cfi.top); printk(KERN_INFO "CFI:SUP:role=0x%02x:id=0x%02x:var=0x%02x:b/t=%d/%d\n", hw->cap_sup_cfi.role, hw->cap_sup_cfi.id, hw->cap_sup_cfi.variant, hw->cap_sup_cfi.bottom, hw->cap_sup_cfi.top); /* Compatibility range, Primary f/w supplier */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_PRISUPRANGE, &hw->cap_sup_pri, sizeof(hfa384x_caplevel_t)); if (result) { printk(KERN_ERR "Failed to retrieve PRISUPRANGE\n"); goto failed; } /* get all the Compatibility range, primary firmware supplier fields in byte order */ hw->cap_sup_pri.role = le16_to_cpu(hw->cap_sup_pri.role); hw->cap_sup_pri.id = le16_to_cpu(hw->cap_sup_pri.id); hw->cap_sup_pri.variant = le16_to_cpu(hw->cap_sup_pri.variant); hw->cap_sup_pri.bottom = le16_to_cpu(hw->cap_sup_pri.bottom); hw->cap_sup_pri.top = le16_to_cpu(hw->cap_sup_pri.top); printk(KERN_INFO "PRI:SUP:role=0x%02x:id=0x%02x:var=0x%02x:b/t=%d/%d\n", hw->cap_sup_pri.role, hw->cap_sup_pri.id, hw->cap_sup_pri.variant, hw->cap_sup_pri.bottom, hw->cap_sup_pri.top); /* Compatibility range, Station f/w supplier */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_STASUPRANGE, &hw->cap_sup_sta, sizeof(hfa384x_caplevel_t)); if (result) { printk(KERN_ERR "Failed to retrieve STASUPRANGE\n"); goto failed; } /* get all the Compatibility range, station firmware supplier fields in byte order */ hw->cap_sup_sta.role = le16_to_cpu(hw->cap_sup_sta.role); hw->cap_sup_sta.id = le16_to_cpu(hw->cap_sup_sta.id); hw->cap_sup_sta.variant = le16_to_cpu(hw->cap_sup_sta.variant); hw->cap_sup_sta.bottom = le16_to_cpu(hw->cap_sup_sta.bottom); hw->cap_sup_sta.top = le16_to_cpu(hw->cap_sup_sta.top); if (hw->cap_sup_sta.id == 0x04) { printk(KERN_INFO "STA:SUP:role=0x%02x:id=0x%02x:var=0x%02x:b/t=%d/%d\n", hw->cap_sup_sta.role, hw->cap_sup_sta.id, hw->cap_sup_sta.variant, hw->cap_sup_sta.bottom, hw->cap_sup_sta.top); } else { printk(KERN_INFO "AP:SUP:role=0x%02x:id=0x%02x:var=0x%02x:b/t=%d/%d\n", hw->cap_sup_sta.role, hw->cap_sup_sta.id, hw->cap_sup_sta.variant, hw->cap_sup_sta.bottom, hw->cap_sup_sta.top); } /* Compatibility range, primary f/w actor, CFI supplier */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_PRI_CFIACTRANGES, &hw->cap_act_pri_cfi, sizeof(hfa384x_caplevel_t)); if (result) { printk(KERN_ERR "Failed to retrieve PRI_CFIACTRANGES\n"); goto failed; } /* get all the Compatibility range, primary f/w actor, CFI supplier fields in byte order */ hw->cap_act_pri_cfi.role = le16_to_cpu(hw->cap_act_pri_cfi.role); hw->cap_act_pri_cfi.id = le16_to_cpu(hw->cap_act_pri_cfi.id); hw->cap_act_pri_cfi.variant = le16_to_cpu(hw->cap_act_pri_cfi.variant); hw->cap_act_pri_cfi.bottom = le16_to_cpu(hw->cap_act_pri_cfi.bottom); hw->cap_act_pri_cfi.top = le16_to_cpu(hw->cap_act_pri_cfi.top); printk(KERN_INFO "PRI-CFI:ACT:role=0x%02x:id=0x%02x:var=0x%02x:b/t=%d/%d\n", hw->cap_act_pri_cfi.role, hw->cap_act_pri_cfi.id, hw->cap_act_pri_cfi.variant, hw->cap_act_pri_cfi.bottom, hw->cap_act_pri_cfi.top); /* Compatibility range, sta f/w actor, CFI supplier */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_STA_CFIACTRANGES, &hw->cap_act_sta_cfi, sizeof(hfa384x_caplevel_t)); if (result) { printk(KERN_ERR "Failed to retrieve STA_CFIACTRANGES\n"); goto failed; } /* get all the Compatibility range, station f/w actor, CFI supplier fields in byte order */ hw->cap_act_sta_cfi.role = le16_to_cpu(hw->cap_act_sta_cfi.role); hw->cap_act_sta_cfi.id = le16_to_cpu(hw->cap_act_sta_cfi.id); hw->cap_act_sta_cfi.variant = le16_to_cpu(hw->cap_act_sta_cfi.variant); hw->cap_act_sta_cfi.bottom = le16_to_cpu(hw->cap_act_sta_cfi.bottom); hw->cap_act_sta_cfi.top = le16_to_cpu(hw->cap_act_sta_cfi.top); printk(KERN_INFO "STA-CFI:ACT:role=0x%02x:id=0x%02x:var=0x%02x:b/t=%d/%d\n", hw->cap_act_sta_cfi.role, hw->cap_act_sta_cfi.id, hw->cap_act_sta_cfi.variant, hw->cap_act_sta_cfi.bottom, hw->cap_act_sta_cfi.top); /* Compatibility range, sta f/w actor, MFI supplier */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_STA_MFIACTRANGES, &hw->cap_act_sta_mfi, sizeof(hfa384x_caplevel_t)); if (result) { printk(KERN_ERR "Failed to retrieve STA_MFIACTRANGES\n"); goto failed; } /* get all the Compatibility range, station f/w actor, MFI supplier fields in byte order */ hw->cap_act_sta_mfi.role = le16_to_cpu(hw->cap_act_sta_mfi.role); hw->cap_act_sta_mfi.id = le16_to_cpu(hw->cap_act_sta_mfi.id); hw->cap_act_sta_mfi.variant = le16_to_cpu(hw->cap_act_sta_mfi.variant); hw->cap_act_sta_mfi.bottom = le16_to_cpu(hw->cap_act_sta_mfi.bottom); hw->cap_act_sta_mfi.top = le16_to_cpu(hw->cap_act_sta_mfi.top); printk(KERN_INFO "STA-MFI:ACT:role=0x%02x:id=0x%02x:var=0x%02x:b/t=%d/%d\n", hw->cap_act_sta_mfi.role, hw->cap_act_sta_mfi.id, hw->cap_act_sta_mfi.variant, hw->cap_act_sta_mfi.bottom, hw->cap_act_sta_mfi.top); /* Serial Number */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_NICSERIALNUMBER, snum, HFA384x_RID_NICSERIALNUMBER_LEN); if (!result) { wlan_mkprintstr(snum, HFA384x_RID_NICSERIALNUMBER_LEN, pstr, sizeof(pstr)); printk(KERN_INFO "Prism2 card SN: %s\n", pstr); } else { printk(KERN_ERR "Failed to retrieve Prism2 Card SN\n"); goto failed; } /* Collect the MAC address */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_CNFOWNMACADDR, wlandev->netdev->dev_addr, ETH_ALEN); if (result != 0) { printk(KERN_ERR "Failed to retrieve mac address\n"); goto failed; } /* short preamble is always implemented */ wlandev->nsdcaps |= P80211_NSDCAP_SHORT_PREAMBLE; /* find out if hardware wep is implemented */ hfa384x_drvr_getconfig16(hw, HFA384x_RID_PRIVACYOPTIMP, &temp); if (temp) wlandev->nsdcaps |= P80211_NSDCAP_HARDWAREWEP; /* get the dBm Scaling constant */ hfa384x_drvr_getconfig16(hw, HFA384x_RID_CNFDBMADJUST, &temp); hw->dbmadjust = temp; /* Only enable scan by default on newer firmware */ if (HFA384x_FIRMWARE_VERSION(hw->ident_sta_fw.major, hw->ident_sta_fw.minor, hw->ident_sta_fw.variant) < HFA384x_FIRMWARE_VERSION(1, 5, 5)) { wlandev->nsdcaps |= P80211_NSDCAP_NOSCAN; } /* TODO: Set any internally managed config items */ goto done; failed: printk(KERN_ERR "Failed, result=%d\n", result); done: return result; } /*---------------------------------------------------------------- * prism2sta_globalsetup * * Set any global RIDs that we want to set at device activation. * * Arguments: * wlandev wlan device structure * * Returns: * 0 success * >0 f/w reported error * <0 driver reported error * * Side effects: * * Call context: * process thread ----------------------------------------------------------------*/ static int prism2sta_globalsetup(wlandevice_t *wlandev) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; /* Set the maximum frame size */ return hfa384x_drvr_setconfig16(hw, HFA384x_RID_CNFMAXDATALEN, WLAN_DATA_MAXLEN); } static int prism2sta_setmulticast(wlandevice_t *wlandev, netdevice_t *dev) { int result = 0; hfa384x_t *hw = (hfa384x_t *) wlandev->priv; u16 promisc; /* If we're not ready, what's the point? */ if (hw->state != HFA384x_STATE_RUNNING) goto exit; if ((dev->flags & (IFF_PROMISC | IFF_ALLMULTI)) != 0) promisc = P80211ENUM_truth_true; else promisc = P80211ENUM_truth_false; result = hfa384x_drvr_setconfig16_async(hw, HFA384x_RID_PROMISCMODE, promisc); exit: return result; } /*---------------------------------------------------------------- * prism2sta_inf_handover * * Handles the receipt of a Handover info frame. Should only be present * in APs only. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ static void prism2sta_inf_handover(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { pr_debug("received infoframe:HANDOVER (unhandled)\n"); return; } /*---------------------------------------------------------------- * prism2sta_inf_tallies * * Handles the receipt of a CommTallies info frame. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ static void prism2sta_inf_tallies(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; u16 *src16; u32 *dst; u32 *src32; int i; int cnt; /* ** Determine if these are 16-bit or 32-bit tallies, based on the ** record length of the info record. */ cnt = sizeof(hfa384x_CommTallies32_t) / sizeof(u32); if (inf->framelen > 22) { dst = (u32 *) &hw->tallies; src32 = (u32 *) &inf->info.commtallies32; for (i = 0; i < cnt; i++, dst++, src32++) *dst += le32_to_cpu(*src32); } else { dst = (u32 *) &hw->tallies; src16 = (u16 *) &inf->info.commtallies16; for (i = 0; i < cnt; i++, dst++, src16++) *dst += le16_to_cpu(*src16); } return; } /*---------------------------------------------------------------- * prism2sta_inf_scanresults * * Handles the receipt of a Scan Results info frame. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ static void prism2sta_inf_scanresults(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; int nbss; hfa384x_ScanResult_t *sr = &(inf->info.scanresult); int i; hfa384x_JoinRequest_data_t joinreq; int result; /* Get the number of results, first in bytes, then in results */ nbss = (inf->framelen * sizeof(u16)) - sizeof(inf->infotype) - sizeof(inf->info.scanresult.scanreason); nbss /= sizeof(hfa384x_ScanResultSub_t); /* Print em */ pr_debug("rx scanresults, reason=%d, nbss=%d:\n", inf->info.scanresult.scanreason, nbss); for (i = 0; i < nbss; i++) { pr_debug("chid=%d anl=%d sl=%d bcnint=%d\n", sr->result[i].chid, sr->result[i].anl, sr->result[i].sl, sr->result[i].bcnint); pr_debug(" capinfo=0x%04x proberesp_rate=%d\n", sr->result[i].capinfo, sr->result[i].proberesp_rate); } /* issue a join request */ joinreq.channel = sr->result[0].chid; memcpy(joinreq.bssid, sr->result[0].bssid, WLAN_BSSID_LEN); result = hfa384x_drvr_setconfig(hw, HFA384x_RID_JOINREQUEST, &joinreq, HFA384x_RID_JOINREQUEST_LEN); if (result) { printk(KERN_ERR "setconfig(joinreq) failed, result=%d\n", result); } return; } /*---------------------------------------------------------------- * prism2sta_inf_hostscanresults * * Handles the receipt of a Scan Results info frame. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ static void prism2sta_inf_hostscanresults(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; int nbss; nbss = (inf->framelen - 3) / 32; pr_debug("Received %d hostscan results\n", nbss); if (nbss > 32) nbss = 32; kfree(hw->scanresults); hw->scanresults = kmalloc(sizeof(hfa384x_InfFrame_t), GFP_ATOMIC); memcpy(hw->scanresults, inf, sizeof(hfa384x_InfFrame_t)); if (nbss == 0) nbss = -1; /* Notify/wake the sleeping caller. */ hw->scanflag = nbss; wake_up_interruptible(&hw->cmdq); }; /*---------------------------------------------------------------- * prism2sta_inf_chinforesults * * Handles the receipt of a Channel Info Results info frame. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ static void prism2sta_inf_chinforesults(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; unsigned int i, n; hw->channel_info.results.scanchannels = le16_to_cpu(inf->info.chinforesult.scanchannels); for (i = 0, n = 0; i < HFA384x_CHINFORESULT_MAX; i++) { if (hw->channel_info.results.scanchannels & (1 << i)) { int channel = le16_to_cpu(inf->info.chinforesult.result[n].chid) - 1; hfa384x_ChInfoResultSub_t *chinforesult = &hw->channel_info.results.result[channel]; chinforesult->chid = channel; chinforesult->anl = le16_to_cpu(inf->info.chinforesult.result[n].anl); chinforesult->pnl = le16_to_cpu(inf->info.chinforesult.result[n].pnl); chinforesult->active = le16_to_cpu(inf->info.chinforesult.result[n]. active); pr_debug ("chinfo: channel %d, %s level (avg/peak)=%d/%d dB, pcf %d\n", channel + 1, chinforesult-> active & HFA384x_CHINFORESULT_BSSACTIVE ? "signal" : "noise", chinforesult->anl, chinforesult->pnl, chinforesult-> active & HFA384x_CHINFORESULT_PCFACTIVE ? 1 : 0); n++; } } atomic_set(&hw->channel_info.done, 2); hw->channel_info.count = n; return; } void prism2sta_processing_defer(struct work_struct *data) { hfa384x_t *hw = container_of(data, struct hfa384x, link_bh); wlandevice_t *wlandev = hw->wlandev; hfa384x_bytestr32_t ssid; int result; /* First let's process the auth frames */ { struct sk_buff *skb; hfa384x_InfFrame_t *inf; while ((skb = skb_dequeue(&hw->authq))) { inf = (hfa384x_InfFrame_t *) skb->data; prism2sta_inf_authreq_defer(wlandev, inf); } } /* Now let's handle the linkstatus stuff */ if (hw->link_status == hw->link_status_new) goto failed; hw->link_status = hw->link_status_new; switch (hw->link_status) { case HFA384x_LINK_NOTCONNECTED: /* I'm currently assuming that this is the initial link * state. It should only be possible immediately * following an Enable command. * Response: * Block Transmits, Ignore receives of data frames */ netif_carrier_off(wlandev->netdev); printk(KERN_INFO "linkstatus=NOTCONNECTED (unhandled)\n"); break; case HFA384x_LINK_CONNECTED: /* This one indicates a successful scan/join/auth/assoc. * When we have the full MLME complement, this event will * signify successful completion of both mlme_authenticate * and mlme_associate. State management will get a little * ugly here. * Response: * Indicate authentication and/or association * Enable Transmits, Receives and pass up data frames */ netif_carrier_on(wlandev->netdev); /* If we are joining a specific AP, set our * state and reset retries */ if (hw->join_ap == 1) hw->join_ap = 2; hw->join_retries = 60; /* Don't call this in monitor mode */ if (wlandev->netdev->type == ARPHRD_ETHER) { u16 portstatus; printk(KERN_INFO "linkstatus=CONNECTED\n"); /* For non-usb devices, we can use the sync versions */ /* Collect the BSSID, and set state to allow tx */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_CURRENTBSSID, wlandev->bssid, WLAN_BSSID_LEN); if (result) { pr_debug ("getconfig(0x%02x) failed, result = %d\n", HFA384x_RID_CURRENTBSSID, result); goto failed; } result = hfa384x_drvr_getconfig(hw, HFA384x_RID_CURRENTSSID, &ssid, sizeof(ssid)); if (result) { pr_debug ("getconfig(0x%02x) failed, result = %d\n", HFA384x_RID_CURRENTSSID, result); goto failed; } prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *) &ssid, (p80211pstrd_t *) & wlandev->ssid); /* Collect the port status */ result = hfa384x_drvr_getconfig16(hw, HFA384x_RID_PORTSTATUS, &portstatus); if (result) { pr_debug ("getconfig(0x%02x) failed, result = %d\n", HFA384x_RID_PORTSTATUS, result); goto failed; } wlandev->macmode = (portstatus == HFA384x_PSTATUS_CONN_IBSS) ? WLAN_MACMODE_IBSS_STA : WLAN_MACMODE_ESS_STA; /* signal back up to cfg80211 layer */ prism2_connect_result(wlandev, P80211ENUM_truth_false); /* Get the ball rolling on the comms quality stuff */ prism2sta_commsqual_defer(&hw->commsqual_bh); } break; case HFA384x_LINK_DISCONNECTED: /* This one indicates that our association is gone. We've * lost connection with the AP and/or been disassociated. * This indicates that the MAC has completely cleared it's * associated state. We * should send a deauth indication * (implying disassoc) up * to the MLME. * Response: * Indicate Deauthentication * Block Transmits, Ignore receives of data frames */ if (wlandev->netdev->type == ARPHRD_ETHER) printk(KERN_INFO "linkstatus=DISCONNECTED (unhandled)\n"); wlandev->macmode = WLAN_MACMODE_NONE; netif_carrier_off(wlandev->netdev); /* signal back up to cfg80211 layer */ prism2_disconnected(wlandev); break; case HFA384x_LINK_AP_CHANGE: /* This one indicates that the MAC has decided to and * successfully completed a change to another AP. We * should probably implement a reassociation indication * in response to this one. I'm thinking that the the * p80211 layer needs to be notified in case of * buffering/queueing issues. User mode also needs to be * notified so that any BSS dependent elements can be * updated. * associated state. We * should send a deauth indication * (implying disassoc) up * to the MLME. * Response: * Indicate Reassociation * Enable Transmits, Receives and pass up data frames */ printk(KERN_INFO "linkstatus=AP_CHANGE\n"); result = hfa384x_drvr_getconfig(hw, HFA384x_RID_CURRENTBSSID, wlandev->bssid, WLAN_BSSID_LEN); if (result) { pr_debug("getconfig(0x%02x) failed, result = %d\n", HFA384x_RID_CURRENTBSSID, result); goto failed; } result = hfa384x_drvr_getconfig(hw, HFA384x_RID_CURRENTSSID, &ssid, sizeof(ssid)); if (result) { pr_debug("getconfig(0x%02x) failed, result = %d\n", HFA384x_RID_CURRENTSSID, result); goto failed; } prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *) &ssid, (p80211pstrd_t *) &wlandev->ssid); hw->link_status = HFA384x_LINK_CONNECTED; netif_carrier_on(wlandev->netdev); /* signal back up to cfg80211 layer */ prism2_roamed(wlandev); break; case HFA384x_LINK_AP_OUTOFRANGE: /* This one indicates that the MAC has decided that the * AP is out of range, but hasn't found a better candidate * so the MAC maintains its "associated" state in case * we get back in range. We should block transmits and * receives in this state. Do we need an indication here? * Probably not since a polling user-mode element would * get this status from from p2PortStatus(FD40). What about * p80211? * Response: * Block Transmits, Ignore receives of data frames */ printk(KERN_INFO "linkstatus=AP_OUTOFRANGE (unhandled)\n"); netif_carrier_off(wlandev->netdev); break; case HFA384x_LINK_AP_INRANGE: /* This one indicates that the MAC has decided that the * AP is back in range. We continue working with our * existing association. * Response: * Enable Transmits, Receives and pass up data frames */ printk(KERN_INFO "linkstatus=AP_INRANGE\n"); hw->link_status = HFA384x_LINK_CONNECTED; netif_carrier_on(wlandev->netdev); break; case HFA384x_LINK_ASSOCFAIL: /* This one is actually a peer to CONNECTED. We've * requested a join for a given SSID and optionally BSSID. * We can use this one to indicate authentication and * association failures. The trick is going to be * 1) identifying the failure, and 2) state management. * Response: * Disable Transmits, Ignore receives of data frames */ if (hw->join_ap && --hw->join_retries > 0) { hfa384x_JoinRequest_data_t joinreq; joinreq = hw->joinreq; /* Send the join request */ hfa384x_drvr_setconfig(hw, HFA384x_RID_JOINREQUEST, &joinreq, HFA384x_RID_JOINREQUEST_LEN); printk(KERN_INFO "linkstatus=ASSOCFAIL (re-submitting join)\n"); } else { printk(KERN_INFO "linkstatus=ASSOCFAIL (unhandled)\n"); } netif_carrier_off(wlandev->netdev); /* signal back up to cfg80211 layer */ prism2_connect_result(wlandev, P80211ENUM_truth_true); break; default: /* This is bad, IO port problems? */ printk(KERN_WARNING "unknown linkstatus=0x%02x\n", hw->link_status); goto failed; break; } wlandev->linkstatus = (hw->link_status == HFA384x_LINK_CONNECTED); failed: return; } /*---------------------------------------------------------------- * prism2sta_inf_linkstatus * * Handles the receipt of a Link Status info frame. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ static void prism2sta_inf_linkstatus(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; hw->link_status_new = le16_to_cpu(inf->info.linkstatus.linkstatus); schedule_work(&hw->link_bh); return; } /*---------------------------------------------------------------- * prism2sta_inf_assocstatus * * Handles the receipt of an Association Status info frame. Should * be present in APs only. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ static void prism2sta_inf_assocstatus(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; hfa384x_AssocStatus_t rec; int i; memcpy(&rec, &inf->info.assocstatus, sizeof(rec)); rec.assocstatus = le16_to_cpu(rec.assocstatus); rec.reason = le16_to_cpu(rec.reason); /* ** Find the address in the list of authenticated stations. ** If it wasn't found, then this address has not been previously ** authenticated and something weird has happened if this is ** anything other than an "authentication failed" message. ** If the address was found, then set the "associated" flag for ** that station, based on whether the station is associating or ** losing its association. Something weird has also happened ** if we find the address in the list of authenticated stations ** but we are getting an "authentication failed" message. */ for (i = 0; i < hw->authlist.cnt; i++) if (memcmp(rec.sta_addr, hw->authlist.addr[i], ETH_ALEN) == 0) break; if (i >= hw->authlist.cnt) { if (rec.assocstatus != HFA384x_ASSOCSTATUS_AUTHFAIL) printk(KERN_WARNING "assocstatus info frame received for non-authenticated station.\n"); } else { hw->authlist.assoc[i] = (rec.assocstatus == HFA384x_ASSOCSTATUS_STAASSOC || rec.assocstatus == HFA384x_ASSOCSTATUS_REASSOC); if (rec.assocstatus == HFA384x_ASSOCSTATUS_AUTHFAIL) printk(KERN_WARNING "authfail assocstatus info frame received for authenticated station.\n"); } return; } /*---------------------------------------------------------------- * prism2sta_inf_authreq * * Handles the receipt of an Authentication Request info frame. Should * be present in APs only. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt * ----------------------------------------------------------------*/ static void prism2sta_inf_authreq(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; struct sk_buff *skb; skb = dev_alloc_skb(sizeof(*inf)); if (skb) { skb_put(skb, sizeof(*inf)); memcpy(skb->data, inf, sizeof(*inf)); skb_queue_tail(&hw->authq, skb); schedule_work(&hw->link_bh); } } static void prism2sta_inf_authreq_defer(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; hfa384x_authenticateStation_data_t rec; int i, added, result, cnt; u8 *addr; /* ** Build the AuthenticateStation record. Initialize it for denying ** authentication. */ memcpy(rec.address, inf->info.authreq.sta_addr, ETH_ALEN); rec.status = P80211ENUM_status_unspec_failure; /* ** Authenticate based on the access mode. */ switch (hw->accessmode) { case WLAN_ACCESS_NONE: /* ** Deny all new authentications. However, if a station ** is ALREADY authenticated, then accept it. */ for (i = 0; i < hw->authlist.cnt; i++) if (memcmp(rec.address, hw->authlist.addr[i], ETH_ALEN) == 0) { rec.status = P80211ENUM_status_successful; break; } break; case WLAN_ACCESS_ALL: /* ** Allow all authentications. */ rec.status = P80211ENUM_status_successful; break; case WLAN_ACCESS_ALLOW: /* ** Only allow the authentication if the MAC address ** is in the list of allowed addresses. ** ** Since this is the interrupt handler, we may be here ** while the access list is in the middle of being ** updated. Choose the list which is currently okay. ** See "prism2mib_priv_accessallow()" for details. */ if (hw->allow.modify == 0) { cnt = hw->allow.cnt; addr = hw->allow.addr[0]; } else { cnt = hw->allow.cnt1; addr = hw->allow.addr1[0]; } for (i = 0; i < cnt; i++, addr += ETH_ALEN) if (memcmp(rec.address, addr, ETH_ALEN) == 0) { rec.status = P80211ENUM_status_successful; break; } break; case WLAN_ACCESS_DENY: /* ** Allow the authentication UNLESS the MAC address is ** in the list of denied addresses. ** ** Since this is the interrupt handler, we may be here ** while the access list is in the middle of being ** updated. Choose the list which is currently okay. ** See "prism2mib_priv_accessdeny()" for details. */ if (hw->deny.modify == 0) { cnt = hw->deny.cnt; addr = hw->deny.addr[0]; } else { cnt = hw->deny.cnt1; addr = hw->deny.addr1[0]; } rec.status = P80211ENUM_status_successful; for (i = 0; i < cnt; i++, addr += ETH_ALEN) if (memcmp(rec.address, addr, ETH_ALEN) == 0) { rec.status = P80211ENUM_status_unspec_failure; break; } break; } /* ** If the authentication is okay, then add the MAC address to the ** list of authenticated stations. Don't add the address if it ** is already in the list. (802.11b does not seem to disallow ** a station from issuing an authentication request when the ** station is already authenticated. Does this sort of thing ** ever happen? We might as well do the check just in case.) */ added = 0; if (rec.status == P80211ENUM_status_successful) { for (i = 0; i < hw->authlist.cnt; i++) if (memcmp(rec.address, hw->authlist.addr[i], ETH_ALEN) == 0) break; if (i >= hw->authlist.cnt) { if (hw->authlist.cnt >= WLAN_AUTH_MAX) { rec.status = P80211ENUM_status_ap_full; } else { memcpy(hw->authlist.addr[hw->authlist.cnt], rec.address, ETH_ALEN); hw->authlist.cnt++; added = 1; } } } /* ** Send back the results of the authentication. If this doesn't work, ** then make sure to remove the address from the authenticated list if ** it was added. */ rec.status = cpu_to_le16(rec.status); rec.algorithm = inf->info.authreq.algorithm; result = hfa384x_drvr_setconfig(hw, HFA384x_RID_AUTHENTICATESTA, &rec, sizeof(rec)); if (result) { if (added) hw->authlist.cnt--; printk(KERN_ERR "setconfig(authenticatestation) failed, result=%d\n", result); } return; } /*---------------------------------------------------------------- * prism2sta_inf_psusercnt * * Handles the receipt of a PowerSaveUserCount info frame. Should * be present in APs only. * * Arguments: * wlandev wlan device structure * inf ptr to info frame (contents in hfa384x order) * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ static void prism2sta_inf_psusercnt(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { hfa384x_t *hw = (hfa384x_t *) wlandev->priv; hw->psusercount = le16_to_cpu(inf->info.psusercnt.usercnt); return; } /*---------------------------------------------------------------- * prism2sta_ev_info * * Handles the Info event. * * Arguments: * wlandev wlan device structure * inf ptr to a generic info frame * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ void prism2sta_ev_info(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf) { inf->infotype = le16_to_cpu(inf->infotype); /* Dispatch */ switch (inf->infotype) { case HFA384x_IT_HANDOVERADDR: prism2sta_inf_handover(wlandev, inf); break; case HFA384x_IT_COMMTALLIES: prism2sta_inf_tallies(wlandev, inf); break; case HFA384x_IT_HOSTSCANRESULTS: prism2sta_inf_hostscanresults(wlandev, inf); break; case HFA384x_IT_SCANRESULTS: prism2sta_inf_scanresults(wlandev, inf); break; case HFA384x_IT_CHINFORESULTS: prism2sta_inf_chinforesults(wlandev, inf); break; case HFA384x_IT_LINKSTATUS: prism2sta_inf_linkstatus(wlandev, inf); break; case HFA384x_IT_ASSOCSTATUS: prism2sta_inf_assocstatus(wlandev, inf); break; case HFA384x_IT_AUTHREQ: prism2sta_inf_authreq(wlandev, inf); break; case HFA384x_IT_PSUSERCNT: prism2sta_inf_psusercnt(wlandev, inf); break; case HFA384x_IT_KEYIDCHANGED: printk(KERN_WARNING "Unhandled IT_KEYIDCHANGED\n"); break; case HFA384x_IT_ASSOCREQ: printk(KERN_WARNING "Unhandled IT_ASSOCREQ\n"); break; case HFA384x_IT_MICFAILURE: printk(KERN_WARNING "Unhandled IT_MICFAILURE\n"); break; default: printk(KERN_WARNING "Unknown info type=0x%02x\n", inf->infotype); break; } return; } /*---------------------------------------------------------------- * prism2sta_ev_txexc * * Handles the TxExc event. A Transmit Exception event indicates * that the MAC's TX process was unsuccessful - so the packet did * not get transmitted. * * Arguments: * wlandev wlan device structure * status tx frame status word * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ void prism2sta_ev_txexc(wlandevice_t *wlandev, u16 status) { pr_debug("TxExc status=0x%x.\n", status); return; } /*---------------------------------------------------------------- * prism2sta_ev_tx * * Handles the Tx event. * * Arguments: * wlandev wlan device structure * status tx frame status word * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ void prism2sta_ev_tx(wlandevice_t *wlandev, u16 status) { pr_debug("Tx Complete, status=0x%04x\n", status); /* update linux network stats */ wlandev->linux_stats.tx_packets++; return; } /*---------------------------------------------------------------- * prism2sta_ev_rx * * Handles the Rx event. * * Arguments: * wlandev wlan device structure * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ void prism2sta_ev_rx(wlandevice_t *wlandev, struct sk_buff *skb) { p80211netdev_rx(wlandev, skb); return; } /*---------------------------------------------------------------- * prism2sta_ev_alloc * * Handles the Alloc event. * * Arguments: * wlandev wlan device structure * * Returns: * nothing * * Side effects: * * Call context: * interrupt ----------------------------------------------------------------*/ void prism2sta_ev_alloc(wlandevice_t *wlandev) { netif_wake_queue(wlandev->netdev); return; } /*---------------------------------------------------------------- * create_wlan * * Called at module init time. This creates the wlandevice_t structure * and initializes it with relevant bits. * * Arguments: * none * * Returns: * the created wlandevice_t structure. * * Side effects: * also allocates the priv/hw structures. * * Call context: * process thread * ----------------------------------------------------------------*/ static wlandevice_t *create_wlan(void) { wlandevice_t *wlandev = NULL; hfa384x_t *hw = NULL; /* Alloc our structures */ wlandev = kmalloc(sizeof(wlandevice_t), GFP_KERNEL); hw = kmalloc(sizeof(hfa384x_t), GFP_KERNEL); if (!wlandev || !hw) { printk(KERN_ERR "%s: Memory allocation failure.\n", dev_info); kfree(wlandev); kfree(hw); return NULL; } /* Clear all the structs */ memset(wlandev, 0, sizeof(wlandevice_t)); memset(hw, 0, sizeof(hfa384x_t)); /* Initialize the network device object. */ wlandev->nsdname = dev_info; wlandev->msdstate = WLAN_MSD_HWPRESENT_PENDING; wlandev->priv = hw; wlandev->open = prism2sta_open; wlandev->close = prism2sta_close; wlandev->reset = prism2sta_reset; wlandev->txframe = prism2sta_txframe; wlandev->mlmerequest = prism2sta_mlmerequest; wlandev->set_multicast_list = prism2sta_setmulticast; wlandev->tx_timeout = hfa384x_tx_timeout; wlandev->nsdcaps = P80211_NSDCAP_HWFRAGMENT | P80211_NSDCAP_AUTOJOIN; /* Initialize the device private data stucture. */ hw->dot11_desired_bss_type = 1; return wlandev; } void prism2sta_commsqual_defer(struct work_struct *data) { hfa384x_t *hw = container_of(data, struct hfa384x, commsqual_bh); wlandevice_t *wlandev = hw->wlandev; hfa384x_bytestr32_t ssid; struct p80211msg_dot11req_mibget msg; p80211item_uint32_t *mibitem = (p80211item_uint32_t *) &msg.mibattribute.data; int result = 0; if (hw->wlandev->hwremoved) goto done; /* we don't care if we're in AP mode */ if ((wlandev->macmode == WLAN_MACMODE_NONE) || (wlandev->macmode == WLAN_MACMODE_ESS_AP)) { goto done; } /* It only makes sense to poll these in non-IBSS */ if (wlandev->macmode != WLAN_MACMODE_IBSS_STA) { result = hfa384x_drvr_getconfig( hw, HFA384x_RID_DBMCOMMSQUALITY, &hw->qual, HFA384x_RID_DBMCOMMSQUALITY_LEN); if (result) { printk(KERN_ERR "error fetching commsqual\n"); goto done; } pr_debug("commsqual %d %d %d\n", le16_to_cpu(hw->qual.CQ_currBSS), le16_to_cpu(hw->qual.ASL_currBSS), le16_to_cpu(hw->qual.ANL_currFC)); } /* Get the signal rate */ msg.msgcode = DIDmsg_dot11req_mibget; mibitem->did = DIDmib_p2_p2MAC_p2CurrentTxRate; result = p80211req_dorequest(wlandev, (u8 *) &msg); if (result) { pr_debug("get signal rate failed, result = %d\n", result); goto done; } switch (mibitem->data) { case HFA384x_RATEBIT_1: hw->txrate = 10; break; case HFA384x_RATEBIT_2: hw->txrate = 20; break; case HFA384x_RATEBIT_5dot5: hw->txrate = 55; break; case HFA384x_RATEBIT_11: hw->txrate = 110; break; default: pr_debug("Bad ratebit (%d)\n", mibitem->data); } /* Lastly, we need to make sure the BSSID didn't change on us */ result = hfa384x_drvr_getconfig(hw, HFA384x_RID_CURRENTBSSID, wlandev->bssid, WLAN_BSSID_LEN); if (result) { pr_debug("getconfig(0x%02x) failed, result = %d\n", HFA384x_RID_CURRENTBSSID, result); goto done; } result = hfa384x_drvr_getconfig(hw, HFA384x_RID_CURRENTSSID, &ssid, sizeof(ssid)); if (result) { pr_debug("getconfig(0x%02x) failed, result = %d\n", HFA384x_RID_CURRENTSSID, result); goto done; } prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *) &ssid, (p80211pstrd_t *) &wlandev->ssid); /* Reschedule timer */ mod_timer(&hw->commsqual_timer, jiffies + HZ); done: ; } void prism2sta_commsqual_timer(unsigned long data) { hfa384x_t *hw = (hfa384x_t *) data; schedule_work(&hw->commsqual_bh); }
gpl-2.0
CoderSherlock/Mondroid
kernelsource/msm/fs/proc/array.c
549
18605
/* * linux/fs/proc/array.c * * Copyright (C) 1992 by Linus Torvalds * based on ideas by Darren Senn * * Fixes: * Michael. K. Johnson: stat,statm extensions. * <johnsonm@stolaf.edu> * * Pauline Middelink : Made cmdline,envline only break at '\0's, to * make sure SET_PROCTITLE works. Also removed * bad '!' which forced address recalculation for * EVERY character on the current page. * <middelin@polyware.iaf.nl> * * Danny ter Haar : added cpuinfo * <dth@cistron.nl> * * Alessandro Rubini : profile extension. * <rubini@ipvvis.unipv.it> * * Jeff Tranter : added BogoMips field to cpuinfo * <Jeff_Tranter@Mitel.COM> * * Bruno Haible : remove 4K limit for the maps file * <haible@ma2s2.mathematik.uni-karlsruhe.de> * * Yves Arrouye : remove removal of trailing spaces in get_array. * <Yves.Arrouye@marin.fdn.fr> * * Jerome Forissier : added per-CPU time information to /proc/stat * and /proc/<pid>/cpu extension * <forissier@isia.cma.fr> * - Incorporation and non-SMP safe operation * of forissier patch in 2.1.78 by * Hans Marcus <crowbar@concepts.nl> * * aeb@cwi.nl : /proc/partitions * * * Alan Cox : security fixes. * <alan@lxorguk.ukuu.org.uk> * * Al Viro : safe handling of mm_struct * * Gerhard Wichert : added BIGMEM support * Siemens AG <Gerhard.Wichert@pdb.siemens.de> * * Al Viro & Jeff Garzik : moved most of the thing into base.c and * : proc_misc.c. The rest may eventually go into * : base.c too. */ #include <linux/types.h> #include <linux/errno.h> #include <linux/time.h> #include <linux/kernel.h> #include <linux/kernel_stat.h> #include <linux/tty.h> #include <linux/string.h> #include <linux/mman.h> #include <linux/proc_fs.h> #include <linux/ioport.h> #include <linux/uaccess.h> #include <linux/io.h> #include <linux/mm.h> #include <linux/hugetlb.h> #include <linux/pagemap.h> #include <linux/swap.h> #include <linux/smp.h> #include <linux/signal.h> #include <linux/highmem.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/times.h> #include <linux/cpuset.h> #include <linux/rcupdate.h> #include <linux/delayacct.h> #include <linux/seq_file.h> #include <linux/pid_namespace.h> #include <linux/ptrace.h> #include <linux/tracehook.h> #include <linux/user_namespace.h> #include <asm/pgtable.h> #include <asm/processor.h> #include "internal.h" static inline void task_name(struct seq_file *m, struct task_struct *p) { int i; char *buf, *end; char *name; char tcomm[sizeof(p->comm)]; get_task_comm(tcomm, p); seq_puts(m, "Name:\t"); end = m->buf + m->size; buf = m->buf + m->count; name = tcomm; i = sizeof(tcomm); while (i && (buf < end)) { unsigned char c = *name; name++; i--; *buf = c; if (!c) break; if (c == '\\') { buf++; if (buf < end) *buf++ = c; continue; } if (c == '\n') { *buf++ = '\\'; if (buf < end) *buf++ = 'n'; continue; } buf++; } m->count = buf - m->buf; seq_putc(m, '\n'); } /* * The task state array is a strange "bitmap" of * reasons to sleep. Thus "running" is zero, and * you can test for combinations of others with * simple bit tests. */ static const char * const task_state_array[] = { "R (running)", /* 0 */ "S (sleeping)", /* 1 */ "D (disk sleep)", /* 2 */ "T (stopped)", /* 4 */ "t (tracing stop)", /* 8 */ "Z (zombie)", /* 16 */ "X (dead)", /* 32 */ "x (dead)", /* 64 */ "K (wakekill)", /* 128 */ "W (waking)", /* 256 */ "P (parked)", /* 512 */ }; static inline const char *get_task_state(struct task_struct *tsk) { unsigned int state = (tsk->state & TASK_REPORT) | tsk->exit_state; const char * const *p = &task_state_array[0]; BUILD_BUG_ON(1 + ilog2(TASK_STATE_MAX) != ARRAY_SIZE(task_state_array)); while (state) { p++; state >>= 1; } return *p; } static inline void task_state(struct seq_file *m, struct pid_namespace *ns, struct pid *pid, struct task_struct *p) { struct user_namespace *user_ns = seq_user_ns(m); struct group_info *group_info; int g; struct fdtable *fdt = NULL; const struct cred *cred; pid_t ppid, tpid; rcu_read_lock(); ppid = pid_alive(p) ? task_tgid_nr_ns(rcu_dereference(p->real_parent), ns) : 0; tpid = 0; if (pid_alive(p)) { struct task_struct *tracer = ptrace_parent(p); if (tracer) tpid = task_pid_nr_ns(tracer, ns); } cred = get_task_cred(p); seq_printf(m, "State:\t%s\n" "Tgid:\t%d\n" "Pid:\t%d\n" "PPid:\t%d\n" "TracerPid:\t%d\n" "Uid:\t%d\t%d\t%d\t%d\n" "Gid:\t%d\t%d\t%d\t%d\n", get_task_state(p), task_tgid_nr_ns(p, ns), pid_nr_ns(pid, ns), ppid, tpid, from_kuid_munged(user_ns, cred->uid), from_kuid_munged(user_ns, cred->euid), from_kuid_munged(user_ns, cred->suid), from_kuid_munged(user_ns, cred->fsuid), from_kgid_munged(user_ns, cred->gid), from_kgid_munged(user_ns, cred->egid), from_kgid_munged(user_ns, cred->sgid), from_kgid_munged(user_ns, cred->fsgid)); task_lock(p); if (p->files) fdt = files_fdtable(p->files); seq_printf(m, "FDSize:\t%d\n" "Groups:\t", fdt ? fdt->max_fds : 0); rcu_read_unlock(); group_info = cred->group_info; task_unlock(p); for (g = 0; g < group_info->ngroups; g++) seq_printf(m, "%d ", from_kgid_munged(user_ns, GROUP_AT(group_info, g))); put_cred(cred); seq_putc(m, '\n'); } void render_sigset_t(struct seq_file *m, const char *header, sigset_t *set) { int i; seq_puts(m, header); i = _NSIG; do { int x = 0; i -= 4; if (sigismember(set, i+1)) x |= 1; if (sigismember(set, i+2)) x |= 2; if (sigismember(set, i+3)) x |= 4; if (sigismember(set, i+4)) x |= 8; seq_printf(m, "%x", x); } while (i >= 4); seq_putc(m, '\n'); } static void collect_sigign_sigcatch(struct task_struct *p, sigset_t *ign, sigset_t *catch) { struct k_sigaction *k; int i; k = p->sighand->action; for (i = 1; i <= _NSIG; ++i, ++k) { if (k->sa.sa_handler == SIG_IGN) sigaddset(ign, i); else if (k->sa.sa_handler != SIG_DFL) sigaddset(catch, i); } } static inline void task_sig(struct seq_file *m, struct task_struct *p) { unsigned long flags; sigset_t pending, shpending, blocked, ignored, caught; int num_threads = 0; unsigned long qsize = 0; unsigned long qlim = 0; sigemptyset(&pending); sigemptyset(&shpending); sigemptyset(&blocked); sigemptyset(&ignored); sigemptyset(&caught); if (lock_task_sighand(p, &flags)) { pending = p->pending.signal; shpending = p->signal->shared_pending.signal; blocked = p->blocked; collect_sigign_sigcatch(p, &ignored, &caught); num_threads = get_nr_threads(p); rcu_read_lock(); /* FIXME: is this correct? */ qsize = atomic_read(&__task_cred(p)->user->sigpending); rcu_read_unlock(); qlim = task_rlimit(p, RLIMIT_SIGPENDING); unlock_task_sighand(p, &flags); } seq_printf(m, "Threads:\t%d\n", num_threads); seq_printf(m, "SigQ:\t%lu/%lu\n", qsize, qlim); /* render them all */ render_sigset_t(m, "SigPnd:\t", &pending); render_sigset_t(m, "ShdPnd:\t", &shpending); render_sigset_t(m, "SigBlk:\t", &blocked); render_sigset_t(m, "SigIgn:\t", &ignored); render_sigset_t(m, "SigCgt:\t", &caught); } static void render_cap_t(struct seq_file *m, const char *header, kernel_cap_t *a) { unsigned __capi; seq_puts(m, header); CAP_FOR_EACH_U32(__capi) { seq_printf(m, "%08x", a->cap[CAP_LAST_U32 - __capi]); } seq_putc(m, '\n'); } static inline void task_cap(struct seq_file *m, struct task_struct *p) { const struct cred *cred; kernel_cap_t cap_inheritable, cap_permitted, cap_effective, cap_bset; rcu_read_lock(); cred = __task_cred(p); cap_inheritable = cred->cap_inheritable; cap_permitted = cred->cap_permitted; cap_effective = cred->cap_effective; cap_bset = cred->cap_bset; rcu_read_unlock(); render_cap_t(m, "CapInh:\t", &cap_inheritable); render_cap_t(m, "CapPrm:\t", &cap_permitted); render_cap_t(m, "CapEff:\t", &cap_effective); render_cap_t(m, "CapBnd:\t", &cap_bset); } static inline void task_seccomp(struct seq_file *m, struct task_struct *p) { #ifdef CONFIG_SECCOMP seq_printf(m, "Seccomp:\t%d\n", p->seccomp.mode); #endif } static inline void task_context_switch_counts(struct seq_file *m, struct task_struct *p) { seq_printf(m, "voluntary_ctxt_switches:\t%lu\n" "nonvoluntary_ctxt_switches:\t%lu\n", p->nvcsw, p->nivcsw); } static void task_cpus_allowed(struct seq_file *m, struct task_struct *task) { seq_puts(m, "Cpus_allowed:\t"); seq_cpumask(m, &task->cpus_allowed); seq_putc(m, '\n'); seq_puts(m, "Cpus_allowed_list:\t"); seq_cpumask_list(m, &task->cpus_allowed); seq_putc(m, '\n'); } int proc_pid_status(struct seq_file *m, struct pid_namespace *ns, struct pid *pid, struct task_struct *task) { struct mm_struct *mm = get_task_mm(task); task_name(m, task); task_state(m, ns, pid, task); if (mm) { task_mem(m, mm); mmput(mm); } task_sig(m, task); task_cap(m, task); task_seccomp(m, task); task_cpus_allowed(m, task); cpuset_task_status_allowed(m, task); task_context_switch_counts(m, task); return 0; } static int do_task_stat(struct seq_file *m, struct pid_namespace *ns, struct pid *pid, struct task_struct *task, int whole) { unsigned long vsize, eip, esp, wchan = ~0UL; int priority, nice; int tty_pgrp = -1, tty_nr = 0; sigset_t sigign, sigcatch; char state; pid_t ppid = 0, pgid = -1, sid = -1; int num_threads = 0; int permitted; struct mm_struct *mm; unsigned long long start_time; unsigned long cmin_flt = 0, cmaj_flt = 0; unsigned long min_flt = 0, maj_flt = 0; cputime_t cutime, cstime, utime, stime; cputime_t cgtime, gtime; unsigned long rsslim = 0; char tcomm[sizeof(task->comm)]; unsigned long flags; state = *get_task_state(task); vsize = eip = esp = 0; permitted = ptrace_may_access(task, PTRACE_MODE_READ | PTRACE_MODE_NOAUDIT); mm = get_task_mm(task); if (mm) { vsize = task_vsize(mm); if (permitted) { eip = KSTK_EIP(task); esp = KSTK_ESP(task); } } get_task_comm(tcomm, task); sigemptyset(&sigign); sigemptyset(&sigcatch); cutime = cstime = utime = stime = 0; cgtime = gtime = 0; if (lock_task_sighand(task, &flags)) { struct signal_struct *sig = task->signal; if (sig->tty) { struct pid *pgrp = tty_get_pgrp(sig->tty); tty_pgrp = pid_nr_ns(pgrp, ns); put_pid(pgrp); tty_nr = new_encode_dev(tty_devnum(sig->tty)); } num_threads = get_nr_threads(task); collect_sigign_sigcatch(task, &sigign, &sigcatch); cmin_flt = sig->cmin_flt; cmaj_flt = sig->cmaj_flt; cutime = sig->cutime; cstime = sig->cstime; cgtime = sig->cgtime; rsslim = ACCESS_ONCE(sig->rlim[RLIMIT_RSS].rlim_cur); /* add up live thread stats at the group level */ if (whole) { struct task_struct *t = task; do { min_flt += t->min_flt; maj_flt += t->maj_flt; gtime += task_gtime(t); t = next_thread(t); } while (t != task); min_flt += sig->min_flt; maj_flt += sig->maj_flt; thread_group_cputime_adjusted(task, &utime, &stime); gtime += sig->gtime; } sid = task_session_nr_ns(task, ns); ppid = task_tgid_nr_ns(task->real_parent, ns); pgid = task_pgrp_nr_ns(task, ns); unlock_task_sighand(task, &flags); } if (permitted && (!whole || num_threads < 2)) wchan = get_wchan(task); if (!whole) { min_flt = task->min_flt; maj_flt = task->maj_flt; task_cputime_adjusted(task, &utime, &stime); gtime = task_gtime(task); } /* scale priority and nice values from timeslices to -20..20 */ /* to make it look like a "normal" Unix priority/nice value */ priority = task_prio(task); nice = task_nice(task); /* Temporary variable needed for gcc-2.96 */ /* convert timespec -> nsec*/ start_time = (unsigned long long)task->real_start_time.tv_sec * NSEC_PER_SEC + task->real_start_time.tv_nsec; /* convert nsec -> ticks */ start_time = nsec_to_clock_t(start_time); seq_printf(m, "%d (%s) %c", pid_nr_ns(pid, ns), tcomm, state); seq_put_decimal_ll(m, ' ', ppid); seq_put_decimal_ll(m, ' ', pgid); seq_put_decimal_ll(m, ' ', sid); seq_put_decimal_ll(m, ' ', tty_nr); seq_put_decimal_ll(m, ' ', tty_pgrp); seq_put_decimal_ull(m, ' ', task->flags); seq_put_decimal_ull(m, ' ', min_flt); seq_put_decimal_ull(m, ' ', cmin_flt); seq_put_decimal_ull(m, ' ', maj_flt); seq_put_decimal_ull(m, ' ', cmaj_flt); seq_put_decimal_ull(m, ' ', cputime_to_clock_t(utime)); seq_put_decimal_ull(m, ' ', cputime_to_clock_t(stime)); seq_put_decimal_ll(m, ' ', cputime_to_clock_t(cutime)); seq_put_decimal_ll(m, ' ', cputime_to_clock_t(cstime)); seq_put_decimal_ll(m, ' ', priority); seq_put_decimal_ll(m, ' ', nice); seq_put_decimal_ll(m, ' ', num_threads); seq_put_decimal_ull(m, ' ', 0); seq_put_decimal_ull(m, ' ', start_time); seq_put_decimal_ull(m, ' ', vsize); seq_put_decimal_ull(m, ' ', mm ? get_mm_rss(mm) : 0); seq_put_decimal_ull(m, ' ', rsslim); seq_put_decimal_ull(m, ' ', mm ? (permitted ? mm->start_code : 1) : 0); seq_put_decimal_ull(m, ' ', mm ? (permitted ? mm->end_code : 1) : 0); seq_put_decimal_ull(m, ' ', (permitted && mm) ? mm->start_stack : 0); seq_put_decimal_ull(m, ' ', esp); seq_put_decimal_ull(m, ' ', eip); /* The signal information here is obsolete. * It must be decimal for Linux 2.0 compatibility. * Use /proc/#/status for real-time signals. */ seq_put_decimal_ull(m, ' ', task->pending.signal.sig[0] & 0x7fffffffUL); seq_put_decimal_ull(m, ' ', task->blocked.sig[0] & 0x7fffffffUL); seq_put_decimal_ull(m, ' ', sigign.sig[0] & 0x7fffffffUL); seq_put_decimal_ull(m, ' ', sigcatch.sig[0] & 0x7fffffffUL); seq_put_decimal_ull(m, ' ', wchan); seq_put_decimal_ull(m, ' ', 0); seq_put_decimal_ull(m, ' ', 0); seq_put_decimal_ll(m, ' ', task->exit_signal); seq_put_decimal_ll(m, ' ', task_cpu(task)); seq_put_decimal_ull(m, ' ', task->rt_priority); seq_put_decimal_ull(m, ' ', task->policy); seq_put_decimal_ull(m, ' ', delayacct_blkio_ticks(task)); seq_put_decimal_ull(m, ' ', cputime_to_clock_t(gtime)); seq_put_decimal_ll(m, ' ', cputime_to_clock_t(cgtime)); if (mm && permitted) { seq_put_decimal_ull(m, ' ', mm->start_data); seq_put_decimal_ull(m, ' ', mm->end_data); seq_put_decimal_ull(m, ' ', mm->start_brk); seq_put_decimal_ull(m, ' ', mm->arg_start); seq_put_decimal_ull(m, ' ', mm->arg_end); seq_put_decimal_ull(m, ' ', mm->env_start); seq_put_decimal_ull(m, ' ', mm->env_end); } else seq_printf(m, " 0 0 0 0 0 0 0"); if (permitted) seq_put_decimal_ll(m, ' ', task->exit_code); else seq_put_decimal_ll(m, ' ', 0); seq_putc(m, '\n'); if (mm) mmput(mm); return 0; } int proc_tid_stat(struct seq_file *m, struct pid_namespace *ns, struct pid *pid, struct task_struct *task) { return do_task_stat(m, ns, pid, task, 0); } int proc_tgid_stat(struct seq_file *m, struct pid_namespace *ns, struct pid *pid, struct task_struct *task) { return do_task_stat(m, ns, pid, task, 1); } int proc_pid_statm(struct seq_file *m, struct pid_namespace *ns, struct pid *pid, struct task_struct *task) { unsigned long size = 0, resident = 0, shared = 0, text = 0, data = 0; struct mm_struct *mm = get_task_mm(task); if (mm) { size = task_statm(mm, &shared, &text, &data, &resident); mmput(mm); } /* * For quick read, open code by putting numbers directly * expected format is * seq_printf(m, "%lu %lu %lu %lu 0 %lu 0\n", * size, resident, shared, text, data); */ seq_put_decimal_ull(m, 0, size); seq_put_decimal_ull(m, ' ', resident); seq_put_decimal_ull(m, ' ', shared); seq_put_decimal_ull(m, ' ', text); seq_put_decimal_ull(m, ' ', 0); seq_put_decimal_ull(m, ' ', data); seq_put_decimal_ull(m, ' ', 0); seq_putc(m, '\n'); return 0; } #ifdef CONFIG_CHECKPOINT_RESTORE static struct pid * get_children_pid(struct inode *inode, struct pid *pid_prev, loff_t pos) { struct task_struct *start, *task; struct pid *pid = NULL; read_lock(&tasklist_lock); start = pid_task(proc_pid(inode), PIDTYPE_PID); if (!start) goto out; /* * Lets try to continue searching first, this gives * us significant speedup on children-rich processes. */ if (pid_prev) { task = pid_task(pid_prev, PIDTYPE_PID); if (task && task->real_parent == start && !(list_empty(&task->sibling))) { if (list_is_last(&task->sibling, &start->children)) goto out; task = list_first_entry(&task->sibling, struct task_struct, sibling); pid = get_pid(task_pid(task)); goto out; } } /* * Slow search case. * * We might miss some children here if children * are exited while we were not holding the lock, * but it was never promised to be accurate that * much. * * "Just suppose that the parent sleeps, but N children * exit after we printed their tids. Now the slow paths * skips N extra children, we miss N tasks." (c) * * So one need to stop or freeze the leader and all * its children to get a precise result. */ list_for_each_entry(task, &start->children, sibling) { if (pos-- == 0) { pid = get_pid(task_pid(task)); break; } } out: read_unlock(&tasklist_lock); return pid; } static int children_seq_show(struct seq_file *seq, void *v) { struct inode *inode = seq->private; pid_t pid; pid = pid_nr_ns(v, inode->i_sb->s_fs_info); return seq_printf(seq, "%d ", pid); } static void *children_seq_start(struct seq_file *seq, loff_t *pos) { return get_children_pid(seq->private, NULL, *pos); } static void *children_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct pid *pid; pid = get_children_pid(seq->private, v, *pos + 1); put_pid(v); ++*pos; return pid; } static void children_seq_stop(struct seq_file *seq, void *v) { put_pid(v); } static const struct seq_operations children_seq_ops = { .start = children_seq_start, .next = children_seq_next, .stop = children_seq_stop, .show = children_seq_show, }; static int children_seq_open(struct inode *inode, struct file *file) { struct seq_file *m; int ret; ret = seq_open(file, &children_seq_ops); if (ret) return ret; m = file->private_data; m->private = inode; return ret; } int children_seq_release(struct inode *inode, struct file *file) { seq_release(inode, file); return 0; } const struct file_operations proc_tid_children_operations = { .open = children_seq_open, .read = seq_read, .llseek = seq_lseek, .release = children_seq_release, }; #endif /* CONFIG_CHECKPOINT_RESTORE */
gpl-2.0